From 1c66c97db501ac03e0ba5e5544bb4e90bcaf06a0 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 07:21:49 -0800 Subject: [PATCH 001/221] docs(ast): define source documentation extraction contract --- docs/development/documentation_extraction.md | 749 +++++++++++++++++++ docs/development/grammar_dispatch.md | 4 + 2 files changed, 753 insertions(+) create mode 100644 docs/development/documentation_extraction.md diff --git a/docs/development/documentation_extraction.md b/docs/development/documentation_extraction.md new file mode 100644 index 000000000..6822adadb --- /dev/null +++ b/docs/development/documentation_extraction.md @@ -0,0 +1,749 @@ +# Source-documentation extraction contract + +This is the contributor implementation contract for declaration-to-documentation +queries in `big-code-analysis-ast` and the root library's `Ast`. It specifies what +the documentation index must preserve, how it differs from documentation line +counting, and which outcomes its tests must establish. It assumes familiarity +with the project's [grammar dispatch](grammar_dispatch.md) and +[tree-sitter](https://tree-sitter.github.io/tree-sitter/) syntax trees. + +The extraction API is planned work under +[#1654](https://github.com/dekobon/big-code-analysis/issues/1654). Operation and +type names below describe required behavior; they do not claim an API is already +available. The current public surface is listed in [STABILITY.md](../../STABILITY.md). +Track implementation status and review evidence in the issues, rather than in +this contract. + +## Recognition serves two consumers {#recognition} + +A documentation line count answers which physical source rows the legacy +convention bills as documentation. Extraction answers which source fragments +form a document and which declaration or other owner that document describes. +An owner is the source entity being documented. It can differ from the metric +space containing the comment. + +```text +AST role/context recognition and shared binding + +-- legacy candidate view -> exact streaming reading -> root LOC/MI + `-- source candidate view -> documents/associations -> local text/mappings +``` + +The source and legacy views may select different candidates before applying +the same binding algorithm. For example, Java source attachment recognizes +`/**/`, while the current legacy marker excludes it. An older block followed +by `/**/` selects the newer block for extraction and the older block for DLOC. +Filtering source-selected documents afterwards cannot recover the old reading. + +Keep these decisions separate: + +| Decision | Question | +| --- | --- | +| Recognition | Does the syntax contain a documentation candidate? | +| Profile selection | Which candidates does this named convention retain? | +| Source attachment | Which source owner does the selected document describe? | +| Publication eligibility | Would the named tool/configuration include that owner? | +| Legacy reading | Which original rows does the existing metric path bill, and when? | + +Use the existing documentation roles and their named context functions in +[`roles/mod.rs`](../../big-code-analysis-ast/src/roles/mod.rs). `Comment` and +`DocComment` partition comment kinds; `is_comment` reads their kind union and +`is_doc_comment` applies documentation gates. A `Docstring` is a positional +string, not a comment. `DocTarget` is a candidate, not a resolved owner. +`DocBodyResidual` supplements callable/closure recognition and the language's +body-child test; it is not the complete body predicate. + +Attributes recognized by extraction do not automatically enter the legacy +`DocComment` or `Docstring` rows. This applies to Rust `#[doc = ...]` and Elixir +`@doc`, `@moduledoc` and `@typedoc`. Do not put metric flags on public facts. +The AST supplies the exact legacy reading through internal intercrate plumbing; +the root retains physical row sets, metric-space attribution and aggregation. + +### Streaming and evidence requests + +The legacy-only path does not construct a documentation index or render text. +A private request or sink controls additional source evidence: + +| Existing situation | Legacy-only work | Source-evidence request | +| --- | --- | --- | +| `StretchEnd::Undecided` | Defer until the final member | Also defer; never scan every prefix | +| Rejected placement or `Elsewhere` without a gatherer | Keep the current early exit | Inspect only when retaining rejected/unbound evidence was requested | +| Existing in-body documentation | Preserve the current reading | Resolve source attachment separately | +| Doxygen gathering | Preserve gatherer and coverage order | Retain contributing occurrences once | +| Python additional-string run | Preserve one backward run scan | Retain primary/additional owners and fragments in that scan | +| Logical continuation rows | Retain the root's existing `BareRows` prepass | Reuse only structural source facts, not metric policy | + +Count additional-evidence materialization in tests. Metrics-only requests must +perform zero new materialization. Preserve all existing row corrections and +emission timing, including Python parentheses and Rust comment newline handling. +Do not count rows from cleaned text or semantic owner spans. + +## The source-bound index {#index} + +Collection borrows the language, tree and parsed source with explicit immutable +context and options. It returns a caller-owned immutable index. Typed +`Parser`/`AnyParser` convenience is the preferred direct-AST entry point and +checks retained parse completion provenance. + +The direct AST crate also exposes collection over borrowed language/tree/source. +Its preconditions are a matching grammar, tree and buffer, and a complete parse. +This permits early benchmark and fuzz callers to reuse `Ast`'s existing tree +and source accessors. No reparse, clone-and-adopt workaround or early root API +addition is required. The later stable `Ast::documentation` delegates through +its typed parser. `Ast` stores no persistent or self-referential documentation +cache. + +### Fragments, documents and associations + +| Record | Identity and contents | +| --- | --- | +| Physical fragment | One source occurrence; ordered included byte ranges; optional exact syntax node | +| Logical document | Ordered fragment composition, role and text state; shared by its associations | +| Association | One document, its convention/provenance, binding wrapper and resolved owner or unresolved candidates | +| Owner | Exact node, location-backed slot, file/root, logical declaration group or virtual target | + +An occurrence's identity is not its text. Equal strings at different offsets +remain different fragments. A document describing several qualifying fields +is stored once and has several resolved associations. A conditional declaration +with alternative branches has unresolved alternatives, not several claims that +all branches are active. + +Preserve the lexical containing scope and binding wrapper separately from +normalized owners. A slot contains its enclosing owner, role, ordinal and source +span. It does not pretend to be a tree-sitter node. Recovered declarations can +retain several ordered source pieces; insufficient evidence yields an unresolved +candidate, not a fabricated function inferred from a declarator's shape. + +Type-leading documentation belongs to the type even when metrics synthesize a +primary-constructor or record-header function space. Explicit Java and compact +constructors, Kotlin secondary constructors and other declared-constructor targets +remain owners. Keep signature-holder-only forms distinct. A parameter-local +document belongs to its parameter slot; `@param` text in a type document stays +markup rather than creating another document. + +### Outcomes + +| Situation | Required outcome | +| --- | --- | +| Supported owner with no selected documentation | Successful empty owner query | +| Unsupported owner kind | Unsupported-owner outcome, distinguishable from an empty query | +| Foreign tree or noncanonical node | Distinguishable identity errors | +| Handle from another index | Foreign-index error, or API shape preventing transfer | +| Parser feature disabled | Language-disabled error | +| Requested convention not supported for this language | Unsupported-profile error | +| Valid empty prose | Present document, complete text `""`, empty mapping | +| Explicitly disabled documentation | Retained disabled state; not empty prose | +| Explicitly absent value such as Elixir `nil` | Retained explicit-absence state | +| Metadata-only attribute | Retained metadata-only state; no prose value | +| Dynamic, undecodable or incomplete local content | Retained raw fragments and explicit text-unavailable reason | +| Missing, duplicate or conditional named target | Unresolved association with reason and available candidates | +| Ccomment or Preproc | `NoDeclarationModel`; empty documents/associations; declaration lookup unsupported | + +Default enumeration retains selected documents, including disabled/metadata +states. An explicit evidence option also exposes superseded and dangling +candidates; ordinary owner queries do not return them as attached documents. + +### Identity and ordering + +Prefer opaque references borrowing their index. Node convenience checks the +held tree and an indexed canonical representation of the node. The pinned +tree-sitter binding provides safe `Node::into_raw()`: compare its tree pointer +without dereferencing it. Also compare the canonical context, node identity, +kind and spans recorded during collection. Node ID or byte range alone is not +provenance. The returned index, handles and result types retain `Send + Sync`. +Keep safe borrowed tree/node values rather than a stored raw pointer that +changes those auto-traits. + +Reject nodes from another parse, cloned or incrementally edited trees, shifted +roots, and individually edited node values. If two indices borrow one tree, +their handles remain distinct. Moving an index before obtaining its borrowed +references is valid. No identifier is promised to persist across indices. + +Document order is `(first_fragment.start, first_fragment.end, role_rank, +creation_ordinal)`. Creation ordinals are unique within the index and assigned +by deterministic root-down/source-order collection. Role ranks are explicit +contract values, not incidental enum discriminants. Associations follow document +order, then owner source anchor and slot ordinal. Fragments retain composition +order. File and virtual documents use their own first fragment as anchor. +Hash iteration and pointer order never reach output. Initial role order is +primary, additional, attribute, leading comment, body comment, file/package, +virtual, then inferred. Future roles append; content states such +as disabled text do not change an existing role's rank. + +Every document has a physical occurrence. Empty prose still has nonempty raw +syntax, such as `/*!*/` or `""`; do not invent zero-width text fragments. + +## Profiles and source forms {#profiles} + +An index selects one attachment profile for its language. A BCA composition +states precedence explicitly. Private or nested source-attached docs remain +discoverable even when a documentation tool omits them. Publication means known +eligibility under the specified configuration, or unknown; it is not a claim +that a generator was run. + +| Language | Default and required alternatives | Attachment scope | +| --- | --- | --- | +| Rust | [Compiler documentation attributes](https://doc.rust-lang.org/reference/comments.html#doc-comments) | Outer/inner comments and literal attributes; private/nested items remain source-visible | +| Python | [PEP 257](https://peps.python.org/pep-0257/), [PEP 258](https://peps.python.org/pep-0258/) and named [Sphinx attribute comments](https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#directive-autoattribute) | Primary, additional, attribute and Sphinx roles remain distinct | +| Java | [JDK 25 source attachment](https://docs.oracle.com/en/java/javase/25/docs/specs/javadoc/doc-comment-spec.html), BCA local cleanup | Traditional and Markdown docs; explicit logical filename for filename-dependent eligibility | +| Kotlin | [KDoc](https://kotlinlang.org/docs/kotlin-doc.html) | Declarations and supported parameter slots through annotation wrappers | +| Groovy | [Groovydoc](https://groovy-lang.org/groovydoc.html) | Types, members, constructors and current grammar shapes | +| Csharp | [C# XML documentation](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/xmldoc/) | Documented declarations through leading trivia, attributes and directives | +| Php | `BcaPhpSource`; required selectable `PhpDocumentor` | Declaration-first default; file-first alternate, detailed below | +| Javascript, Mozjs | [JSDoc](https://jsdoc.app/) | Declarations, supported assignments/members/exports, file and virtual docs | +| Typescript, Tsx | `BcaTypescriptSource`: [TypeScript](https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html) attachment and [TypeDoc](https://typedoc.org/documents/Doc_Comments.html) structural file rules | File structural blocks take precedence over tsc declaration attachment; source overloads stay distinct | +| C, Cpp, Mozcpp, Objc | [Doxygen](https://www.doxygen.nl/manual/docblocks.html) | Leading, trailing, in-body, signature, gathered and bounded structural-name forms | +| Go | [go/doc](https://pkg.go.dev/go/doc) source groups | Package, declaration group, spec, field and interface docs; directive evidence separate | +| Ruby | [YARD](https://yardoc.org/); required selectable [RDoc](https://ruby.github.io/rdoc/) | Separate scope, virtual and visibility rules; no union of incompatible results | +| Lua | [LDoc](https://lunarmodules.github.io/ldoc/) | Marked runs/long comments, module, supported assignment/function/table targets | +| Perl | [POD](https://perldoc.perl.org/perlpod), optional unique-heading inference | File/package docs by default; unique same-file subroutine association only when selected | +| Elixir | [Compiler source documentation](https://hexdocs.pm/elixir/writing-documentation.html) | Module/function/macro/type/callback attributes and explicit heads/clauses | +| Bash | [shdoc](https://github.com/reconquest/shdoc) | File/function marked comments; generic adjacency opt-in | +| Tcl | [Static Ruff! 3.0.4](https://ruff.magicsplat.com/v3.0/ruff-ruff.html) | Procedure/method/constructor body docs and literal namespace preambles | +| Irules | BCA leading/body convention | Separate same-scope leading and initial body docs for each proc/when occurrence | +| Ccomment, Preproc | Helper capability | No declaration model | + +### Conflicting conventions and static ownership + +For PHP, the default first selects +[Zend/reflection declaration documentation](https://www.php.net/manual/en/reflectionfunctionabstract.getdoccomment.php). +It then considers phpDocumentor-qualified `define` forms and file docs, with +declaration-before-file precedence. The file selector reads the original +candidate sequence, not a sequence with consumed declaration blocks removed. +An already-consumed block cannot receive a second file association. + +The file rule is the pinned +[phpDocumentor Reflection 7.0.0 selector](https://github.com/phpDocumentor/Reflection/blob/70254fa0b3058b16908a3a9d95f7dca904e03396/src/phpDocumentor/Reflection/Php/Factory/File.php). +Before class/function/constant/interface/trait, exactly two blocks permit the +first to be file documentation. Other first-node kinds use the first block. +There is no `@package` or license-tag override. The alternate selects file docs +first, then remaining declaration docs using +[PHP-Parser](https://github.com/nikic/PHP-Parser) attachment. This +one-owner precedence is explicit even where an upstream implementation retains +duplicate associations. + +Thus one block before a class documents the class in both profiles; two blocks +document the file then class; three do not satisfy the exactly-two file rule. +A block before an enum or supported `define` is the conflict control: the +default associates the declaration, the alternate the file. Native attributes, +promoted properties and signature-local comments retain their own source owner +evidence. An imported callee name is not proof that a call is builtin `define`. + +YARD handles `@!` virtual directives and its own scope/call rules. RDoc handles +`##`, `=begin`/`=end`, and its visibility directives separately. Hidden source +documents remain retained with the appropriate publication state. An explicit +virtual method does not become a concrete declaration merely because a same-name +method exists later. + +Elixir documentation groups use enclosing module, definition kind, name and +source-written arity. Preserve explicit heads and clauses in the group. Default +arguments do not create extra synthetic arity owners. `@spec` is signature +metadata; `@typedoc` associates types and `@doc` can describe supported callbacks. +Private source docs remain inspectable even where the compiler discards them. +`false`, `nil`, empty strings and keyword-only metadata are distinct states. +Repeated attributes follow the inspected +[Elixir 1.20.1 module implementation](https://github.com/elixir-lang/elixir/blob/v1.20.1/lib/elixir/lib/module.ex): +within an attribute run, the last non-keyword value replaces the prior value; +keyword attributes merge metadata and later keys replace earlier keys. Thus +`@doc false; @doc "text"` selects text, while the reversed order disables it. +`false` is not sticky. Across explicit clauses of one owner group, a new nil +value leaves the current effective value unchanged; a new non-nil value replaces +it. Retain superseded value occurrences as evidence, not extra selected prose. +Explicit nil evidence remains distinguishable even where group composition +retains an earlier effective value. + +Tcl's first body comment block needs no `#ruff` marker. Leading blank source +lines are allowed; a blank source line or code ends the block. Later `#ruff` +blocks append fragments to that procedure/method document. A bare `#ruff` line +contributes a blank line; text following it contributes that text. Preserve +`#ruffopt` as local source evidence without formatter-dependent filtering. +Literal `_ruff_preamble` describes its namespace. Dynamic preambles and runtime +`_ruffClassHook` evaluation have explicit unavailable content. + +Static TclOO method, constructor and destructor owners are commands named +`method`, `constructor` or `destructor` directly in a literal +`oo::class create NAME { ... }` or `oo::define NAME { ... }` body. Recognize +them through named context over the `Call` row. They do not acquire metric +function spaces. Dynamic class names/bodies do not yield guessed concrete owners. +For literal `variable _ruff_preamble ...` inside `namespace eval NAME { ... }`, +the owner is that enclosing namespace occurrence. A qualified top-level +`set ::ns::_ruff_preamble ...` is an unresolved name-keyed candidate initially. + +For iRules, leading comment siblings occupy consecutive rows and end directly +above the proc/when's first row. Initial body docs use the same blank-line +boundary as Tcl's lead block. Leading and body docs remain two documents when +both exist. Priority/modifiers do not change owner or body selection. + +Generic leading-comment inference is opt-in only for Bash, Tcl, Lua and Perl. +A contiguous ordinary run must immediately precede a statically named supported +same-scope declaration, with no blank source row, command or excluded-range gap. +It cannot override native attachment and carries BCA-inferred provenance. +This does not suppress native unmarked Ruff, Go or YARD documentation. + +## Local text and source mappings {#text} + +Raw syntax, decoded static value and cleaned local content are separate views. +Raw included bytes remain available when decoding fails. Complete local text is +a UTF-8 string plus forward mappings, or an explicit unavailable result. It +contains local markup and reference directives, including XML, Markdown, POD, +`inheritdoc`, `copydoc` and `include`; no generator, inheritance or macro +expansion runs. + +An optional segmented view contains known text and explicit opaque gaps. It +cannot silently join known prefixes/suffixes across a dynamic expression into +an apparent annotation. A pure implicit Python literal concatenation has no +separator; separate additional strings remain separate logical documents. + +### Decoding and cleanup boundaries + +- Python supports ordinary/raw static strings, standard control/punctuation, + octal, hex and Unicode-scalar escapes, and escaped line endings. Unknown + escapes preserve the backslash according to the pinned Python semantics. + Named `\N{...}` escapes are explicitly unsupported in this delivery; lone + surrogates and out-of-range scalars are unrepresentable. `f`, `b` and `t` + prefixed strings are not docstrings. Whole-document cleanup follows + Python 3.12 [`inspect.cleandoc`](https://docs.python.org/3.12/library/inspect.html#inspect.cleandoc): + expand tabs, remove first-line indentation and common later-line margin, + then remove surrounding empty lines. Preserve trailing content spaces. +- Rust supports static cooked/raw doc attribute strings and documentation + comments. Mixed cleanup follows the pinned Rust 1.99.0 + [`beautify_doc_string`](https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_ast/src/util/comments.rs#L37), + [`unindent_doc_fragments` and `add_doc_fragment`](https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_resolve/src/rustdoc.rs#L107-L198), + then removes the final assembly newline once, as + [`opt_doc_value`](https://github.com/rust-lang/rust/blob/1.99.0/src/librustdoc/clean/types.rs#L1130-L1137) does. + This is not universal trimming or tab expansion. Computed values and + `include_str!` retain source evidence with unavailable local content. +- Java source tokens containing raw backslash-u have explicit unsupported + semantic decoding. Preserve separately labeled source-cleaned spelling. + The trigger deliberately over-approximates JLS eligibility, including an + ineligible spelling with an even number of preceding backslashes. + [JLS Unicode prelexing](https://docs.oracle.com/javase/specs/jls/se25/html/jls-3.html#jls-3.3) + can also alter delimiters or line endings; affected associations remain + uncertain even when tree-sitter reports no ERROR node. Ordinary docs remain + supported. For `/**/`, BCA delimiter-cleaned text is empty by design; observed + JDK 25.0.5 `DocTrees` returns `/`. Java `////` is different: removing `///` + leaves the real content `/`, which BCA retains. +- Elixir static strings, heredocs and supported raw/cooked string sigils follow + their language decoding and heredoc margin. Interpolation or computed values + make full content unavailable. A constant-looking expression is not evaluated. +- Comment adapters remove only their specified delimiter/line prefixes and + structural margins. A profile's exact LF/CRLF, blank-line, trailing-space and + join behavior belongs in its fixtures. Keep Markdown hard-break spaces and + code indentation. General annotation interpretation is consumer work. + +The local comment-cleanup policy is a BCA source view, not formatted generator +output. Freeze these transformations separately from attachment: + +| Forms | Local cleanup | +| --- | --- | +| Java Markdown | Remove each `///` and the minimum leading space/tab margin of nonblank lines across the selected run; preserve trailing spaces and remaining indentation | +| C# XML lines, Doxygen lines, Go, Ruby, Bash, Tcl and iRules hash/line forms | Remove the exact recognized marker and at most one following ASCII space from each member; preserve the remaining whitespace | +| LDoc lines | Remove the recognized `---` opener; continuation `--` lines lose their own marker; remove at most one following ASCII space | +| Java traditional, KDoc, Groovydoc, PHPDoc, JSDoc, TypeScript, Doxygen and C# block forms | Remove the outer recognized delimiters; remove one immediate ASCII space inside either delimiter on its boundary line; on later lines remove indentation plus one decoration `*` and at most one following space when present | +| Lua long documentation comments | Remove the matching long-comment opener/closer, including the matching equals depth; no star decoration rule | +| Perl POD | Preserve POD markup and internal spacing; omit the terminal `=cut` line and surrounding empty boundary lines; comment-only POD has no prose | + +For comment forms in this table, normalize CRLF to LF with the complete CRLF +token as its source origin, discard only empty boundary lines, and insert one +synthetic LF between selected physical line-comment members or separately +gathered blocks. Keep interior blank comment lines. Do not append a final LF +just because the source file has one. Block-internal LF bytes retain copied +origins; joins across removed delimiters are synthetic. This differs deliberately +from Go's `CommentGroup.Text` final newline and renderer-specific whitespace. +Rust/Python/Elixir literals keep their separately specified language cleanup. + +Examples: `/** audit */` becomes `audit`; `/**\n * a \n * b\n */` becomes +`a \n b`; `/// a \n/// b` in Java becomes `a \n b`; `# a\n#\n# b` in +an attached hash-comment run becomes `a\n\nb`. A source blank line between +separate runs still participates in attachment rules; cleanup never joins runs +that the profile did not select together. + +Required Elixir static forms are ordinary strings, heredocs, `~s` and `~S` +string sigils with static delimiters and no unsupported modifiers. Decode cooked +string escapes and remove language-defined heredoc indentation before mapping. +Raw `~S` preserves interpolation-looking bytes and escapes except delimiter +syntax. Cooked forms containing interpolation are unavailable, as are charlist +or non-string values, unsupported sigils/modifiers and computed expressions. +Keep the raw attribute and explicit reason for each. + +Required Rust cooked escapes are escaped quote/backslash, newline/carriage +return/tab/NUL, valid ASCII hex and Unicode-scalar escapes, and Rust's escaped +line-continuation removal. Raw strings preserve interior bytes. Invalid escape +spelling, non-scalar values and non-UTF-8 source make complete content unavailable. +Nested block-comment delimiters inside an outer doc block remain content; only +the outer documentation delimiters are removed. + +### Forward mapping rules + +Mappings partition the output UTF-8 byte range into ordered runs: + +| Origin | Query behavior | +| --- | --- | +| Copied source | Clip source bytes exactly with the requested output subrange | +| Decoded token | Return the complete responsible source token for any intersecting output scalar | +| Expanded token | Return the complete token, such as a tab expanded into several spaces | +| Synthetic | Retain the output portion with no source range, such as an inserted fragment separator | + +A query returns ordered output subranges with origin information. Disjoint +origins stay disjoint; never use an envelope containing intervening code or +comments. Removed prefixes, delimiters and continuations emit no mapping run. +If a token itself crosses included ranges, preserve its included pieces rather +than return an envelope spanning excluded bytes. + +Reject reversed/out-of-bounds ranges and endpoints inside a UTF-8 scalar. +A valid empty range returns an empty origin sequence, including at EOF and for +empty text. Synthetic-only queries return synthetic output, not an empty answer. +No reverse source-to-text mapping is promised. + +## Parse context and cancellation {#parse-context} + +Offsets refer to the actual parsed buffer, including file-loading normalization +and C-family masking. `Ast::source()` is that buffer. Masking preserves comment +bytes but does not justify recovering an original identifier from dollar runs. + +Logical filename is explicit caller metadata. The facade issue adds a private +path-provenance field populated by `Ast::from_path`; today no such field exists. +`Source::with_name` and adopted-tree display labels remain display labels. A +logical filename is context for documentation rules, not a filesystem credential. + +Read included ranges from the supplied tree. Excluded gaps are positional +attachment barriers. A node envelope may contain excluded bytes; intersect it +with the included ranges before returning fragments. Required gap-spanning +content has unavailable text. Preserve unrelated valid docs and do not reparse +the source to manufacture a continuous tree. + +Retain actual parse completion provenance at parse time in internal parser +state. The new typed documentation query rejects a cancelled parse even after +the cancellation flag's scope ends. Existing metric behavior remains unchanged. +Adopted parses carry the caller's completeness precondition, not fabricated +internally verified provenance. Empty roots and restricted parses do not imply +cancellation. + +The raw-triple seam cannot observe past cancellation. Supplying a cancelled +parse through raw accessors violates its precondition. Ordinary early benchmark +and fuzz paths do not install `ParseCancel`; cancellation probes use the typed +parser entry point. Active collection cancellation applies to both entry points. + +Collection, named finalization and text construction observe cancellation at +bounded work intervals, including within a large single fragment. Return an +explicit cancelled outcome rather than a partial successful index/text result. +Tests cover pre-cancelled parses, mid-work cancellation, nested flag restoration, +unwinding, valid empty/restricted parses and the next successful parse. + +## Traversal and implementation boundaries {#traversal} + +Use `Ancestors::for_walk(chain, node, &folds, &siblings)`, or the explicit +without-siblings constructor only when no sibling query can occur. Maintain one +borrowed `ChildAncestors` holder through descent/ascent; do not repeatedly copy +derived tails. `nearest_level_answer` requires complete ancestry. Preserve +source bytes and the current typed gate signatures through all callbacks. + +The collector performs one coordinated structural pass, permitting existing +amortized sibling scans and indexed finalization. Source/legacy/profile queries +use different keys or caches when their questions can disagree. Drop build-only +`RefCell` caches before returning an index. Query validation uses indexed +canonical context, never `Node::parent` on deep zero-width nodes. + +Same-file structural name references finalize through adapter-defined +scope/kind/name/signature indices. Missing or duplicate names stay unresolved. +No all-pairs matching, cross-file symbol resolver or macro evaluator is required. +Build fragment text once per document, not once per association. + +State costs in source bytes/nodes, fragments, associations, rendered bytes and +map segments. Separate sorting cost, field lookup and cached-state search from +the structural walk. Cold collection, prepared-index lookup, text/map creation +and retained-result reads have separate probes. Exact counters measure both +state computation and slot search. Deep construction, owner extraction, assembly +and teardown are iterative and tested on a small stack. + +The Tcl/iRules continuation limitation in +[#1802](https://github.com/dekobon/big-code-analysis/issues/1802) follows its +approved upstream grammar repair and adoption. Until then, mark affected +comment boundaries and apparent proc/when targets uncertain. A bounded source +check can identify uncertainty; it cannot become a replacement command parser. +Ordinary unrelated docs remain available. + +The Rust attribute-value pruning behavior in +[#1786](https://github.com/dekobon/big-code-analysis/issues/1786) is a documented +retained limitation. Do not treat its closed issue as a code fix or erase the +corrected outer-attribute pruning baseline. + +## Worked acceptance cases {#acceptance-cases} + +These are required extraction outcomes, not results from an implementation. +In escaped source examples, `\n`, `\r`, `\t` and `\\` denote LF, CR, tab and +one literal backslash. Other characters are literal UTF-8. Each primary source +cell ends exactly where shown, without a final newline. Ranges are half-open +bytes. The primary roster has one document and one resolved declaration +association per row; Perl selects its explicit unique-heading profile. +`audit` is arbitrary prose, not a structural +tag. The source spelling independently fixes the ranges and content. + +| LANG | Exact source | Fragment range | Owner and range | Local text | +| --- | --- | --- | --- | --- | +| Rust | `///audit\nfn f() {}` | `0..8` | f, `9..18` | `audit` | +| Python | `def f():\n "audit"\n pass` | `13..20` | f, `0..29`, primary role | `audit` | +| Java | `///audit\nclass C {}` | `0..8` | C, `9..19` | `audit` | +| Kotlin | `/**audit*/\nfun f() {}` | `0..10` | f, `11..21` | `audit` | +| Groovy | `/**audit*/\nclass C {}` | `0..10` | C, `11..21` | `audit` | +| Csharp | `///audit\nclass C {}` | `0..27` | C, `28..38` | `audit` | +| Php | `; }` | `0..10` | f, `11..42` | `audit` | +| C | `/**audit*/\nvoid f(void) {}` | `0..10` | f, `11..26` | `audit` | +| Cpp | `/**audit*/\nvoid f() {}` | `0..10` | f, `11..22` | `audit` | +| Mozcpp | `/**audit*/\nvoid f() {}` | `0..10` | f, `11..22` | `audit` | +| Objc | `/**audit*/\nvoid f(void) {}` | `0..10` | f, `11..26` | `audit` | +| Go | `package p\n// audit\nfunc F() {}` | `10..18` | F, `19..30` | `audit` | +| Ruby | `# audit\ndef f\nend` | `0..7` | f, `8..17` | `audit` | +| Lua | `---audit\nfunction f() end` | `0..8` | f, `9..25` | `audit` | +| Perl | `=head2 f\n\nAudit\n\n=cut\n\nsub f {}` | `0..21` | f, `23..31`, inferred role | `=head2 f\n\nAudit` | +| Elixir | `defmodule M do\n @doc "audit"\n def f(), do: :ok\nend` | `17..29` | M/def/f/0, `32..48` | `audit` | +| Bash | `# @description audit\nf() { :; }` | `0..20` | f, `21..31` | `@description audit` | +| Tcl | `proc f {} {\n# audit\nreturn\n}` | `12..19` | f, `0..28` | `audit` | +| Irules | `# audit\nwhen HTTP_REQUEST {\n}` | `0..7` | HTTP_REQUEST occurrence, `8..29` | `audit` | + +For Ccomment input `/**audit*/` and Preproc input `#define X 1\n`, collection +reports `NoDeclarationModel` and no documents/associations. A disabled feature +instead returns language-disabled before collection. Neither helper case can +satisfy a source language's positive requirement. + +### Independent source and legacy readings + +For Java, use these exact bytes, including the final LF: + +```java +/** a + * b + * c */ +/**/ +class C {} +``` + +The old block occupies `0..18`, the new block `19..23`, and C `24..34`. +Extraction selects the new block, with complete BCA-local text `""`; the old +block is superseded evidence. Legacy DLOC bills the first three rows, not the +fourth. At the pre-implementation base, `bca metrics --no-config --no-ignore +--no-skip-generated --language java --format json --metrics loc ` reports +unit `(sloc, ploc, lloc, cloc, blank, dloc) = (5, 1, 0, 4, 0, 3)` and C's +`dloc = 0`. The empty-block-only twin has unit `dloc = 0` and `cloc = 1`. +The independently specified row set discriminates a wrong three-row selection +that would have the same count. + +For `function f() {\n /** note */\n return 1;\n}\n`, legacy DLOC is one +in f and the unit. The comment at `19..30` does not describe a declaration +under the source JSDoc profile; retain it only as unattached evidence when +requested. Legacy coverage is not evidence of a semantic owner. + +For `/*!*/\nfn f() {}\n`, the fragment `0..5` describes the file/root and has +empty local text. Legacy unit DLOC is one, while f's DLOC is zero. For +`/// outer\n#[test]\nfn test_f() {}\n\n/// kept\nfn f() {}\n`, source docs describe +both functions. Legacy default DLOC is two; `--exclude-tests` leaves only f +and DLOC one. Source collection does not inherit the metric pruning option. + +For `/** Record doc */\nrecord R(int a) {}\n`, the doc belongs to type R, +not its synthesized header function space. Adding `R {}` inside the record +replaces that synthesized metric space with the explicit compact constructor; +the doc owner remains R. Both baseline unit DLOC values are one, and both +type/function DLOC values are zero. Check the constructor node span, not just +the unchanged number of spaces. + +### Composition, slots and mapping + +Python `def f():\n ""\n "extra"\n return 1\n` has primary fragment +`13..15` and additional fragment `20..27`. They form two documents with texts +`""` and `"extra"`, both associated with f. Legacy f/unit DLOC is two; runtime +`__doc__` remains empty. A b/f/t-prefixed second expression does not become +an additional docstring. + +Python `def f():\n ("@au" # ordinary\n "dit")\n` has fragments `14..19` +and `36..41`. Complete text is `@audit`. Output `0..3` maps to `15..18`, and +`3..6` to `37..40`. The full `0..6` query returns both copied ranges and no +separator; the intervening ordinary comment is not text. This lets a consumer +find `@audit` while preserving its two physical origins. + +For an escaped source example `"a\\x40b"`, the decoded value is `a@b`: +output `1..2` maps to complete escape token `2..6`. For `"é"`, output `0..2` +maps to source `1..3`; output query `0..1` fails because it splits the UTF-8 +scalar. For `"\\N{COMMERCIAL AT}audit"`, raw bytes survive and complete text is +unsupported; an opaque escape followed by known `audit` is not a complete tag. +For `"\\ud800"`, the state is non-scalar/unrepresentable rather than replacement +character text. + +For `///a\n///b\nfn f() {}`, the logical text `a\nb` maps `0..1` to source +`3..4`, `1..2` to a synthetic separator, and `2..3` to `8..9`. Removed `///` +prefixes emit nothing. An empty query at `0`, `1`, `2` or `3` returns no origins; +`3..4`, `2..1` and an out-of-bounds empty query fail. A query of only `1..2` +still returns its synthetic origin. + +In `struct S(///first\n u32, ///second\n u32);`, each doc belongs to a tuple +field slot identified by parent S and its ordinal, even when no dedicated +field node exists. For `/**both*/\nint a, b;`, one document associates with +both qualifying declarators. Python receiver assignments enumerate only +qualifying receiver targets: in an `__init__` body, docs after +`self.x, other.y = values` associate with self.x, not other.y. + +For Doxygen docs before `#if A\nvoid f();\n#else\nvoid g();\n#endif`, preserve +the conditional alternatives and an unresolved association. Do not claim that +the single document resolves simultaneously to f and g. A forward explicit +name resolves only under the adapter's same-file key; two matching overloads +without a disambiguating signature remain ambiguous. + +### Query, context and state controls + +| Input or operation | Required result | +| --- | --- | +| Rust `fn f() {}` queried for f | Supported owner, successful empty document list | +| Its `fn` keyword token queried as owner | Unsupported owner kind, not a successful empty list | +| Another parse of the same bytes, or `tree.clone()` | Foreign-tree error for its nodes | +| Two indices over the same tree | Equal source nodes may be queried in both; a handle from one index cannot be used in the other | +| Offset root or edited node value from the held tree | Noncanonical-node error when context no longer matches the indexed node | +| Rust profile requested for Python | Unsupported-profile error | +| Python feature disabled, even with empty input | Language-disabled error | +| Pre-cancelled typed parse of `///x\nfn f() {}` | Documentation query returns Cancelled outside the cancellation scope too | +| Complete parse of empty Rust input | Successful empty index | +| Elixir `@doc false` before f | Retained disabled state for f, no successful empty prose | +| Elixir `@doc nil` before f | Retained explicit-absence occurrence for f | +| Elixir `@doc ""` before f | Present-empty prose for f | +| Elixir `@doc since: "1"` before f | Metadata-only document for f | +| Elixir `@doc "text"` and `@doc since: "1"` before f | One document with text `text` and metadata, in either attribute order | +| Elixir `@doc "old"` then `@doc "new"` before f | Selected text `new`; old occurrence available as superseded evidence | +| Elixir `@doc "a#{x}b"` before f | Full text unavailable; known `a` and `b` separated by opaque interpolation | + +For Java `/**pkg*/\npackage p;\nclass C {}`, the comment `0..8` has a source +association to package p. Explicit logical filename `package-info.java` permits +package-doc eligibility under the profile; another filename is ineligible and +missing filename is unknown. Merely setting the display label to +`package-info.java` does not change unknown into eligible. Attachment and raw +text do not disappear because publication eligibility is unavailable. + +For the exact Rust source `///x\n\nfn f() {}`, supply included ranges `0..4` +and `6..15` with their corresponding tree-sitter points. The excluded `4..6` +gap prevents attaching the first range's comment to f. Preserve the comment as +unattached/uncertain evidence when requested, and never reparse to bridge the +gap. For a token envelope spanning such a gap, return only included source +pieces and unavailable complete text. An ordinary document wholly in a later +included range must still work. + +For `# before\nwhen HTTP_REQUEST {\n# inside\n}\n`, iRules returns a leading +document `before` and a body document `inside`, in that order, both associated +with the same handler occurrence. Their fragments and roles remain distinct. +For `proc f {} {\n# first\nset x 1\n#ruff\n# later\n}`, Tcl returns one logical +body document `first\n\nlater`, composed from the lead block and marked block. +Replacing `#ruff` with an ordinary comment does not append the later block. + +For Ruby `# @!method generated\n# audit\n`, the YARD profile retains a +virtual method named generated. RDoc does not synthesize that YARD virtual +method. For `# audit\ndef f; end # :nodoc:\n`, RDoc retains the source document +for f with ineligible publication. A virtual document and a later concrete +method of the same name remain separate unless a profile explicitly defines +that named resolution. + +### Required additional forms + +Each row below is an acceptance family owned by the linked adapter issue. +Its fixture inventory must include every listed spelling/context, in addition +to the positive roster. A documented limitation has a named unavailable or +unresolved result; it cannot silently omit a promised form. + +| Adapter | Required forms | Exact outcome rule | +| --- | --- | --- | +| [Rust #1664](https://github.com/dekobon/big-code-analysis/issues/1664) | `//!`, `/*!...*/`, `///`, `/**...*/`; cooked/raw `#[doc]` and `#![doc]`; mixtures | Inner docs describe the enclosing item/root; outer docs describe the following item/field/variant/slot; ordered mixed fragments form one document | +| Rust | Empty `/*!*/`, literal `#[doc = ""]`, `#[doc(hidden)]`, aliases and computed/cfg attributes | First two are present-empty; hidden/alias are metadata, not prose; computed/cfg-dependent content is unavailable or conditional evidence, never evaluated | +| Rust | Macro token trees, docs across attributes/plain comments, pruned test runs | Preserve macro/source uncertainty and original legacy coverage; source docs are independent of metric pruning | +| [Python #1665](https://github.com/dekobon/big-code-analysis/issues/1665) | Module/class/function/method first strings, additional strings, attribute assignments/type aliases, `#:` blocks | Distinct primary/additional/attribute/Sphinx roles; same-line/leading comments resolve qualifying target subsets | +| Python | Parentheses, implicit concatenation, comments/continuations between literals, raw strings, named escapes and surrogates | Parentheses/trivia are coverage only; literals compose without separators; named/non-scalar unavailability follows the decoder boundary | +| [JVM #1666](https://github.com/dekobon/big-code-analysis/issues/1666) | Java traditional/Markdown/package/module/record docs; Kotlin KDoc and split annotations; Groovy types/members/constructors | Preserve per-language nearest/last selection and normalized declaration owners; synthetic metric constructors do not steal type docs | +| JVM | Empty/new Java docs, `////`, blank source lines, annotations/body placements, package-info filename and Unicode escapes | Source marker rules differ from legacy; blank source lines split Markdown runs; filename eligibility requires explicit context; prelexing uncertainty remains explicit | +| [Csharp #1667](https://github.com/dekobon/big-code-analysis/issues/1667) | Types/delegates; methods/constructors/destructors/operators; fields/events/properties/indexers/enum members | XML stays literal; owners normalize expression-bodied/signature forms and preserve attributes/directive evidence | +| Csharp | Primary constructors, getter/setter trivia, function-body comments and `#if` members | Type docs remain type docs; excluded accessor/body placements remain unattached; uncertain branches remain alternatives | +| [Php #1668](https://github.com/dekobon/big-code-analysis/issues/1668) | File preambles, one/two/three blocks, native declarations, attributes, promoted properties, enum/define | Apply the explicit selected profile precedence; promoted-property docs belong to the property slot, not automatically the constructor | +| Php | `define`, `\\define`, grouping/uppercase, qualified/imported aliases, in-body calls | Static supported builtin forms have declared provenance; imported/dynamic identities remain unresolved rather than guessed | +| [JS #1669](https://github.com/dekobon/big-code-analysis/issues/1669) | Both dialects; functions/classes/members/variables/assignments/exports; nested bound callables | Normalize semantic binding owner and retain wrapper; do not attach to every declarator in a multi-declaration | +| JS | In-body comments, @file/@module/@name, duplicate or forward names, line-versus-block trivia | Unattached legacy DLOC has no fabricated owner; file/virtual docs preserve roles; collisions remain unresolved | +| [TS #1670](https://github.com/dekobon/big-code-analysis/issues/1670) | Both variants; export/declare/decorators, anonymous defaults, overloads, namespaces/interfaces/types/enums, supported parameters | Distinct source overload owners; declaration wrapper normalization and parameter-only after-code subset remain explicit | +| TS | @module/@packageDocumentation, assignment/destructuring exclusions, TSX JSX neighbors | Structural file blocks take precedence; excluded assignment forms remain unsupported/unattached rather than copied JS behavior | +| [C-family #1671](https://github.com/dekobon/big-code-analysis/issues/1671) | Every dialect; leading/trailing/member/signature/in-body docs, multi-declarators, ObjC methods/properties/protocols | Resolve qualifying concrete owners or source slots, with shared documents rather than copied text | +| C-family | @file gathering, page/group/explicit names, recovery/conditionals, masked names, quoted/CDATA tags | Preserve gatherer once; bounded structural keys finalize; ambiguity/masked original names remain unresolved; quoted/CDATA text does not create structural targets | +| [Go #1672](https://github.com/dekobon/big-code-analysis/issues/1672) | Package/function/method, type/var/const groups/specs, multi-name fields and interface elements | Group docs stay group docs; member docs remain separate; one field document can serve several named slots | +| Go | Build/generate/other directives, blank comment rows versus source rows, local/trailing placements | Retain directives as evidence but exclude them from prose as specified; source blank rows detach; excluded local/trailing placements do not get inferred owners | +| [Ruby #1673](https://github.com/dekobon/big-code-analysis/issues/1673) | Both profiles; methods/classes/modules/singletons/constants/aliases/attributes/visibility wrappers; body/modifier wrappers | Source attachment follows selected scope/call policy; later visibility changes affect eligibility, not occurrence identity | +| Ruby | `##`, `@!method`, `@!attribute`, `:nodoc:`, shebang/magic comments and named collisions | RDoc/YARD differences stay profile-qualified; virtual docs remain virtual; directives/magic comments are not arbitrary prose | +| [Lua #1674](https://github.com/dekobon/big-code-analysis/issues/1674) | `---`, long comments, first-file/module contexts, functions/assignments/returns/table fields, structural tags | Opener content and context determine attachment; plain `--` attaches only through selected inference; missing named targets remain virtual/unresolved | +| [Perl #1675](https://github.com/dekobon/big-code-analysis/issues/1675) | Direct POD, multiple opaque-node/data-section blocks, headings, comment-only and mixed regions, EOF/CRLF | Preserve physical subranges and POD markup; comment-only regions are not prose; default file/package docs do not attach to the nearest sub | +| Perl | Unique/forward/duplicate local headings, missing symbols | Explicit heading profile resolves only one qualifying local sub; duplicate/missing cases remain unresolved, with default file docs still available | +| [Elixir #1676](https://github.com/dekobon/big-code-analysis/issues/1676) | Module/function/macro/type/callback docs, explicit heads/clauses, distinct arities and visibility | Group source-written definitions by module/kind/name/arity; no synthesized default-argument arities or quote-template concrete owners | +| Elixir | Static/raw/cooked strings/heredocs/sigils; interpolation/computed; false/nil/empty/metadata; repeated attributes | Preserve per-attribute source evidence and selected compiler-style value/metadata composition; dynamic content unavailable; false/nil/empty/metadata remain distinct | +| [Bash #1677](https://github.com/dekobon/big-code-analysis/issues/1677) | Both function spellings, shdoc file/description blocks, opt-in leading inference, lexical continuation boundaries | Associate static same-scope functions/file; intervening commands detach; shebang/tool directives and heredoc/string look-alikes are not prose | +| [Tcl #1678](https://github.com/dekobon/big-code-analysis/issues/1678) | Static proc/TclOO method/constructor, lead/later #ruff blocks, literal namespace preamble | One logical body document per declaration with ordered block fragments; namespace preamble has namespace owner | +| Tcl | Dynamic names/hooks/preambles, later ordinary comments, continuations/recovery | Dynamic owner/content remains explicit; later unmarked comments excluded; #1802 affected boundaries/phantom declarations remain uncertain | +| [Irules #1679](https://github.com/dekobon/big-code-analysis/issues/1679) | proc/when, priority/modifiers, neighboring equal-name handlers, leading and body docs | Each handler occurrence has independent identity; both roles remain separate; exact same-scope/row adjacency | +| Irules | Nested control comments, quoted text, blank/intervening commands, continuations/recovery | No inferred nested control owner; continuation-affected apparent handlers remain uncertain; unrelated positive docs survive | + +### Reference evidence and baseline + +The semantic baseline is commit +[`91087f52f5d4a58e31ae320851351990f1436411`](https://github.com/dekobon/big-code-analysis/tree/91087f52f5d4a58e31ae320851351990f1436411). +Its grammar versions are recorded in the versioned +[`langs.rs`](https://github.com/dekobon/big-code-analysis/blob/91087f52f5d4a58e31ae320851351990f1436411/big-code-analysis-ast/src/langs.rs) +and [`Cargo.toml`](https://github.com/dekobon/big-code-analysis/blob/91087f52f5d4a58e31ae320851351990f1436411/Cargo.toml). +The characterization manifest records those exact pins rather than relying on +the current branch's versions. Recapture if the implementation base changes. + +| Reference | Evidence used here | Qualification boundary | +| --- | --- | --- | +| Zulu OpenJDK 25.0.5.0.3 | `JavacTask.parse`, `DocTrees.getDocComment` and `getDocCommentTree` report `/` for `/**/` and `////`, empty for `/***/` and `/****/` | Observed source attachment/text anomaly, not universal version parity | +| Python 3.12.13 | `ast.get_docstring(clean=False)` then `inspect.cleandoc` returns empty primary, disjoint `@audit`, and preserved trailing spaces | Named escapes work in Python itself; BCA's unsupported result is deliberate | +| Rust 1.99.0 | Tag-qualified cleanup source above | Source inspection, not a claimed rustdoc output comparison | +| phpDocumentor Reflection 7.0.0 | Commit `70254fa0b3058b16908a3a9d95f7dca904e03396`, `createFileDocBlock` | Source inspection; exactly-two rule and restricted declaration set | +| Elixir 1.20.1 | `Module.put_attribute`, `compile_doc` and metadata merge source | Source inspection; later non-keyword values replace, false is not sticky | +| Ruff! 3.0.4 | Procedure and directive manual sections | Manual evidence; adapter qualification also checks implementation | +| Other named profiles | Linked authoritative manuals and each adapter's source/tool fixtures | Do not claim executed tool parity until its issue records version, configuration and command | + +The legacy numbers in these worked cases were measured with the baseline's +`bca` after its full validation gate passed. The command above selects LOC; +each language case forces its own language and uses the exact written source. +The characterization issue retains whole-metric captures, both MI modes and +additional independent row-set assertions before migration. + +## Qualification and delivery {#qualification} + +Author the source/form inventory independently from implementation capabilities. +Each source/dialect variant requires useful declaration-associated nonempty text; +helper outcomes are explicit exceptions. Test Tsx, Mozjs and Mozcpp separately. +Every additional promised form needs its own exact result: empty, disabled, +metadata-only, ambiguous and unavailable results cannot stand in for missing +positive language support. + +Create raw-byte fixtures under `tests/fixtures/documentation/` in the +[characterization issue](https://github.com/dekobon/big-code-analysis/issues/1657). +Share routing through AST test-support, keeping root metric assertions at the +root. Record baseline revision, exact grammar pins, tool/configuration references, +source bytes and independently specified expected owners/text/spans. External +tools are optional reproduction oracles; CI uses committed deterministic inputs. + +Keep source semantics and legacy preservation assertions separate. Compare +whole relevant metrics and physical row sets in both MI documentation modes, +selected-metric paths and `exclude_tests`. Run EOF/CRLF inputs verbatim. Do not +sort or trim observations, derive expected owners from capabilities, or rely +only on facade/delegate equality. Follow the [testing guide](testing.md) to +perturb decision-bearing expressions and verify the intended assertion fails. + +| Work | Completion evidence | +| --- | --- | +| Facts and characterization (#1656/#1657) | Contract examples fit the model; independent fixtures and baseline precede migrations | +| Marker/positional migrations (#1658/#1659) | Atomic root caller migration; legacy reading/timing and zero extra metric-only materialization | +| Text and index (#1660/#1661) | Joint real comment → owner → complete text → exact map production smoke | +| Initial performance/fuzz infrastructure (#1662/#1663) | Direct-AST dispatch and representative positive implemented paths | +| Each adapter (#1664–#1679) | Its promised forms, independent positive cases, negative controls, probes and seeds | +| Stable facade (#1680) | Shared implementation, root API/docs/stability/changelog, facade probes and fuzz fanout | +| Full qualification (#1681) | Exhaustive independent language/form inventory, feature isolation and legacy compatibility | +| Guide and closeout (#1682) | Consumer guide matches implementation and all earlier evidence is linked | + +The text/index pair is a coordinated completion unit. Initial infrastructure +does not wait for future adapters; each adapter supplies its own positive +qualification. The full inventory is checked again at final qualification. +Run required gates and triggered scaling/chain/fuzz checks from [AGENTS.md](../../AGENTS.md). +Tie review and validation evidence to exact revisions. Local completion and +integration remain distinct from publication and merge. diff --git a/docs/development/grammar_dispatch.md b/docs/development/grammar_dispatch.md index a4b71aa1e..2024b75e4 100644 --- a/docs/development/grammar_dispatch.md +++ b/docs/development/grammar_dispatch.md @@ -9,6 +9,10 @@ reference for the row grammar, what a table emits, how a consumer reads a row, and the section "What the mechanism cannot see". Read that section first; this checklist is the manual half it describes. +For declaration documentation, also read the +[extraction contract](documentation_extraction.md#recognition). It defines how +shared recognition serves source attachment and legacy documentation metrics. + A kind list is a coverage claim, not a specification. The compiler cannot tell you it is incomplete, and a metric that scores a valid construct as zero looks exactly like a construct that legitimately From 93c0049f59a07a40127aad8523abcfcf7d0b46bb Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 08:22:52 -0800 Subject: [PATCH 002/221] docs(ast): resolve documentation contract review findings --- docs/development/documentation_extraction.md | 174 ++++++++++--- .../documentation_extraction_cases.md | 238 ++++++++++++++++++ 2 files changed, 381 insertions(+), 31 deletions(-) create mode 100644 docs/development/documentation_extraction_cases.md diff --git a/docs/development/documentation_extraction.md b/docs/development/documentation_extraction.md index 6822adadb..0c6403e91 100644 --- a/docs/development/documentation_extraction.md +++ b/docs/development/documentation_extraction.md @@ -22,6 +22,11 @@ form a document and which declaration or other owner that document describes. An owner is the source entity being documented. It can differ from the metric space containing the comment. +Documentation lines of code (DLOC) are part of the +[lines-of-code (LOC) metrics](../../big-code-analysis-book/src/metrics.md#lines-of-code). +They also affect the documentation-aware +[maintainability index (MI)](../../big-code-analysis-book/src/metrics.md#maintainability-index-mi). + ```text AST role/context recognition and shared binding +-- legacy candidate view -> exact streaming reading -> root LOC/MI @@ -101,6 +106,13 @@ cache. | Association | One document, its convention/provenance, binding wrapper and resolved owner or unresolved candidates | | Owner | Exact node, location-backed slot, file/root, logical declaration group or virtual target | +A line-comment fragment excludes its terminating LF/CRLF, even when the grammar +includes that terminator in the optional syntax node. Its range need not equal +that node's range. Block comments and literal fragments include their outer +delimiters; attribute-form fragments include the entire attribute spelling, +not just its value literal. A Tcl preamble fragment is its value word, including +braces or quotes. Included-range intersection applies to each of these spellings. + An occurrence's identity is not its text. Equal strings at different offsets remain different fragments. A document describing several qualifying fields is stored once and has several resolved associations. A conditional declaration @@ -116,7 +128,8 @@ candidate, not a fabricated function inferred from a declarator's shape. Type-leading documentation belongs to the type even when metrics synthesize a primary-constructor or record-header function space. Explicit Java and compact constructors, Kotlin secondary constructors and other declared-constructor targets -remain owners. Keep signature-holder-only forms distinct. A parameter-local +remain owners. A parameter-list node can contain documentation without owning it; +the profile selects the declaration or parameter/property slot. A parameter-local document belongs to its parameter slot; `@param` text in a type document stays markup rather than creating another document. @@ -165,9 +178,13 @@ contract values, not incidental enum discriminants. Associations follow document order, then owner source anchor and slot ordinal. Fragments retain composition order. File and virtual documents use their own first fragment as anchor. Hash iteration and pointer order never reach output. Initial role order is -primary, additional, attribute, leading comment, body comment, file/package, -virtual, then inferred. Future roles append; content states such -as disabled text do not change an existing role's rank. +primary, additional, attribute-binding, Sphinx, leading comment, body comment, +file/package, virtual, then inferred. Here attribute-binding means a Python +PEP 258 string describing a binding. Rust `#[doc]` and Elixir `@doc` are syntax +forms, not that role: item documentation uses primary, module documentation +uses file/package. Mixed Rust comments/attributes retain primary. A metadata-only +attribute keeps its owner's documentation role. Future roles append; content +states such as disabled text do not change an existing role's rank. Every document has a physical occurrence. Empty prose still has nonempty raw syntax, such as `/*!*/` or `""`; do not invent zero-width text fragments. @@ -251,6 +268,22 @@ it. Retain superseded value occurrences as evidence, not extra selected prose. Explicit nil evidence remains distinguishable even where group composition retains an earlier effective value. +Separate raw metadata occurrences from effective metadata. Elixir filters +user-supplied `opaque` and `defaults` keys before merging; retain those raw +occurrences without applying their values. Validate supported built-in keys +such as string-valued `since` and `deprecated`; invalid values retain explicit +invalid-metadata evidence rather than a valid effective value. Arbitrary keys +remain source metadata without evaluation. This is not a general annotation map. + +With no `@doc` occurrence, `@impl true` supplies owner evidence and ineligible +publication, not a fabricated documentation occurrence. For a documented group, +the compiler's `@impl` fallback disables a nil effective value; it does not +override explicit string or false values. Retain an explicit nil occurrence +even when that fallback disables the effective value. `@deprecated "reason"` +is separate owner evidence and contributes `deprecated` to an existing +document's effective metadata; it does not create prose. Explicit documentation +metadata overrides the same compiler-provided key, following `compile_doc_meta`. + Tcl's first body comment block needs no `#ruff` marker. Leading blank source lines are allowed; a blank source line or code ends the block. Later `#ruff` blocks append fragments to that procedure/method document. A bare `#ruff` line @@ -315,16 +348,20 @@ separator; separate additional strings remain separate logical documents. - Java source tokens containing raw backslash-u have explicit unsupported semantic decoding. Preserve separately labeled source-cleaned spelling. The trigger deliberately over-approximates JLS eligibility, including an - ineligible spelling with an even number of preceding backslashes. + ineligible spelling whose Unicode-escape backslash has an odd number of + preceding backslashes, such as the literal source spelling `\\u0041`. [JLS Unicode prelexing](https://docs.oracle.com/javase/specs/jls/se25/html/jls-3.html#jls-3.3) can also alter delimiters or line endings; affected associations remain uncertain even when tree-sitter reports no ERROR node. Ordinary docs remain supported. For `/**/`, BCA delimiter-cleaned text is empty by design; observed JDK 25.0.5 `DocTrees` returns `/`. Java `////` is different: removing `///` leaves the real content `/`, which BCA retains. -- Elixir static strings, heredocs and supported raw/cooked string sigils follow - their language decoding and heredoc margin. Interpolation or computed values - make full content unavailable. A constant-looking expression is not evaluated. +- Elixir supports ordinary strings, heredocs, and `~s`/`~S` string sigils with + static delimiters and no modifiers. Decode cooked escapes and language-defined + heredoc indentation. Raw `~S` preserves interpolation-looking bytes and escapes + except delimiter syntax. Cooked interpolation, computed expressions, + charlist/non-string values, other sigils and modifiers have unavailable content. + Keep the raw attribute and explicit reason; do not evaluate expressions. - Comment adapters remove only their specified delimiter/line prefixes and structural margins. A profile's exact LF/CRLF, blank-line, trailing-space and join behavior belongs in its fixtures. Keep Markdown hard-break spaces and @@ -338,6 +375,9 @@ output. Freeze these transformations separately from attachment: | Java Markdown | Remove each `///` and the minimum leading space/tab margin of nonblank lines across the selected run; preserve trailing spaces and remaining indentation | | C# XML lines, Doxygen lines, Go, Ruby, Bash, Tcl and iRules hash/line forms | Remove the exact recognized marker and at most one following ASCII space from each member; preserve the remaining whitespace | | LDoc lines | Remove the recognized `---` opener; continuation `--` lines lose their own marker; remove at most one following ASCII space | +| Python Sphinx comments | Remove `#:` and at most one following ASCII space; do not apply string-literal decoding | +| Go block comments | Remove `/*` and `*/` and at most one immediate interior ASCII space on either boundary; keep internal indentation and stars literally | +| Ruby RDoc blocks | Remove the `=begin` opener line and `=end` terminator line; retain interior text and indentation | | Java traditional, KDoc, Groovydoc, PHPDoc, JSDoc, TypeScript, Doxygen and C# block forms | Remove the outer recognized delimiters; remove one immediate ASCII space inside either delimiter on its boundary line; on later lines remove indentation plus one decoration `*` and at most one following space when present | | Lua long documentation comments | Remove the matching long-comment opener/closer, including the matching equals depth; no star decoration rule | | Perl POD | Preserve POD markup and internal spacing; omit the terminal `=cut` line and surrounding empty boundary lines; comment-only POD has no prose | @@ -349,7 +389,9 @@ gathered blocks. Keep interior blank comment lines. Do not append a final LF just because the source file has one. Block-internal LF bytes retain copied origins; joins across removed delimiters are synthetic. This differs deliberately from Go's `CommentGroup.Text` final newline and renderer-specific whitespace. -Rust/Python/Elixir literals keep their separately specified language cleanup. +Rust/Python/Elixir literals and Tcl preamble values keep their separately +specified language cleanup. Sphinx, Go block and RDoc block forms follow the +table's CRLF, empty-boundary-line and join rules. Examples: `/** audit */` becomes `audit`; `/**\n * a \n * b\n */` becomes `a \n b`; `/// a \n/// b` in Java becomes `a \n b`; `# a\n#\n# b` in @@ -357,13 +399,24 @@ an attached hash-comment run becomes `a\n\nb`. A source blank line between separate runs still participates in attachment rules; cleanup never joins runs that the profile did not select together. -Required Elixir static forms are ordinary strings, heredocs, `~s` and `~S` -string sigils with static delimiters and no unsupported modifiers. Decode cooked -string escapes and remove language-defined heredoc indentation before mapping. -Raw `~S` preserves interpolation-looking bytes and escapes except delimiter -syntax. Cooked forms containing interpolation are unavailable, as are charlist -or non-string values, unsupported sigils/modifiers and computed expressions. -Keep the raw attribute and explicit reason for each. +Tcl preambles accept static braced or quoted words under the +[Tcl 8.6 substitution rules](https://www.tcl-lang.org/man/tcl8.6/TclCmd/Tcl.htm). +Braced words preserve ordinary escapes, dollar signs and brackets. Quoted words +decode Tcl backslash escapes; variable or command substitution makes complete +text unavailable. Non-scalar decoded values are unavailable. Backslash-newline +and following indentation decode to one space only where the supplied parse +has reliable boundaries; continuation-affected parses retain the #1802 limitation. +Never execute Tcl to obtain a value. + +After value decoding, use Ruff's namespace preamble margin: take the leading +space/tab prefix of the first nonblank content line and remove that prefix from +each line that has it. Remove empty boundary lines, preserve internal whitespace +and `#` headings, and normalize CRLF to LF. Do not use the hash-comment cleaner +or append a terminal newline. In literal Tcl source notation, quoted +`"# Heading\n detail"` produces a line break, whereas braced +`{# Heading\n detail}` retains the backslash and `n`. +Both preserve the heading marker. Decoded escapes map to complete source tokens; +unchanged braced content has copied origins. Required Rust cooked escapes are escaped quote/backslash, newline/carriage return/tab/NUL, valid ASCII hex and Unicode-scalar escapes, and Rust's escaped @@ -431,11 +484,14 @@ unwinding, valid empty/restricted parses and the next successful parse. ## Traversal and implementation boundaries {#traversal} -Use `Ancestors::for_walk(chain, node, &folds, &siblings)`, or the explicit -without-siblings constructor only when no sibling query can occur. Maintain one -borrowed `ChildAncestors` holder through descent/ascent; do not repeatedly copy -derived tails. `nearest_level_answer` requires complete ancestry. Preserve -source bytes and the current typed gate signatures through all callbacks. +Primary visits use `Ancestors::for_walk(chain, node, &folds, &siblings)` with +the walk's sibling records. Use the without-siblings constructor only when no +sibling query can occur. A derived secondary walk maintains one borrowed +`ChildAncestors` holder through descent/ascent rather than copying derived tails. +That holder drops sibling-cache access: broad secondary sibling queries need a +recorded batch or a justified cursor, not repeated uncached seeks. +`nearest_level_answer` requires complete ancestry. Preserve source bytes and +the current typed gate signatures through all callbacks. The collector performs one coordinated structural pass, permitting existing amortized sibling scans and indexed finalization. Source/legacy/profile queries @@ -455,6 +511,27 @@ and retained-result reads have separate probes. Exact counters measure both state computation and slot search. Deep construction, owner extraction, assembly and teardown are iterative and tested on a small stack. +The following bounds exclude parsing. Let N/B be input nodes/bytes, F physical +fragments, E associations, R included ranges, T rendered bytes, S map segments, +I emitted source intersections, and K query-result records or pieces. + +| Operation | Required bound | +| --- | --- | +| Collection before sorting | Amortized `O(N + B + F + E + R + I)` structural work; indexed intersections may add `O(F log(R + 1))` instead of a monotone sweep | +| Prepared owner/node query | Expected `O(1 + K)` indexed lookup, or `O(log(N + F + E + 1) + K)` ordered lookup; no full association/file rescan | +| Mapping range query | `O(log(S + 1) + K)` including returned source pieces; valid empty-range handling is `O(1)` | +| Text/map construction | Linear in contributing input bytes, T, S and I; no repeated copying of a growing prefix | +| Retained text/map access | Borrow a handle or slice in `O(1)` without reconstruction | +| Retained storage | Borrow source bytes; index `O(N + F + E + R + I)`; rendered T/S storage once per document, not multiplied by owner fanout | + +State index-building and deterministic sorting terms separately, including name +bytes compared and queued references. A full included-range scan per fragment +is not permitted. Probe small queries near the last owner/map segment, many +included ranges, a many-fragment document, and independently growing text size +and owner fanout. Count index comparisons, range intersections and copied bytes +where output cannot reveal a quadratic regression. Retained-result access must +not silently rebuild a document on every call. + The Tcl/iRules continuation limitation in [#1802](https://github.com/dekobon/big-code-analysis/issues/1802) follows its approved upstream grammar repair and adoption. Until then, mark affected @@ -475,8 +552,8 @@ one literal backslash. Other characters are literal UTF-8. Each primary source cell ends exactly where shown, without a final newline. Ranges are half-open bytes. The primary roster has one document and one resolved declaration association per row; Perl selects its explicit unique-heading profile. -`audit` is arbitrary prose, not a structural -tag. The source spelling independently fixes the ranges and content. +`audit` is arbitrary prose, not a structural tag. The source spelling +independently fixes the ranges and content. | LANG | Exact source | Fragment range | Owner and range | Local text | | --- | --- | --- | --- | --- | @@ -497,7 +574,7 @@ tag. The source spelling independently fixes the ranges and content. | Objc | `/**audit*/\nvoid f(void) {}` | `0..10` | f, `11..26` | `audit` | | Go | `package p\n// audit\nfunc F() {}` | `10..18` | F, `19..30` | `audit` | | Ruby | `# audit\ndef f\nend` | `0..7` | f, `8..17` | `audit` | -| Lua | `---audit\nfunction f() end` | `0..8` | f, `9..25` | `audit` | +| Lua | `module("m")\n---audit\nfunction f() end` | `12..20` | f, `21..37` | `audit` | | Perl | `=head2 f\n\nAudit\n\n=cut\n\nsub f {}` | `0..21` | f, `23..31`, inferred role | `=head2 f\n\nAudit` | | Elixir | `defmodule M do\n @doc "audit"\n def f(), do: :ok\nend` | `17..29` | M/def/f/0, `32..48` | `audit` | | Bash | `# @description audit\nf() { :; }` | `0..20` | f, `21..31` | `@description audit` | @@ -509,6 +586,11 @@ reports `NoDeclarationModel` and no documents/associations. A disabled feature instead returns language-disabled before collection. Neither helper case can satisfy a source language's positive requirement. +Lua's original first-file input `---audit\nfunction f() end` is a separate +module-document control, with no f association. A preceding `module("m")` makes +the roster's later block declaration documentation. An undocumented `module()` +call does not create a synthetic prose document. + ### Independent source and legacy readings For Java, use these exact bytes, including the final LF: @@ -542,6 +624,13 @@ empty local text. Legacy unit DLOC is one, while f's DLOC is zero. For both functions. Legacy default DLOC is two; `--exclude-tests` leaves only f and DLOC one. Source collection does not inherit the metric pruning option. +For exact Rust input `m! { ///audit\nfn f() {} }\n`, the comment fragment is +`5..13`, with text `audit` copied from `8..13`. Retain an unresolved macro-expansion +association and unknown publication; the token-tree spelling does not establish +a concrete f owner. On the baseline, unit +`(sloc, ploc, lloc, cloc, blank, dloc) = (2, 2, 0, 1, 0, 1)` and there are no +nested metric spaces. This source uncertainty does not erase its legacy DLOC. + For `/** Record doc */\nrecord R(int a) {}\n`, the doc belongs to type R, not its synthesized header function space. Adding `R {}` inside the record replaces that synthesized metric space with the explicit compact constructor; @@ -601,7 +690,7 @@ without a disambiguating signature remain ambiguous. | Offset root or edited node value from the held tree | Noncanonical-node error when context no longer matches the indexed node | | Rust profile requested for Python | Unsupported-profile error | | Python feature disabled, even with empty input | Language-disabled error | -| Pre-cancelled typed parse of `///x\nfn f() {}` | Documentation query returns Cancelled outside the cancellation scope too | +| Typed parse of a long input whose progress callback demonstrably aborts | Retained cancelled provenance; documentation query returns Cancelled outside the cancellation scope too | | Complete parse of empty Rust input | Successful empty index | | Elixir `@doc false` before f | Retained disabled state for f, no successful empty prose | | Elixir `@doc nil` before f | Retained explicit-absence occurrence for f | @@ -610,6 +699,16 @@ without a disambiguating signature remain ambiguous. | Elixir `@doc "text"` and `@doc since: "1"` before f | One document with text `text` and metadata, in either attribute order | | Elixir `@doc "old"` then `@doc "new"` before f | Selected text `new`; old occurrence available as superseded evidence | | Elixir `@doc "a#{x}b"` before f | Full text unavailable; known `a` and `b` separated by opaque interpolation | +| Elixir `@impl true` before f without `@doc` | No document; retain owner evidence with ineligible publication | +| Elixir `@impl true` and explicit `@doc "text"` before f | Present text `text`; impl fallback does not replace it | +| Elixir `@deprecated "old"` before f without `@doc` | Separate owner metadata evidence, no prose document | + +For retained-abort tests, use the existing long-input cancellation fixture or a +deterministic progress hook and assert that parsing actually aborted. A short +parse can finish before tree-sitter calls its progress callback. An installed +cancelled flag alone is not retained-abort provenance. Collection invoked while +that flag is active returns Cancelled on either entry point; a genuinely +completed parse queried after the flag is removed remains complete. For Java `/**pkg*/\npackage p;\nclass C {}`, the comment `0..8` has a source association to package p. Explicit logical filename `package-info.java` permits @@ -642,10 +741,13 @@ that named resolution. ### Required additional forms -Each row below is an acceptance family owned by the linked adapter issue. -Its fixture inventory must include every listed spelling/context, in addition -to the positive roster. A documented limitation has a named unavailable or -unresolved result; it cannot silently omit a promised form. +The [case-keyed form inventory](documentation_extraction_cases.md#ownership) +supplies concrete inputs and outcomes for these acceptance families, including +the missing-form cleanup, TclOO, Elixir head/clauses and PHP callee matrices. +Its notation derives exact ranges from written source occurrences, independently +of implementation results. The families below track coverage ownership; they +do not let adapters choose between incompatible outcomes. A documented limitation +has a named unavailable or unresolved result, not an omitted promised form. | Adapter | Required forms | Exact outcome rule | | --- | --- | --- | @@ -663,14 +765,14 @@ unresolved result; it cannot silently omit a promised form. | [JS #1669](https://github.com/dekobon/big-code-analysis/issues/1669) | Both dialects; functions/classes/members/variables/assignments/exports; nested bound callables | Normalize semantic binding owner and retain wrapper; do not attach to every declarator in a multi-declaration | | JS | In-body comments, @file/@module/@name, duplicate or forward names, line-versus-block trivia | Unattached legacy DLOC has no fabricated owner; file/virtual docs preserve roles; collisions remain unresolved | | [TS #1670](https://github.com/dekobon/big-code-analysis/issues/1670) | Both variants; export/declare/decorators, anonymous defaults, overloads, namespaces/interfaces/types/enums, supported parameters | Distinct source overload owners; declaration wrapper normalization and parameter-only after-code subset remain explicit | -| TS | @module/@packageDocumentation, assignment/destructuring exclusions, TSX JSX neighbors | Structural file blocks take precedence; excluded assignment forms remain unsupported/unattached rather than copied JS behavior | +| TS | @module/@packageDocumentation, assignment/destructuring exclusions, TSX JSX neighbors | Structural file blocks take precedence; excluded assignment/destructuring blocks remain unattached evidence, with no resolved binding edge | | [C-family #1671](https://github.com/dekobon/big-code-analysis/issues/1671) | Every dialect; leading/trailing/member/signature/in-body docs, multi-declarators, ObjC methods/properties/protocols | Resolve qualifying concrete owners or source slots, with shared documents rather than copied text | | C-family | @file gathering, page/group/explicit names, recovery/conditionals, masked names, quoted/CDATA tags | Preserve gatherer once; bounded structural keys finalize; ambiguity/masked original names remain unresolved; quoted/CDATA text does not create structural targets | | [Go #1672](https://github.com/dekobon/big-code-analysis/issues/1672) | Package/function/method, type/var/const groups/specs, multi-name fields and interface elements | Group docs stay group docs; member docs remain separate; one field document can serve several named slots | | Go | Build/generate/other directives, blank comment rows versus source rows, local/trailing placements | Retain directives as evidence but exclude them from prose as specified; source blank rows detach; excluded local/trailing placements do not get inferred owners | | [Ruby #1673](https://github.com/dekobon/big-code-analysis/issues/1673) | Both profiles; methods/classes/modules/singletons/constants/aliases/attributes/visibility wrappers; body/modifier wrappers | Source attachment follows selected scope/call policy; later visibility changes affect eligibility, not occurrence identity | | Ruby | `##`, `@!method`, `@!attribute`, `:nodoc:`, shebang/magic comments and named collisions | RDoc/YARD differences stay profile-qualified; virtual docs remain virtual; directives/magic comments are not arbitrary prose | -| [Lua #1674](https://github.com/dekobon/big-code-analysis/issues/1674) | `---`, long comments, first-file/module contexts, functions/assignments/returns/table fields, structural tags | Opener content and context determine attachment; plain `--` attaches only through selected inference; missing named targets remain virtual/unresolved | +| [Lua #1674](https://github.com/dekobon/big-code-analysis/issues/1674) | `---`, long comments, first-file/module contexts, functions/assignments/returns/table fields, structural tags | Opener content and context determine attachment; standalone ordinary leading runs require inference; native comments on documented table fields/function parameters retain LDoc provenance | | [Perl #1675](https://github.com/dekobon/big-code-analysis/issues/1675) | Direct POD, multiple opaque-node/data-section blocks, headings, comment-only and mixed regions, EOF/CRLF | Preserve physical subranges and POD markup; comment-only regions are not prose; default file/package docs do not attach to the nearest sub | | Perl | Unique/forward/duplicate local headings, missing symbols | Explicit heading profile resolves only one qualifying local sub; duplicate/missing cases remain unresolved, with default file docs still available | | [Elixir #1676](https://github.com/dekobon/big-code-analysis/issues/1676) | Module/function/macro/type/callback docs, explicit heads/clauses, distinct arities and visibility | Group source-written definitions by module/kind/name/arity; no synthesized default-argument arities or quote-template concrete owners | @@ -681,6 +783,13 @@ unresolved result; it cannot silently omit a promised form. | [Irules #1679](https://github.com/dekobon/big-code-analysis/issues/1679) | proc/when, priority/modifiers, neighboring equal-name handlers, leading and body docs | Each handler occurrence has independent identity; both roles remain separate; exact same-scope/row adjacency | | Irules | Nested control comments, quoted text, blank/intervening commands, continuations/recovery | No inferred nested control owner; continuation-affected apparent handlers remain uncertain; unrelated positive docs survive | +Sphinx, RDoc block and Go block mapping examples are in +[comment cleanup cases](documentation_extraction_cases.md#comment-cleanup). +Lua ordinary trailing comments on documented table fields and function +parameters have native LDoc provenance, as described in +[LDoc's code-inference reference](https://lunarmodules.github.io/ldoc/manual/manual.md.html#Inferring_more_from_Code). +They are not the standalone ordinary leading runs that require generic inference. + ### Reference evidence and baseline The semantic baseline is commit @@ -707,6 +816,9 @@ each language case forces its own language and uses the exact written source. The characterization issue retains whole-metric captures, both MI modes and additional independent row-set assertions before migration. +The [reference observation record](https://gist.github.com/dekobon/acb5b4fd9ada1c2b63f86ae0f0514524) +preserves the exact Java/Python commands, source inputs and legacy measurements. + ## Qualification and delivery {#qualification} Author the source/form inventory independently from implementation capabilities. diff --git a/docs/development/documentation_extraction_cases.md b/docs/development/documentation_extraction_cases.md new file mode 100644 index 000000000..28b106f97 --- /dev/null +++ b/docs/development/documentation_extraction_cases.md @@ -0,0 +1,238 @@ +# Documentation extraction form cases + +This is the independently specified form inventory for contributors implementing +the [documentation extraction contract](documentation_extraction.md#acceptance-cases). +It supplements the primary language roster with inputs that distinguish attachment, +composition, text availability and profile choices. These are required outcomes, +not observations from a shipped extractor. Profile definitions and references +are in the contract. + +Each source cell expands `\n`, `\r`, `\t` and `\\` only. Inputs are standalone +and have no unshown terminal newline unless an enclosing template is specified. +An owner such as `f` or `C.x` denotes the declaration occurrence or name slot in +that input, not a global name. Its range is the exact declaration/name spelling +in the input; repeated clauses are numbered in source order. Attribute fragments +span the whole attribute, literal fragments include quotes, and comment fragments +include markers but exclude a terminating LF/CRLF. Those spelling-based ranges +are independent expectations and must not be taken from extractor output. + +Unless a row says otherwise, a single selected block or literal expression +produces one document with complete marker-cleaned text `audit`, resolved to +the named owner. Members of a selected run compose into that document in written +source order, using the contract's join rule; superseded members are evidence, +not extra selected prose. Publication is unknown unless a row supplies enough +information to classify it. The semantic role follows the contract; a syntactic +attribute form does not mean Python's attribute-binding role. + +## Implementation ownership {#ownership} + +| Case prefix | Owning issue | +| --- | --- | +| `rust-` | [#1664](https://github.com/dekobon/big-code-analysis/issues/1664) | +| `python-` | [#1665](https://github.com/dekobon/big-code-analysis/issues/1665) | +| `java-`, `kotlin-`, `groovy-` | [#1666](https://github.com/dekobon/big-code-analysis/issues/1666) | +| `csharp-` | [#1667](https://github.com/dekobon/big-code-analysis/issues/1667) | +| `php-` and PHP matrix | [#1668](https://github.com/dekobon/big-code-analysis/issues/1668) | +| `js-` | [#1669](https://github.com/dekobon/big-code-analysis/issues/1669) | +| `ts-` | [#1670](https://github.com/dekobon/big-code-analysis/issues/1670) | +| `doxygen-`, `objc-` | [#1671](https://github.com/dekobon/big-code-analysis/issues/1671) | +| `go-` | [#1672](https://github.com/dekobon/big-code-analysis/issues/1672) | +| `ruby-` | [#1673](https://github.com/dekobon/big-code-analysis/issues/1673) | +| `lua-` | [#1674](https://github.com/dekobon/big-code-analysis/issues/1674) | +| `perl-` | [#1675](https://github.com/dekobon/big-code-analysis/issues/1675) | +| `elixir-` and metadata matrix | [#1676](https://github.com/dekobon/big-code-analysis/issues/1676) | +| `bash-` | [#1677](https://github.com/dekobon/big-code-analysis/issues/1677) | +| `tcl-` | [#1678](https://github.com/dekobon/big-code-analysis/issues/1678) | +| `irules-` | [#1679](https://github.com/dekobon/big-code-analysis/issues/1679) | + +## Comment and preamble cleanup {#comment-cleanup} + +| Case | Source | Exact text/origins | +| --- | --- | --- | +| python-sphinx | `#: audit\nx = 1` | attribute x; one comment fragment 0..8; `audit` output 0..5 copies source 3..8 | +| ruby-block | `=begin\naudit\n=end\ndef f\nend` | RDoc method f; fragment 0..17; `audit` output 0..5 copies 7..12; boundary lines no output | +| go-block | `package p\n/* audit */\nfunc F() {}` | function F; fragment 10..21; `audit` output 0..5 copies 13..18 | +| tcl-quoted-preamble | `namespace eval n { variable _ruff_preamble "# Heading\\n detail" }` | namespace n; text `# Heading\n detail`, escape maps to complete backslash-n token; # preserved | +| tcl-braced-preamble | `namespace eval n { variable _ruff_preamble {# Heading\\n detail} }` | namespace n; text `# Heading\\n detail`, literal backslash-n copied; # preserved | +| tcl-braced-substitutions | `namespace eval n { variable _ruff_preamble {# $name [call]} }` | namespace n; literal `# $name [call]`; no variable/command evaluation | +| tcl-dynamic-preamble | `namespace eval n { variable _ruff_preamble "# $name" }` | namespace owner resolved; text unavailable(dynamic substitution), raw retained | + +## Rust source forms + +| Case | Source | Exact selected outcome | +| --- | --- | --- | +| rust-inner-module | `mod m { //!audit\n}` | 1 inner comment document -> module m, text audit | +| rust-outer-block | `/**audit*/\nfn f() {}` | 1 document -> f, text audit | +| rust-raw-attribute | `#[doc = r"audit"]\nfn f() {}` | 1 primary document in attribute form -> f, text audit; attribute remains code for legacy LOC | +| rust-mixed | `/// first\n#[doc = "second"]\nfn f() {}` | 1 document -> f, 2 contributing fragments in order, text `first\nsecond` | +| rust-field-variant | `enum E { ///audit\nV }` | 1 document -> variant E.V, text audit | +| rust-metadata-only | `#[doc(hidden)]\nfn f() {}` | 1 metadata-only record -> f; no prose; eligibility ineligible | +| rust-computed | `#[doc = include_str!("doc.md")]\nfn f() {}` | owner f resolved; raw attribute retained; complete text unavailable(external/computed) | +| rust-macro | `m! { ///audit\nfn f() {} }` | raw comment recognized; owner unresolved(macro expansion); text audit; publication unknown; no concrete f association | + +## Elixir groups and states + +Use module wrapper `defmodule M do\n` + body + `\nend` for every row. + +| Case | Body | Exact selected outcome | +| --- | --- | --- | +| elixir-head | `@doc "audit"\ndef f(x)\ndef f(0), do: 0\ndef f(x), do: x` | 1 document audit -> M/def/f/1; owner group has head and two explicit clauses in source order | +| elixir-clause-replace | `@doc "old"\ndef f(0), do: 0\n@doc "new"\ndef f(x), do: x` | 1 group, text new; old prose superseded evidence; two clause pieces | +| elixir-arity | `@doc "one"\ndef f(x), do: x\n@doc "two"\ndef f(x,y), do: x+y` | 2 docs one/two -> distinct f/1, f/2 | +| elixir-default-arity | `@doc "audit"\ndef f(x \\\\ 0), do: x` | one source owner f/1; no synthetic f/0 | +| elixir-private | `@doc "audit"\ndefp f(), do: :ok` | source doc retained -> defp/f/0; compiler publication ineligible | +| elixir-moduledoc | `@moduledoc "audit"` | 1 module document audit -> M | +| elixir-typedoc | `@typedoc "audit"\n@type t :: integer()` | 1 type document audit -> M/type/t/0 | +| elixir-callback | `@doc "audit"\n@callback f() :: atom()` | 1 doc audit -> M/callback/f/0 | +| elixir-meta-text | `@doc since: "1"\n@doc "audit"\ndef f(), do: :ok` | one doc audit with metadata since=1 | +| elixir-false-then-text | `@doc false\n@doc "audit"\ndef f(), do: :ok` | one selected prose doc audit; false superseded evidence | +| elixir-text-then-false | `@doc "audit"\n@doc false\ndef f(), do: :ok` | one selected disabled record; text superseded evidence | +| elixir-raw-sigil | `@doc ~S(a#{x}b)\ndef f(), do: :ok` | one doc with literal `a#{x}b`, no interpolation | +| elixir-quote | `quote do\n@doc "audit"\ndef f(), do: :ok\nend` | template evidence only; no concrete M/f owner | + +## TclOO and iRules + +| Case | Source | Exact selected outcome | +| --- | --- | --- | +| tcl-method | `oo::class create C {\nmethod f {} {\n# audit\nreturn\n}\n}` | one doc audit -> direct method command C.f; no metric function space promotion | +| tcl-constructor | `oo::class create C {\nconstructor {} {\n# audit\n}\n}` | one doc audit -> constructor command C; not class prose | +| tcl-destructor | `oo::define C {\ndestructor {\n# audit\n}\n}` | one doc audit -> destructor occurrence under definition C | +| tcl-outside-method | `method f {} {\n# audit\n}` | no native concrete method owner; owner unsupported outside specified class context | +| tcl-dynamic-class | `oo::class create $name {\nmethod f {} {\n# audit\n}\n}` | raw source candidate; class/method association unresolved(dynamic name) | +| irules-two-handlers | `# first\nwhen HTTP_REQUEST {}\n# second\nwhen HTTP_REQUEST priority 200 {}` | two docs -> separate handler occurrences, source order; priority not identity substitution | +| irules-body | `when HTTP_REQUEST {\n# audit\n}` | one body-role doc audit -> handler occurrence | +| irules-separated | `# audit\n\nwhen HTTP_REQUEST {}` | no selected leading doc; candidate unattached under evidence option | + +## Lua source contexts + +| Case | Source | Exact selected outcome | +| --- | --- | --- | +| lua-first-file | `---audit\nfunction f() end` | module/file doc audit, no f association | +| lua-after-module | `module("m")\n---audit\nfunction f() end` | function f doc audit; module() itself creates no documentation prose occurrence | +| lua-ordinary-leading | `module("m")\n-- audit\nfunction f() end` | default no selected doc; explicit leading-inference doc audit -> f | +| lua-table-field | `module("m")\n--- settings\n-- @table options\noptions = {\nalpha = 1, -- correction\n}` | table doc `settings\n@table options` -> options; native field doc correction -> alpha slot | +| lua-parameter | `module("m")\n---audit\nfunction f(\nx -- input\n) end` | function doc audit; native parameter doc input -> x slot | +| lua-explicit-virtual | `module("m")\n---audit\n-- @function ghost\n` | explicit virtual function ghost with local text `audit\n@function ghost`; no fabricated concrete node | + +## JVM, C# and PHP owner controls + +| Case | Source | Exact selected outcome | +| --- | --- | --- | +| java-annotation | `/**audit*/\n@Deprecated class C {}` | one doc audit -> C, wrapper retained | +| java-explicit-constructor | `class C { /**audit*/ C() {} }` | one doc audit -> constructor C(), not class C | +| java-compact-constructor | `record R(int x) { /**audit*/ R {} }` | one doc audit -> compact constructor R, not synthesized header | +| java-markdown-separated | `///old\n\n///new\nclass C {}` | new -> C; old superseded/dangling evidence, never joined | +| java-markdown-slash | `////\nclass C {}` | one doc / -> C | +| java-unicode | `/** \\u0040audit */\nclass C {}` | owner C source candidate; full semantic text unavailable(prelex); raw/source-cleaned spelling retained | +| kotlin-annotation | `/**audit*/\n@Deprecated("x") fun f() {}` | one doc audit -> f | +| kotlin-secondary | `class C { /**audit*/ constructor(x: Int) {} }` | one doc audit -> secondary constructor, not C | +| kotlin-parameter | `class C(/**audit*/ val x: Int)` | one doc audit -> x parameter/property slot | +| groovy-constructor | `class C { /**audit*/ C() {} }` | one doc audit -> explicit constructor C | +| groovy-field | `class C { /**audit*/ int x }` | one doc audit -> field x | +| csharp-attribute | `///audit\n[System.Obsolete] class C {}` | one XML doc -> C; text `audit` | +| csharp-property | `class C {\n///audit\nint P => 1;\n}` | one doc, text `audit` -> P, not generated getter | +| csharp-indexer | `class C {\n///audit\nint this[int x] => x;\n}` | one doc, text `audit` -> indexer occurrence | +| csharp-inheritdoc | `class C {\n/// \nvoid F() {}\n}` | one doc -> F, text ``, no expansion | +| csharp-accessor | `class C { int P { /**audit*/ get; } }` | no selected accessor doc; candidate unattached evidence; no implicit P attachment | +| php-one | ` C; no file doc | +| php-two | ` root, item -> C; two docs | +| php-three | ` C; a/b superseded evidence | +| php-enum | ` E; alternate audit -> file, exclusive | +| php-define | ` constant slot X with qualified provenance; alternate -> file | +| php-namespace | ` promoted property/parameter slot x, not constructor | + +## JS, TS and C-family controls + +| Case | Source | Exact selected outcome | +| --- | --- | --- | +| js-variable | `/**audit*/\nconst f = () => 1;` | one doc audit -> binding f with declarator/arrow evidence | +| js-multi-declarator | `/**audit*/\nconst a = 1, b = 2;` | one doc -> first eligible binding a, not automatically b | +| js-export | `/**audit*/\nexport function f() {}` | one doc audit -> f, export binding wrapper retained | +| js-inner-declaration | `function outer() { /**audit*/ function inner() {} }` | one doc audit -> inner, not outer | +| js-file | `/**@file audit*/\nfunction f() {}` | one file doc `@file audit`; no f edge | +| js-virtual | `/**@name ghost\n * @function\n * audit*/` | one virtual ghost doc, text `@name ghost\n@function\naudit`; no concrete node fabricated | +| ts-ambient | `/**audit*/\ndeclare function f(): void;` | one doc audit -> signature f with ambient wrapper | +| ts-default-anonymous | `/**audit*/\nexport default function() {}` | one doc audit -> anonymous default-export declaration occurrence | +| ts-overloads | `/**one*/\nfunction f(x: string): string;\n/**two*/\nfunction f(x: number): number;` | two docs one/two -> distinct overload signature occurrences | +| ts-file | `/** @packageDocumentation */\nexport const x = 1;` | one file doc @packageDocumentation, no x edge | +| ts-parameter | `function f(/**audit*/ x: number) {}` | one doc audit -> parameter x | +| ts-destructure | `/**audit*/\nexport const {x} = value;` | candidate unattached under default; no supported declaration doc edge to x | +| doxygen-trailing | `struct S { int x; /// x member slot | +| doxygen-multi | `/**audit*/\nint a, b;` | one doc audit -> both qualifying a and b slots | +| doxygen-file | `/**@file*/\nint x;` | one file doc @file, no fabricated x edge | +| doxygen-forward | `/**@fn void f()\n * audit*/\nvoid f();` | explicit signature resolves same-file f; text `@fn void f()\naudit` | +| doxygen-missing | `/**@fn void missing()\n * audit*/\nvoid f();` | text `@fn void missing()\naudit`; unresolved missing-name association, no f edge | +| doxygen-ambiguous | `/**@fn f\n * audit*/\nvoid f(int);\nvoid f(double);` | text `@fn f\naudit`; unresolved alternatives, no first-wins overload | +| doxygen-quoted | `/** text "@file" */\nvoid f();` | declaration doc -> f, text `text "@file"`; quoted @file does not reassign to file | +| objc-method | `@interface C\n/**audit*/\n- (void)f;\n@end` | one doc audit -> Objective-C method f | + +JS controls run separately for Javascript and Mozjs; TS controls for Typescript +and Tsx where syntax is common. C-family controls run independently for each +grammar that accepts the spelling; ObjC-specific method case is separate. + +## Go, Ruby, Perl, Bash and Python controls + +| Case | Source | Exact selected outcome | +| --- | --- | --- | +| go-package | `// audit\npackage p` | one package doc audit -> package p | +| go-group | `package p\n// group\nvar (\n// member\nX int\n)` | group -> var group; member -> X spec, two documents | +| go-multi-field | `package p\ntype S struct {\n// both\nX, Y int\n}` | one doc both -> X and Y field slots | +| go-directive | `package p\n// audit\n//go:generate tool\nfunc F() {}` | one doc -> F with text audit; directive retained as non-prose evidence | +| ruby-attribute | `# audit\nattr_reader :x` | YARD one source doc -> x attribute slot | +| ruby-visibility | `class C\n# audit\nprivate def f; end\nend` | source doc -> f; private publication disposition retained | +| ruby-virtual | `# @!method ghost\n# audit\n` | YARD virtual ghost, text `@!method ghost\n audit`; RDoc no YARD virtual owner | +| perl-default-pod | `=head2 f\n\nAudit\n\n=cut\n\nsub f {}` | default file doc, text `=head2 f\n\nAudit`, no f edge; unique-heading option yields inferred f edge | +| perl-comment-only | `=begin comment\n\nnot prose\n\n=end comment\n\n=cut\n` | comment region, no selected prose document | +| perl-opaque | `__END__\n=head1 NAME\n\nAudit\n\n=cut\n` | file POD doc, text `=head1 NAME\n\nAudit`, source subrange inside opaque data node | +| perl-collision | `=head2 f\n\nAudit\n\n=cut\n\nsub f {}\nsub f {}` | text `=head2 f\n\nAudit`; heading inference unresolved duplicate local definitions | +| bash-function-keyword | `# @description audit\nfunction f { :; }` | one shdoc doc @description audit -> f | +| bash-file | `# @file sample\n# @description audit\necho ok` | one file doc, text `@file sample\n@description audit`; no echo owner | +| bash-unmarked | `# audit\nf() { :; }` | default no selected doc; inference option doc audit -> f | +| bash-heredoc | `cat <<'EOF'\n# @description audit\nEOF\nf() { :; }` | no documentation from heredoc text | +| python-module | `"audit"\nx = 1` | primary module doc audit | +| python-class | `class C:\n "audit"\n pass` | primary doc audit -> C | +| python-attribute | `x = 1\n"audit"` | attribute doc audit -> binding x | +| python-chained | `x = y = 1\n"audit"` | one attribute doc -> qualifying x and y binding slots | +| python-nondoc | `x = 1\nprint(x)\n"audit"` | discarded string, no selected primary/additional/attribute document | +| python-prefix | `def f():\n b"audit"\n pass` | bytes statement not primary doc; same exclusion for f/t strings | + +## PHP callee and placement matrix + +Use ` Date: Wed, 18 Nov 2026 09:00:45 -0800 Subject: [PATCH 003/221] docs(ast): correct reference-specific documentation fixtures --- docs/development/documentation_extraction.md | 26 ++++++++++++++----- .../documentation_extraction_cases.md | 24 ++++++++++------- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/docs/development/documentation_extraction.md b/docs/development/documentation_extraction.md index 0c6403e91..3ffe68c1f 100644 --- a/docs/development/documentation_extraction.md +++ b/docs/development/documentation_extraction.md @@ -245,12 +245,19 @@ default associates the declaration, the alternate the file. Native attributes, promoted properties and signature-local comments retain their own source owner evidence. An imported callee name is not proof that a call is builtin `define`. -YARD handles `@!` virtual directives and its own scope/call rules. RDoc handles -`##`, `=begin`/`=end`, and its visibility directives separately. Hidden source -documents remain retained with the appropriate publication state. An explicit +YARD and RDoc both read `=begin`/`=end` blocks. YARD handles `@!` virtual +directives and its own scope/call rules; RDoc has separate `##` and visibility +directive rules. Hidden source documents retain the appropriate publication +state. An explicit virtual method does not become a concrete declaration merely because a same-name method exists later. +Python attribute strings follow the Sphinx target subset where it extends +PEP 258: a string after `x = y = 1` describes x only, while Sphinx `#:` comments +can describe both assignment targets. A tuple within the first assignment target +still enumerates its qualifying leaves. Do not turn the legacy existence test +into an association for every syntactic target. + Elixir documentation groups use enclosing module, definition kind, name and source-written arity. Preserve explicit heads and clauses in the group. Default arguments do not create extra synthetic arity owners. `@spec` is signature @@ -349,7 +356,7 @@ separator; separate additional strings remain separate logical documents. semantic decoding. Preserve separately labeled source-cleaned spelling. The trigger deliberately over-approximates JLS eligibility, including an ineligible spelling whose Unicode-escape backslash has an odd number of - preceding backslashes, such as the literal source spelling `\\u0041`. + preceding backslashes, such as two backslashes followed by `u0041`. [JLS Unicode prelexing](https://docs.oracle.com/javase/specs/jls/se25/html/jls-3.html#jls-3.3) can also alter delimiters or line endings; affected associations remain uncertain even when tree-sitter reports no ERROR node. Ordinary docs remain @@ -377,7 +384,7 @@ output. Freeze these transformations separately from attachment: | LDoc lines | Remove the recognized `---` opener; continuation `--` lines lose their own marker; remove at most one following ASCII space | | Python Sphinx comments | Remove `#:` and at most one following ASCII space; do not apply string-literal decoding | | Go block comments | Remove `/*` and `*/` and at most one immediate interior ASCII space on either boundary; keep internal indentation and stars literally | -| Ruby RDoc blocks | Remove the `=begin` opener line and `=end` terminator line; retain interior text and indentation | +| Ruby YARD/RDoc blocks | Remove the `=begin` opener line and `=end` terminator line; retain interior text and indentation | | Java traditional, KDoc, Groovydoc, PHPDoc, JSDoc, TypeScript, Doxygen and C# block forms | Remove the outer recognized delimiters; remove one immediate ASCII space inside either delimiter on its boundary line; on later lines remove indentation plus one decoration `*` and at most one following space when present | | Lua long documentation comments | Remove the matching long-comment opener/closer, including the matching equals depth; no star decoration rule | | Perl POD | Preserve POD markup and internal spacing; omit the terminal `=cut` line and surrounding empty boundary lines; comment-only POD has no prose | @@ -390,7 +397,7 @@ just because the source file has one. Block-internal LF bytes retain copied origins; joins across removed delimiters are synthetic. This differs deliberately from Go's `CommentGroup.Text` final newline and renderer-specific whitespace. Rust/Python/Elixir literals and Tcl preamble values keep their separately -specified language cleanup. Sphinx, Go block and RDoc block forms follow the +specified language cleanup. Sphinx, Go block and Ruby block forms follow the table's CRLF, empty-boundary-line and join rules. Examples: `/** audit */` becomes `audit`; `/**\n * a \n * b\n */` becomes @@ -408,6 +415,13 @@ and following indentation decode to one space only where the supplied parse has reliable boundaries; continuation-affected parses retain the #1802 limitation. Never execute Tcl to obtain a value. +The pinned Tcl grammar can misparse a braced preamble when its `#` content and +closing brace share a source line. That form retains explicit grammar-boundary +uncertainty and cannot produce a confirmed namespace association or complete +preamble text. Multiline controls put the closing brace on its own line so the +parser supplies the namespace and value word. This is a grammar limitation, not +a Tcl string-substitution rule. + After value decoding, use Ruff's namespace preamble margin: take the leading space/tab prefix of the first nonblank content line and remove that prefix from each line that has it. Remove empty boundary lines, preserve internal whitespace diff --git a/docs/development/documentation_extraction_cases.md b/docs/development/documentation_extraction_cases.md index 28b106f97..4ebd9607d 100644 --- a/docs/development/documentation_extraction_cases.md +++ b/docs/development/documentation_extraction_cases.md @@ -50,11 +50,12 @@ attribute form does not mean Python's attribute-binding role. | Case | Source | Exact text/origins | | --- | --- | --- | | python-sphinx | `#: audit\nx = 1` | attribute x; one comment fragment 0..8; `audit` output 0..5 copies source 3..8 | -| ruby-block | `=begin\naudit\n=end\ndef f\nend` | RDoc method f; fragment 0..17; `audit` output 0..5 copies 7..12; boundary lines no output | +| ruby-block | `=begin\naudit\n=end\ndef f\nend` | Both YARD and RDoc: method f; fragment 0..17; `audit` output 0..5 copies 7..12; boundary lines no output | | go-block | `package p\n/* audit */\nfunc F() {}` | function F; fragment 10..21; `audit` output 0..5 copies 13..18 | | tcl-quoted-preamble | `namespace eval n { variable _ruff_preamble "# Heading\\n detail" }` | namespace n; text `# Heading\n detail`, escape maps to complete backslash-n token; # preserved | -| tcl-braced-preamble | `namespace eval n { variable _ruff_preamble {# Heading\\n detail} }` | namespace n; text `# Heading\\n detail`, literal backslash-n copied; # preserved | -| tcl-braced-substitutions | `namespace eval n { variable _ruff_preamble {# $name [call]} }` | namespace n; literal `# $name [call]`; no variable/command evaluation | +| tcl-braced-preamble | `namespace eval n {\nvariable _ruff_preamble {\n# Heading\\n detail\n}\n}` | namespace n; text `# Heading\\n detail`, literal backslash-n copied; # preserved | +| tcl-braced-substitutions | `namespace eval n {\nvariable _ruff_preamble {\n# $name [call]\n}\n}` | namespace n; literal `# $name [call]`; no variable/command evaluation | +| tcl-braced-same-line | `namespace eval n { variable _ruff_preamble {# Heading\\n detail} }` | grammar-boundary uncertainty; no confirmed namespace owner or complete preamble text | | tcl-dynamic-preamble | `namespace eval n { variable _ruff_preamble "# $name" }` | namespace owner resolved; text unavailable(dynamic substitution), raw retained | ## Rust source forms @@ -193,16 +194,19 @@ grammar that accepts the spelling; ObjC-specific method case is separate. | python-module | `"audit"\nx = 1` | primary module doc audit | | python-class | `class C:\n "audit"\n pass` | primary doc audit -> C | | python-attribute | `x = 1\n"audit"` | attribute doc audit -> binding x | -| python-chained | `x = y = 1\n"audit"` | one attribute doc -> qualifying x and y binding slots | +| python-chained | `x = y = 1\n"audit"` | one attribute-binding doc -> x only under Sphinx's first-target rule; no y association | +| python-chained-comment | `#: audit\nx = y = 1` | one Sphinx comment doc -> x and y under the comment path's all-target rule | | python-nondoc | `x = 1\nprint(x)\n"audit"` | discarded string, no selected primary/additional/attribute document | | python-prefix | `def f():\n b"audit"\n pass` | bytes statement not primary doc; same exclusion for f/t strings | ## PHP callee and placement matrix Use ` Date: Wed, 18 Nov 2026 09:23:20 -0800 Subject: [PATCH 004/221] feat(ast): add source-backed documentation facts and parse provenance --- big-code-analysis-ast/src/documentation.rs | 365 ++++++++++++++++++ .../src/documentation/content.rs | 110 ++++++ .../src/documentation/owners.rs | 159 ++++++++ .../src/documentation/source.rs | 167 ++++++++ .../src/documentation/streaming.rs | 107 +++++ .../src/documentation/tests.rs | 305 +++++++++++++++ .../src/documentation/tests/model_cases.rs | 206 ++++++++++ .../src/documentation/tests/ownership.rs | 221 +++++++++++ .../src/documentation/tests/provenance.rs | 130 +++++++ .../src/documentation/tests/streaming.rs | 138 +++++++ big-code-analysis-ast/src/lib.rs | 1 + big-code-analysis-ast/src/macros/mod.rs | 6 + big-code-analysis-ast/src/node.rs | 21 +- .../src/node/parser_cache.rs | 32 +- big-code-analysis-ast/src/parser.rs | 22 ++ tests/api/parser_reuse.rs | 22 ++ utils/documentation-facts-perturb.json | 70 ++++ 17 files changed, 2066 insertions(+), 16 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation.rs create mode 100644 big-code-analysis-ast/src/documentation/content.rs create mode 100644 big-code-analysis-ast/src/documentation/owners.rs create mode 100644 big-code-analysis-ast/src/documentation/source.rs create mode 100644 big-code-analysis-ast/src/documentation/streaming.rs create mode 100644 big-code-analysis-ast/src/documentation/tests.rs create mode 100644 big-code-analysis-ast/src/documentation/tests/model_cases.rs create mode 100644 big-code-analysis-ast/src/documentation/tests/ownership.rs create mode 100644 big-code-analysis-ast/src/documentation/tests/provenance.rs create mode 100644 big-code-analysis-ast/src/documentation/tests/streaming.rs create mode 100644 utils/documentation-facts-perturb.json diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs new file mode 100644 index 000000000..27faac38e --- /dev/null +++ b/big-code-analysis-ast/src/documentation.rs @@ -0,0 +1,365 @@ +//! Source-backed documentation records, independent of metric policy. +//! +//! Role/context predicates recognize candidates; they do not supply semantic +//! owners. Fragments add included source spelling, documents add composition +//! and content state, and associations add profile-qualified attachment. +//! This module supplies storage and identity primitives, not a collector. +//! All items are unstable direct-AST plumbing; no root facade is introduced. + +mod content; +mod owners; +mod source; +#[doc(hidden)] +pub mod streaming; + +pub use content::*; +pub use owners::*; +pub use source::*; + +/// One physical occurrence, whose spelling may be narrower than its syntax node. +#[derive(Debug)] +#[non_exhaustive] +pub struct Fragment<'s> { + pub(crate) source: SourcePieces<'s>, + pub(crate) node: Option>, + pub(crate) form: FragmentForm, +} + +impl<'s> Fragment<'s> { + /// Included raw spelling, available even when decoding is unavailable. + #[must_use] + pub fn source(&self) -> &SourcePieces<'s> { + &self.source + } + + /// Exact syntax evidence, not necessarily the fragment's spelling range. + #[must_use] + pub fn node(&self) -> Option> { + self.node + } + + /// The syntax form, independent of the document's semantic role. + #[must_use] + pub fn form(&self) -> FragmentForm { + self.form + } +} + +/// The spelling carrying a documentation occurrence. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum FragmentForm { + /// A line or block comment. + Comment, + /// A string literal, including its delimiters. + Literal, + /// A whole documentation attribute, including its value syntax. + Attribute, + /// POD spelling inside an opaque syntax node. + Pod, + /// A literal Tcl namespace preamble word. + Preamble, +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct FragmentId(pub(crate) usize); +#[derive(Clone, Copy, Debug)] +pub(crate) struct DocumentId(pub(crate) usize); +#[derive(Clone, Copy, Debug)] +pub(crate) struct OwnerId(pub(crate) usize); + +/// One logical document, stored once regardless of owner fanout. +#[derive(Debug)] +#[non_exhaustive] +pub struct Document<'s> { + pub(crate) fragments: Vec, + pub(crate) composition: Composition, + pub(crate) role: DocumentRole, + pub(crate) content: Content<'s>, +} + +impl<'s> Document<'s> { + /// Number of ordered physical occurrences composing this document. + #[must_use] + pub fn fragment_count(&self) -> usize { + self.fragments.len() + } + + /// How ordered fragments compose; additional Python strings are documents + /// of their own, not a concatenation mode. + #[must_use] + pub fn composition(&self) -> Composition { + self.composition + } + + /// The semantic documentation role. + #[must_use] + pub fn role(&self) -> DocumentRole { + self.role + } + + /// Local text state, independent of whether an owner resolved. + #[must_use] + pub fn content(&self) -> &Content<'s> { + &self.content + } +} + +/// Ordered physical-fragment composition. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Composition { + /// One physical occurrence. + Single, + /// Adjacent static literals with no separator. + LiteralConcatenation, + /// A selected comment run or gathered blocks. + CommentRun, + /// Language-defined composition of comments and attributes. + AttributeSequence, +} + +/// Semantic roles in the contract's explicit source-order tie-break order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum DocumentRole { + /// Primary item or module string documentation. + Primary, + /// A separate additional Python string expression. + Additional, + /// A PEP 258 string describing a binding. + AttributeBinding, + /// A Sphinx attribute comment. + Sphinx, + /// Documentation preceding a declaration. + LeadingComment, + /// Documentation in a declaration's body. + BodyComment, + /// File or package documentation. + FilePackage, + /// Documentation declaring a virtual target. + Virtual, + /// Explicitly opted-in BCA inference. + Inferred, +} + +impl DocumentRole { + /// Stable role rank within a source-order key, not an enum discriminant. + #[must_use] + pub const fn source_rank(self) -> u8 { + match self { + Self::Primary => 0, + Self::Additional => 1, + Self::AttributeBinding => 2, + Self::Sphinx => 3, + Self::LeadingComment => 4, + Self::BodyComment => 5, + Self::FilePackage => 6, + Self::Virtual => 7, + Self::Inferred => 8, + } + } +} + +/// Immutable record storage. Construction and indexed owner lookup belong to +/// the collector; an empty store does not claim a completed collection. +#[derive(Debug, Default)] +pub struct Facts<'s> { + scope: u8, + pub(crate) fragments: Vec>, + pub(crate) documents: Vec>, + pub(crate) owners: Vec>, + pub(crate) associations: Vec>, +} + +/// An index-local borrowed occurrence. Equality is identity, never text equality. +/// Moving storage before borrowing it is valid. No persistent ID or pointer +/// ordering is exposed, and two stores over one tree have distinct identities. +#[derive(Debug)] +pub struct FactRef<'i, T> { + scope: &'i u8, + ordinal: usize, + fact: &'i T, +} + +impl Copy for FactRef<'_, T> {} +impl Clone for FactRef<'_, T> { + fn clone(&self) -> Self { + *self + } +} +impl PartialEq for FactRef<'_, T> { + fn eq(&self, other: &Self) -> bool { + std::ptr::eq(self.scope, other.scope) && self.ordinal == other.ordinal + } +} +impl Eq for FactRef<'_, T> {} +impl<'i, T> FactRef<'i, T> { + /// Borrow the retained record without reconstruction. + #[must_use] + pub fn get(self) -> &'i T { + self.fact + } +} + +impl<'s> Facts<'s> { + fn reference<'i, T>(&'i self, records: &'i [T], ordinal: usize) -> Option> { + Some(FactRef { + scope: &self.scope, + ordinal, + fact: records.get(ordinal)?, + }) + } + + fn references<'i, T>( + &'i self, + records: &'i [T], + ) -> impl ExactSizeIterator> { + records.iter().enumerate().map(|(ordinal, fact)| FactRef { + scope: &self.scope, + ordinal, + fact, + }) + } + + /// Physical occurrences in retained order. + pub fn fragments(&self) -> impl ExactSizeIterator>> { + self.references(&self.fragments) + } + + /// Logical documents in retained order. + pub fn documents(&self) -> impl ExactSizeIterator>> { + self.references(&self.documents) + } + + /// Semantic owners, independently of metric spaces. + pub fn owners(&self) -> impl ExactSizeIterator>> { + self.references(&self.owners) + } + + /// Profile-qualified attachment records in retained order. + pub fn associations(&self) -> impl ExactSizeIterator>> { + self.references(&self.associations) + } + + /// The fragment at a composition position, or an identity/bounds error. + /// + /// # Errors + /// Rejects handles from another store and absent composition positions. + pub fn document_fragment( + &self, + document: FactRef<'_, Document<'s>>, + position: usize, + ) -> Result>, FactError> { + self.check_scope(document)?; + let id = document + .fact + .fragments + .get(position) + .ok_or(FactError::MissingRecord)?; + self.reference(&self.fragments, id.0) + .ok_or(FactError::MissingRecord) + } + + /// The shared document referred to by an association. + /// + /// # Errors + /// Rejects foreign handles or an invalid internal document reference. + pub fn associated_document( + &self, + association: FactRef<'_, Association<'s>>, + ) -> Result>, FactError> { + self.check_scope(association)?; + self.reference(&self.documents, association.fact.document.0) + .ok_or(FactError::MissingRecord) + } + + /// One resolved owner or uncertain candidate, in the association's order. + /// Consult `resolution` before treating a candidate as an owner claim. + /// + /// # Errors + /// Rejects foreign handles or an absent owner position. + pub fn associated_owner( + &self, + association: FactRef<'_, Association<'s>>, + position: usize, + ) -> Result>, FactError> { + self.check_scope(association)?; + let id = association + .fact + .owners + .get(position) + .ok_or(FactError::MissingRecord)?; + self.reference(&self.owners, id.0) + .ok_or(FactError::MissingRecord) + } + + /// A slot's enclosing semantic owner, distinct from lexical scope. + /// + /// # Errors + /// Rejects a foreign handle, a non-slot owner or an invalid enclosure. + pub fn slot_enclosing( + &self, + owner: FactRef<'_, Owner<'s>>, + ) -> Result>, FactError> { + self.check_scope(owner)?; + let Owner::Slot(slot) = owner.fact else { + return Err(FactError::MissingRecord); + }; + self.reference(&self.owners, slot.enclosing.0) + .ok_or(FactError::MissingRecord) + } + + /// Source ordering key, kept separate from occurrence equality. + /// + /// # Errors + /// Rejects foreign handles and a document without a physical fragment. + pub fn document_order( + &self, + document: FactRef<'_, Document<'s>>, + ) -> Result<(usize, usize, u8, usize), FactError> { + let fragment = self.document_fragment(document, 0)?; + let first = fragment + .fact + .source + .pieces() + .first() + .ok_or(FactError::MissingRecord)?; + let range = first.range(); + let end = fragment + .fact + .source + .pieces() + .last() + .ok_or(FactError::MissingRecord)? + .range() + .end; + Ok(( + range.start, + end, + document.fact.role.source_rank(), + document.ordinal, + )) + } + + fn check_scope(&self, reference: FactRef<'_, T>) -> Result<(), FactError> { + if std::ptr::eq(&raw const self.scope, reference.scope) { + Ok(()) + } else { + Err(FactError::ForeignIndex) + } + } +} + +/// Identity or storage lookup failure; not an empty owner query. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum FactError { + /// A handle belongs to another store, even if it borrows the same tree. + ForeignIndex, + /// The requested record or composition position does not exist. + MissingRecord, +} + +#[cfg(test)] +mod tests; diff --git a/big-code-analysis-ast/src/documentation/content.rs b/big-code-analysis-ast/src/documentation/content.rs new file mode 100644 index 000000000..3d0667613 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/content.rs @@ -0,0 +1,110 @@ +//! Local content states and forward-map coordinates, without a renderer. + +use super::SourcePieces; +use std::ops::Range; + +/// Document-local UTF-8 byte coordinates, distinct from source coordinates. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TextRange(Range); + +impl TextRange { + /// Validate a range against its output string. Empty ranges, including EOF, + /// are valid; endpoints inside a scalar are not. + /// + /// # Errors + /// Rejects reversed/out-of-bounds ranges or split UTF-8 scalars. + pub fn new(text: &str, range: Range) -> Result { + if range.start > range.end || range.end > text.len() { + return Err(TextRangeError::Bounds); + } + if !text.is_char_boundary(range.start) || !text.is_char_boundary(range.end) { + return Err(TextRangeError::ScalarBoundary); + } + Ok(Self(range)) + } + + /// Half-open output byte coordinates. + #[must_use] + pub fn range(&self) -> Range { + self.0.clone() + } +} + +/// Invalid output coordinates. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum TextRangeError { + /// Reversed or out-of-bounds range. + Bounds, + /// Endpoint inside a UTF-8 scalar. + ScalarBoundary, +} + +/// The source responsible for one output run. Disjoint included pieces stay +/// disjoint, including when a decoded token crosses an excluded range. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Origin<'s> { + /// A byte-for-byte copy; a subrange query clips its source correspondingly. + Copied(SourcePieces<'s>), + /// A decoded escape/token; any intersecting scalar returns the whole token. + Decoded(SourcePieces<'s>), + /// A token expanded to more bytes, such as indentation tabs. + Expanded(SourcePieces<'s>), + /// Inserted output, with no responsible source bytes. + Synthetic, +} + +/// One ordered output run and its origin. A complete map partitions the output; +/// validation and range queries are the text builder's responsibility. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Mapping<'s> { + /// Document-local output coordinates. + pub output: TextRange, + /// The source transformation for this run. + pub origin: Origin<'s>, +} + +/// Local prose state. Missing documentation is absence of a document, not a +/// variant here. Raw bytes remain on the document's physical fragments. +#[derive(Debug)] +#[non_exhaustive] +pub enum Content<'s> { + /// Complete decoded/cleaned local text; `""` is present-empty prose. + #[non_exhaustive] + Complete { + /// UTF-8 local markup, without generator expansion. + text: String, + /// Ordered forward origins; empty for empty text. + mappings: Vec>, + }, + /// Explicit `false` or equivalent source suppression. + Disabled, + /// Explicit nil/absence value, retained as a source occurrence. + ExplicitAbsence, + /// Documentation metadata with no prose value. + MetadataOnly, + /// A complete value cannot be provided; raw fragments are retained. + Unavailable(UnavailableReason), +} + +/// Why complete local text cannot be represented. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum UnavailableReason { + /// Dynamic interpolation, substitution or computed expression. + Dynamic, + /// External or macro-expanded content would require evaluation. + External, + /// Unsupported escape or semantic prelexing. + UnsupportedDecoding, + /// Invalid source encoding or escape spelling. + InvalidEncoding, + /// Decoding produces a value outside Unicode scalar values. + NonScalar, + /// Required content crosses excluded source bytes. + ExcludedGap, + /// Recovery or a known grammar limitation obscures content boundaries. + GrammarBoundary, +} diff --git a/big-code-analysis-ast/src/documentation/owners.rs b/big-code-analysis-ast/src/documentation/owners.rs new file mode 100644 index 000000000..dac119be2 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/owners.rs @@ -0,0 +1,159 @@ +//! Semantic owners and profile-qualified associations. + +use super::{DocumentId, NodeEvidence, OwnerId, SourcePieces}; + +/// A semantic source owner; none of these variants implies a metric space. +#[derive(Debug)] +#[non_exhaustive] +pub enum Owner<'s> { + /// A concrete declaration, including explicitly written constructors. + Node(NodeEvidence<'s>), + /// A location-backed field, parameter, property or binding. + Slot(Slot<'s>), + /// The file represented by this parse root. + File(NodeEvidence<'s>), + /// One logical declaration with ordered recovered pieces or explicit clauses. + Group(OwnerGroup<'s>), + /// An explicitly documented virtual target, never a fabricated syntax node. + Virtual(VirtualOwner<'s>), +} + +/// A source slot that need not have its own syntax node. +#[derive(Debug)] +#[non_exhaustive] +pub struct Slot<'s> { + pub(crate) enclosing: OwnerId, + /// The slot's semantic role, independent of grammar kind IDs. + pub role: SlotRole, + /// Zero-based ordinal within that enclosing owner's role. + pub ordinal: usize, + /// Included source spelling identifying this slot. + pub source: SourcePieces<'s>, +} + +/// Location-backed owner roles. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SlotRole { + /// Named or positional field. + Field, + /// Function/type parameter. + Parameter, + /// Property, including promoted constructor parameters. + Property, + /// Binding or declared constant. + Binding, +} + +/// One contributing declaration piece, not an envelope across intervening code. +#[derive(Debug)] +#[non_exhaustive] +pub struct OwnerPiece<'s> { + /// Included source spelling of this piece. + pub source: SourcePieces<'s>, + /// Exact syntax evidence when present. + pub node: Option>, +} + +/// One source-written declaration group, without synthesized arities or symbols. +#[derive(Debug)] +#[non_exhaustive] +pub struct OwnerGroup<'s> { + /// Lexical enclosing context used to qualify this group. + pub scope: NodeEvidence<'s>, + /// Ordered explicit heads, clauses or recovered declaration pieces. + pub pieces: Vec>, +} + +/// An explicit virtual declaration described by local markup. +#[derive(Debug)] +#[non_exhaustive] +pub struct VirtualOwner<'s> { + /// Included name spelling; byte-backed even when not UTF-8. + pub name: SourcePieces<'s>, + /// The directive spelling that establishes this virtual owner. + pub declaration: SourcePieces<'s>, +} + +/// Attachment disposition. A resolved set asserts every retained owner; +/// alternatives preserve uncertainty and assert none of them individually. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Resolution { + /// Every listed qualifying owner is resolved. + Resolved, + /// Available candidates with an explicit reason resolution failed. + Unresolved(UnresolvedReason), + /// Source evidence without a selected owner. + Unattached, +} + +/// Why an association is not a concrete owner claim. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum UnresolvedReason { + /// Mutually conditional source alternatives. + Conditional, + /// Several same-file matches with insufficient disambiguation. + Ambiguous, + /// No matching source target. + MissingName, + /// Name or target requires execution. + Dynamic, + /// Macro expansion or quoted code does not establish a concrete owner. + Expansion, + /// Recovery or known grammar boundaries are insufficient. + GrammarBoundary, +} + +/// Known publication eligibility under a convention, separate from attachment. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Publication { + /// Known eligible under the named profile/context. + Eligible, + /// Source docs exist but the named profile excludes publication. + Ineligible, + /// Not enough context to decide, or runtime existence is unknown. + Unknown, +} + +/// A named attachment convention. The adapter supplies its contract name; +/// this is neither an inferred language nor an invitation to mix profiles. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Convention(pub(crate) &'static str); + +impl Convention { + /// Contract-qualified name, such as `BcaPhpSource` or `PhpDocumentor`. + #[must_use] + pub fn name(&self) -> &'static str { + self.0 + } +} + +/// An attachment edge/set sharing its document with any other associations. +#[derive(Debug)] +#[non_exhaustive] +pub struct Association<'s> { + pub(crate) document: DocumentId, + pub(crate) owners: Vec, + /// Resolved set versus uncertain alternatives; never an existence boolean. + pub resolution: Resolution, + /// Convention responsible for selection and attachment. + pub convention: Convention, + /// Original wrapper seen by binding, such as `export` or an annotation. + pub binding: Option>, + /// Lexical containing scope, independently of normalized semantic owners. + pub lexical_scope: NodeEvidence<'s>, + /// Known publication result under the convention and supplied context. + pub publication: Publication, +} + +impl Association<'_> { + /// Number of resolved owners or uncertain candidates, as distinguished by + /// `resolution`. This is the qualifying subset, not all syntactic targets. + #[must_use] + pub fn owner_count(&self) -> usize { + self.owners.len() + } +} diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs new file mode 100644 index 000000000..f30df9f7e --- /dev/null +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -0,0 +1,167 @@ +//! Included raw source pieces and safe canonical-node evidence. + +use std::ops::Range; + +/// A nonempty, half-open source byte range and its borrowed raw bytes. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SourcePiece<'s> { + range: Range, + bytes: &'s [u8], +} + +impl<'s> SourcePiece<'s> { + /// Half-open byte coordinates in the actual parsed buffer. + #[must_use] + pub fn range(&self) -> Range { + self.range.clone() + } + + /// Raw bytes, without UTF-8 conversion or replacement characters. + #[must_use] + pub fn bytes(&self) -> &'s [u8] { + self.bytes + } +} + +/// Ordered intersections of one spelling with the tree's included ranges. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SourcePieces<'s> { + pieces: Vec>, + has_excluded_gap: bool, +} + +impl<'s> SourcePieces<'s> { + /// The individual pieces; intervening excluded bytes are never returned. + #[must_use] + pub fn pieces(&self) -> &[SourcePiece<'s>] { + &self.pieces + } + + /// Whether any of the requested spelling was excluded from parsing. + #[must_use] + pub fn has_excluded_gap(&self) -> bool { + self.has_excluded_gap + } +} + +/// Borrowed parse input with included ranges prepared once for binary search. +/// The caller must supply the exact buffer used to produce the tree. +#[derive(Debug)] +pub struct SourceContext<'s> { + tree: &'s tree_sitter::Tree, + bytes: &'s [u8], + included: Vec, +} + +impl<'s> SourceContext<'s> { + /// Bind the actual parsed source to its tree. This does not reparse or + /// infer completion; adopted/raw inputs retain the caller's precondition. + #[must_use] + pub fn new(tree: &'s tree_sitter::Tree, bytes: &'s [u8]) -> Self { + Self { + tree, + bytes, + included: tree.included_ranges(), + } + } + + /// Intersect a nonempty spelling in `O(log R + I)` work for R included + /// ranges and I returned pieces. No excluded bytes are copied or returned. + /// + /// # Errors + /// Rejects empty, reversed, out-of-buffer and wholly excluded spellings. + // bca: suppress(halstead.effort) -- one interval-intersection loop retains raw slices and excluded-gap evidence together. + pub fn pieces(&self, spelling: Range) -> Result, SourceError> { + if spelling.start >= spelling.end || spelling.end > self.bytes.len() { + return Err(SourceError::InvalidRange); + } + let first = self + .included + .partition_point(|range| range.end_byte <= spelling.start); + let mut pieces = Vec::new(); + let mut included_bytes = 0; + for range in &self.included[first..] { + if range.start_byte >= spelling.end { + break; + } + let start = spelling.start.max(range.start_byte); + let end = spelling.end.min(range.end_byte); + if start < end { + pieces.push(SourcePiece { + range: start..end, + bytes: &self.bytes[start..end], + }); + included_bytes += end - start; + } + } + if pieces.is_empty() { + return Err(SourceError::Excluded); + } + Ok(SourcePieces { + pieces, + has_excluded_gap: included_bytes != spelling.end - spelling.start, + }) + } + + /// Record a node reached canonically by a collector cursor. The caller + /// supplies canonical traversal context; foreign trees are rejected here. + /// Later validation compares against this retained value without parent walks. + /// + /// # Errors + /// Rejects a node from a different tree, including a cloned tree. + pub fn node(&self, canonical: tree_sitter::Node<'s>) -> Result, SourceError> { + if canonical.into_raw().tree != self.tree.root_node().into_raw().tree { + return Err(SourceError::ForeignTree); + } + Ok(NodeEvidence { canonical }) + } +} + +/// A safe borrowed canonical value; raw pointers are only compared transiently. +/// This retains the tree-sitter node's `Send + Sync` guarantees. +#[derive(Clone, Copy, Debug)] +pub struct NodeEvidence<'s> { + canonical: tree_sitter::Node<'s>, +} + +impl<'s> NodeEvidence<'s> { + /// Exact node recorded during canonical traversal. + #[must_use] + pub fn node(self) -> tree_sitter::Node<'s> { + self.canonical + } + + /// Validate tree and full node context rather than only ID or byte range. + /// + /// # Errors + /// Distinguishes foreign trees from changed/noncanonical node values. + pub fn validate(self, node: tree_sitter::Node<'_>) -> Result<(), SourceError> { + let expected = self.canonical.into_raw(); + let actual = node.into_raw(); + if actual.tree != expected.tree { + return Err(SourceError::ForeignTree); + } + if actual.id != expected.id + || actual.context != expected.context + || node.kind_id() != self.canonical.kind_id() + || node.range() != self.canonical.range() + { + return Err(SourceError::NoncanonicalNode); + } + Ok(()) + } +} + +/// Source evidence failures, distinct from text availability. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum SourceError { + /// Empty, reversed or out-of-buffer spelling. + InvalidRange, + /// No requested bytes were included in the parse. + Excluded, + /// A node belongs to another tree handle. + ForeignTree, + /// The held tree matches but canonical node context does not. + NoncanonicalNode, +} diff --git a/big-code-analysis-ast/src/documentation/streaming.rs b/big-code-analysis-ast/src/documentation/streaming.rs new file mode 100644 index 000000000..b6d632be9 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming.rs @@ -0,0 +1,107 @@ +//! Exact legacy intercrate event vocabulary. Not a stable documentation API. +//! Consumers retain event order and apply their existing row corrections; +//! source selection cannot be substituted for this stream after binding. + +use crate::Node; + +/// A legacy recognition/coverage event, emitted at the original callback point. +/// Root LOC retains row sets, physical space attribution and aggregation. +#[derive(Clone, Copy, Debug)] +#[non_exhaustive] +pub enum LegacyEvent<'t> { + /// Marker and placement answers for the current comment. Keeping them + /// separate permits Rust's marker-dependent newline correction at the root. + Comment { + /// The original syntax node, including any grammar-owned terminator. + node: Node<'t>, + /// Exact legacy marker answer, before binding selection. + marker: bool, + /// Exact unbound/placement decision, independently of source owners. + by_placement: bool, + }, + /// A bound/gathered comment, in the existing callback order. The root applies + /// its language-specific row span rather than a fragment spelling span. + BoundComment(Node<'t>), + /// Original POD/data row classification inside an opaque Perl node. + PerlDataRows(crate::lang_helpers::perl::PerlDataSectionRows), + /// Exact inclusive rows from a positional callback, including Python + /// parentheses. These are not reconstructed from cleaned text. + Coverage { + /// Which original callback supplied the rows. + kind: CoverageKind, + /// First zero-based source row, inclusive. + first: usize, + /// Last zero-based source row, inclusive. + last: usize, + }, +} + +/// The positional callback that produced legacy coverage. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum CoverageKind { + /// Go/Ruby/Lua comment-run callback. + LeadingRun, + /// Python primary/additional/attribute-string callback. + PythonStringRun, + /// Python Sphinx attribute-comment callback. + SphinxComment, +} + +// The marker/positional migrations wire these private requests into the shared +// scan. Keeping the lazy sink concrete here pins zero extra materialization +// without changing existing callbacks before their atomic root migration. +#[allow(dead_code)] +pub(crate) mod evidence { + use super::super::{Convention, NodeEvidence}; + + #[derive(Clone, Debug, PartialEq, Eq)] + pub(crate) enum View { + Legacy, + Source(Convention), + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub(crate) enum Question { + Candidate, + Placement, + Binding, + } + + #[derive(Clone, Debug)] + pub(crate) struct SelectionKey<'s> { + pub node: NodeEvidence<'s>, + pub view: View, + pub question: Question, + } + + impl PartialEq for SelectionKey<'_> { + fn eq(&self, other: &Self) -> bool { + self.view == other.view + && self.question == other.question + && self.node.validate(other.node.node()).is_ok() + } + } + impl Eq for SelectionKey<'_> {} + + pub(crate) enum Request<'a, E> { + LegacyOnly, + Source { + retain_unbound: bool, + sink: &'a mut dyn FnMut(E), + }, + } + + impl Request<'_, E> { + pub(crate) fn emit(&mut self, selected: bool, build: impl FnOnce() -> E) { + if let Self::Source { + retain_unbound, + sink, + } = self + && (selected || *retain_unbound) + { + sink(build()); + } + } + } +} diff --git a/big-code-analysis-ast/src/documentation/tests.rs b/big-code-analysis-ast/src/documentation/tests.rs new file mode 100644 index 000000000..eee2e2f17 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/tests.rs @@ -0,0 +1,305 @@ +#![allow(clippy::reversed_empty_ranges)] + +use super::*; +use crate::{AnyParser, LANG}; + +mod model_cases; +mod ownership; +mod provenance; +mod streaming; + +#[cfg(feature = "rust")] +#[test] +fn spelling_excludes_crlf_while_node_retains_it_and_equal_text_is_not_identity() { + let source = b"///same\r\n///same\r\nfn f() {}"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut facts = Facts::default(); + for (node, range) in parser.root_node().children().take(2).zip([0..7, 9..16]) { + facts.fragments.push(Fragment { + source: context.pieces(range).unwrap(), + node: Some(context.node(node.as_tree_sitter()).unwrap()), + form: FragmentForm::Comment, + }); + } + let fragments: Vec<_> = facts.fragments().collect(); + assert_eq!(fragments.len(), 2); + assert_ne!(fragments[0], fragments[1]); + assert_eq!(fragments[0], facts.fragments().next().unwrap()); + assert_eq!(fragments[0].get().source().pieces()[0].range(), 0..7); + assert_eq!(fragments[1].get().source().pieces()[0].range(), 9..16); + assert_eq!(fragments[0].get().source().pieces()[0].bytes(), b"///same"); + assert_eq!(fragments[1].get().source().pieces()[0].bytes(), b"///same"); + assert_eq!(fragments[0].get().node().unwrap().node().byte_range(), 0..9); + assert_eq!( + fragments[1].get().node().unwrap().node().byte_range(), + 9..18 + ); +} + +#[cfg(feature = "rust")] +#[test] +fn included_pieces_keep_raw_invalid_bytes_and_never_return_the_gap() { + let source = b"///a\xff\n///b\nfn f() {}"; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser + .set_included_ranges(&[ + tree_sitter::Range { + start_byte: 0, + end_byte: 5, + start_point: tree_sitter::Point::new(0, 0), + end_point: tree_sitter::Point::new(0, 5), + }, + tree_sitter::Range { + start_byte: 6, + end_byte: 20, + start_point: tree_sitter::Point::new(1, 0), + end_point: tree_sitter::Point::new(2, 9), + }, + ]) + .unwrap(); + let tree = parser.parse(source, None).unwrap(); + let context = SourceContext::new(&tree, source); + let pieces = context.pieces(0..10).unwrap(); + assert!(pieces.has_excluded_gap()); + assert_eq!(pieces.pieces().len(), 2); + assert_eq!(pieces.pieces()[0].range(), 0..5); + assert_eq!(pieces.pieces()[0].bytes(), b"///a\xff"); + assert_eq!(pieces.pieces()[1].range(), 6..10); + assert_eq!(pieces.pieces()[1].bytes(), b"///b"); + let mut facts = Facts::default(); + facts.fragments.push(Fragment { + source: pieces, + node: None, + form: FragmentForm::Comment, + }); + facts.documents.push(Document { + fragments: vec![FragmentId(0)], + composition: Composition::Single, + role: DocumentRole::LeadingComment, + content: Content::Unavailable(UnavailableReason::ExcludedGap), + }); + assert_eq!( + facts.document_order(facts.documents().next().unwrap()), + Ok((0, 10, 4, 0)) + ); + assert!(!context.pieces(6..10).unwrap().has_excluded_gap()); + assert_eq!(context.pieces(5..6), Err(SourceError::Excluded)); + for range in [0..0, 8..7, 0..21] { + assert_eq!(context.pieces(range), Err(SourceError::InvalidRange)); + } +} + +#[cfg(feature = "perl")] +#[test] +fn disjoint_pod_occurrences_can_share_one_opaque_node() { + let source = b"__END__\n=head1 A\n\na\n\n=cut\n\n=head1 B\n\nb\n\n=cut\n"; + let parser = AnyParser::parse(LANG::Perl, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let opaque = parser + .root_node() + .preorder() + .find(|node| node.kind() == "data_not_for_compiler") + .unwrap(); + let mut facts = Facts::default(); + for range in [8..25, 27..44] { + facts.fragments.push(Fragment { + source: context.pieces(range).unwrap(), + node: Some(context.node(opaque.as_tree_sitter()).unwrap()), + form: FragmentForm::Pod, + }); + } + let fragments: Vec<_> = facts.fragments().collect(); + assert_eq!(fragments.len(), 2); + assert_ne!(fragments[0], fragments[1]); + assert_eq!( + fragments[0].get().source().pieces()[0].bytes(), + b"=head1 A\n\na\n\n=cut" + ); + assert_eq!( + fragments[1].get().source().pieces()[0].bytes(), + b"=head1 B\n\nb\n\n=cut" + ); + assert_eq!( + fragments[0].get().node().unwrap().node(), + fragments[1].get().node().unwrap().node() + ); +} + +#[test] +fn text_coordinates_distinguish_scalars_empty_queries_and_origin_kinds() { + assert_eq!(TextRange::new("é!", 0..2).unwrap().range(), 0..2); + assert_eq!( + TextRange::new("é!", 0..1), + Err(TextRangeError::ScalarBoundary) + ); + assert_eq!( + TextRange::new("é!", 1..2), + Err(TextRangeError::ScalarBoundary) + ); + assert_eq!(TextRange::new("é!", 3..3).unwrap().range(), 3..3); + assert_eq!(TextRange::new("", 0..0).unwrap().range(), 0..0); + for range in [3..2, 4..4, 0..4] { + assert_eq!(TextRange::new("é!", range), Err(TextRangeError::Bounds)); + } +} + +#[cfg(feature = "python")] +#[test] +fn primary_additional_documents_differ_from_literal_concatenation() { + let source = b"def f():\n \"\"\n \"extra\"\n (\"@au\" # ordinary\n \"dit\")\n"; + let parser = AnyParser::parse(LANG::Python, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut facts = Facts::default(); + for range in [13..15, 20..27, 33..38, 55..60] { + facts.fragments.push(Fragment { + source: context.pieces(range).unwrap(), + node: None, + form: FragmentForm::Literal, + }); + } + facts.documents = vec![ + Document { + fragments: vec![FragmentId(0)], + composition: Composition::Single, + role: DocumentRole::Primary, + content: Content::Complete { + text: String::new(), + mappings: vec![], + }, + }, + Document { + fragments: vec![FragmentId(1)], + composition: Composition::Single, + role: DocumentRole::Additional, + content: Content::Complete { + text: "extra".into(), + mappings: vec![], + }, + }, + Document { + fragments: vec![FragmentId(2), FragmentId(3)], + composition: Composition::LiteralConcatenation, + role: DocumentRole::Additional, + content: Content::Complete { + text: "@audit".into(), + mappings: vec![], + }, + }, + ]; + let docs: Vec<_> = facts.documents().collect(); + assert_eq!(docs.len(), 3); + assert_eq!(docs[0].get().fragment_count(), 1); + assert_eq!(docs[2].get().fragment_count(), 2); + assert_eq!(docs[0].get().role(), DocumentRole::Primary); + assert_eq!(docs[1].get().role(), DocumentRole::Additional); + assert_eq!( + docs[2].get().composition(), + Composition::LiteralConcatenation + ); + assert_eq!( + facts + .document_fragment(docs[0], 0) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"\"\"" + ); + assert_eq!( + facts + .document_fragment(docs[1], 0) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"\"extra\"" + ); + assert_eq!( + facts + .document_fragment(docs[2], 0) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"\"@au\"" + ); + assert_eq!( + facts + .document_fragment(docs[2], 1) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"\"dit\"" + ); + assert_eq!(facts.document_order(docs[0]), Ok((13, 15, 0, 0))); + assert_eq!(facts.document_order(docs[1]), Ok((20, 27, 1, 1))); + assert_eq!(facts.document_order(docs[2]), Ok((33, 38, 1, 2))); +} + +#[cfg(feature = "elixir")] +#[test] +fn absent_disabled_metadata_empty_and_unavailable_have_physical_evidence() { + let source = b"@doc false\n@doc nil\n@doc since: \"1\"\n@doc \"\"\n@doc \"a#{x}b\""; + let parser = AnyParser::parse(LANG::Elixir, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut facts = Facts::default(); + let states = [ + Content::Disabled, + Content::ExplicitAbsence, + Content::MetadataOnly, + Content::Complete { + text: String::new(), + mappings: vec![], + }, + Content::Unavailable(UnavailableReason::Dynamic), + ]; + for (ordinal, (range, content)) in [0..10, 11..19, 20..35, 36..43, 44..57] + .into_iter() + .zip(states) + .enumerate() + { + facts.fragments.push(Fragment { + source: context.pieces(range).unwrap(), + node: None, + form: FragmentForm::Attribute, + }); + facts.documents.push(Document { + fragments: vec![FragmentId(ordinal)], + composition: Composition::Single, + role: DocumentRole::Primary, + content, + }); + } + let docs: Vec<_> = facts.documents().collect(); + assert_eq!(docs.len(), 5); + assert!(matches!(docs[0].get().content(), Content::Disabled)); + assert!(matches!(docs[1].get().content(), Content::ExplicitAbsence)); + assert!(matches!(docs[2].get().content(), Content::MetadataOnly)); + assert!( + matches!(docs[3].get().content(), Content::Complete { text, mappings } if text.is_empty() && mappings.is_empty()) + ); + assert!(matches!( + docs[4].get().content(), + Content::Unavailable(UnavailableReason::Dynamic) + )); + assert_eq!( + facts + .document_fragment(docs[4], 0) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"@doc \"a#{x}b\"" + ); + assert_eq!(Facts::default().documents().len(), 0); +} diff --git a/big-code-analysis-ast/src/documentation/tests/model_cases.rs b/big-code-analysis-ast/src/documentation/tests/model_cases.rs new file mode 100644 index 000000000..02480f9bd --- /dev/null +++ b/big-code-analysis-ast/src/documentation/tests/model_cases.rs @@ -0,0 +1,206 @@ +use super::*; + +#[cfg(feature = "ruby")] +#[test] +fn file_and_virtual_owners_retain_distinct_source_evidence() { + let source = b"# @!method ghost\n# audit\n"; + let parser = AnyParser::parse(LANG::Ruby, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let facts = Facts { + owners: vec![ + Owner::File(context.node(parser.ts_tree().root_node()).unwrap()), + Owner::Virtual(VirtualOwner { + name: context.pieces(11..16).unwrap(), + declaration: context.pieces(2..16).unwrap(), + }), + ], + ..Facts::default() + }; + let owners: Vec<_> = facts.owners().collect(); + assert_eq!(owners.len(), 2); + let Owner::File(file) = owners[0].get() else { + panic!("file owner"); + }; + assert_eq!(file.node().byte_range(), 0..27); + let Owner::Virtual(virtual_owner) = owners[1].get() else { + panic!("virtual owner"); + }; + assert_eq!(virtual_owner.name.pieces()[0].range(), 11..16); + assert_eq!(virtual_owner.name.pieces()[0].bytes(), b"ghost"); + assert_eq!( + virtual_owner.declaration.pieces()[0].bytes(), + b"@!method ghost" + ); +} + +#[cfg(feature = "php")] +#[test] +fn rejected_target_and_ordinary_doc_kind_remain_raw_evidence() { + use crate::{Ancestors, Checker, PhpCode, roles::php}; + let source = b" = first + .documents() + .map(|doc| first.document_order(doc).unwrap()) + .collect(); + assert_eq!( + keys, + [ + (0, 4, 0, 0), + (0, 4, 1, 1), + (0, 4, 2, 2), + (0, 4, 3, 3), + (0, 4, 4, 4), + (0, 4, 5, 5), + (0, 4, 6, 6), + (0, 4, 7, 7), + (0, 4, 8, 8) + ] + ); +} diff --git a/big-code-analysis-ast/src/documentation/tests/ownership.rs b/big-code-analysis-ast/src/documentation/tests/ownership.rs new file mode 100644 index 000000000..14ca6ae8c --- /dev/null +++ b/big-code-analysis-ast/src/documentation/tests/ownership.rs @@ -0,0 +1,221 @@ +use super::*; + +#[cfg(feature = "cpp")] +#[test] +fn one_document_shared_by_two_owners_is_not_two_alternative_claims() { + let source = b"/**both*/\nint a, b;"; + let parser = AnyParser::parse(LANG::Cpp, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let root = context.node(parser.ts_tree().root_node()).unwrap(); + let declaration = parser + .root_node() + .children() + .find(|node| node.kind() == "declaration") + .unwrap(); + let mut facts = Facts::default(); + facts.fragments.push(Fragment { + source: context.pieces(0..9).unwrap(), + node: None, + form: FragmentForm::Comment, + }); + facts.documents.push(Document { + fragments: vec![FragmentId(0)], + composition: Composition::Single, + role: DocumentRole::LeadingComment, + content: Content::Complete { + text: "both".into(), + mappings: vec![], + }, + }); + let names: Vec<_> = declaration + .children() + .filter(|node| node.kind() == "identifier") + .collect(); + assert_eq!(names.len(), 2); + assert_eq!(names[0].as_tree_sitter().byte_range(), 14..15); + assert_eq!(names[1].as_tree_sitter().byte_range(), 17..18); + facts.owners.extend( + names + .iter() + .map(|node| Owner::Node(context.node(node.as_tree_sitter()).unwrap())), + ); + for resolution in [ + Resolution::Resolved, + Resolution::Unresolved(UnresolvedReason::Conditional), + ] { + facts.associations.push(Association { + document: DocumentId(0), + owners: vec![OwnerId(0), OwnerId(1)], + resolution, + convention: Convention("Doxygen"), + binding: Some(context.node(declaration.as_tree_sitter()).unwrap()), + lexical_scope: root, + publication: Publication::Unknown, + }); + } + let associations: Vec<_> = facts.associations().collect(); + assert_eq!(facts.documents().len(), 1); + assert_eq!(associations.len(), 2); + assert_eq!(associations[0].get().owner_count(), 2); + assert_eq!(associations[0].get().resolution, Resolution::Resolved); + assert_eq!( + associations[1].get().resolution, + Resolution::Unresolved(UnresolvedReason::Conditional) + ); + assert_eq!( + facts.associated_document(associations[0]).unwrap(), + facts.associated_document(associations[1]).unwrap() + ); + assert_ne!( + facts.associated_owner(associations[0], 0).unwrap(), + facts.associated_owner(associations[0], 1).unwrap() + ); + let foreign = Facts::default(); + assert_eq!( + foreign.associated_document(associations[0]), + Err(FactError::ForeignIndex) + ); + assert_eq!( + foreign.associated_owner(associations[0], 0), + Err(FactError::ForeignIndex) + ); + assert_eq!( + foreign.document_order(facts.documents().next().unwrap()), + Err(FactError::ForeignIndex) + ); + assert_eq!( + facts.associated_owner(associations[0], 2), + Err(FactError::MissingRecord) + ); + assert_eq!( + facts.document_fragment(facts.documents().next().unwrap(), 1), + Err(FactError::MissingRecord) + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn export_binding_wrapper_is_distinct_from_semantic_owner_and_lexical_scope() { + let source = b"/**audit*/\nexport function f() {}"; + let parser = AnyParser::parse(LANG::Typescript, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let wrapper = parser + .root_node() + .children() + .find(|node| node.kind() == "export_statement") + .unwrap(); + let owner = wrapper.child_by_field_name("declaration").unwrap(); + let mut facts = Facts::default(); + facts + .owners + .push(Owner::Node(context.node(owner.as_tree_sitter()).unwrap())); + facts.associations.push(Association { + document: DocumentId(0), + owners: vec![OwnerId(0)], + resolution: Resolution::Resolved, + convention: Convention("BcaTypescriptSource"), + binding: Some(context.node(wrapper.as_tree_sitter()).unwrap()), + lexical_scope: context.node(parser.ts_tree().root_node()).unwrap(), + publication: Publication::Unknown, + }); + let association = facts.associations().next().unwrap(); + assert_eq!( + association.get().binding.unwrap().node().byte_range(), + 11..33 + ); + assert_eq!(association.get().lexical_scope.node().byte_range(), 0..33); + let Owner::Node(owner) = facts.associated_owner(association, 0).unwrap().get() else { + panic!("concrete function owner"); + }; + assert_eq!(owner.node().byte_range(), 18..33); + assert_eq!(owner.node().kind(), "function_declaration"); +} + +#[cfg(feature = "rust")] +#[test] +fn slots_have_enclosing_owner_role_ordinal_and_source_without_fabricated_nodes() { + let source = b"struct S(///first\n u32, ///second\n u32);"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let item = parser.root_node().children().next().unwrap(); + let mut facts = Facts::default(); + facts + .owners + .push(Owner::Node(context.node(item.as_tree_sitter()).unwrap())); + for (ordinal, range) in [19..22, 35..38].into_iter().enumerate() { + facts.owners.push(Owner::Slot(Slot { + enclosing: OwnerId(0), + role: SlotRole::Field, + ordinal, + source: context.pieces(range).unwrap(), + })); + } + let owners: Vec<_> = facts.owners().collect(); + assert_eq!(owners.len(), 3); + assert_eq!(facts.slot_enclosing(owners[1]).unwrap(), owners[0]); + assert_eq!(facts.slot_enclosing(owners[2]).unwrap(), owners[0]); + let Owner::Slot(slot) = owners[2].get() else { + panic!("second slot"); + }; + assert_eq!(slot.role, SlotRole::Field); + assert_eq!(slot.ordinal, 1); + assert_eq!(slot.source.pieces()[0].range(), 35..38); + assert_eq!(slot.source.pieces()[0].bytes(), b"u32"); +} + +#[cfg(feature = "cpp")] +#[test] +fn recovered_owner_retains_ordered_pieces_without_an_envelope_claim() { + let source = b"/**audit*/\nvoid f() ???;"; + let parser = AnyParser::parse(LANG::Cpp, source.to_vec(), None, None).unwrap(); + assert!(parser.root_node().has_error()); + let context = SourceContext::new(parser.ts_tree(), source); + let owner = Owner::Group(OwnerGroup { + scope: context.node(parser.ts_tree().root_node()).unwrap(), + pieces: vec![ + OwnerPiece { + source: context.pieces(11..15).unwrap(), + node: None, + }, + OwnerPiece { + source: context.pieces(16..19).unwrap(), + node: None, + }, + ], + }); + let Owner::Group(group) = owner else { + panic!("recovered group"); + }; + assert_eq!(group.pieces.len(), 2); + assert_eq!(group.pieces[0].source.pieces()[0].range(), 11..15); + assert_eq!(group.pieces[0].source.pieces()[0].bytes(), b"void"); + assert_eq!(group.pieces[1].source.pieces()[0].range(), 16..19); + assert_eq!(group.pieces[1].source.pieces()[0].bytes(), b"f()"); +} + +#[cfg(feature = "java")] +#[test] +fn record_type_owner_does_not_become_the_synthetic_header_space() { + use crate::{Ancestors, Checker, JavaCode}; + let source = b"/**audit*/\nrecord R(int a) {}"; + let parser = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let record = parser + .root_node() + .children() + .find(|node| node.kind() == "record_declaration") + .unwrap(); + let header = record.child_by_field_name("parameters").unwrap(); + assert!(JavaCode::is_func_space_with_code( + &header, + source, + Ancestors::unknown() + )); + let owner = Owner::Node(context.node(record.as_tree_sitter()).unwrap()); + let Owner::Node(node) = owner else { + panic!("record owner"); + }; + assert_eq!(node.node().kind(), "record_declaration"); + assert_eq!(node.node().byte_range(), 11..29); + assert_eq!(header.as_tree_sitter().byte_range(), 19..26); +} diff --git a/big-code-analysis-ast/src/documentation/tests/provenance.rs b/big-code-analysis-ast/src/documentation/tests/provenance.rs new file mode 100644 index 000000000..8e775734a --- /dev/null +++ b/big-code-analysis-ast/src/documentation/tests/provenance.rs @@ -0,0 +1,130 @@ +use super::super::{SourceContext, SourceError}; +use crate::cancel::ParseCancel; +use crate::parser::ParseCompletion; +use crate::{AnyParser, LANG, ParserTrait, RustParser}; + +#[cfg(feature = "rust")] +#[test] +fn actual_abort_survives_scope_exit_and_next_parse_completes() { + let source = "fn f() { let x = 1; }\n".repeat(200).into_bytes(); + let cancel = ParseCancel::new(); + cancel.cancel(); + let parsed = cancel.run(|| AnyParser::parse(LANG::Rust, source, None, None).unwrap()); + assert!(!crate::cancel::requested()); + assert_eq!(parsed.parse_completion(), ParseCompletion::Cancelled); + assert_eq!(parsed.root_node().start_byte(), 0); + assert_eq!(parsed.root_node().end_byte(), 0); + assert_eq!(parsed.root_node().child_count(), 0); + + let next = AnyParser::parse(LANG::Rust, b"fn g() {}".to_vec(), None, None).unwrap(); + assert_eq!(next.parse_completion(), ParseCompletion::Complete); + assert_eq!(next.root_node().end_byte(), 9); + assert_eq!( + next.root_node().children().next().unwrap().kind(), + "function_item" + ); +} + +#[cfg(feature = "rust")] +#[test] +fn empty_and_error_parses_are_complete_and_later_flags_do_not_change_them() { + let empty = RustParser::new(vec![], std::path::Path::new(""), None); + let malformed = RustParser::new(b"fn {".to_vec(), std::path::Path::new(""), None); + assert_eq!(empty.parse_completion(), ParseCompletion::Complete); + assert_eq!(empty.root().end_byte(), 0); + assert!(malformed.root().has_error()); + assert_eq!(malformed.parse_completion(), ParseCompletion::Complete); + let cancel = ParseCancel::new(); + cancel.cancel(); + cancel.run(|| assert_eq!(empty.parse_completion(), ParseCompletion::Complete)); + // This input completes before the runtime's first progress callback. + let under_flag = cancel.run(|| RustParser::new(vec![], std::path::Path::new(""), None)); + assert_eq!(under_flag.parse_completion(), ParseCompletion::Complete); +} + +#[cfg(feature = "rust")] +#[test] +fn adopted_restricted_parse_retains_caller_provenance() { + let source = b"///x\n\nfn f() {}"; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser + .set_included_ranges(&[ + tree_sitter::Range { + start_byte: 0, + end_byte: 4, + start_point: tree_sitter::Point::new(0, 0), + end_point: tree_sitter::Point::new(0, 4), + }, + tree_sitter::Range { + start_byte: 6, + end_byte: 15, + start_point: tree_sitter::Point::new(2, 0), + end_point: tree_sitter::Point::new(2, 9), + }, + ]) + .unwrap(); + let tree = parser.parse(source, None).unwrap(); + let adopted = AnyParser::from_tree(LANG::Rust, tree, source.to_vec()).unwrap(); + assert_eq!(adopted.parse_completion(), ParseCompletion::Adopted); + assert_eq!(adopted.ts_tree().included_ranges().len(), 2); + assert_eq!(adopted.root_node().end_byte(), 15); + let empty = parser.parse(b"", None).unwrap(); + let empty = RustParser::from_tree(empty, vec![]); + assert_eq!(empty.parse_completion(), ParseCompletion::Adopted); +} + +#[cfg(feature = "rust")] +#[test] +fn canonical_evidence_rejects_clones_shifted_roots_and_edited_values() { + let parser = AnyParser::parse(LANG::Rust, b"fn f() {}".to_vec(), None, None).unwrap(); + let second = AnyParser::parse(LANG::Rust, b"fn f() {}".to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let root = parser.ts_tree().root_node(); + let canonical = context.node(root).unwrap(); + assert_eq!(canonical.validate(root), Ok(())); + assert_eq!( + canonical.validate(second.ts_tree().root_node()), + Err(SourceError::ForeignTree) + ); + let cloned = parser.ts_tree().clone(); + assert_eq!( + canonical.validate(cloned.root_node()), + Err(SourceError::ForeignTree) + ); + assert!(matches!( + context.node(cloned.root_node()), + Err(SourceError::ForeignTree) + )); + let shifted = parser + .ts_tree() + .root_node_with_offset(5, tree_sitter::Point::new(1, 2)); + assert_eq!( + canonical.validate(shifted), + Err(SourceError::NoncanonicalNode) + ); + let mut edited = root; + edited.edit(&tree_sitter::InputEdit { + start_byte: 0, + old_end_byte: 0, + new_end_byte: 1, + start_position: tree_sitter::Point::new(0, 0), + old_end_position: tree_sitter::Point::new(0, 0), + new_end_position: tree_sitter::Point::new(0, 1), + }); + assert_eq!( + canonical.validate(edited), + Err(SourceError::NoncanonicalNode) + ); +} + +#[test] +fn retained_parser_and_facts_are_send_sync() { + fn require() {} + require::(); + require::>(); + require::>>(); + require::>(); +} diff --git a/big-code-analysis-ast/src/documentation/tests/streaming.rs b/big-code-analysis-ast/src/documentation/tests/streaming.rs new file mode 100644 index 000000000..769e486da --- /dev/null +++ b/big-code-analysis-ast/src/documentation/tests/streaming.rs @@ -0,0 +1,138 @@ +use super::super::streaming::{ + CoverageKind, LegacyEvent, + evidence::{Question, Request, SelectionKey, View}, +}; +use super::*; + +#[test] +fn extra_evidence_is_lazy_and_unbound_retention_is_explicit() { + let builds = std::cell::Cell::new(0); + let build = || { + builds.set(builds.get() + 1); + 7 + }; + let mut legacy = Request::LegacyOnly; + legacy.emit(true, build); + legacy.emit(false, build); + assert_eq!(builds.get(), 0); + let mut events = Vec::new(); + let mut sink = |event| events.push(event); + let mut source = Request::Source { + retain_unbound: false, + sink: &mut sink, + }; + source.emit(false, build); + assert_eq!(builds.get(), 0); + source.emit(true, build); + assert_eq!(builds.get(), 1); + let mut evidence = Request::Source { + retain_unbound: true, + sink: &mut sink, + }; + evidence.emit(false, build); + assert_eq!(builds.get(), 2); + assert_eq!(events, [7, 7]); +} + +#[cfg(feature = "java")] +#[test] +fn selection_identity_includes_view_profile_question_and_canonical_context() { + let parser = AnyParser::parse(LANG::Java, b"/**/\nclass C {}".to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let node = context.node(parser.ts_tree().root_node()).unwrap(); + let legacy = SelectionKey { + node, + view: View::Legacy, + question: Question::Candidate, + }; + let same = SelectionKey { + node, + view: View::Legacy, + question: Question::Candidate, + }; + assert_eq!(legacy, same); + assert_ne!( + legacy, + SelectionKey { + node, + view: View::Source(Convention("Jdk25")), + question: Question::Candidate + } + ); + assert_ne!( + legacy, + SelectionKey { + node, + view: View::Legacy, + question: Question::Placement + } + ); + let source = SelectionKey { + node, + view: View::Source(Convention("Jdk25")), + question: Question::Binding, + }; + assert_ne!( + source, + SelectionKey { + node, + view: View::Source(Convention("BcaOther")), + question: Question::Binding + } + ); + let shifted = context + .node( + parser + .ts_tree() + .root_node_with_offset(2, tree_sitter::Point::new(1, 0)), + ) + .unwrap(); + assert_ne!( + legacy, + SelectionKey { + node: shifted, + view: View::Legacy, + question: Question::Candidate + } + ); +} + +#[cfg(feature = "java")] +#[test] +fn legacy_events_preserve_marker_vs_placement_and_inclusive_coverage_order() { + let parser = AnyParser::parse(LANG::Java, b"/**/\nclass C {}".to_vec(), None, None).unwrap(); + let node = parser.root_node().children().next().unwrap(); + let events = [ + LegacyEvent::Comment { + node, + marker: false, + by_placement: true, + }, + LegacyEvent::BoundComment(node), + LegacyEvent::Coverage { + kind: CoverageKind::PythonStringRun, + first: 3, + last: 7, + }, + ]; + assert!(matches!( + events[0], + LegacyEvent::Comment { + marker: false, + by_placement: true, + .. + } + )); + let LegacyEvent::BoundComment(bound) = events[1] else { + panic!("bound event"); + }; + assert_eq!(bound.as_tree_sitter().byte_range(), 0..4); + assert!(matches!( + events[2], + LegacyEvent::Coverage { + kind: CoverageKind::PythonStringRun, + first: 3, + last: 7 + } + )); +} diff --git a/big-code-analysis-ast/src/lib.rs b/big-code-analysis-ast/src/lib.rs index cf73abbd2..4882bdd31 100644 --- a/big-code-analysis-ast/src/lib.rs +++ b/big-code-analysis-ast/src/lib.rs @@ -97,6 +97,7 @@ pub(crate) mod cfg_predicate; pub mod checker; pub(crate) mod comment_rm; pub mod count; +pub mod documentation; pub mod error; pub(crate) mod find; pub mod getter; diff --git a/big-code-analysis-ast/src/macros/mod.rs b/big-code-analysis-ast/src/macros/mod.rs index 0d86257f3..dcbd3dadd 100644 --- a/big-code-analysis-ast/src/macros/mod.rs +++ b/big-code-analysis-ast/src/macros/mod.rs @@ -389,6 +389,12 @@ macro_rules! mk_action { $crate::with_any_parser!(self, |p| p.ts_tree()) } + /// The outcome retained when this tree was parsed or adopted. + #[must_use] + pub fn parse_completion(&self) -> $crate::parser::ParseCompletion { + $crate::with_any_parser!(self, |p| p.parse_completion()) + } + /// The root [`Node`] of the held tree. #[must_use] pub fn root_node(&self) -> Node<'_> { diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index b2b3dd5bf..faf6ac8bb 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -87,7 +87,10 @@ crate::observation::counter!(child_scan_cursors, cfg(any(test, feature = "test-s /// caller-built `tree_sitter::Tree` directly; this wrapper stays /// internal so the metric walker is the only thing that observes it. #[derive(Clone, Debug)] -pub(crate) struct Tree(OtherTree); +pub(crate) struct Tree { + tree: OtherTree, + completion: crate::parser::ParseCompletion, +} impl Tree { /// # Panics @@ -108,19 +111,27 @@ impl Tree { let language = T::lang().get_ts_language().expect( "invariant: the caller checked LANG::is_enabled, or reached this through AnyParser", ); - Self(parse_on_scratch_parser(&language, code)) + let (tree, completion) = parse_on_scratch_parser(&language, code); + Self { tree, completion } } pub(crate) fn from_ts_tree(tree: OtherTree) -> Self { - Self(tree) + Self { + tree, + completion: crate::parser::ParseCompletion::Adopted, + } } pub(crate) fn get_root(&self) -> Node<'_> { - Node(self.0.root_node()) + Node(self.tree.root_node()) } pub(crate) fn as_ts_tree(&self) -> &OtherTree { - &self.0 + &self.tree + } + + pub(crate) fn completion(&self) -> crate::parser::ParseCompletion { + self.completion } } diff --git a/big-code-analysis-ast/src/node/parser_cache.rs b/big-code-analysis-ast/src/node/parser_cache.rs index 35c5c99ac..075d22038 100644 --- a/big-code-analysis-ast/src/node/parser_cache.rs +++ b/big-code-analysis-ast/src/node/parser_cache.rs @@ -27,6 +27,8 @@ use std::ops::ControlFlow; use tree_sitter::{Language, ParseOptions, ParseState, Parser, Tree}; +use crate::parser::ParseCompletion; + thread_local! { /// The parser this thread reuses across the files it analyzes. static SCRATCH_PARSER: Cell> = const { Cell::new(None) }; @@ -56,14 +58,15 @@ crate::observation::counter!(parsers_built); /// the cached parser and the thread that built it. /// /// Under a cancelled [`crate::cancel::ParseCancel`] the parse stops and -/// this returns the tree of an empty input instead (#1939). The stop is a +/// this returns the tree of an empty input with retained cancelled provenance. +/// The stop is a /// per-call progress callback, not parser state; the parser is reset /// after it, because a stopped parser resumes where it left off on the /// next call. Nothing in this crate sets a timeout, a cancellation flag, /// or included ranges, which *are* parser state: `set_language` does not /// clear those, so anything that starts setting one must clear it before /// the parser goes back. -pub fn parse_on_scratch_parser(language: &Language, code: &[u8]) -> Tree { +pub(super) fn parse_on_scratch_parser(language: &Language, code: &[u8]) -> (Tree, ParseCompletion) { let mut parser = SCRATCH_PARSER .try_with(Cell::take) .ok() @@ -74,15 +77,18 @@ pub fn parse_on_scratch_parser(language: &Language, code: &[u8]) -> Tree { parser .set_language(language) .expect("invariant: grammar version is pinned and compatible with bundled tree-sitter"); - let tree = parse_unless_cancelled(&mut parser, code).unwrap_or_else(|| { + let result = if let Some(tree) = parse_unless_cancelled(&mut parser, code) { + (tree, ParseCompletion::Complete) + } else { parser.reset(); - parser + let tree = parser .parse(b"", None) - .expect("invariant: parser has a language set and nothing stops this parse") - }); + .expect("invariant: parser has a language set and nothing stops this parse"); + (tree, ParseCompletion::Cancelled) + }; // Dropped rather than cached when the slot is already gone. let _ = SCRATCH_PARSER.try_with(|slot| slot.set(Some(parser))); - tree + result } /// Parses `code`, or answers `None` once the [`crate::cancel`] flag @@ -148,7 +154,7 @@ mod tests { ); let language = rust_language(); for i in 0..PARSES { - let tree = parse_on_scratch_parser(&language, b"fn f() { let x = 1; }"); + let (tree, _) = parse_on_scratch_parser(&language, b"fn f() { let x = 1; }"); assert!( !tree.root_node().to_sexp().contains("ERROR"), "parse {i} must succeed" @@ -178,12 +184,15 @@ mod tests { let long = "fn f() { let x = 1; }\n".repeat(200); let cancel = crate::cancel::ParseCancel::new(); cancel.cancel(); - let stopped = cancel.run(|| parse_on_scratch_parser(&language, long.as_bytes())); + let (stopped, completion) = + cancel.run(|| parse_on_scratch_parser(&language, long.as_bytes())); + assert_eq!(completion, ParseCompletion::Cancelled); assert_eq!(stopped.root_node().byte_range(), 0..0); assert_eq!(stopped.root_node().child_count(), 0); let code = b"fn g() { let y = 2; }"; - let next = parse_on_scratch_parser(&language, code); + let (next, completion) = parse_on_scratch_parser(&language, code); + assert_eq!(completion, ParseCompletion::Complete); let mut fresh = Parser::new(); fresh .set_language(&language) @@ -201,8 +210,9 @@ mod tests { fn an_uncancelled_flag_parses_in_full() { let language = rust_language(); let code = "fn f() { let x = 1; }\n".repeat(200); - let tree = crate::cancel::ParseCancel::new() + let (tree, completion) = crate::cancel::ParseCancel::new() .run(|| parse_on_scratch_parser(&language, code.as_bytes())); + assert_eq!(completion, ParseCompletion::Complete); assert_eq!(tree.root_node().byte_range(), 0..code.len()); assert!(!tree.root_node().has_error()); } diff --git a/big-code-analysis-ast/src/parser.rs b/big-code-analysis-ast/src/parser.rs index c0cf5ace3..b8a265c24 100644 --- a/big-code-analysis-ast/src/parser.rs +++ b/big-code-analysis-ast/src/parser.rs @@ -24,6 +24,19 @@ use crate::node::{Node, Tree}; use crate::preproc::{PreprocResults, visible_macros}; use crate::traits::*; +/// Provenance of the held parse, independent of its shape or syntax errors. +/// This direct-AST plumbing is not a stable root-library API. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum ParseCompletion { + /// The parser returned a tree for the supplied input. + Complete, + /// The progress callback stopped parsing; metrics see the legacy empty tree. + Cancelled, + /// The caller supplied the tree and is responsible for completeness. + Adopted, +} + /// Parsed source plus the tree-sitter `Tree` for a given language `T`. /// /// Construct with [`Parser::new`] and feed the result into the metric, @@ -234,6 +247,8 @@ impl Parser { /// not `unsafe`, but metric values will be nonsensical because /// the tree's `kind_id` values will not correspond to the per- /// language enum the metric `compute` functions match on. + /// Documentation consumers additionally require a complete parse; adoption + /// records caller-supplied provenance rather than verifying completeness. #[must_use] pub fn from_tree(tree: tree_sitter::Tree, code: Vec) -> Self { Self { @@ -253,6 +268,13 @@ impl Parser { pub fn ts_tree(&self) -> &tree_sitter::Tree { self.tree.as_ts_tree() } + + /// The outcome retained when this tree was parsed or adopted. + /// An active cancellation flag does not change an earlier outcome. + #[must_use] + pub fn parse_completion(&self) -> ParseCompletion { + self.tree.completion() + } } #[cfg(test)] diff --git a/tests/api/parser_reuse.rs b/tests/api/parser_reuse.rs index a7f605e15..fa926af7c 100644 --- a/tests/api/parser_reuse.rs +++ b/tests/api/parser_reuse.rs @@ -33,6 +33,28 @@ use std::sync::atomic::{AtomicBool, Ordering}; use big_code_analysis::{Ast, LANG, Source, tree_sitter}; +#[cfg(feature = "rust")] +#[test] +fn retained_parse_provenance_preserves_legacy_cancelled_metrics() { + let source = "/// doc\nfn f() {}\n".repeat(200); + let cancel = big_code_analysis::ParseCancel::new(); + cancel.cancel(); + let stopped = cancel.run(|| Ast::parse(Source::new(LANG::Rust, source.as_bytes())).unwrap()); + assert_eq!(stopped.as_tree_sitter().root_node().byte_range(), 0..0); + assert_eq!(stopped.source(), source.as_bytes()); + let metrics = stopped + .metrics(big_code_analysis::MetricsOptions::default()) + .unwrap(); + assert!(metrics.spaces.is_empty()); + assert_eq!(metrics.metrics.loc.dloc(), 0); + let next = Ast::parse(Source::new(LANG::Rust, b"/// doc\nfn g() {}\n")).unwrap(); + let metrics = next + .metrics(big_code_analysis::MetricsOptions::default()) + .unwrap(); + assert_eq!(metrics.spaces.len(), 1); + assert_eq!(metrics.metrics.loc.dloc(), 1); +} + #[cfg(any(feature = "rust", feature = "typescript"))] const RUST_SRC: &str = r#" fn classify(n: i32) -> &'static str { diff --git a/utils/documentation-facts-perturb.json b/utils/documentation-facts-perturb.json new file mode 100644 index 000000000..6b3777138 --- /dev/null +++ b/utils/documentation-facts-perturb.json @@ -0,0 +1,70 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "retained-abort-is-not-complete", + "file": "big-code-analysis-ast/src/node/parser_cache.rs", + "old": "(tree, ParseCompletion::Cancelled)", + "new": "(tree, ParseCompletion::Complete)", + "expect": ["documentation::tests::provenance::actual_abort_survives_scope_exit_and_next_parse_completes"] + }, + { + "name": "adoption-is-not-internally-verified", + "file": "big-code-analysis-ast/src/node.rs", + "old": "completion: crate::parser::ParseCompletion::Adopted,", + "new": "completion: crate::parser::ParseCompletion::Complete,", + "expect": ["documentation::tests::provenance::adopted_restricted_parse_retains_caller_provenance"] + }, + { + "name": "included-piece-start-is-exact", + "file": "big-code-analysis-ast/src/documentation/source.rs", + "old": "let start = spelling.start.max(range.start_byte);", + "new": "let start = spelling.start.max(range.start_byte) + 1;", + "expect": ["documentation::tests::included_pieces_keep_raw_invalid_bytes_and_never_return_the_gap"] + }, + { + "name": "occurrence-equality-needs-ordinal", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "std::ptr::eq(self.scope, other.scope) && self.ordinal == other.ordinal", + "new": "std::ptr::eq(self.scope, other.scope)", + "expect": ["documentation::tests::spelling_excludes_crlf_while_node_retains_it_and_equal_text_is_not_identity"] + }, + { + "name": "occurrence-equality-needs-store", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "std::ptr::eq(self.scope, other.scope) && self.ordinal == other.ordinal", + "new": "self.ordinal == other.ordinal", + "expect": ["documentation::tests::model_cases::independent_stores_have_distinct_handles_and_explicit_role_order"] + }, + { + "name": "lookup-rejects-foreign-store", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "if std::ptr::eq(&raw const self.scope, reference.scope) {", + "new": "if true || std::ptr::eq(&raw const self.scope, reference.scope) {", + "expect": ["documentation::tests::ownership::one_document_shared_by_two_owners_is_not_two_alternative_claims"] + }, + { + "name": "selection-identity-needs-view", + "file": "big-code-analysis-ast/src/documentation/streaming.rs", + "old": "self.view == other.view", + "new": "true", + "expect": ["documentation::tests::streaming::selection_identity_includes_view_profile_question_and_canonical_context"] + }, + { + "name": "requested-unbound-evidence-is-materialized", + "file": "big-code-analysis-ast/src/documentation/streaming.rs", + "old": "&& (selected || *retain_unbound)", + "new": "&& (selected && *retain_unbound)", + "expect": ["documentation::tests::streaming::extra_evidence_is_lazy_and_unbound_retention_is_explicit"] + }, + { + "name": "output-endpoints-cannot-split-scalars", + "file": "big-code-analysis-ast/src/documentation/content.rs", + "old": "if !text.is_char_boundary(range.start) || !text.is_char_boundary(range.end) {", + "new": "if false {", + "expect": ["documentation::tests::text_coordinates_distinguish_scalars_empty_queries_and_origin_kinds"] + } + ] +} From 10227e77320f479972ed50f3c28a1b666fb19485 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:26:37 -0800 Subject: [PATCH 005/221] test(ast): use exact cancelled metric space count --- tests/api/parser_reuse.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/api/parser_reuse.rs b/tests/api/parser_reuse.rs index fa926af7c..439addbeb 100644 --- a/tests/api/parser_reuse.rs +++ b/tests/api/parser_reuse.rs @@ -45,7 +45,7 @@ fn retained_parse_provenance_preserves_legacy_cancelled_metrics() { let metrics = stopped .metrics(big_code_analysis::MetricsOptions::default()) .unwrap(); - assert!(metrics.spaces.is_empty()); + assert_eq!(metrics.spaces.len(), 0); assert_eq!(metrics.metrics.loc.dloc(), 0); let next = Ast::parse(Source::new(LANG::Rust, b"/// doc\nfn g() {}\n")).unwrap(); let metrics = next From 740451a6f902181f00d1aca9fa299cde78596647 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:31:58 -0800 Subject: [PATCH 006/221] chore(ast): scope canonical Halstead suppression to intersection --- big-code-analysis-ast/src/documentation/source.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index f30df9f7e..9c2de4fe6 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -70,8 +70,8 @@ impl<'s> SourceContext<'s> { /// /// # Errors /// Rejects empty, reversed, out-of-buffer and wholly excluded spellings. - // bca: suppress(halstead.effort) -- one interval-intersection loop retains raw slices and excluded-gap evidence together. pub fn pieces(&self, spelling: Range) -> Result, SourceError> { + // bca: suppress(halstead) -- one interval-intersection loop retains raw slices and excluded-gap evidence together. if spelling.start >= spelling.end || spelling.end > self.bytes.len() { return Err(SourceError::InvalidRange); } From 97d7f3be19ff66cd78420a36491fedc9b53ffbc3 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:47:17 -0800 Subject: [PATCH 007/221] test(documentation): exercise nonzero fact lookup identities --- .../src/documentation/tests/ownership.rs | 54 +++++++++++++++---- utils/documentation-facts-perturb.json | 14 +++++ 2 files changed, 58 insertions(+), 10 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/tests/ownership.rs b/big-code-analysis-ast/src/documentation/tests/ownership.rs index 14ca6ae8c..3b211b25f 100644 --- a/big-code-analysis-ast/src/documentation/tests/ownership.rs +++ b/big-code-analysis-ast/src/documentation/tests/ownership.rs @@ -96,7 +96,7 @@ fn one_document_shared_by_two_owners_is_not_two_alternative_claims() { #[cfg(feature = "typescript")] #[test] fn export_binding_wrapper_is_distinct_from_semantic_owner_and_lexical_scope() { - let source = b"/**audit*/\nexport function f() {}"; + let source = b"/**old*/\n/**audit*/\nexport function f() {}"; let parser = AnyParser::parse(LANG::Typescript, source.to_vec(), None, None).unwrap(); let context = SourceContext::new(parser.ts_tree(), source); let wrapper = parser @@ -106,11 +106,27 @@ fn export_binding_wrapper_is_distinct_from_semantic_owner_and_lexical_scope() { .unwrap(); let owner = wrapper.child_by_field_name("declaration").unwrap(); let mut facts = Facts::default(); + for (ordinal, (range, text)) in [(0..8, "old"), (9..19, "audit")].into_iter().enumerate() { + facts.fragments.push(Fragment { + source: context.pieces(range).unwrap(), + node: None, + form: FragmentForm::Comment, + }); + facts.documents.push(Document { + fragments: vec![FragmentId(ordinal)], + composition: Composition::Single, + role: DocumentRole::LeadingComment, + content: Content::Complete { + text: text.into(), + mappings: vec![], + }, + }); + } facts .owners .push(Owner::Node(context.node(owner.as_tree_sitter()).unwrap())); facts.associations.push(Association { - document: DocumentId(0), + document: DocumentId(1), owners: vec![OwnerId(0)], resolution: Resolution::Resolved, convention: Convention("BcaTypescriptSource"), @@ -119,15 +135,30 @@ fn export_binding_wrapper_is_distinct_from_semantic_owner_and_lexical_scope() { publication: Publication::Unknown, }); let association = facts.associations().next().unwrap(); + let documents: Vec<_> = facts.documents().collect(); + assert_eq!(documents.len(), 2); + let selected = facts.associated_document(association).unwrap(); + assert_eq!(selected, documents[1]); + assert_ne!(selected, documents[0]); + assert_eq!( + facts + .document_fragment(selected, 0) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"/**audit*/" + ); assert_eq!( association.get().binding.unwrap().node().byte_range(), - 11..33 + 20..42 ); - assert_eq!(association.get().lexical_scope.node().byte_range(), 0..33); + assert_eq!(association.get().lexical_scope.node().byte_range(), 0..42); let Owner::Node(owner) = facts.associated_owner(association, 0).unwrap().get() else { panic!("concrete function owner"); }; - assert_eq!(owner.node().byte_range(), 18..33); + assert_eq!(owner.node().byte_range(), 27..42); assert_eq!(owner.node().kind(), "function_declaration"); } @@ -139,22 +170,25 @@ fn slots_have_enclosing_owner_role_ordinal_and_source_without_fabricated_nodes() let context = SourceContext::new(parser.ts_tree(), source); let item = parser.root_node().children().next().unwrap(); let mut facts = Facts::default(); + facts.owners.push(Owner::File( + context.node(parser.ts_tree().root_node()).unwrap(), + )); facts .owners .push(Owner::Node(context.node(item.as_tree_sitter()).unwrap())); for (ordinal, range) in [19..22, 35..38].into_iter().enumerate() { facts.owners.push(Owner::Slot(Slot { - enclosing: OwnerId(0), + enclosing: OwnerId(1), role: SlotRole::Field, ordinal, source: context.pieces(range).unwrap(), })); } let owners: Vec<_> = facts.owners().collect(); - assert_eq!(owners.len(), 3); - assert_eq!(facts.slot_enclosing(owners[1]).unwrap(), owners[0]); - assert_eq!(facts.slot_enclosing(owners[2]).unwrap(), owners[0]); - let Owner::Slot(slot) = owners[2].get() else { + assert_eq!(owners.len(), 4); + assert_eq!(facts.slot_enclosing(owners[2]).unwrap(), owners[1]); + assert_eq!(facts.slot_enclosing(owners[3]).unwrap(), owners[1]); + let Owner::Slot(slot) = owners[3].get() else { panic!("second slot"); }; assert_eq!(slot.role, SlotRole::Field); diff --git a/utils/documentation-facts-perturb.json b/utils/documentation-facts-perturb.json index 6b3777138..4a2835e50 100644 --- a/utils/documentation-facts-perturb.json +++ b/utils/documentation-facts-perturb.json @@ -45,6 +45,20 @@ "new": "if true || std::ptr::eq(&raw const self.scope, reference.scope) {", "expect": ["documentation::tests::ownership::one_document_shared_by_two_owners_is_not_two_alternative_claims"] }, + { + "name": "association-document-id-must-not-be-zero", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "self.reference(&self.documents, association.fact.document.0)", + "new": "self.reference(&self.documents, 0)", + "expect": ["documentation::tests::ownership::export_binding_wrapper_is_distinct_from_semantic_owner_and_lexical_scope"] + }, + { + "name": "slot-enclosure-id-must-not-be-zero", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "self.reference(&self.owners, slot.enclosing.0)", + "new": "self.reference(&self.owners, 0)", + "expect": ["documentation::tests::ownership::slots_have_enclosing_owner_role_ordinal_and_source_without_fabricated_nodes"] + }, { "name": "selection-identity-needs-view", "file": "big-code-analysis-ast/src/documentation/streaming.rs", From cbe43de60eb1070c94863ff0da867096784462a9 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:47:55 -0800 Subject: [PATCH 008/221] test(oracle): characterize paired MI options in CLI and verbatim views --- .../src/bin/verbatim_oracle.rs | 2 + big-code-analysis-bench/src/verbatim.rs | 374 +++++++++++++++++- utils/drift-compare-test.py | 46 +++ utils/drift-compare.py | 8 +- utils/drift-oracle-test.py | 65 ++- utils/drift-oracle.py | 39 +- 6 files changed, 517 insertions(+), 17 deletions(-) diff --git a/big-code-analysis-bench/src/bin/verbatim_oracle.rs b/big-code-analysis-bench/src/bin/verbatim_oracle.rs index 6d23261ab..edb9166db 100644 --- a/big-code-analysis-bench/src/bin/verbatim_oracle.rs +++ b/big-code-analysis-bench/src/bin/verbatim_oracle.rs @@ -2,6 +2,8 @@ //! file on stdout, from the library's verbatim path. The body lives in //! `big_code_analysis_bench::verbatim` so it is covered by tests; this //! file only maps its result onto the exit status. +//! `--metrics-view [options] -- ...` selects the +//! metrics-only record with explicit options (see `verbatim::USAGE`). use std::io::Write; use std::process::ExitCode; diff --git a/big-code-analysis-bench/src/verbatim.rs b/big-code-analysis-bench/src/verbatim.rs index 6bc5539e4..40622f92f 100644 --- a/big-code-analysis-bench/src/verbatim.rs +++ b/big-code-analysis-bench/src/verbatim.rs @@ -12,6 +12,11 @@ //! (`utils/drift-oracle.py` captures them, `utils/drift-compare.py` //! compares). //! +//! `--metrics-view` emits only the metric space tree with explicit +//! effective options and parsed byte length. It shares the raw reader +//! and parser with the default record; no filesystem configuration is +//! consulted. The default invocation retains its original record shape. +//! //! A view that fails is an error for the whole file, never a record: //! the cached driver serialised a failed `find` as `[]`, which compares //! equal to a real empty result, so a regression that broke the view @@ -24,15 +29,103 @@ use std::io::Write; use std::path::Path; -use big_code_analysis::{Ast, AstCfg, AstResponse, LANG, MetricsOptions, Source}; +use big_code_analysis::{Ast, AstCfg, AstResponse, LANG, Metric, MetricsOptions, Source}; /// Usage text for the `verbatim-oracle` binary. -pub const USAGE: &str = "usage: verbatim-oracle ...\n"; +pub const USAGE: &str = "\ +usage: verbatim-oracle ... + verbatim-oracle --metrics-view [options] -- ... + +Metrics-only records carry the selected options and the full metric space tree. +Options (each at most once; no configuration or environment overrides): + --mi-charges-docs=false|true default false + --exclude-tests default false + --cyclomatic-count-try=false|true default true + --metrics NAME one canonical metric; default all +"; /// The node-kind filters each record carries `find` and `count` results /// for, in output order. const FILTERS: [&str; 3] = ["call", "string", "function"]; +struct MetricView { + exclude_tests: bool, + count_cyclomatic_try: bool, + mi_charges_docs: bool, + metric: Option, +} + +impl MetricView { + fn parse(args: &[String]) -> Result { + let mut view = Self { + exclude_tests: false, + count_cyclomatic_try: true, + mi_charges_docs: false, + metric: None, + }; + let mut seen = std::collections::BTreeSet::new(); + let mut args = args.iter(); + while let Some(arg) = args.next() { + let (name, value) = arg.split_once('=').unwrap_or((arg, "")); + if !seen.insert(name) { + return Err(format!("duplicate option: {name}")); + } + match (name, value) { + ("--exclude-tests", "") if arg == name => view.exclude_tests = true, + ("--metrics", "") if arg == name => { + let metric = args + .next() + .ok_or("--metrics needs a canonical metric name")?; + view.metric = Some(metric.parse::().map_err(|e| e.to_string())?); + } + ("--mi-charges-docs", value) => { + view.mi_charges_docs = value + .parse() + .map_err(|_| "--mi-charges-docs requires =false or =true")?; + } + ("--cyclomatic-count-try", value) => { + view.count_cyclomatic_try = value + .parse() + .map_err(|_| "--cyclomatic-count-try requires =false or =true")?; + } + _ => return Err(format!("unknown metrics-view option: {arg}")), + } + } + Ok(view) + } + + fn record(&self, lang: LANG, path: &str, code: &[u8]) -> Result { + let ast = parse(lang, path, code)?; + let mut options = MetricsOptions::default() + .with_exclude_tests(self.exclude_tests) + .with_count_cyclomatic_try(self.count_cyclomatic_try) + .with_mi_charges_docs(self.mi_charges_docs); + if let Some(metric) = self.metric { + options = options.with_only(&[metric]); + } + let metrics = ast + .metrics(options) + .map_err(|e| format!("{path}: metrics: {e}"))?; + Ok(serde_json::json!({ + "path": path, + "lang": lang.to_string(), + "source_bytes": ast.source().len(), + "options": { + "exclude_tests": self.exclude_tests, + "count_cyclomatic_try": self.count_cyclomatic_try, + "mi_charges_docs": self.mi_charges_docs, + "metrics": self.metric.map_or_else(|| "all".to_owned(), |m| m.to_string()), + }, + "metrics": metrics.to_wire(), + })) + } +} + +fn parse(lang: LANG, path: &str, code: &[u8]) -> Result { + Ast::parse(Source::new(lang, code).with_name(Some(path.to_owned()))) + .map_err(|e| format!("{path}: parse: {e}")) +} + /// One file's verbatim record as a JSON value, or the first view that /// failed, naming the file. [`run`] streams the value to its writer /// rather than rendering it to a `String` first: the export of a large @@ -47,8 +140,7 @@ const FILTERS: [&str; 3] = ["call", "string", "function"]; /// record, so an `Err` can never compare equal to any `Ok` value. pub fn record(lang: LANG, path: &str, code: &[u8]) -> Result { let fail = |view: &str, e: &dyn std::fmt::Display| format!("{path}: {view}: {e}"); - let ast = Ast::parse(Source::new(lang, code).with_name(Some(path.to_owned()))) - .map_err(|e| fail("parse", &e))?; + let ast = parse(lang, path, code)?; let metrics = ast .metrics(MetricsOptions::default()) .map_err(|e| fail("metrics", &e))?; @@ -103,14 +195,31 @@ fn rooted(response: AstResponse) -> Result { /// /// # Errors /// -/// An unknown language slug, an unreadable file (named), a failed view +/// No input files, an unknown language slug, an unreadable file (named), a failed view /// (named with its file by [`record`]), or a write failure. pub fn run(lang: &str, paths: I, out: &mut impl Write) -> Result<(), String> +where + I: IntoIterator, + I::Item: AsRef, +{ + run_with(lang, paths, out, record) +} + +fn run_with( + lang: &str, + paths: I, + out: &mut impl Write, + record: impl Fn(LANG, &str, &[u8]) -> Result, +) -> Result<(), String> where I: IntoIterator, I::Item: AsRef, { let lang: LANG = lang.parse().map_err(|e| format!("{lang}: {e}"))?; + let mut paths = paths.into_iter().peekable(); + if paths.peek().is_none() { + return Err(format!("no input files\n{USAGE}")); + } for path in paths { let path = path.as_ref(); let name = path @@ -130,15 +239,28 @@ where /// /// # Errors /// -/// Missing arguments (with [`USAGE`]) or anything [`run`] reports. +/// Missing arguments (with [`USAGE`]), invalid metrics-view options, or +/// anything [`run`] reports. pub fn main_with(argv: &[String], out: &mut impl Write) -> Result<(), String> { + let (view, argv) = if argv.first().is_some_and(|arg| arg == "--metrics-view") { + let end = argv + .iter() + .position(|arg| arg == "--") + .ok_or_else(|| format!("--metrics-view requires -- before the language\n{USAGE}"))?; + (Some(MetricView::parse(&argv[1..end])?), &argv[end + 1..]) + } else { + (None, argv) + }; let [lang, paths @ ..] = argv else { return Err(format!("missing language slug\n{USAGE}")); }; - if paths.is_empty() { - return Err(format!("no input files\n{USAGE}")); + if let Some(view) = view { + run_with(lang, paths, out, |lang, path, code| { + view.record(lang, path, code) + }) + } else { + run(lang, paths, out) } - run(lang, paths, out) } #[cfg(test)] @@ -154,6 +276,240 @@ mod tests { v.to_string() } + fn metric_view(lang: &str, source: &[u8], options: &[&str]) -> serde_json::Value { + let dir = tempfile::tempdir().expect("tempdir"); + let path = dir.path().join("input"); + std::fs::write(&path, source).expect("write verbatim"); + let mut argv = vec!["--metrics-view".to_owned()]; + argv.extend(options.iter().map(|s| (*s).to_owned())); + argv.extend([ + "--".to_owned(), + lang.to_owned(), + path.to_str().expect("UTF-8").to_owned(), + ]); + let mut out = Vec::new(); + main_with(&argv, &mut out).expect("metrics view"); + let text = String::from_utf8(out).expect("UTF-8"); + assert_eq!(text.lines().count(), 1, "exactly one input record"); + assert!(text.ends_with('\n')); + let value = parse_line(&text); + assert_eq!(value["path"], path.to_str().expect("UTF-8")); + assert_eq!(value["lang"], lang); + assert_eq!(value["source_bytes"], source.len(), "parsed buffer length"); + value + } + + #[test] + fn metrics_view_defaults_preserve_metrics_and_raw_endings() { + for source in [ + b"fn f() {}\r\n/// tail".as_slice(), + b"fn f() {}\n/// tail", + b"fn f() {}\n/// tail\n", + b"fn f() {}\r\n/// tail\r\n", + ] { + let view = metric_view("rust", source, &[]); + let default = record(LANG::Rust, view["path"].as_str().expect("path"), source) + .expect("default record"); + assert_eq!(view["metrics"], default["metrics"]); + assert_eq!( + view["options"], + serde_json::json!({ + "exclude_tests": false, + "count_cyclomatic_try": true, + "mi_charges_docs": false, + "metrics": "all", + }) + ); + assert_eq!(view.as_object().expect("record").len(), 5); + assert_eq!(default.as_object().expect("record").len(), 12); + assert_eq!(view["metrics"]["metrics"]["loc"]["sloc"], 2); + assert_eq!(view["metrics"]["spaces"].as_array().map(Vec::len), Some(1)); + } + } + + #[test] + fn metrics_view_mi_modes_and_dependency_closure_reach_each_space() { + // The existing MI fixture's independent inputs: N=25, n=12, + // ploc=6, cloc=dloc=5, sloc=11; G=4 at root, 3 in clamp. + let source = b"def clamp(value, low, high):\n \"\"\"Return ``value`` held within ``[low, high]``.\n\n The bounds are inclusive and are not checked against each\n other, so ``low > high`` returns ``high`` for every input.\n \"\"\"\n if value < low:\n return low\n if value > high:\n return high\n return value\n"; + for selection in [vec![], vec!["--metrics", "mi"]] { + for (mode, charged) in [ + ("--mi-charges-docs=false", false), + ("--mi-charges-docs=true", true), + ] { + let mut options = selection.clone(); + options.push(mode); + let view = metric_view("python", source, &options); + assert_eq!(view["options"]["mi_charges_docs"], charged); + assert_eq!( + view["options"]["metrics"], + if selection.is_empty() { "all" } else { "mi" } + ); + let root = &view["metrics"]; + let children = root["spaces"].as_array().expect("spaces"); + assert_eq!(children.len(), 1); + assert_eq!(children[0]["name"], "clamp"); + for (space, g, original, sei) in [ + (root, 4, 117.676_252_636_666_53, 160.909_070_973_313_36), + ( + &children[0], + 3, + 117.906_252_636_666_52, + 161.139_070_973_313_32, + ), + ] { + let m = &space["metrics"]; + for (key, expected) in [("ploc", 6), ("cloc", 5), ("dloc", 5), ("sloc", 11)] { + assert_eq!(m["loc"][key], expected, "{key}: {m}"); + } + assert_eq!(m["cyclomatic"]["sum"], g); + assert_eq!(m["halstead"]["length"], 25); + assert_eq!(m["halstead"]["vocabulary"], 12); + assert!((m["mi"]["original"].as_f64().expect("MI") - original).abs() < 1e-9); + let expected_sei = if charged { sei } else { original }; + assert!((m["mi"]["sei"].as_f64().expect("MI") - expected_sei).abs() < 1e-9); + if !selection.is_empty() { + assert_eq!( + m.as_object() + .expect("metrics") + .keys() + .map(String::as_str) + .collect::>(), + ["cyclomatic", "halstead", "loc", "mi"] + ); + } + } + } + } + } + + #[test] + fn metrics_view_combines_pruning_try_count_and_mi_modes() { + let source = b"/// kept\r\nfn kept() { work()?; }\r\n/// pruned\r\n#[test]\r\nfn removed() { work()?; }"; + for exclude in [false, true] { + for count_try in [false, true] { + for charged in [false, true] { + let mut options = vec![ + "--metrics", + "mi", + if count_try { + "--cyclomatic-count-try=true" + } else { + "--cyclomatic-count-try=false" + }, + if charged { + "--mi-charges-docs=true" + } else { + "--mi-charges-docs=false" + }, + ]; + if exclude { + options.push("--exclude-tests"); + } + let view = metric_view("rust", source, &options); + assert_eq!( + view["options"], + serde_json::json!({ + "metrics": "mi", "exclude_tests": exclude, + "count_cyclomatic_try": count_try, "mi_charges_docs": charged, + }) + ); + let root = &view["metrics"]; + let children = root["spaces"].as_array().expect("spaces"); + let names: Vec<_> = children + .iter() + .map(|s| s["name"].as_str().expect("name")) + .collect(); + assert_eq!( + names, + if exclude { + vec!["kept"] + } else { + vec!["kept", "removed"] + } + ); + assert_eq!(root["metrics"]["loc"]["dloc"], if exclude { 1 } else { 2 }); + let child_cyclomatic = if count_try { 2 } else { 1 }; + assert_eq!( + root["metrics"]["cyclomatic"]["sum"], + 1 + names.len() * child_cyclomatic + ); + for child in children { + assert_eq!(child["metrics"]["cyclomatic"]["sum"], child_cyclomatic); + assert_eq!(child["metrics"]["loc"]["dloc"], 0); + } + let mi = &root["metrics"]["mi"]; + let original = mi["original"].as_f64().expect("MI"); + assert!(original > 0.0, "real code, not the empty sentinel"); + if charged { + assert!(mi["sei"].as_f64().expect("MI") > original); + } else { + assert_eq!(mi["sei"], mi["original"]); + } + } + } + } + } + + #[test] + fn metrics_view_rejects_ambiguous_or_invalid_options_before_reading() { + for options in [ + vec!["--mi-charges-docs"], + vec!["--mi-charges-docs=yes"], + vec!["--mi-charges-docs=false", "--mi-charges-docs=true"], + vec!["--cyclomatic-count-try=0"], + vec!["--cyclomatic-count-try=true", "--cyclomatic-count-try=true"], + vec!["--exclude-tests=false"], + vec!["--exclude-tests="], + vec!["--exclude-tests", "--exclude-tests"], + vec!["--metrics"], + vec!["--metrics", "unknown"], + vec!["--metrics", "mi,loc"], + vec!["--metrics", "mi", "--metrics", "loc"], + vec!["--unknown"], + ] { + let mut args = vec!["--metrics-view".to_owned()]; + args.extend(options.iter().map(|s| (*s).to_owned())); + args.extend([ + "--".to_owned(), + "rust".to_owned(), + "never-read.rs".to_owned(), + ]); + let mut out = Vec::new(); + let err = main_with(&args, &mut out).expect_err("invalid options"); + assert!( + !err.contains("never-read.rs"), + "validated before I/O: {err}" + ); + assert!(out.is_empty()); + } + } + + #[test] + fn metrics_view_and_run_reject_zero_inputs() { + for args in [ + vec!["--metrics-view", "rust", "file.rs"], + vec!["--metrics-view", "--"], + vec!["--metrics-view", "--", "rust"], + ] { + let args: Vec<_> = args.into_iter().map(str::to_owned).collect(); + let mut out = Vec::new(); + assert!( + main_with(&args, &mut out) + .expect_err("incomplete invocation") + .contains("usage: verbatim-oracle") + ); + assert!(out.is_empty()); + } + let mut out = Vec::new(); + assert!( + run("rust", std::iter::empty::<&str>(), &mut out) + .expect_err("zero files") + .starts_with("no input files") + ); + assert!(out.is_empty()); + } + /// A record carries every view, on the raw bytes: the input has no /// trailing newline, and the `function` kind the Rust grammar emits /// for `fn` is found and counted. diff --git a/utils/drift-compare-test.py b/utils/drift-compare-test.py index 4038e83c5..106cab81c 100644 --- a/utils/drift-compare-test.py +++ b/utils/drift-compare-test.py @@ -173,6 +173,52 @@ def test_no_shared_view_is_refused(self) -> None: self.assertEqual(rc, 2) self.assertIn("no view on both sides", text) + def test_empty_key_sets_are_refused_even_without_a_filter(self) -> None: + base = _capture(self.root / "base", verbatim=True, keys=[]) + head = _capture(self.root / "head", verbatim=True, keys=[]) + rc, text, summary = self._run(base, head) + self.assertEqual(rc, 2) + self.assertIn("no keys on one side", text) + self.assertEqual(summary, {}) + + def test_mi_view_and_option_differences_cannot_report_zero_drift(self) -> None: + base = _capture(self.root / "base", verbatim=True) + head = _capture(self.root / "head", verbatim=True) + view = "verbatim_metrics_only_mi_mi_charges_docs_true" + views = [*CLI, *METRICS, "verbatim", view] + matrix = {**METRICS, view: ["--metrics-view", "--metrics", "mi", "--mi-charges-docs=true", "--"]} + self._edit(head, views=views, metrics_options=matrix) + rc, text, summary = self._run(base, head) + self.assertEqual(rc, 2) + self.assertIn(f"VIEW only in head: {view}", text) + self.assertEqual(summary, {}) + rc, _, summary = self._run(base, head, "--only-shared-views") + self.assertEqual(rc, 0) + self.assertEqual(summary["outputs_compared"], 8) + self.assertEqual(summary["views_uncompared"], [view]) + + self._edit(base, views=views, metrics_options=matrix) + for capture in (base, head): + for key in KEYS: + (capture / f"{key}.{view}.txt").write_bytes(b'{"metrics": {}}\n') + rc, _, summary = self._run(base, head) + self.assertEqual(rc, 0) + self.assertEqual(summary["outputs_compared"], 10) + (head / f"{KEYS[0]}.{view}.txt").write_bytes(b'{"metrics": {"mi": 1}}\n') + rc, _, summary = self._run(base, head) + self.assertEqual(rc, 1) + self.assertEqual(summary["differing"], 1) + + self._edit(head, metrics_options={**matrix, view: ["--metrics-view", "--metrics", "mi", "--mi-charges-docs=false", "--"]}) + rc, text, summary = self._run(base, head) + self.assertEqual(rc, 1) + self.assertIn("option matrix or command set differs", text) + self.assertEqual(summary["key_problems"], 1) + rc, text, summary = self._run(base, head, "--only-shared-views") + self.assertEqual(rc, 1) + self.assertIn("option matrix or command set differs", text) + self.assertEqual(summary["key_problems"], 1) + def test_a_key_on_one_side_is_a_problem_not_a_skip(self) -> None: base = _capture(self.root / "base", verbatim=True) head = _capture(self.root / "head", verbatim=True, keys=KEYS[:1]) diff --git a/utils/drift-compare.py b/utils/drift-compare.py index aac087443..a51da7373 100755 --- a/utils/drift-compare.py +++ b/utils/drift-compare.py @@ -80,6 +80,9 @@ def main(argv: list[str] | None = None) -> int: if mb is None or mh is None: return 2 kb, kh = set(mb["keys"]), set(mh["keys"]) + if not kb or not kh: + print("no keys on one side; nothing compared") + return 2 if args.lang: langs = set(args.lang) kb = {k for k in kb if k.split("/", 1)[0] in langs} @@ -128,7 +131,10 @@ def main(argv: list[str] | None = None) -> int: for k in sorted(kh - kb): print(f"KEY only in head: {k}") problems += len(kb ^ kh) - if mb["metrics_options"] != mh["metrics_options"] or mb["cli_cmds"] != mh["cli_cmds"]: + def compared_options(matrix: dict) -> dict: + return {name: argv for name, argv in matrix.items() if not args.only_shared_views or name not in one_sided} + + if compared_options(mb["metrics_options"]) != compared_options(mh["metrics_options"]) or mb["cli_cmds"] != mh["cli_cmds"]: print("option matrix or command set differs between captures") problems += 1 compared = 0 diff --git a/utils/drift-oracle-test.py b/utils/drift-oracle-test.py index 013125018..3fd6ec49b 100644 --- a/utils/drift-oracle-test.py +++ b/utils/drift-oracle-test.py @@ -38,6 +38,30 @@ def _load(name: str, filename: str): oracle = _load("drift_oracle", "drift-oracle.py") dc = oracle.dc +EXPECTED_MI_OPTIONS = { + "metrics_mi_charges_docs_false": ["--mi-charges-docs=false"], + "metrics_mi_charges_docs_true": ["--mi-charges-docs=true"], + "metrics_exclude_tests_mi_charges_docs_false": ["--exclude-tests", "--mi-charges-docs=false"], + "metrics_exclude_tests_mi_charges_docs_true": ["--exclude-tests", "--mi-charges-docs=true"], + "metrics_only_mi_mi_charges_docs_false": ["--metrics", "mi", "--mi-charges-docs=false"], + "metrics_only_mi_mi_charges_docs_true": ["--metrics", "mi", "--mi-charges-docs=true"], + "metrics_only_mi_exclude_tests_mi_charges_docs_false": ["--metrics", "mi", "--exclude-tests", "--mi-charges-docs=false"], + "metrics_only_mi_exclude_tests_mi_charges_docs_true": ["--metrics", "mi", "--exclude-tests", "--mi-charges-docs=true"], + "metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false": ["--metrics", "mi", "--exclude-tests", "--cyclomatic-count-try=false", "--mi-charges-docs=false"], + "metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true": ["--metrics", "mi", "--exclude-tests", "--cyclomatic-count-try=false", "--mi-charges-docs=true"], +} + +EXPECTED_METRICS_OPTIONS = { + "metrics": [], + "metrics_exclude_tests": ["--exclude-tests"], + "metrics_no_count_try": ["--cyclomatic-count-try=false"], + "metrics_exclude_tests_no_count_try": ["--exclude-tests", "--cyclomatic-count-try=false"], + "metrics_only_cyclomatic": ["--metrics", "cyclomatic"], + "metrics_only_cognitive": ["--metrics", "cognitive"], + "metrics_only_nexits": ["--metrics", "nexits"], + **EXPECTED_MI_OPTIONS, +} + def _stub(path: pathlib.Path, body: str) -> pathlib.Path: path.write_text(f"#!{sys.executable}\nimport sys\n{body}\n") @@ -75,8 +99,8 @@ def test_capture_with_verbatim_records_every_view(self) -> None: rc, _, _, m = self._run("--verbatim", str(self.verbatim), "--lang", "rust", "--lang", "python") self.assertEqual(rc, 0) self.assertTrue(m["complete"]) - self.assertEqual(m["views"], [*oracle.CLI_CMDS, *oracle.METRICS_OPTIONS, "verbatim"]) - self.assertEqual(m["outputs_per_file"], len(m["views"])) + self.assertEqual(m["views"], [*oracle.CLI_CMDS, *EXPECTED_METRICS_OPTIONS, "verbatim", *oracle.VERBATIM_OPTIONS]) + self.assertEqual(m["outputs_per_file"], 34) self.assertEqual(sorted(m["keys"]), ["python/fx/b.py", "rust/fx/a.rs"]) self.assertEqual(m["verbatim"]["path"], str(self.verbatim)) self.assertEqual(m["version"], dc.MANIFEST_VERSION) @@ -92,6 +116,42 @@ def test_capture_with_verbatim_records_every_view(self) -> None: self.assertTrue(key.with_name("a.rs.ops.txt").is_file()) self.assertIn("--language rust", key.with_name("a.rs.metrics_exclude_tests.txt").read_text()) + def test_mi_matrix_and_every_argv_are_symmetric_and_explicit(self) -> None: + _stub(self.bca, "import json; print(json.dumps(sys.argv[1:]))") + rc, out, _, m = self._run("--verbatim", str(self.verbatim), "--lang", "rust") + self.assertEqual(rc, 0) + expected_verbatim = { + f"verbatim_{name}": ["--metrics-view", *extra, "--"] + for name, extra in EXPECTED_MI_OPTIONS.items() + } + self.assertEqual(oracle.METRICS_OPTIONS, EXPECTED_METRICS_OPTIONS) + self.assertEqual(oracle.VERBATIM_OPTIONS, expected_verbatim) + self.assertEqual(m["metrics_options"], {**EXPECTED_METRICS_OPTIONS, **expected_verbatim}) + self.assertEqual(m["views"], [*oracle.CLI_CMDS, *EXPECTED_METRICS_OPTIONS, "verbatim", *expected_verbatim]) + self.assertEqual(json.loads(out)["outputs"], 34) + path = str(self.fixtures / "a.rs") + key = self.out / "rust" / "fx" / "a.rs" + for name, extra in EXPECTED_METRICS_OPTIONS.items(): + with self.subTest(view=name): + self.assertEqual( + json.loads(key.with_name(f"a.rs.{name}.txt").read_text()), + ["metrics", "-O", "json", *extra, "--no-config", "--language", "rust", "-p", path], + ) + for name, extra in expected_verbatim.items(): + with self.subTest(view=name): + self.assertEqual( + json.loads(key.with_name(f"a.rs.{name}.txt").read_text()), + {"v": [*extra, "rust", path]}, + ) + + def test_a_failed_mi_verbatim_view_is_not_a_baseline(self) -> None: + _stub(self.verbatim, "sys.exit(4 if '--mi-charges-docs=true' in sys.argv else 0)") + rc, _, err, m = self._run("--verbatim", str(self.verbatim), "--lang", "rust") + self.assertEqual(rc, 1) + self.assertFalse(m["complete"]) + self.assertEqual(m["failed_executions"], 5) + self.assertIn("not a baseline", err) + def test_outputs_are_captured_as_bytes(self) -> None: # A text capture would fold b"\xff\r\n" and b"\xfe\n" to the same # "\ufffd\n", so a real change in the binary's output would @@ -129,6 +189,7 @@ def test_capture_without_verbatim_records_only_cli_views(self) -> None: self.assertEqual(rc, 0) self.assertNotIn("verbatim", m["views"]) self.assertIsNone(m["verbatim"]) + self.assertEqual(m["metrics_options"], EXPECTED_METRICS_OPTIONS) self.assertEqual(m["outputs_per_file"], len(oracle.CLI_CMDS) + len(oracle.METRICS_OPTIONS)) self.assertFalse((self.out / "rust" / "fx" / "a.rs.verbatim.jsonl").exists()) diff --git a/utils/drift-oracle.py b/utils/drift-oracle.py index 2475c767a..650b96548 100755 --- a/utils/drift-oracle.py +++ b/utils/drift-oracle.py @@ -7,7 +7,13 @@ (`cargo build -p big-code-analysis-bench --bin verbatim-oracle`) — the library-level verbatim record: metrics, ops, the Alterator-built AST export, find/count, on the raw bytes, the only path that reaches a -node ending at EOF. +node ending at EOF. Paired MI views run through both binaries, with +selected-metric dependency closure and Rust prune/try combinations. +The default verbatim record stays compatible with recovery captures; +additional metrics-only records use `--metrics-view` and spell their +effective options in the output. `metrics_options` maps each CLI or +verbatim metric view to its argv; additional views use the usual `.txt` +suffix even though their payload is JSON. The verbatim view is optional per side because a base commit older than #1744 has no `verbatim-oracle` to build: a base-vs-head run over @@ -75,8 +81,23 @@ # what the sweep measures. FIXTURE_ONLY = {"ccomment", "preproc"} -# `metrics` option matrix: name -> extra argv. The other commands take -# no metric-affecting options. +# Paired MI modes cover documentation, pruning and dependency closure. +# The last pair combines the Rust axes without multiplying every legacy +# selection by options that cannot affect it. +MI_METRICS_OPTIONS = { + f"{name}_mi_charges_docs_{mode}": [*extra, f"--mi-charges-docs={mode}"] + for name, extra in { + "metrics": [], + "metrics_exclude_tests": ["--exclude-tests"], + "metrics_only_mi": ["--metrics", "mi"], + "metrics_only_mi_exclude_tests": ["--metrics", "mi", "--exclude-tests"], + "metrics_only_mi_exclude_tests_no_count_try": ["--metrics", "mi", "--exclude-tests", "--cyclomatic-count-try=false"], + }.items() + for mode in ("false", "true") +} + +# `metrics` option matrix: name -> extra argv. Keep the original views +# so existing default captures retain their names and commands. METRICS_OPTIONS = { "metrics": [], "metrics_exclude_tests": ["--exclude-tests"], @@ -85,6 +106,12 @@ "metrics_only_cyclomatic": ["--metrics", "cyclomatic"], "metrics_only_cognitive": ["--metrics", "cognitive"], "metrics_only_nexits": ["--metrics", "nexits"], + **MI_METRICS_OPTIONS, +} + +VERBATIM_OPTIONS = { + f"verbatim_{name}": ["--metrics-view", *extra, "--"] + for name, extra in MI_METRICS_OPTIONS.items() } CLI_CMDS = { @@ -154,7 +181,7 @@ def run(argv: list[str]) -> bytes: def views(verbatim: bool) -> list[str]: """The per-file output names a capture carries, in the order `drift-compare.py` walks them.""" - return [*CLI_CMDS, *METRICS_OPTIONS, *(["verbatim"] if verbatim else [])] + return [*CLI_CMDS, *METRICS_OPTIONS, *(["verbatim", *VERBATIM_OPTIONS] if verbatim else [])] def main(argv: list[str] | None = None) -> int: @@ -223,7 +250,7 @@ def manifest(complete: bool) -> dict: verbatim=None if args.verbatim is None else {"path": str(args.verbatim), "sha256": sha256(args.verbatim)}, views=views(args.verbatim is not None), roots={k: str(v) for k, v in roots.items()}, - metrics_options=METRICS_OPTIONS, + metrics_options={**METRICS_OPTIONS, **(VERBATIM_OPTIONS if args.verbatim is not None else {})}, cli_cmds=CLI_CMDS, populations=counts, keys=sorted(keys), @@ -249,6 +276,8 @@ def one(job: tuple[str, str, pathlib.Path, pathlib.Path]) -> None: dst.with_name(dst.name + f".{name}.txt").write_bytes(run([*base, "metrics", "-O", "json", *extra, *tail])) if args.verbatim is not None: dst.with_name(dst.name + ".verbatim.jsonl").write_bytes(run([str(args.verbatim), lang, str(p)])) + for name, extra in VERBATIM_OPTIONS.items(): + dst.with_name(dst.name + f".{name}.txt").write_bytes(run([str(args.verbatim), *extra, lang, str(p)])) with ThreadPoolExecutor(max_workers=args.jobs) as ex: list(ex.map(one, jobs)) From a776c9d4a4927c016413c94596d9cd12925c5b0c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 09:53:49 -0800 Subject: [PATCH 009/221] test(oracle): persist option propagation and raw-source mutations --- big-code-analysis-bench/src/verbatim.rs | 6 +-- utils/documentation-oracle-perturb.json | 35 +++++++++++++ utils/documentation-oracle-rust-perturb.json | 53 ++++++++++++++++++++ 3 files changed, 91 insertions(+), 3 deletions(-) create mode 100644 utils/documentation-oracle-perturb.json create mode 100644 utils/documentation-oracle-rust-perturb.json diff --git a/big-code-analysis-bench/src/verbatim.rs b/big-code-analysis-bench/src/verbatim.rs index 40622f92f..47fe9b4bb 100644 --- a/big-code-analysis-bench/src/verbatim.rs +++ b/big-code-analysis-bench/src/verbatim.rs @@ -481,7 +481,7 @@ mod tests { !err.contains("never-read.rs"), "validated before I/O: {err}" ); - assert!(out.is_empty()); + assert_eq!(out, b""); } } @@ -499,7 +499,7 @@ mod tests { .expect_err("incomplete invocation") .contains("usage: verbatim-oracle") ); - assert!(out.is_empty()); + assert_eq!(out, b""); } let mut out = Vec::new(); assert!( @@ -507,7 +507,7 @@ mod tests { .expect_err("zero files") .starts_with("no input files") ); - assert!(out.is_empty()); + assert_eq!(out, b""); } /// A record carries every view, on the raw bytes: the input has no diff --git a/utils/documentation-oracle-perturb.json b/utils/documentation-oracle-perturb.json new file mode 100644 index 000000000..ac7057689 --- /dev/null +++ b/utils/documentation-oracle-perturb.json @@ -0,0 +1,35 @@ +{ + "description": "Run from the repository root with python3 -B utils/perturb.py utils/documentation-oracle-perturb.json. Targets must be tracked and clean. Rust companion: documentation-oracle-rust-perturb.json.", + "cwd": ".", + "runner": "unittest", + "command": [ + "python3", "-B", "-m", "unittest", "-q", + "utils/drift-oracle-test.py", "utils/drift-compare-test.py" + ], + "cases": [ + { + "name": "drop-cli-metric-options", + "file": "utils/drift-oracle.py", + "old": "[*base, \"metrics\", \"-O\", \"json\", *extra, *tail]", + "new": "[*base, \"metrics\", \"-O\", \"json\", *tail]", + "expect": ["utils.drift-oracle-test.DriftOracleTests.test_mi_matrix_and_every_argv_are_symmetric_and_explicit"] + }, + { + "name": "drop-verbatim-metric-options", + "file": "utils/drift-oracle.py", + "old": "[str(args.verbatim), *extra, lang, str(p)]", + "new": "[str(args.verbatim), lang, str(p)]", + "expect": [ + "utils.drift-oracle-test.DriftOracleTests.test_mi_matrix_and_every_argv_are_symmetric_and_explicit", + "utils.drift-oracle-test.DriftOracleTests.test_a_failed_mi_verbatim_view_is_not_a_baseline" + ] + }, + { + "name": "accept-empty-key-sets", + "file": "utils/drift-compare.py", + "old": " if not kb or not kh:\n print(\"no keys on one side; nothing compared\")\n return 2\n", + "new": "", + "expect": ["utils.drift-compare-test.DriftCompareTests.test_empty_key_sets_are_refused_even_without_a_filter"] + } + ] +} diff --git a/utils/documentation-oracle-rust-perturb.json b/utils/documentation-oracle-rust-perturb.json new file mode 100644 index 000000000..4d599096b --- /dev/null +++ b/utils/documentation-oracle-rust-perturb.json @@ -0,0 +1,53 @@ +{ + "description": "Run from the repository root after cargo test -p big-code-analysis-bench --lib passes, with python3 -B utils/perturb.py utils/documentation-oracle-rust-perturb.json. Sweeps the whole bench library; no claim of unique guards outside this target. Targets must be tracked and clean.", + "cwd": ".", + "runner": "cargo", + "command": ["cargo", "test", "-p", "big-code-analysis-bench", "--lib"], + "cases": [ + { + "name": "drop-mi-doc-charging", + "file": "big-code-analysis-bench/src/verbatim.rs", + "old": ".with_mi_charges_docs(self.mi_charges_docs)", + "new": ".with_mi_charges_docs(false)", + "expect": [ + "verbatim::tests::metrics_view_mi_modes_and_dependency_closure_reach_each_space", + "verbatim::tests::metrics_view_combines_pruning_try_count_and_mi_modes" + ] + }, + { + "name": "drop-test-pruning", + "file": "big-code-analysis-bench/src/verbatim.rs", + "old": ".with_exclude_tests(self.exclude_tests)", + "new": ".with_exclude_tests(false)", + "expect": ["verbatim::tests::metrics_view_combines_pruning_try_count_and_mi_modes"] + }, + { + "name": "drop-try-count-option", + "file": "big-code-analysis-bench/src/verbatim.rs", + "old": ".with_count_cyclomatic_try(self.count_cyclomatic_try)", + "new": ".with_count_cyclomatic_try(true)", + "expect": ["verbatim::tests::metrics_view_combines_pruning_try_count_and_mi_modes"] + }, + { + "name": "drop-metric-selection", + "file": "big-code-analysis-bench/src/verbatim.rs", + "old": " options = options.with_only(&[metric]);", + "new": " let _ = metric;", + "expect": ["verbatim::tests::metrics_view_mi_modes_and_dependency_closure_reach_each_space"] + }, + { + "name": "append-newline-before-parse", + "file": "big-code-analysis-bench/src/verbatim.rs", + "old": "Source::new(lang, code)", + "new": "Source::from_bytes(lang, [code, b\"\\n\"].concat())", + "expect": ["verbatim::tests::metrics_view_defaults_preserve_metrics_and_raw_endings"] + }, + { + "name": "normalize-crlf-before-parse", + "file": "big-code-analysis-bench/src/verbatim.rs", + "old": "Source::new(lang, code)", + "new": "Source::from_bytes(lang, code.iter().copied().filter(|byte| *byte != b'\\r').collect::>())", + "expect": ["verbatim::tests::metrics_view_defaults_preserve_metrics_and_raw_endings"] + } + ] +} From b47ea189ba51fe50d6362f876e77126c35d307d0 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 10:58:44 -0800 Subject: [PATCH 010/221] fix(ast): bound documentation source intersection work --- CHANGELOG.md | 7 ++ .../src/documentation/source.rs | 11 ++- .../src/documentation/tests.rs | 1 + .../src/documentation/tests/ownership.rs | 16 +++-- .../src/documentation/tests/provenance.rs | 9 +++ .../src/documentation/tests/ranges.rs | 72 +++++++++++++++++++ tests/api/parser_reuse.rs | 2 +- utils/documentation-facts-perturb.json | 28 ++++++++ 8 files changed, 139 insertions(+), 7 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/tests/ranges.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d0745346..f46595328 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,13 @@ for historical reference. ## [Unreleased] +### Added + +- Added unstable `big-code-analysis-ast::documentation` fact, source and owner + primitives, plus retained `Complete` / `Cancelled` / `Adopted` parse provenance + on `Parser` and `AnyParser`. The root library's documentation facade follows + separately; existing metric behavior is unchanged. (#1656) + ### Changed - **(breaking), deferred to the next major (3.0):** the MI of a space diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index 9c2de4fe6..e004d58d9 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -2,6 +2,12 @@ use std::ops::Range; +// Output alone cannot reveal scanning empty ranges or seeking from the start. +crate::observation::counter!( + included_range_visits, + cfg(any(test, feature = "test-support")) +); + /// A nonempty, half-open source byte range and its borrowed raw bytes. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SourcePiece<'s> { @@ -58,10 +64,12 @@ impl<'s> SourceContext<'s> { /// infer completion; adopted/raw inputs retain the caller's precondition. #[must_use] pub fn new(tree: &'s tree_sitter::Tree, bytes: &'s [u8]) -> Self { + let mut included = tree.included_ranges(); + included.retain(|range| range.start_byte < range.end_byte); Self { tree, bytes, - included: tree.included_ranges(), + included, } } @@ -81,6 +89,7 @@ impl<'s> SourceContext<'s> { let mut pieces = Vec::new(); let mut included_bytes = 0; for range in &self.included[first..] { + included_range_visits::record(); if range.start_byte >= spelling.end { break; } diff --git a/big-code-analysis-ast/src/documentation/tests.rs b/big-code-analysis-ast/src/documentation/tests.rs index eee2e2f17..aaa755e65 100644 --- a/big-code-analysis-ast/src/documentation/tests.rs +++ b/big-code-analysis-ast/src/documentation/tests.rs @@ -6,6 +6,7 @@ use crate::{AnyParser, LANG}; mod model_cases; mod ownership; mod provenance; +mod ranges; mod streaming; #[cfg(feature = "rust")] diff --git a/big-code-analysis-ast/src/documentation/tests/ownership.rs b/big-code-analysis-ast/src/documentation/tests/ownership.rs index 3b211b25f..895307799 100644 --- a/big-code-analysis-ast/src/documentation/tests/ownership.rs +++ b/big-code-analysis-ast/src/documentation/tests/ownership.rs @@ -34,6 +34,7 @@ fn one_document_shared_by_two_owners_is_not_two_alternative_claims() { assert_eq!(names.len(), 2); assert_eq!(names[0].as_tree_sitter().byte_range(), 14..15); assert_eq!(names[1].as_tree_sitter().byte_range(), 17..18); + facts.owners.push(Owner::File(root)); facts.owners.extend( names .iter() @@ -45,7 +46,7 @@ fn one_document_shared_by_two_owners_is_not_two_alternative_claims() { ] { facts.associations.push(Association { document: DocumentId(0), - owners: vec![OwnerId(0), OwnerId(1)], + owners: vec![OwnerId(1), OwnerId(2)], resolution, convention: Convention("Doxygen"), binding: Some(context.node(declaration.as_tree_sitter()).unwrap()), @@ -66,10 +67,15 @@ fn one_document_shared_by_two_owners_is_not_two_alternative_claims() { facts.associated_document(associations[0]).unwrap(), facts.associated_document(associations[1]).unwrap() ); - assert_ne!( - facts.associated_owner(associations[0], 0).unwrap(), - facts.associated_owner(associations[0], 1).unwrap() - ); + for association in &associations { + for (position, expected) in [14..15, 17..18].into_iter().enumerate() { + let owner = facts.associated_owner(*association, position).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("association must resolve its name owner, not the file decoy"); + }; + assert_eq!(node.node().byte_range(), expected); + } + } let foreign = Facts::default(); assert_eq!( foreign.associated_document(associations[0]), diff --git a/big-code-analysis-ast/src/documentation/tests/provenance.rs b/big-code-analysis-ast/src/documentation/tests/provenance.rs index 8e775734a..268127c7b 100644 --- a/big-code-analysis-ast/src/documentation/tests/provenance.rs +++ b/big-code-analysis-ast/src/documentation/tests/provenance.rs @@ -85,6 +85,15 @@ fn canonical_evidence_rejects_clones_shifted_roots_and_edited_values() { let root = parser.ts_tree().root_node(); let canonical = context.node(root).unwrap(); assert_eq!(canonical.validate(root), Ok(())); + let child = root.named_child(0).unwrap(); + assert_eq!(child.range(), root.range()); + assert_eq!(child.into_raw().context, root.into_raw().context); + assert_ne!(child.id(), root.id()); + assert_ne!(child.kind_id(), root.kind_id()); + assert_eq!( + canonical.validate(child), + Err(SourceError::NoncanonicalNode) + ); assert_eq!( canonical.validate(second.ts_tree().root_node()), Err(SourceError::ForeignTree) diff --git a/big-code-analysis-ast/src/documentation/tests/ranges.rs b/big-code-analysis-ast/src/documentation/tests/ranges.rs new file mode 100644 index 000000000..8932f08b2 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/tests/ranges.rs @@ -0,0 +1,72 @@ +use super::*; + +#[cfg(feature = "rust")] +fn tree_with_ranges(source: &[u8], ranges: &[std::ops::Range]) -> tree_sitter::Tree { + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + let ranges: Vec<_> = ranges + .iter() + .map(|range| tree_sitter::Range { + start_byte: range.start, + end_byte: range.end, + start_point: tree_sitter::Point::new(0, range.start), + end_point: tree_sitter::Point::new(0, range.end), + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + parser.parse(source, None).unwrap() +} + +#[cfg(feature = "rust")] +#[test] +fn empty_included_ranges_do_not_add_per_query_scan_work() { + let source = b"///aXb"; + let mut ranges = Vec::with_capacity(258); + ranges.push(0..4); + ranges.extend(std::iter::repeat_n(4..4, 256)); + ranges.push(5..6); + let tree = tree_with_ranges(source, &ranges); + assert_eq!(tree.included_ranges().len(), 258); + let context = SourceContext::new(&tree, source); + let before = included_range_visits::observed(); + let pieces = context.pieces(0..6).unwrap(); + // expected: the two nonempty intersections, with no following stop candidate. + assert_eq!(included_range_visits::observed() - before, 2); + assert_eq!(pieces.pieces().len(), 2); + assert_eq!(pieces.pieces()[0].range(), 0..4); + assert_eq!(pieces.pieces()[0].bytes(), b"///a"); + assert_eq!(pieces.pieces()[1].range(), 5..6); + assert_eq!(pieces.pieces()[1].bytes(), b"b"); + assert!(pieces.has_excluded_gap()); +} + +#[cfg(feature = "rust")] +#[test] +fn late_intersection_seeks_past_earlier_nonempty_ranges() { + let source = b"a ".repeat(256); + let ranges: Vec<_> = (0..256).map(|i| i * 2..i * 2 + 1).collect(); + let tree = tree_with_ranges(&source, &ranges); + let context = SourceContext::new(&tree, &source); + let before = included_range_visits::observed(); + let pieces = context.pieces(510..511).unwrap(); + // expected: only the last included range intersects the requested byte. + assert_eq!(included_range_visits::observed() - before, 1); + assert_eq!(pieces.pieces().len(), 1); + assert_eq!(pieces.pieces()[0].range(), 510..511); + assert_eq!(pieces.pieces()[0].bytes(), b"a"); + assert!(!pieces.has_excluded_gap()); +} + +#[cfg(feature = "rust")] +#[test] +fn empty_only_included_ranges_do_not_become_an_unrestricted_parse() { + let source = b"fn f() {}"; + let tree = tree_with_ranges(source, &[0..0, 4..4]); + assert_eq!(tree.included_ranges().len(), 2); + let context = SourceContext::new(&tree, source); + let before = included_range_visits::observed(); + assert_eq!(context.pieces(0..9), Err(SourceError::Excluded)); + assert_eq!(included_range_visits::observed() - before, 0); +} diff --git a/tests/api/parser_reuse.rs b/tests/api/parser_reuse.rs index 439addbeb..244f08ed6 100644 --- a/tests/api/parser_reuse.rs +++ b/tests/api/parser_reuse.rs @@ -35,7 +35,7 @@ use big_code_analysis::{Ast, LANG, Source, tree_sitter}; #[cfg(feature = "rust")] #[test] -fn retained_parse_provenance_preserves_legacy_cancelled_metrics() { +fn cancelled_parse_keeps_legacy_metrics_empty_and_next_parse_recovers() { let source = "/// doc\nfn f() {}\n".repeat(200); let cancel = big_code_analysis::ParseCancel::new(); cancel.cancel(); diff --git a/utils/documentation-facts-perturb.json b/utils/documentation-facts-perturb.json index 4a2835e50..797f9fa54 100644 --- a/utils/documentation-facts-perturb.json +++ b/utils/documentation-facts-perturb.json @@ -24,6 +24,27 @@ "new": "let start = spelling.start.max(range.start_byte) + 1;", "expect": ["documentation::tests::included_pieces_keep_raw_invalid_bytes_and_never_return_the_gap"] }, + { + "name": "empty-ranges-are-filtered-once", + "file": "big-code-analysis-ast/src/documentation/source.rs", + "old": "included.retain(|range| range.start_byte < range.end_byte);", + "new": "included.retain(|_| true);", + "expect": ["documentation::tests::ranges::empty_included_ranges_do_not_add_per_query_scan_work"] + }, + { + "name": "late-intersection-uses-indexed-start", + "file": "big-code-analysis-ast/src/documentation/source.rs", + "old": "let first = self\n .included\n .partition_point(|range| range.end_byte <= spelling.start);", + "new": "let first = 0;", + "expect": ["documentation::tests::ranges::late_intersection_seeks_past_earlier_nonempty_ranges"] + }, + { + "name": "canonical-node-identity-is-not-just-position", + "file": "big-code-analysis-ast/src/documentation/source.rs", + "old": "if actual.id != expected.id\n || actual.context != expected.context\n || node.kind_id() != self.canonical.kind_id()\n || node.range() != self.canonical.range()", + "new": "if actual.context != expected.context\n || node.range() != self.canonical.range()", + "expect": ["documentation::tests::provenance::canonical_evidence_rejects_clones_shifted_roots_and_edited_values"] + }, { "name": "occurrence-equality-needs-ordinal", "file": "big-code-analysis-ast/src/documentation.rs", @@ -59,6 +80,13 @@ "new": "self.reference(&self.owners, 0)", "expect": ["documentation::tests::ownership::slots_have_enclosing_owner_role_ordinal_and_source_without_fabricated_nodes"] }, + { + "name": "owner-id-is-not-association-position", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "self.reference(&self.owners, id.0)", + "new": "self.reference(&self.owners, position)", + "expect": ["documentation::tests::ownership::one_document_shared_by_two_owners_is_not_two_alternative_claims"] + }, { "name": "selection-identity-needs-view", "file": "big-code-analysis-ast/src/documentation/streaming.rs", From 0a5b6e38d9d294209bd6e59c71a7b703dcbb9b46 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:32:07 -0800 Subject: [PATCH 011/221] test(ast): establish raw documentation characterization and selected captures --- .bcaignore | 1 + .gitattributes | 3 + big-code-analysis-ast/Cargo.toml | 3 +- big-code-analysis-ast/src/test_support.rs | 2 + .../src/test_support/documentation.rs | 284 +++++++++ src/metrics/loc.rs | 3 + src/metrics/loc/documentation_tests.rs | 202 ++++++ tests/fixtures/README.md | 9 +- tests/fixtures/documentation/README.md | 79 +++ tests/fixtures/documentation/forms.json | 34 + tests/fixtures/documentation/inventory.json | 593 ++++++++++++++++++ tests/fixtures/documentation/legacy.json | 34 + tests/fixtures/documentation/provenance.json | 44 ++ ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + .../documentation/reference/manifest.json | 229 +++++++ ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + ...cs_exclude_tests_mi_charges_docs_false.txt | 1 + ...ics_exclude_tests_mi_charges_docs_true.txt | 1 + ...verbatim_metrics_mi_charges_docs_false.txt | 1 + ....verbatim_metrics_mi_charges_docs_true.txt | 1 + ...mi_exclude_tests_mi_charges_docs_false.txt | 1 + ..._mi_exclude_tests_mi_charges_docs_true.txt | 1 + ...sts_no_count_try_mi_charges_docs_false.txt | 1 + ...ests_no_count_try_mi_charges_docs_true.txt | 1 + ..._metrics_only_mi_mi_charges_docs_false.txt | 1 + ...m_metrics_only_mi_mi_charges_docs_true.txt | 1 + tests/fixtures/documentation/selection.json | 41 ++ .../documentation/sources/csharp-primary.cs | 2 + .../documentation/sources/doxygen-cdata.h | 2 + .../documentation/sources/doxygen-quote.h | 2 + .../documentation/sources/doxygen-quoted.h | 9 + .../sources/groovy-spaces.groovy | 11 + .../documentation/sources/helper-comment.c | 1 + .../documentation/sources/helper-preproc.h | 1 + .../sources/irules-continuation.irule | 4 + .../documentation/sources/irules-crlf.irule | 4 + .../documentation/sources/java-compact.java | 2 + .../documentation/sources/java-empty.java | 2 + .../documentation/sources/java-record.java | 2 + .../documentation/sources/java-selection.java | 5 + .../fixtures/documentation/sources/js-body.js | 4 + .../documentation/sources/perl-mixed.pl | 19 + .../documentation/sources/php-define.php | 4 + .../documentation/sources/primary.bash | 2 + .../fixtures/documentation/sources/primary.c | 2 + .../documentation/sources/primary.cpp | 2 + .../fixtures/documentation/sources/primary.cs | 2 + .../fixtures/documentation/sources/primary.ex | 4 + .../fixtures/documentation/sources/primary.go | 3 + .../documentation/sources/primary.groovy | 2 + .../documentation/sources/primary.irule | 3 + .../documentation/sources/primary.java | 2 + .../fixtures/documentation/sources/primary.js | 2 + .../fixtures/documentation/sources/primary.kt | 2 + .../documentation/sources/primary.lua | 3 + .../fixtures/documentation/sources/primary.m | 2 + .../documentation/sources/primary.php | 3 + .../fixtures/documentation/sources/primary.pl | 7 + .../fixtures/documentation/sources/primary.py | 3 + .../fixtures/documentation/sources/primary.rb | 3 + .../fixtures/documentation/sources/primary.rs | 2 + .../documentation/sources/primary.tcl | 4 + .../fixtures/documentation/sources/primary.ts | 2 + .../documentation/sources/primary.tsx | 2 + .../sources/python-continuation.py | 6 + .../documentation/sources/python-extras.py | 6 + .../documentation/sources/python-named.py | 3 + .../documentation/sources/python-paren.py | 3 + .../documentation/sources/python-runs.py | 10 + .../documentation/sources/rust-attribute.rs | 3 + .../documentation/sources/rust-crlf.rs | 3 + .../documentation/sources/rust-empty.rs | 2 + .../documentation/sources/rust-eof.rs | 2 + .../documentation/sources/rust-macro.rs | 2 + .../documentation/sources/rust-prune.rs | 13 + .../documentation/sources/rust-reach.rs | 3 + .../documentation/sources/rust-same-row.rs | 1 + .../sources/tcl-continuation.tcl | 4 + .../documentation/sources/tcl-crlf.tcl | 4 + ...ocumentation-characterization-perturb.json | 14 + utils/documentation-selection-perturb.json | 11 + utils/drift-oracle-test.py | 62 ++ utils/drift-oracle.py | 79 ++- 461 files changed, 2300 insertions(+), 13 deletions(-) create mode 100644 big-code-analysis-ast/src/test_support/documentation.rs create mode 100644 src/metrics/loc/documentation_tests.rs create mode 100644 tests/fixtures/documentation/README.md create mode 100644 tests/fixtures/documentation/forms.json create mode 100644 tests/fixtures/documentation/inventory.json create mode 100644 tests/fixtures/documentation/legacy.json create mode 100644 tests/fixtures/documentation/provenance.json create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/manifest.json create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt create mode 100644 tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt create mode 100644 tests/fixtures/documentation/selection.json create mode 100644 tests/fixtures/documentation/sources/csharp-primary.cs create mode 100644 tests/fixtures/documentation/sources/doxygen-cdata.h create mode 100644 tests/fixtures/documentation/sources/doxygen-quote.h create mode 100644 tests/fixtures/documentation/sources/doxygen-quoted.h create mode 100644 tests/fixtures/documentation/sources/groovy-spaces.groovy create mode 100644 tests/fixtures/documentation/sources/helper-comment.c create mode 100644 tests/fixtures/documentation/sources/helper-preproc.h create mode 100644 tests/fixtures/documentation/sources/irules-continuation.irule create mode 100644 tests/fixtures/documentation/sources/irules-crlf.irule create mode 100644 tests/fixtures/documentation/sources/java-compact.java create mode 100644 tests/fixtures/documentation/sources/java-empty.java create mode 100644 tests/fixtures/documentation/sources/java-record.java create mode 100644 tests/fixtures/documentation/sources/java-selection.java create mode 100644 tests/fixtures/documentation/sources/js-body.js create mode 100644 tests/fixtures/documentation/sources/perl-mixed.pl create mode 100644 tests/fixtures/documentation/sources/php-define.php create mode 100644 tests/fixtures/documentation/sources/primary.bash create mode 100644 tests/fixtures/documentation/sources/primary.c create mode 100644 tests/fixtures/documentation/sources/primary.cpp create mode 100644 tests/fixtures/documentation/sources/primary.cs create mode 100644 tests/fixtures/documentation/sources/primary.ex create mode 100644 tests/fixtures/documentation/sources/primary.go create mode 100644 tests/fixtures/documentation/sources/primary.groovy create mode 100644 tests/fixtures/documentation/sources/primary.irule create mode 100644 tests/fixtures/documentation/sources/primary.java create mode 100644 tests/fixtures/documentation/sources/primary.js create mode 100644 tests/fixtures/documentation/sources/primary.kt create mode 100644 tests/fixtures/documentation/sources/primary.lua create mode 100644 tests/fixtures/documentation/sources/primary.m create mode 100644 tests/fixtures/documentation/sources/primary.php create mode 100644 tests/fixtures/documentation/sources/primary.pl create mode 100644 tests/fixtures/documentation/sources/primary.py create mode 100644 tests/fixtures/documentation/sources/primary.rb create mode 100644 tests/fixtures/documentation/sources/primary.rs create mode 100644 tests/fixtures/documentation/sources/primary.tcl create mode 100644 tests/fixtures/documentation/sources/primary.ts create mode 100644 tests/fixtures/documentation/sources/primary.tsx create mode 100644 tests/fixtures/documentation/sources/python-continuation.py create mode 100644 tests/fixtures/documentation/sources/python-extras.py create mode 100644 tests/fixtures/documentation/sources/python-named.py create mode 100644 tests/fixtures/documentation/sources/python-paren.py create mode 100644 tests/fixtures/documentation/sources/python-runs.py create mode 100644 tests/fixtures/documentation/sources/rust-attribute.rs create mode 100644 tests/fixtures/documentation/sources/rust-crlf.rs create mode 100644 tests/fixtures/documentation/sources/rust-empty.rs create mode 100644 tests/fixtures/documentation/sources/rust-eof.rs create mode 100644 tests/fixtures/documentation/sources/rust-macro.rs create mode 100644 tests/fixtures/documentation/sources/rust-prune.rs create mode 100644 tests/fixtures/documentation/sources/rust-reach.rs create mode 100644 tests/fixtures/documentation/sources/rust-same-row.rs create mode 100644 tests/fixtures/documentation/sources/tcl-continuation.tcl create mode 100644 tests/fixtures/documentation/sources/tcl-crlf.tcl create mode 100644 utils/documentation-characterization-perturb.json create mode 100644 utils/documentation-selection-perturb.json diff --git a/.bcaignore b/.bcaignore index 34a57a53b..e0ed01ddb 100644 --- a/.bcaignore +++ b/.bcaignore @@ -42,6 +42,7 @@ # test modules (#1066). It is not a sibling unit-test file, so the # `*_tests.rs` glob does not reach it, and none of it ships. ./**/test_support.rs +./**/test_support/** ./target/** # Fuzzing scratch (#1154). The seed corpora are deliberately malformed # source — invalid UTF-8, NUL bytes, unterminated constructs — so diff --git a/.gitattributes b/.gitattributes index d332b110e..838032f02 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,6 @@ tree-sitter-preproc/** linguist-vendored # committed, and the fuzz run still passes because the seeds are only a # starting point. `-diff` keeps the binary ones out of patch output. fuzz/corpus/** -text -diff + +# Documentation characterization includes raw CRLF and missing-final-LF inputs. +tests/fixtures/documentation/sources/** -text diff --git a/big-code-analysis-ast/Cargo.toml b/big-code-analysis-ast/Cargo.toml index 15ec678fc..b08d3e901 100644 --- a/big-code-analysis-ast/Cargo.toml +++ b/big-code-analysis-ast/Cargo.toml @@ -25,6 +25,7 @@ num-traits = "^0.2" petgraph = "^0.8" regex = "^1.7" serde.workspace = true +serde_json = { workspace = true, optional = true } tree-sitter.workspace = true # Grammar crates are gated behind per-language Cargo features (see @@ -81,7 +82,7 @@ default = ["all-languages"] # Exposes the parse-and-inspect test helpers in `test_support` to a # dependent crate's test target (the root crate's metric tests use them). # Never enable it in a shipping build. -test-support = [] +test-support = ["dep:serde_json"] all-languages = [ "bash", "c", diff --git a/big-code-analysis-ast/src/test_support.rs b/big-code-analysis-ast/src/test_support.rs index bea267b2d..52a8296f8 100644 --- a/big-code-analysis-ast/src/test_support.rs +++ b/big-code-analysis-ast/src/test_support.rs @@ -7,6 +7,8 @@ use crate::node::{Ancestors, Node, Tree}; use crate::traits::{LanguageInfo, ParserTrait, Search}; +pub mod documentation; + /// Every declared owner of `owners` was met by a fixture (`seen` is the /// kind ids its walk emitted), except the never-emitted aliases in /// `defensive`, which must not have been — and each of those must still diff --git a/big-code-analysis-ast/src/test_support/documentation.rs b/big-code-analysis-ast/src/test_support/documentation.rs new file mode 100644 index 000000000..0e9960327 --- /dev/null +++ b/big-code-analysis-ast/src/test_support/documentation.rs @@ -0,0 +1,284 @@ +//! Independent documentation requirements and raw fixture routing. +//! +//! These describe required source extraction, not current adapter capabilities. +//! Current recognition is tested separately against the production Checker. + +use crate::LANG; + +/// Independent primary expectations, including legacy syntax observations. +/// +/// # Panics +/// If the checked inventory is not valid JSON. +#[must_use] +pub fn inventory() -> serde_json::Value { + serde_json::from_str(include_str!( + "../../../tests/fixtures/documentation/inventory.json" + )) + .expect("independent documentation inventory") +} + +/// Compare a future adapter's primary result with the independent requirement. +/// +/// The adapter projects its result to ordered records with `fragments`, `owner` +/// and `text` keys. Helpers must report `NoDeclarationModel`. Disabled languages +/// are checked separately by the adapter's feature tests, never as positives. +/// This harness does not call or claim an implemented extraction API. +/// +/// # Panics +/// If an enabled source language returns an error, empty documents, wrong ranges, +/// incomplete text, or any result differing from the primary fixture. +pub fn assert_primary_extraction(lang: LANG, result: Result) { + assert!( + lang.is_enabled(), + "a disabled language cannot qualify as a positive" + ); + let expected = &inventory()[lang.to_string()]; + match requirement(lang) { + Requirement::DeclarationText => { + assert_eq!( + result.expect("source adapter must produce declaration text"), + serde_json::json!([{ + "fragments": expected["fragments"], "owner": expected["owner"], "text": expected["text"] + }]) + ); + } + Requirement::NoDeclarationModel => assert_eq!(result, Err("NoDeclarationModel")), + } +} + +/// Required outcome for a language, even when its adapter is not implemented. +#[derive(Debug, PartialEq, Eq)] +pub enum Requirement { + /// A declaration-associated document with nonempty local text is required. + DeclarationText, + /// Helper grammars have no declaration model. + NoDeclarationModel, +} + +/// Exhaustive policy independent of runtime capability reporting. +#[must_use] +pub const fn requirement(lang: LANG) -> Requirement { + match lang { + LANG::Bash + | LANG::C + | LANG::Cpp + | LANG::Csharp + | LANG::Elixir + | LANG::Go + | LANG::Groovy + | LANG::Irules + | LANG::Java + | LANG::Javascript + | LANG::Kotlin + | LANG::Lua + | LANG::Mozcpp + | LANG::Mozjs + | LANG::Objc + | LANG::Perl + | LANG::Php + | LANG::Python + | LANG::Ruby + | LANG::Rust + | LANG::Tcl + | LANG::Tsx + | LANG::Typescript => Requirement::DeclarationText, + LANG::Ccomment | LANG::Preproc => Requirement::NoDeclarationModel, + } +} + +/// Raw source for a named fixture. Never uses the normalizing file loader. +/// +/// # Panics +/// If the tracked fixture is missing or unreadable. +#[must_use] +pub fn source(path: &str) -> Vec { + std::fs::read( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../tests/fixtures/documentation/sources") + .join(path), + ) + .expect("tracked raw documentation fixture") +} + +/// One primary input per LANG variant, including explicit helper controls. +#[must_use] +pub const fn primary(lang: LANG) -> &'static str { + match lang { + LANG::Bash => "primary.bash", + LANG::C => "primary.c", + LANG::Ccomment => "helper-comment.c", + LANG::Cpp | LANG::Mozcpp => "primary.cpp", + LANG::Csharp => "primary.cs", + LANG::Elixir => "primary.ex", + LANG::Go => "primary.go", + LANG::Groovy => "primary.groovy", + LANG::Irules => "primary.irule", + LANG::Java => "primary.java", + LANG::Javascript | LANG::Mozjs => "primary.js", + LANG::Kotlin => "primary.kt", + LANG::Lua => "primary.lua", + LANG::Objc => "primary.m", + LANG::Perl => "primary.pl", + LANG::Php => "primary.php", + LANG::Preproc => "helper-preproc.h", + LANG::Python => "primary.py", + LANG::Ruby => "primary.rb", + LANG::Rust => "primary.rs", + LANG::Tcl => "primary.tcl", + LANG::Tsx => "primary.tsx", + LANG::Typescript => "primary.ts", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Checker, test_support::for_each_node_with_sibling_cache_tolerating_errors}; + + #[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" + ))] + #[test] + fn documentation_primary_recognition() { + let inventory = inventory(); + let mut ran = 0; + assert_eq!( + inventory.as_object().expect("LANG inventory").len(), + LANG::into_enum_iter().count() + ); + for lang in LANG::into_enum_iter().filter(LANG::is_enabled) { + let entry = &inventory[lang.to_string()]; + let source = source(primary(lang)); + let mut comments = Vec::new(); + let mut owners = Vec::new(); + crate::with_code_tag!(lang, |C| { + let (_, recovered) = + for_each_node_with_sibling_cache_tolerating_errors::(&source, |node, _| { + if C::is_comment(node) { + comments.push(serde_json::json!([ + node.start_byte(), + node.end_byte(), + C::is_doc_comment(node, &source) + ])); + } + if node.is_named() + && serde_json::json!([node.start_byte(), node.end_byte()]) + == entry["owner"] + { + owners.push(node.kind()); + } + }); + assert_eq!( + recovered, + entry["recovered"] == true, + "{lang}: parse recovery" + ); + }); + assert_eq!( + serde_json::json!(comments), + entry["legacy_comments"], + "{lang}" + ); + match requirement(lang) { + Requirement::DeclarationText => { + assert!( + !entry["text"] + .as_str() + .expect("required local text") + .is_empty(), + "{lang}" + ); + assert_eq!(entry["fragments"].as_array().expect("fragments").len(), 1); + assert_eq!( + serde_json::json!(owners), + entry["owner_kinds"], + "{lang}: declaration syntax" + ); + assert!(!owners.is_empty(), "missing declaration for {lang}"); + } + Requirement::NoDeclarationModel => { + assert_eq!(entry["profile"], "NoDeclarationModel"); + assert!(entry["owner"].is_null()); + } + } + ran += 1; + } + assert!(ran > 0); + } + + #[cfg(feature = "rust")] + #[test] + fn documentation_conformance_rejects_absent_adapter_and_wrong_identity() { + for result in [ + Err("Unsupported"), + Err("NoDeclarationModel"), + Ok(serde_json::json!([])), + Ok(serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"text":""}])), + Ok(serde_json::json!([{"fragments":[[1,9]],"owner":[9,18],"text":"audit"}])), + Ok(serde_json::json!([{"fragments":[[0,8]],"owner":[0,18],"text":"audit"}])), + ] { + assert!( + std::panic::catch_unwind(|| assert_primary_extraction(LANG::Rust, result)).is_err() + ); + } + } + + #[cfg(feature = "java")] + #[test] + fn documentation_record_header_and_compact_constructor_are_distinct_nodes() { + for (file, expected) in [ + ("java-record.java", vec![("formal_parameters", 26, 33)]), + ( + "java-compact.java", + vec![("compact_constructor_declaration", 36, 40)], + ), + ] { + let source = source(file); + let mut callables = Vec::new(); + super::super::for_each_node_with_sibling_cache::( + &source, + |node, ancestors| { + if crate::JavaCode::is_func_with_code(node, &source, ancestors) { + callables.push((node.kind(), node.start_byte(), node.end_byte())); + } + }, + ); + assert_eq!(callables, expected, "{file}"); + } + } + + #[cfg(feature = "python")] + #[test] + fn documentation_named_continuation_extras_remain_in_the_tree() { + let source = source("python-extras.py"); + let mut extras = Vec::new(); + super::super::for_each_node_with_sibling_cache::(&source, |node, _| { + if node.kind() == "line_continuation" { + extras.push((node.start_byte(), node.end_byte(), node.is_named())); + } + }); + assert_eq!(extras, [(15, 17, true), (21, 23, true)]); + } +} diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 91010787a..ad7dce7e6 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -89,6 +89,9 @@ fn span_rows(start_row: usize, end_line: usize) -> usize { mod dloc; mod line_set; +#[cfg(test)] +mod documentation_tests; + use dloc::Dloc; use line_set::LineSet; diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs new file mode 100644 index 000000000..dd1e01ff4 --- /dev/null +++ b/src/metrics/loc/documentation_tests.rs @@ -0,0 +1,202 @@ +//! Legacy preservation on raw inputs; source owner/text requirements live in AST fixtures. + +use big_code_analysis_ast::test_support::documentation; +use serde_json::{Value, json}; + +use crate::{LANG, Metric, MetricsOptions, Source, analyze}; + +#[cfg(any( + feature = "c", + feature = "cpp", + feature = "mozcpp", + feature = "objc", + feature = "csharp", + feature = "rust", + feature = "java", + feature = "javascript", + feature = "mozjs", + feature = "python", + feature = "php", + feature = "perl", + feature = "groovy", + feature = "tcl", + feature = "irules" +))] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_legacy_whole_metrics() { + let manifest: Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/documentation/reference/manifest.json" + )) + .expect("capture manifest"); + let selection: Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/documentation/selection.json" + )) + .expect("selected keys"); + assert_eq!(manifest["keys"], selection); + assert_eq!(manifest["complete"], true); + assert_eq!( + manifest["views"], + json!([ + "verbatim_metrics_mi_charges_docs_false", + "verbatim_metrics_mi_charges_docs_true", + "verbatim_metrics_exclude_tests_mi_charges_docs_false", + "verbatim_metrics_exclude_tests_mi_charges_docs_true", + "verbatim_metrics_only_mi_mi_charges_docs_false", + "verbatim_metrics_only_mi_mi_charges_docs_true", + "verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false", + "verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true", + "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false", + "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true" + ]) + ); + let anchors: Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/documentation/legacy.json" + )) + .expect("independent anchors"); + let selected_files: std::collections::BTreeSet<_> = selection + .as_array() + .expect("keys") + .iter() + .map(|k| k.as_str().expect("key").rsplit('/').next().expect("file")) + .collect(); + assert_eq!( + selected_files, + anchors + .as_object() + .expect("anchors") + .keys() + .map(String::as_str) + .collect() + ); + let mut ran = 0; + for key in selection.as_array().expect("keys") { + let key = key.as_str().expect("key"); + let mut parts = key.split('/'); + let lang: LANG = parts.next().expect("language").parse().expect("known LANG"); + assert_eq!(parts.next(), Some("documentation")); + let file = parts.next().expect("file"); + assert!(parts.next().is_none()); + if !lang.is_enabled() { + continue; + } + let source = documentation::source(file); + for view in manifest["views"].as_array().expect("views") { + let view = view.as_str().expect("view"); + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/documentation/reference") + .join(format!("{key}.{view}.txt")); + let expected: Value = + serde_json::from_slice(&std::fs::read(path).expect("checked capture")) + .expect("wire JSON"); + let opt = &expected["options"]; + let excluded = opt["exclude_tests"].as_bool().expect("exclude_tests"); + let mut options = MetricsOptions::default() + .with_exclude_tests(excluded) + .with_count_cyclomatic_try(opt["count_cyclomatic_try"].as_bool().expect("try")) + .with_mi_charges_docs(opt["mi_charges_docs"].as_bool().expect("MI mode")); + match opt["metrics"].as_str().expect("selection") { + "all" => {} + "mi" => options = options.with_only(&[Metric::Mi]), + other => panic!("unexpected selection {other}"), + } + let name = format!("tests/fixtures/documentation/sources/{file}"); + let space = analyze( + Source::new(lang, &source).with_name(Some(name.clone())), + options, + ) + .expect("legacy analysis"); + let observed = json!({ + "path": name, "lang": lang.to_string(), "source_bytes": source.len(), + "options": opt, "metrics": space.to_wire(), + }); + assert_eq!(observed, expected, "{key}/{view}"); + let anchor = anchors[file] + .get(if excluded { "excluded" } else { "included" }) + .unwrap_or(&anchors[file]["included"]); + assert_eq!( + json!([ + space.metrics.loc.sloc(), + space.metrics.loc.ploc(), + space.metrics.loc.lloc(), + space.metrics.loc.cloc(), + space.metrics.loc.blank(), + space.metrics.loc.dloc() + ]), + anchor["loc"], + "{key}/{view}" + ); + let loc = &space.metrics.loc; + let rows: Vec<_> = (0..source.len()) + .filter(|row| loc.dloc.lines.contains(*row)) + .collect(); + assert_eq!(json!(rows), anchor["dloc_rows"], "{key}/{view}"); + assert_eq!(rows.len() as u64, loc.dloc()); + if matches!(lang, LANG::Tcl | LANG::Irules) { + let ploc: Vec<_> = (0..source.len()) + .filter(|row| loc.ploc.lines.contains(*row)) + .collect(); + let cloc: Vec<_> = (0..source.len()) + .filter(|row| { + loc.cloc.only_comment_line_starts.contains(*row) + || loc.cloc.code_comment_line_starts.contains(*row) + }) + .collect(); + let (want_code, want_comment) = if file.contains("crlf") { + (vec![1, 3], vec![0]) + } else { + (vec![3], vec![0, 1]) + }; + assert_eq!(ploc, want_code, "{key}: exact code rows"); + assert_eq!(cloc, want_comment, "{key}: exact comment rows"); + } + let mut nested = Vec::new(); + let mut stack: Vec<_> = space.spaces.iter().rev().collect(); + while let Some(child) = stack.pop() { + let rows: Vec<_> = (0..source.len()) + .filter(|row| child.metrics.loc.dloc.lines.contains(*row)) + .collect(); + assert_eq!(rows.len() as u64, child.metrics.loc.dloc()); + nested.push(json!([ + child.name, + child.kind, + child.start_line, + child.end_line, + rows + ])); + stack.extend(child.spaces.iter().rev()); + } + assert_eq!( + json!(nested), + anchor["spaces"], + "{key}/{view}: exact space/row population" + ); + if opt["metrics"] == "mi" { + assert_eq!( + observed["metrics"]["metrics"] + .as_object() + .expect("metrics") + .keys() + .map(String::as_str) + .collect::>(), + ["cyclomatic", "halstead", "loc", "mi"] + ); + } + if file == "python-runs.py" || file == "rust-prune.rs" { + let mi = &observed["metrics"]["metrics"]["mi"]; + assert!(mi["original"].as_f64().expect("MI") > 0.0); + assert_ne!(observed["metrics"]["metrics"]["halstead"]["length"], 0); + if opt["mi_charges_docs"] == true || file == "rust-prune.rs" { + assert!( + mi["sei"].as_f64().expect("SEI") + > mi["original"].as_f64().expect("original") + ); + } else { + assert_eq!(mi["sei"], mi["original"]); + } + } + ran += 1; + } + } + assert!(ran > 0); +} diff --git a/tests/fixtures/README.md b/tests/fixtures/README.md index 1dfe9dc71..93d4750c8 100644 --- a/tests/fixtures/README.md +++ b/tests/fixtures/README.md @@ -1,8 +1,9 @@ -# Test fixtures: vendored format schemas +# Test fixtures -This directory holds external schemas that the integration test suite -validates emitted output against. Files are vendored, never fetched at -test time, so the suite stays offline and reproducible. +This directory holds external schemas and deterministic source fixtures for the test suite. +Schemas are vendored, never fetched at test time, so the suite stays offline and reproducible. +The [documentation fixtures](documentation/README.md) preserve raw source, independent extraction +requirements and selected legacy metric captures. ## Files diff --git a/tests/fixtures/documentation/README.md b/tests/fixtures/documentation/README.md new file mode 100644 index 000000000..681ae4a6d --- /dev/null +++ b/tests/fixtures/documentation/README.md @@ -0,0 +1,79 @@ +# Documentation characterization fixtures + +These fixtures let contributors check documentation recognition and metric preservation before +changing an adapter. They assume the distinction between source attachment and documentation line +counting in the [extraction contract](../../../docs/development/documentation_extraction.md#recognition). + +`sources/` contains raw inputs. Read them as bytes: several omit the final newline or contain CRLF. +The directory's Git attributes disable newline conversion. AST test-support provides the same raw +reader to AST recognition tests and root metric tests. + +## Requirements and observations + +- `inventory.json` records the contract's primary owner, fragment ranges, profile and nonempty text + for every source dialect. Helper grammars explicitly require `NoDeclarationModel`. +- `forms.json` records additional source requirements and qualifications. The + [complete form inventory](../../../docs/development/documentation_extraction_cases.md#ownership) + remains authoritative for later adapter work. Text and attachment requirements are independently + specified; they are not generated from runtime capabilities. +- `legacy.json` anchors integer LOC values, physical documentation rows and ordered nested spaces. + Rows are zero-based. An absent `excluded` entry means the `included` expectation applies in both + pruning modes. These expectations preserve existing behavior, including named limitations. +- `reference/` holds selected whole-metric wire records from the maintained `verbatim-oracle`. + `selection.json` fixes the exact language/input keys. Its manifest records input hashes, binary + hashes, grammar pins and views. `provenance.json` records revisions and reference evidence. + +Extraction is not implemented here. `assert_primary_extraction` is the shared assertion for future +adapters. It rejects unsupported or empty results for source languages. Current tests run production +parsing, recognition and metrics; they do not claim extraction conformance. + +Rust outer docs and comments inside pruned attribute runs disappear with the item. Plain prefixes +and inner docs survive. The attribute-value reach case preserves the documented +[#1786 limitation](https://github.com/dekobon/big-code-analysis/issues/1786). +Java's empty block has a source requirement distinct from the older block billed by legacy DLOC. +Mixed Perl POD bills comment-only subregions inside a documentation token, although they are not +source prose. Tcl/iRules CRLF continuation cases preserve +[#1802](https://github.com/dekobon/big-code-analysis/issues/1802). + +## Replay + +Run from the repository root. The checked records use repository-relative input names passed to the +oracle before parsing. No observed text, numeric value, row order or output path is rewritten. +Binary and fixture-root paths in the capture manifest are provenance, not metric values. + +```bash +cargo test -p big-code-analysis-ast --all-features --lib documentation_ +cargo test -p big-code-analysis --all-features --lib documentation_ +python3 -B -m unittest -q utils/drift-oracle-test.py utils/drift-compare-test.py +cargo build -p big-code-analysis-cli -p big-code-analysis-bench --bin bca --bin verbatim-oracle +out=$(mktemp -d /tmp/opencode/bca-documentation-replay.XXXXXX) +views=( + verbatim_metrics_mi_charges_docs_false + verbatim_metrics_mi_charges_docs_true + verbatim_metrics_exclude_tests_mi_charges_docs_false + verbatim_metrics_exclude_tests_mi_charges_docs_true + verbatim_metrics_only_mi_mi_charges_docs_false + verbatim_metrics_only_mi_mi_charges_docs_true + verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false + verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true + verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false + verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true +) +args=() +for view in "${views[@]}"; do args+=(--view "$view"); done +python3 -B utils/drift-oracle.py --bca target/debug/bca \ + --verbatim target/debug/verbatim-oracle --out "$out" \ + --root documentation=tests/fixtures/documentation/sources \ + --selection tests/fixtures/documentation/selection.json \ + --relative-paths --jobs 2 "${args[@]}" +python3 -B utils/drift-compare.py tests/fixtures/documentation/reference "$out" +``` + +The selected capture exercises both MI documentation modes with all metrics and MI-only dependency +closure, pruning, and the combined pruning/try-count choice. The root test checks whole serialized +space trees as well as integer and row anchors. No external documentation generator runs in CI. + +To extend the fixtures, specify source outcomes from the contract or a versioned reference first. +Add raw source and independent legacy anchors, select the input explicitly, then review its capture. +Use `utils/perturb.py` with the tracked characterization manifests to verify decision-bearing guards +on a clean checkpoint. The manifests state their sweep scope; they do not claim unique guards. diff --git a/tests/fixtures/documentation/forms.json b/tests/fixtures/documentation/forms.json new file mode 100644 index 000000000..674e01029 --- /dev/null +++ b/tests/fixtures/documentation/forms.json @@ -0,0 +1,34 @@ +{ + "contract": "../../../docs/development/documentation_extraction.md", + "additional_required_cases": "../../../docs/development/documentation_extraction_cases.md", + "status": "independent requirements; extraction is not implemented or claimed conformant", + "range_notation": "Half-open bytes; spelling ranges refer to the exact occurrence in the raw file. Comment terminators exclude LF/CRLF. Owner ranges include the entire declaration unless a slot is named.", + "cases": [ + {"path":"python-extras.py","documents":[{"fragment_spelling":"\"\"\"doc\"\"\"","owner":"f","text":"doc","role":"primary"}],"legacy":"Named line_continuation extras and ordinary comment are read past for recognition; rows 1,4 DLOC, rows 1,2,3,4 CLOC."}, + {"path":"java-selection.java","profile":"Jdk25Source","documents":[{"fragments":[[19,23]],"owner":[24,34],"text":"","availability":"complete"}],"superseded":[[0,18]],"legacy":"Rows 0,1,2 only; empty block on row 3 is not a legacy marker."}, + {"path":"java-empty.java","profile":"Jdk25Source","documents":[{"fragments":[[0,4]],"owner":[5,15],"text":"","availability":"complete"}],"reference_deviation":"JDK 25.0.5 returns slash; BCA delimiter cleanup intentionally returns empty."}, + {"path":"js-body.js","languages":["javascript","mozjs"],"documents":[],"evidence":[{"fragments":[[19,30]],"owner":null,"text":"note","availability":"complete","association":"unattached"}],"legacy":"Row 1 belongs to f and unit; it does not establish a source owner."}, + {"path":"rust-macro.rs","documents":[{"fragments":[[5,13]],"owner":null,"text":"audit","availability":"complete","association":"unresolved macro expansion","publication":"unknown"}],"legacy":"One documentation row and no nested function space."}, + {"path":"rust-empty.rs","documents":[{"fragments":[[0,5]],"owner":"file","text":"","availability":"complete"}]}, + {"path":"rust-attribute.rs","documents":[{"fragments":[[0,9],[10,28]],"owner":"fn f() { work()?; }","text":"first\nsecond","availability":"complete","role":"primary"}],"legacy":"Attribute remains code; only row 0 is DLOC."}, + {"path":"rust-prune.rs","documents":[{"fragment_spelling":"/// outer","owner":"fn removed() { work()?; }","text":"outer"},{"fragment_spelling":"//! inner control","owner":"file","text":"inner control"},{"fragment_spelling":"/// kept","owner":"fn kept() { work()?; }","text":"kept"}],"legacy":"exclude_tests removes outer and between-attributes comments; plain prefix and inner control survive. Source selection is independent of pruning."}, + {"path":"rust-reach.rs","documents":[{"fragment_spelling":"#[doc = { #[cfg(test)] fn helper() { if a {} } \"\" }]","owner":"fn f() {}","availability":"unavailable computed expression"}],"limitation":"#1786: consuming procedural macro can accept expression-valued attribute; retained reach keeps helper even with exclude_tests. No macro execution or repaired-pruning claim."}, + {"path":"rust-eof.rs","documents":[],"evidence":[{"fragment_spelling":"/// tail","owner":null,"text":"tail","association":"dangling"}],"raw":"No final newline."}, + {"path":"rust-crlf.rs","documents":[{"fragment_spelling":"/// kept","owner":"fn kept() { work()?; }","text":"kept"}],"evidence":[{"fragment_spelling":"/// tail","owner":null,"text":"tail","association":"dangling"}],"raw":"CRLF including final terminator; fragment excludes both bytes."}, + {"path":"rust-same-row.rs","documents":[{"fragment_spellings":["/*! a */","/*! b */"],"owner":"file","text":"a\nb"}],"legacy":"Two comments share physical row 0; DLOC is one."}, + {"path":"python-runs.py","documents":[{"fragment_spelling":"\"\"","owner":"f","text":"","role":"primary"},{"fragment_spelling":"\"extra\"","owner":"f","text":"extra","role":"additional"},{"fragment_spelling":"#: setting","owner":"x binding","text":"setting","role":"Sphinx"},{"fragment_spelling":"\"attribute\"","owner":"x binding","text":"attribute","role":"attribute-binding"}]}, + {"path":"python-paren.py","documents":[{"fragments":[[14,19],[36,41]],"owner":"f","text":"@audit","role":"primary","origins":[[0,3,15,18],[3,6,37,40]]}],"legacy":"Parentheses and ordinary comment rows remain coverage, never documentation text."}, + {"path":"python-named.py","documents":[{"fragment_spelling":"\"\\N{COMMERCIAL AT}audit\"","owner":"f","availability":"unavailable named Unicode escape","role":"primary"}],"legacy":"The whole literal row is DLOC. Python itself decodes @audit; initial BCA decoder deliberately does not."}, + {"path":"python-continuation.py","documents":[{"fragment_spelling":"\"primary\"","owner":"f","text":"primary","role":"primary"},{"fragment_spelling":"\"additional\"","owner":"f","text":"additional","role":"additional"}],"limitation":"Pinned grammar exposes no named line_continuation nodes for this spelling and places return at module level; legacy rows 2,4 only."}, + {"path":"php-define.php","profiles":{"BcaPhpSource":[{"fragment_spelling":"/** audit */","owner":"constant slot X","text":"audit"},{"fragment_spelling":"/** body */","owner":"constant slot Y inside f","text":"body"}],"PhpDocumentor":[{"fragment_spelling":"/** audit */","owner":"file","text":"audit"},{"fragment_spelling":"/** body */","owner":"constant slot Y inside f","text":"body"}]},"legacy":"Only row 1 billed; body constant association does not imply DLOC."}, + {"path":"doxygen-quote.h","languages":["c","cpp","mozcpp","objc"],"documents":[],"evidence":[{"fragment_spelling":"/** \"@file\" */","owner":null,"text":"\"@file\"","association":"unattached"}],"legacy":"Quoted structural tag is not a gatherer; DLOC zero."}, + {"path":"doxygen-cdata.h","languages":["c","cpp","mozcpp","objc"],"documents":[],"evidence":[{"fragment_spelling":"/** */","owner":null,"text":"","association":"unattached"}],"legacy":"CDATA structural tag is not a gatherer; DLOC zero."}, + {"path":"doxygen-quoted.h","languages":["c","cpp","mozcpp","objc"],"documents":[{"fragment_spellings":["/** \"@file\" */","/** */","/** \"x\" @file */"],"owner":"file","text":"\"@file\"\n\n\"x\" @file"},{"fragment_spellings":["/** first */","/** second */"],"owner":"f","text":"first\nsecond"}],"legacy":"Later real @file gathers the preceding blocks; all five comment rows are DLOC."}, + {"path":"perl-mixed.pl","profile":"Pod","documents":[{"owner":"file","text":"=head2 f\n\nAudit","excluded_region":"=begin comment through =end comment"},{"owner":"file","text":"=head1 NAME\n\nData docs","location":"inside opaque __END__ node"}],"alternate":"PodUniqueHeading infers first document to unique sub f, never second.","legacy":"Mixed POD token bills its entire span including comment-only subsection; data POD bills rows 14..18. This is preservation, not source prose truth."}, + {"path":"groovy-spaces.groovy","documents":[{"fragment_spelling":"/** record */","owner":"record R","text":"record"},{"fragment_spelling":"/** type */","owner":"class C","text":"type"},{"fragment_spelling":"/** ctor */","owner":"constructor C()","text":"ctor"},{"fragment_spelling":"/** field */","owner":"field C.x","text":"field"},{"fragment_spelling":"/** method */","owner":"method C.f","text":"method"}],"legacy":"Synthetic record header and explicit constructor are distinct function spaces; new-expression identifier aliases remain code."}, + {"path":"java-record.java","documents":[{"fragment_spelling":"/** Record doc */","owner":"record R","text":"Record doc"}],"legacy":"Header (int a), bytes 26..33, opens synthetic function; type docs stay in unit."}, + {"path":"java-compact.java","documents":[{"fragment_spelling":"/** Record doc */","owner":"record R","text":"Record doc"}],"legacy":"R {}, bytes 36..40, opens explicit function instead of header."}, + {"path":"csharp-primary.cs","documents":[{"fragment_spelling":"/// type","owner":"class C","text":"type"}],"legacy":"Parameter list opens primary constructor; it does not own the type's doc."}, + {"paths":["tcl-continuation.tcl","tcl-crlf.tcl","irules-continuation.irule","irules-crlf.irule"],"documents":[],"evidence":"Ordinary comment with continuation; no declaration owner.","limitation":"#1802: CRLF backslash row parses as command/code; LF twin credits comment continuation. Do not infer owners from affected boundaries."} + ] +} diff --git a/tests/fixtures/documentation/inventory.json b/tests/fixtures/documentation/inventory.json new file mode 100644 index 000000000..7a4760304 --- /dev/null +++ b/tests/fixtures/documentation/inventory.json @@ -0,0 +1,593 @@ +{ + "rust": { + "path": "primary.rs", + "profile": "RustCompiler", + "fragments": [ + [ + 0, + 8 + ] + ], + "owner": [ + 9, + 18 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 9, + true + ] + ], + "owner_kinds": [ + "function_item" + ] + }, + "python": { + "path": "primary.py", + "profile": "Pep257Pep258Sphinx", + "fragments": [ + [ + 13, + 20 + ] + ], + "owner": [ + 0, + 29 + ], + "text": "audit", + "legacy_comments": [], + "owner_kinds": [ + "module", + "function_definition" + ] + }, + "java": { + "path": "primary.java", + "profile": "Jdk25Source", + "fragments": [ + [ + 0, + 8 + ] + ], + "owner": [ + 9, + 19 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 8, + true + ] + ], + "owner_kinds": [ + "class_declaration" + ] + }, + "kotlin": { + "path": "primary.kt", + "profile": "KDoc", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 21 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "groovy": { + "path": "primary.groovy", + "profile": "Groovydoc", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 21 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "class_declaration" + ] + }, + "csharp": { + "path": "primary.cs", + "profile": "CsharpXml", + "fragments": [ + [ + 0, + 27 + ] + ], + "owner": [ + 28, + 38 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 27, + true + ] + ], + "owner_kinds": [ + "class_declaration" + ] + }, + "php": { + "path": "primary.php", + "profile": "BcaPhpSource", + "fragments": [ + [ + 6, + 18 + ] + ], + "owner": [ + 19, + 34 + ], + "text": "audit", + "legacy_comments": [ + [ + 6, + 18, + true + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "javascript": { + "path": "primary.js", + "profile": "JsDoc", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 26 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "mozjs": { + "path": "primary.js", + "profile": "JsDoc", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 26 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "typescript": { + "path": "primary.ts", + "profile": "BcaTypescriptSource", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 32 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "tsx": { + "path": "primary.tsx", + "profile": "BcaTypescriptSource", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 42 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "c": { + "path": "primary.c", + "profile": "Doxygen", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 26 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "cpp": { + "path": "primary.cpp", + "profile": "Doxygen", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 22 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "mozcpp": { + "path": "primary.cpp", + "profile": "Doxygen", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 22 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "objc": { + "path": "primary.m", + "profile": "Doxygen", + "fragments": [ + [ + 0, + 10 + ] + ], + "owner": [ + 11, + 26 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 10, + true + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "go": { + "path": "primary.go", + "profile": "GoDoc", + "fragments": [ + [ + 10, + 18 + ] + ], + "owner": [ + 19, + 30 + ], + "text": "audit", + "legacy_comments": [ + [ + 10, + 18, + false + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "ruby": { + "path": "primary.rb", + "profile": "Yard", + "fragments": [ + [ + 0, + 7 + ] + ], + "owner": [ + 8, + 17 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 7, + false + ] + ], + "owner_kinds": [ + "method" + ] + }, + "lua": { + "path": "primary.lua", + "profile": "LDoc", + "fragments": [ + [ + 12, + 20 + ] + ], + "owner": [ + 21, + 37 + ], + "text": "audit", + "legacy_comments": [ + [ + 12, + 20, + false + ] + ], + "owner_kinds": [ + "function_declaration" + ] + }, + "perl": { + "path": "primary.pl", + "profile": "PodUniqueHeading", + "fragments": [ + [ + 0, + 21 + ] + ], + "owner": [ + 23, + 31 + ], + "text": "=head2 f\n\nAudit", + "legacy_comments": [ + [ + 0, + 21, + true + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "elixir": { + "path": "primary.ex", + "profile": "ElixirCompiler", + "fragments": [ + [ + 17, + 29 + ] + ], + "owner": [ + 32, + 48 + ], + "text": "audit", + "legacy_comments": [], + "owner_kinds": [ + "call" + ] + }, + "bash": { + "path": "primary.bash", + "profile": "Shdoc", + "fragments": [ + [ + 0, + 20 + ] + ], + "owner": [ + 21, + 31 + ], + "text": "@description audit", + "legacy_comments": [ + [ + 0, + 20, + false + ] + ], + "owner_kinds": [ + "function_definition" + ] + }, + "tcl": { + "path": "primary.tcl", + "profile": "StaticRuff304", + "fragments": [ + [ + 12, + 19 + ] + ], + "owner": [ + 0, + 28 + ], + "text": "audit", + "legacy_comments": [ + [ + 12, + 19, + false + ] + ], + "recovered": true, + "owner_kinds": [ + "source_file", + "procedure" + ] + }, + "irules": { + "path": "primary.irule", + "profile": "BcaIrules", + "fragments": [ + [ + 0, + 7 + ] + ], + "owner": [ + 8, + 29 + ], + "text": "audit", + "legacy_comments": [ + [ + 0, + 7, + false + ] + ], + "recovered": true, + "owner_kinds": [ + "when_event" + ] + }, + "ccomment": { + "path": "helper-comment.c", + "profile": "NoDeclarationModel", + "fragments": [], + "owner": null, + "text": null, + "legacy_comments": [ + [ + 0, + 10, + false + ] + ], + "owner_kinds": [] + }, + "preproc": { + "path": "helper-preproc.h", + "profile": "NoDeclarationModel", + "fragments": [], + "owner": null, + "text": null, + "legacy_comments": [], + "owner_kinds": [] + } +} diff --git a/tests/fixtures/documentation/legacy.json b/tests/fixtures/documentation/legacy.json new file mode 100644 index 000000000..407aed00c --- /dev/null +++ b/tests/fixtures/documentation/legacy.json @@ -0,0 +1,34 @@ +{ + "python-extras.py": {"included":{"loc":[6,2,2,4,0,2],"dloc_rows":[1,4],"spaces":[["f","function",1,6,[1,4]]]}}, + "python-named.py": {"included":{"loc":[3,2,2,1,0,1],"dloc_rows":[1],"spaces":[["f","function",1,3,[1]]]}}, + "rust-attribute.rs": {"included":{"loc":[3,2,1,1,0,1],"dloc_rows":[0],"spaces":[["f","function",3,3,[]]]}}, + "csharp-primary.cs": {"included":{"loc":[2,1,1,1,0,1],"dloc_rows":[0],"spaces":[["C","class",2,2,[]],["C","function",2,2,[]],["F","function",2,2,[]]]}}, + "java-selection.java": {"included":{"loc":[5,1,0,4,0,3],"dloc_rows":[0,1,2],"spaces":[["C","class",5,5,[]]]}}, + "java-empty.java": {"included":{"loc":[2,1,0,1,0,0],"dloc_rows":[],"spaces":[["C","class",2,2,[]]]}}, + "java-record.java": {"included":{"loc":[2,1,0,1,0,1],"dloc_rows":[0],"spaces":[["R","class",2,2,[]],["R","function",2,2,[]]]}}, + "java-compact.java": {"included":{"loc":[2,1,0,1,0,1],"dloc_rows":[0],"spaces":[["R","class",2,2,[]],["R","function",2,2,[]]]}}, + "js-body.js": {"included":{"loc":[4,3,1,1,0,1],"dloc_rows":[1],"spaces":[["f","function",1,4,[1]]]}}, + "rust-empty.rs": {"included":{"loc":[2,1,0,1,0,1],"dloc_rows":[0],"spaces":[["f","function",2,2,[]]]}}, + "rust-macro.rs": {"included":{"loc":[2,2,0,1,0,1],"dloc_rows":[0],"spaces":[]}}, + "rust-eof.rs": {"included":{"loc":[2,1,1,1,0,0],"dloc_rows":[],"spaces":[["f","function",1,1,[]]]}}, + "rust-crlf.rs": {"included":{"loc":[3,1,1,2,0,1],"dloc_rows":[0],"spaces":[["kept","function",2,2,[]]]}}, + "rust-same-row.rs": {"included":{"loc":[1,1,1,1,0,1],"dloc_rows":[0],"spaces":[["f","function",1,1,[]]]}}, + "rust-reach.rs": {"included":{"loc":[3,3,1,0,0,0],"dloc_rows":[],"spaces":[["helper","function",2,2,[]],["f","function",3,3,[]]]}}, + "rust-prune.rs": { + "included":{"loc":[13,8,4,5,0,3],"dloc_rows":[0,8,11],"spaces":[["removed","function",5,5,[]],["plain","function",8,8,[]],["inner","function",11,11,[]],["kept","function",13,13,[]]]}, + "excluded":{"loc":[4,1,1,3,0,2],"dloc_rows":[8,11],"spaces":[["kept","function",13,13,[]]]} + }, + "python-runs.py": {"included":{"loc":[10,5,7,4,1,4],"dloc_rows":[1,2,7,9],"spaces":[["f","function",1,6,[1,2]]]}}, + "python-paren.py": {"included":{"loc":[3,1,1,2,0,2],"dloc_rows":[1,2],"spaces":[["f","function",1,3,[1,2]]]}}, + "python-continuation.py": {"included":{"loc":[6,2,3,2,2,2],"dloc_rows":[2,4],"spaces":[["f","function",1,5,[2,4]]]}}, + "php-define.php": {"included":{"loc":[4,3,3,2,0,1],"dloc_rows":[1],"spaces":[["f","function",4,4,[]]]}}, + "doxygen-quoted.h": {"included":{"loc":[9,4,1,5,0,5],"dloc_rows":[0,2,4,6,7],"spaces":[["f","function",9,9,[]]]}}, + "doxygen-quote.h": {"included":{"loc":[2,1,0,1,0,0],"dloc_rows":[],"spaces":[]}}, + "doxygen-cdata.h": {"included":{"loc":[2,1,0,1,0,0],"dloc_rows":[],"spaces":[]}}, + "perl-mixed.pl": {"included":{"loc":[19,2,1,16,1,16],"dloc_rows":[0,1,2,3,4,5,6,7,8,9,10,14,15,16,17,18],"spaces":[["f","function",13,13,[]]]}}, + "groovy-spaces.groovy": {"included":{"loc":[11,6,1,5,0,5],"dloc_rows":[0,2,4,6,8],"spaces":[["R","class",2,2,[]],["R","function",2,2,[]],["C","class",4,11,[4,6,8]],["C","function",6,6,[]],["f","function",10,10,[]]]}}, + "tcl-continuation.tcl": {"included":{"loc":[4,1,1,2,1,0],"dloc_rows":[],"spaces":[]}}, + "tcl-crlf.tcl": {"included":{"loc":[4,2,2,1,1,0],"dloc_rows":[],"spaces":[]}}, + "irules-continuation.irule": {"included":{"loc":[4,1,1,2,1,0],"dloc_rows":[],"spaces":[]}}, + "irules-crlf.irule": {"included":{"loc":[4,2,2,1,1,0],"dloc_rows":[],"spaces":[]}} +} diff --git a/tests/fixtures/documentation/provenance.json b/tests/fixtures/documentation/provenance.json new file mode 100644 index 000000000..27ec8b3f5 --- /dev/null +++ b/tests/fixtures/documentation/provenance.json @@ -0,0 +1,44 @@ +{ + "date": "2026-11-18", + "semantic_base": "b47ea189ba51fe50d6362f876e77126c35d307d0", + "oracle_build_revision": "3c25db8e3224abcb6e41fde3c2d011655c868149", + "oracle_portion": "a776c9d4a4927c016413c94596d9cd12925c5b0c", + "build_worktree_changes": "New test-support module routing, cfg(test) root routing and raw fixtures present during build. No shipping metric, Checker, Getter, role or shared binding changes. Capture driver selection additions run from this checkpoint's source.", + "semantic_base_check": "git diff b47ea189 -- src/metrics big-code-analysis-ast/src/checker big-code-analysis-ast/src/lang_helpers big-code-analysis-ast/src/roles src/spaces src/options.rs (only cfg(test) mod documentation_tests added to loc.rs)", + "build_command": "cargo build -p big-code-analysis-cli -p big-code-analysis-bench --bin bca --bin verbatim-oracle", + "rustc": "rustc 1.99.0 (b940084d7 2026-09-28), commit b940084d7eb6a299eb4bfeb8e34901bc051e7ac4; host aarch64-unknown-linux-gnu; LLVM 23.1.1", + "python_driver": "Python 3.14.3", + "grammar_pins": "reference/manifest.json: grammar_pins (exact workspace dependency requirements at the semantic base)", + "capture": { + "command": "python3 -B utils/drift-oracle.py --bca target/debug/bca --verbatim target/debug/verbatim-oracle --out tests/fixtures/documentation/reference --root documentation=tests/fixtures/documentation/sources --selection tests/fixtures/documentation/selection.json --relative-paths --view verbatim_metrics_mi_charges_docs_false --view verbatim_metrics_mi_charges_docs_true --view verbatim_metrics_exclude_tests_mi_charges_docs_false --view verbatim_metrics_exclude_tests_mi_charges_docs_true --view verbatim_metrics_only_mi_mi_charges_docs_false --view verbatim_metrics_only_mi_mi_charges_docs_true --view verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false --view verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true --view verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false --view verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true --jobs 2", + "keys": 39, + "views_per_key": 10, + "outputs": 390, + "format": "Unmodified verbatim-oracle metrics-view JSON bytes with terminal LF; metrics is public FuncSpace::to_wire output, not internal loc::Stats equality.", + "normalization": "None. Repository-relative display paths supplied before analysis; raw source bytes preserve CRLF and missing final LF. No observed arrays sorted or text trimmed.", + "config": "Default cargo features; debug profile; no filesystem metric configuration; options explicit in every view. No external generators executed.", + "scope": "Selected characterization fixtures only. Full repository corpus capture deferred to parent. CLI/default/recovery oracle protocol retained and self-tested separately." + }, + "independent_expectations": { + "revision": "42d39ad8cb854536e432dcce164fb7392121cccb", + "sources": ["docs/development/documentation_extraction.md", "docs/development/documentation_extraction_cases.md"], + "reference_record": "https://gist.github.com/dekobon/acb5b4fd9ada1c2b63f86ae0f0514524", + "qualification": "Source expectations copied from accepted D01, not generated from extractor output. Primary LANG inventory requires declaration-associated nonempty text for each source variant, with explicit helper exceptions. Future extraction conformance remains unimplemented." + }, + "references": [ + {"tool":"Zulu OpenJDK","version":"25.0.5.0.3+1-LTS","evidence":"Prior D01 executed observation, not rerun here","configuration":"JavacTask.parse, -proc:none, logical C.java; DocTrees.getDocComment/getDocCommentTree","command":"jshell --feedback concise; complete source and exact commands in reference_record","reference":"https://docs.oracle.com/en/java/javase/25/docs/specs/javadoc/doc-comment-spec.html","qualification":"BCA empty-block local cleanup intentionally differs from returned slash."}, + {"tool":"Python","version":"3.12.13","evidence":"Prior D01 executed observation, not rerun here","configuration":"ast.get_docstring(clean=False), then inspect.cleandoc; exact command in reference_record","reference":"https://docs.python.org/3.12/library/inspect.html#inspect.cleandoc","qualification":"BCA named escape unavailability is deliberate; raw literal remains recognized by legacy metrics."}, + {"tool":"Rust","version":"1.99.0","evidence":"Source-only D01 inspection","configuration":"beautify_doc_string, unindent_doc_fragments, opt_doc_value; no rustdoc run","reference":"https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_ast/src/util/comments.rs"}, + {"tool":"phpDocumentor Reflection","version":"7.0.0 / 70254fa0b3058b16908a3a9d95f7dca904e03396","evidence":"Source-only D01 inspection","configuration":"createFileDocBlock; BcaPhpSource declaration-first versus PhpDocumentor file-first","reference":"https://github.com/phpDocumentor/Reflection/blob/70254fa0b3058b16908a3a9d95f7dca904e03396/src/phpDocumentor/Reflection/Php/Factory/File.php"}, + {"tool":"Elixir","version":"1.20.1","evidence":"Source-only D01 inspection","configuration":"Module.put_attribute, compile_doc and metadata merge; no compiler run","reference":"https://github.com/elixir-lang/elixir/blob/v1.20.1/lib/elixir/lib/module.ex"}, + {"tool":"Ruff!","version":"3.0.4","evidence":"Manual-only D01 evidence","configuration":"Static procedure body comment profile; no Ruff implementation run","reference":"https://ruff.magicsplat.com/v3.0/ruff-ruff.html"}, + {"tool":"Other profiles","version":null,"evidence":"Authoritative source/manual references in D01; no versioned tool execution claimed","configuration":"Named profile in inventory.json and forms.json","reference":"../../../docs/development/documentation_extraction.md#profiles"} + ], + "retained_limitations": [ + "#1786 retained attribute-value reach; consuming macro input not executed", + "#1802 Tcl/iRules raw CRLF continuation commands", + "Tcl/iRules primary inputs without final LF have a missing newline token at EOF; declaration ranges and comments remain available", + "python-continuation.py pinned parser places return outside function; python-extras.py separately exercises named continuation nodes", + "Mixed Perl POD whole-token legacy billing is not source prose eligibility" + ] +} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..8b863276d --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..2fb593ebb --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..d63c4da75 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..b9b238770 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..01d04a4f0 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..c79f83405 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..51ac4324f --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..c5e71ca0b --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..b1d0c19d9 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..ca9a05ab5 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..3cfee3f1e --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..0c76cb0cb --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..ac9d50c8b --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..58c8631b9 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..59dbeb365 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..22c1f2c67 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..bde51826d --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..f49caef07 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..2e7ab3633 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..01c043cbe --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..61254c1fa --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..237a742a0 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..521cf1b7b --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..585cdd781 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..055480823 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..d20eca88b --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..d8e5f9c4a --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..6a0e29502 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..dc0e04c09 --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..ed497bc1c --- /dev/null +++ b/tests/fixtures/documentation/reference/c/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"c","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..9147d33af --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..353d49a74 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..6506b47a1 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..a467ef551 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..aa337e7d8 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..0e4a21be5 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..769e30874 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..00edca952 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..1ec22c8b3 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..3f4e02bd6 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..e30d0ad29 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..8152f2dfa --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..bc6bf7039 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..83425de4e --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..db8d3143e --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..3b068bfed --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..8e7450e8b --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..6bbc9fdf6 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..d3bebc456 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..bcc54f0b4 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..8389b26a6 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..1a02e15d9 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..34c89a73f --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..a33acf42d --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..e5acaacb5 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..2e0426a31 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..12a796ef0 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..865cef22b --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..ecb7c3f67 --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..7e111995a --- /dev/null +++ b/tests/fixtures/documentation/reference/cpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"cpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..d77bfbbdf --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":149.54439657604067,"visual_studio":87.45286349476062},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":4.75,"max":11,"min":0,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":6.333333333333333,"max":11,"min":4,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..f4ebf1c7a --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":194.00099878240488,"visual_studio":87.45286349476062},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":4.75,"max":11,"min":0,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":6.333333333333333,"max":11,"min":4,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..2cf7b65f2 --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":149.54439657604067,"visual_studio":87.45286349476062},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":4.75,"max":11,"min":0,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":6.333333333333333,"max":11,"min":4,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..49a27528a --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":194.00099878240488,"visual_studio":87.45286349476062},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":4.75,"max":11,"min":0,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722},"nargs":{"average":0.5,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.5,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.5,"class_methods":2,"class_npm_sum":1,"coa":0.5,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":1,"total_methods":2},"tokens":{"average":6.333333333333333,"max":11,"min":4,"tokens":19},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..9f5190d6d --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":149.54439657604067,"visual_studio":87.45286349476062}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..bdc7d8642 --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":194.00099878240488,"visual_studio":87.45286349476062}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..40db141b2 --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":149.54439657604067,"visual_studio":87.45286349476062}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..70a18ce0b --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":194.00099878240488,"visual_studio":87.45286349476062}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..c53272fe7 --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":149.54439657604067,"visual_studio":87.45286349476062}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..bd4ee0afb --- /dev/null +++ b/tests/fixtures/documentation/reference/csharp/documentation/csharp-primary.cs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"csharp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.25,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.25,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.25,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.25,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.5,"sloc_max":2,"sloc_min":1},"mi":{"original":149.54439657604067,"sei":194.00099878240488,"visual_studio":87.45286349476062}},"name":"tests/fixtures/documentation/sources/csharp-primary.cs","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.012404943480462215,"difficulty":4.375,"effort":227.02519997307263,"estimated_program_length":27.651484454403228,"length":15,"level":0.22857142857142856,"purity_ratio":1.8434322969602153,"time":12.612511109615147,"total_operands":5,"total_operators":10,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":51.89147427955946},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.3333333333333333,"sloc_max":1,"sloc_min":1},"mi":{"original":149.77439657604066,"sei":149.77439657604066,"visual_studio":87.58736641873722}},"name":"C","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2},{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.006473720020679235,"difficulty":3.0,"effort":85.58797503894243,"estimated_program_length":20.264662506490403,"length":9,"level":0.3333333333333333,"purity_ratio":2.2516291673878226,"time":4.754887502163468,"total_operands":3,"total_operators":6,"unique_operands":3,"unique_operators":6,"vocabulary":9,"volume":28.52932501298081},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":153.34515096830847,"sei":153.34515096830847,"visual_studio":89.67552688205174}},"name":"F","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/csharp-primary.cs","source_bytes":73} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..a604a425d --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.16666666666666666,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":117.88098616851792,"visual_studio":68.93624922135551},"nargs":{"average":0.3333333333333333,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.3333333333333333,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.3333333333333333,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":3,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":3},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":3,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":3},"tokens":{"average":5.0,"max":11,"min":0,"tokens":30},"wmc":{"class_wmc_sum":3,"interface_wmc_sum":0,"total":3}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.3333333333333333,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":123.57680856060671,"visual_studio":72.26713950912674},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":2,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":2},"tokens":{"average":7.333333333333333,"max":11,"min":5,"tokens":22},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..61228e909 --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.16666666666666666,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":161.11380450516475,"visual_studio":68.93624922135551},"nargs":{"average":0.3333333333333333,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.3333333333333333,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.3333333333333333,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":3,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":3},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":3,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":3},"tokens":{"average":5.0,"max":11,"min":0,"tokens":30},"wmc":{"class_wmc_sum":3,"interface_wmc_sum":0,"total":3}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.3333333333333333,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":164.20925339270855,"visual_studio":72.26713950912674},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":2,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":2},"tokens":{"average":7.333333333333333,"max":11,"min":5,"tokens":22},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..1e9bf6b0c --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.16666666666666666,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":117.88098616851792,"visual_studio":68.93624922135551},"nargs":{"average":0.3333333333333333,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.3333333333333333,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.3333333333333333,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":3,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":3},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":3,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":3},"tokens":{"average":5.0,"max":11,"min":0,"tokens":30},"wmc":{"class_wmc_sum":3,"interface_wmc_sum":0,"total":3}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.3333333333333333,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":123.57680856060671,"visual_studio":72.26713950912674},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":2,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":2},"tokens":{"average":7.333333333333333,"max":11,"min":5,"tokens":22},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..1bf2ef49a --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.16666666666666666,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":161.11380450516475,"visual_studio":68.93624922135551},"nargs":{"average":0.3333333333333333,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":0.3333333333333333,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.3333333333333333,"max":1,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":3,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":3},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":3,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":3},"tokens":{"average":5.0,"max":11,"min":0,"tokens":30},"wmc":{"class_wmc_sum":3,"interface_wmc_sum":0,"total":3}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":0.3333333333333333,"branches_max":1,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":164.20925339270855,"visual_studio":72.26713950912674},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.5,"max":1,"min":0,"sum":1},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":1,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":1},"npm":{"class_coa":0.0,"class_methods":2,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":2},"tokens":{"average":7.333333333333333,"max":11,"min":5,"tokens":22},"wmc":{"class_wmc_sum":2,"interface_wmc_sum":0,"total":2}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..46dc0cb31 --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":117.88098616851792,"visual_studio":68.93624922135551}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":123.57680856060671,"visual_studio":72.26713950912674}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..3d35c9b0c --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":161.11380450516475,"visual_studio":68.93624922135551}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":164.20925339270855,"visual_studio":72.26713950912674}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..56c6a9505 --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":117.88098616851792,"visual_studio":68.93624922135551}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":123.57680856060671,"visual_studio":72.26713950912674}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..9b436e6a7 --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":161.11380450516475,"visual_studio":68.93624922135551}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":164.20925339270855,"visual_studio":72.26713950912674}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..42167a876 --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":117.88098616851792,"visual_studio":68.93624922135551}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":123.57680856060671,"visual_studio":72.26713950912674}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..34f6f9952 --- /dev/null +++ b/tests/fixtures/documentation/reference/groovy/documentation/groovy-spaces.groovy.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"groovy","metrics":{"end_line":11,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":6,"value":1},"sum":6,"value":1},"halstead":{"bugs":0.02243273902813528,"difficulty":7.0,"effort":552.084225111058,"estimated_program_length":32.0,"length":22,"level":0.14285714285714285,"purity_ratio":1.4545454545454546,"time":30.67134583950322,"total_operands":7,"total_operators":15,"unique_operands":4,"unique_operators":8,"vocabulary":12,"volume":78.86917501586544},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":0.8333333333333334,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":0.8333333333333334,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.16666666666666666,"lloc_max":1,"lloc_min":0,"ploc":6,"ploc_average":1.0,"ploc_max":6,"ploc_min":1,"sloc":11,"sloc_average":1.8333333333333333,"sloc_max":11,"sloc_min":1},"mi":{"original":117.88098616851792,"sei":161.11380450516475,"visual_studio":68.93624922135551}},"name":"tests/fixtures/documentation/sources/groovy-spaces.groovy","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2},{"end_line":11,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.015269685120401316,"difficulty":5.833333333333333,"effort":310.0466221894871,"estimated_program_length":24.406371956566694,"length":16,"level":0.17142857142857143,"purity_ratio":1.5253982472854184,"time":17.224812343860393,"total_operands":5,"total_operators":11,"unique_operands":3,"unique_operators":7,"vocabulary":10,"volume":53.150849518197795},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.0,"cloc_max":3,"cloc_min":0,"dloc":3,"dloc_average":1.0,"dloc_max":3,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":5,"ploc_average":1.6666666666666667,"ploc_max":5,"ploc_min":1,"sloc":8,"sloc_average":2.6666666666666665,"sloc_max":8,"sloc_min":1},"mi":{"original":123.57680856060671,"sei":164.20925339270855,"visual_studio":72.26713950912674}},"name":"C","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":6},{"end_line":10,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":10}],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/groovy-spaces.groovy","source_bytes":160} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..f16fe8a86 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..78f4f126c --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..2b14bceb6 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..5045b9535 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..2632150bc --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..d7aeef3a7 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..3a6ed5a8e --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..af31c002d --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..740fd507b --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..d33896e3d --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-continuation.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":162.66230020829434,"sei":207.11890241465855,"visual_studio":95.12415216859318}},"name":"tests/fixtures/documentation/sources/irules-continuation.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-continuation.irule","source_bytes":17} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..6db51bc5b --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.4142135623730951},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":8.0,"max":8,"min":8,"tokens":8}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..12cbfdcf2 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.4142135623730951},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":8.0,"max":8,"min":8,"tokens":8}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..96a985afb --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.4142135623730951},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":8.0,"max":8,"min":8,"tokens":8}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..1e7704993 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":1.0,"assignments_max":1,"assignments_min":1,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.4142135623730951},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":8.0,"max":8,"min":8,"tokens":8}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..a07b720b7 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b6c2cc817 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..9de82600f --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..ed627f107 --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..df0d8fb9f --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..3259e626f --- /dev/null +++ b/tests/fixtures/documentation/reference/irules/documentation/irules-crlf.irule.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"irules","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.000593770903833207,"difficulty":0.5,"effort":2.377443751081734,"estimated_program_length":2.0,"length":3,"level":2.0,"purity_ratio":0.6666666666666666,"time":0.13208020839342968,"total_operands":2,"total_operators":1,"unique_operands":2,"unique_operators":1,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":151.43331588322323,"sei":186.40470940639568,"visual_studio":88.5574946685516}},"name":"tests/fixtures/documentation/sources/irules-crlf.irule","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/irules-crlf.irule","source_bytes":21} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..25a66cc56 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":154.55840677617036,"visual_studio":90.3850332024388},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":3.6666666666666665,"max":8,"min":0,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":5.5,"max":8,"min":3,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":3.0,"max":3,"min":3,"tokens":3}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..8fe181206 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":199.01500898253457,"visual_studio":90.3850332024388},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":3.6666666666666665,"max":8,"min":0,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":5.5,"max":8,"min":3,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":3.0,"max":3,"min":3,"tokens":3}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..86f5c889b --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":154.55840677617036,"visual_studio":90.3850332024388},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":3.6666666666666665,"max":8,"min":0,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":5.5,"max":8,"min":3,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":3.0,"max":3,"min":3,"tokens":3}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..4e847c089 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":199.01500898253457,"visual_studio":90.3850332024388},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":3.6666666666666665,"max":8,"min":0,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":5.5,"max":8,"min":3,"tokens":11},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":3.0,"max":3,"min":3,"tokens":3}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..3d0f612fa --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":154.55840677617036,"visual_studio":90.3850332024388}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..871c3d45a --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":199.01500898253457,"visual_studio":90.3850332024388}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..0abbfc24f --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":154.55840677617036,"visual_studio":90.3850332024388}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..ecd05293a --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":199.01500898253457,"visual_studio":90.3850332024388}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..0b4b763b8 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":154.55840677617036,"visual_studio":90.3850332024388}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..96c8aa2a8 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-compact.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":154.55840677617036,"sei":199.01500898253457,"visual_studio":90.3850332024388}},"name":"tests/fixtures/documentation/sources/java-compact.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.005223830434320225,"difficulty":3.0,"effort":62.039100017307746,"estimated_program_length":10.0,"length":8,"level":0.3333333333333333,"purity_ratio":1.25,"time":3.446616667628208,"total_operands":3,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":20.67970000576925},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.78840677617035,"sei":154.78840677617035,"visual_studio":90.5195361264154}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0003333333333333333,"difficulty":0.5,"effort":1.0,"estimated_program_length":0.0,"length":2,"level":2.0,"purity_ratio":0.0,"time":0.05555555555555555,"total_operands":1,"total_operators":1,"unique_operands":1,"unique_operators":1,"vocabulary":2,"volume":2.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":167.1656346610883,"sei":167.1656346610883,"visual_studio":97.75768108835572}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-compact.java","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..9ed045ee1 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..e242e964d --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..383b809b6 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..1db7296f0 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..1d82a5bed --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..c1e4df860 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..035a13e98 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..24d879950 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..ec4db8697 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..400cb7522 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-empty.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-empty.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-empty.java","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..6ff321ff3 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":156.05435355291962,"visual_studio":91.25985587890037},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":2.6666666666666665,"max":4,"min":0,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..6b0c1c6c5 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":200.51095575928383,"visual_studio":91.25985587890037},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":2.6666666666666665,"max":4,"min":0,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..50e2fa5c0 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":156.05435355291962,"visual_studio":91.25985587890037},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":2.6666666666666665,"max":4,"min":0,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..993754201 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":200.51095575928383,"visual_studio":91.25985587890037},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.3333333333333333,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.3333333333333333,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":2.6666666666666665,"max":4,"min":0,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":1,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":8},"wmc":{"class_wmc_sum":1,"interface_wmc_sum":0,"total":1}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..99b24a7b6 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":156.05435355291962,"visual_studio":91.25985587890037}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..a9f8b2063 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":200.51095575928383,"visual_studio":91.25985587890037}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..dc531b8ac --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":156.05435355291962,"visual_studio":91.25985587890037}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..d4f48629e --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":200.51095575928383,"visual_studio":91.25985587890037}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..0b5086154 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":156.05435355291962,"visual_studio":91.25985587890037}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..40a9a84d3 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-record.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.3333333333333333,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.3333333333333333,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.3333333333333333,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":0.6666666666666666,"sloc_max":2,"sloc_min":1},"mi":{"original":156.05435355291962,"sei":200.51095575928383,"visual_studio":91.25985587890037}},"name":"tests/fixtures/documentation/sources/java-record.java","spaces":[{"end_line":2,"kind":"class","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":156.2843535529196,"sei":156.2843535529196,"visual_studio":91.39435880287697}},"name":"R","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"R","spaces":[],"start_line":2}],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-record.java","source_bytes":37} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..4d4a2b3e3 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..9cdaed20f --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":211.57768029761738,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..75bb2c722 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..796de809b --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":211.57768029761738,"visual_studio":94.98964924461657},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":4,"min":0,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.0,"max":4,"min":4,"tokens":4},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..9b82dd771 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..abfc401cd --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":211.57768029761738,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..98415b457 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..655357177 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":211.57768029761738,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..755cbe25c --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":206.88890241465853,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..86a4d7206 --- /dev/null +++ b/tests/fixtures/documentation/reference/java/documentation/java-selection.java.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"java","metrics":{"end_line":5,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":0,"dloc":3,"dloc_average":1.5,"dloc_max":3,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":2.5,"sloc_max":5,"sloc_min":1},"mi":{"original":162.43230020829432,"sei":211.57768029761738,"visual_studio":94.98964924461657}},"name":"tests/fixtures/documentation/sources/java-selection.java","spaces":[{"end_line":5,"kind":"class","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0009425525573729414,"difficulty":1.0,"effort":4.754887502163468,"estimated_program_length":2.0,"length":3,"level":1.0,"purity_ratio":0.6666666666666666,"time":0.26416041678685936,"total_operands":1,"total_operators":2,"unique_operands":1,"unique_operators":2,"vocabulary":3,"volume":4.754887502163468},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":162.66230020829434,"sei":162.66230020829434,"visual_studio":95.12415216859318}},"name":"C","spaces":[],"start_line":5}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/java-selection.java","source_bytes":35} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..b3d101268 --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..9d31091c0 --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..f8a887bba --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..59f2c84fc --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..785cb9c69 --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..a4a1136d3 --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..9e016e12b --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..0813fa4ad --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..19504fc11 --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..0d00e719f --- /dev/null +++ b/tests/fixtures/documentation/reference/javascript/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"javascript","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/manifest.json b/tests/fixtures/documentation/reference/manifest.json new file mode 100644 index 000000000..c85cf6b6b --- /dev/null +++ b/tests/fixtures/documentation/reference/manifest.json @@ -0,0 +1,229 @@ +{ + "version": 1, + "complete": true, + "failed_executions": 0, + "bca": { + "path": "target/debug/bca", + "sha256": "dbe4ea4892f82072c92faa7028d6512e0152f61f10725d0da9e3ce5af6470b9c" + }, + "verbatim": { + "path": "target/debug/verbatim-oracle", + "sha256": "a848e7ac210e9ebfdb3c73516de27080423e8294af362880b177bb5b35e17f99" + }, + "views": [ + "verbatim_metrics_mi_charges_docs_false", + "verbatim_metrics_mi_charges_docs_true", + "verbatim_metrics_exclude_tests_mi_charges_docs_false", + "verbatim_metrics_exclude_tests_mi_charges_docs_true", + "verbatim_metrics_only_mi_mi_charges_docs_false", + "verbatim_metrics_only_mi_mi_charges_docs_true", + "verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false", + "verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true", + "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false", + "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true" + ], + "roots": { + "documentation": "/home/elijah/Development/Open_Source/big-code-analysis-docs-1657/tests/fixtures/documentation/sources" + }, + "metrics_options": { + "verbatim_metrics_mi_charges_docs_false": [ + "--metrics-view", + "--mi-charges-docs=false", + "--" + ], + "verbatim_metrics_mi_charges_docs_true": [ + "--metrics-view", + "--mi-charges-docs=true", + "--" + ], + "verbatim_metrics_exclude_tests_mi_charges_docs_false": [ + "--metrics-view", + "--exclude-tests", + "--mi-charges-docs=false", + "--" + ], + "verbatim_metrics_exclude_tests_mi_charges_docs_true": [ + "--metrics-view", + "--exclude-tests", + "--mi-charges-docs=true", + "--" + ], + "verbatim_metrics_only_mi_mi_charges_docs_false": [ + "--metrics-view", + "--metrics", + "mi", + "--mi-charges-docs=false", + "--" + ], + "verbatim_metrics_only_mi_mi_charges_docs_true": [ + "--metrics-view", + "--metrics", + "mi", + "--mi-charges-docs=true", + "--" + ], + "verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false": [ + "--metrics-view", + "--metrics", + "mi", + "--exclude-tests", + "--mi-charges-docs=false", + "--" + ], + "verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true": [ + "--metrics-view", + "--metrics", + "mi", + "--exclude-tests", + "--mi-charges-docs=true", + "--" + ], + "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false": [ + "--metrics-view", + "--metrics", + "mi", + "--exclude-tests", + "--cyclomatic-count-try=false", + "--mi-charges-docs=false", + "--" + ], + "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true": [ + "--metrics-view", + "--metrics", + "mi", + "--exclude-tests", + "--cyclomatic-count-try=false", + "--mi-charges-docs=true", + "--" + ] + }, + "cli_cmds": {}, + "outputs_per_file": 10, + "populations": { + "javascript": 1, + "mozjs": 1, + "java": 4, + "rust": 8, + "tcl": 2, + "irules": 2, + "c": 3, + "cpp": 3, + "mozcpp": 3, + "objc": 3, + "csharp": 1, + "python": 5, + "perl": 1, + "php": 1, + "groovy": 1 + }, + "keys": [ + "c/documentation/doxygen-cdata.h", + "c/documentation/doxygen-quote.h", + "c/documentation/doxygen-quoted.h", + "cpp/documentation/doxygen-cdata.h", + "cpp/documentation/doxygen-quote.h", + "cpp/documentation/doxygen-quoted.h", + "csharp/documentation/csharp-primary.cs", + "groovy/documentation/groovy-spaces.groovy", + "irules/documentation/irules-continuation.irule", + "irules/documentation/irules-crlf.irule", + "java/documentation/java-compact.java", + "java/documentation/java-empty.java", + "java/documentation/java-record.java", + "java/documentation/java-selection.java", + "javascript/documentation/js-body.js", + "mozcpp/documentation/doxygen-cdata.h", + "mozcpp/documentation/doxygen-quote.h", + "mozcpp/documentation/doxygen-quoted.h", + "mozjs/documentation/js-body.js", + "objc/documentation/doxygen-cdata.h", + "objc/documentation/doxygen-quote.h", + "objc/documentation/doxygen-quoted.h", + "perl/documentation/perl-mixed.pl", + "php/documentation/php-define.php", + "python/documentation/python-continuation.py", + "python/documentation/python-extras.py", + "python/documentation/python-named.py", + "python/documentation/python-paren.py", + "python/documentation/python-runs.py", + "rust/documentation/rust-attribute.rs", + "rust/documentation/rust-crlf.rs", + "rust/documentation/rust-empty.rs", + "rust/documentation/rust-eof.rs", + "rust/documentation/rust-macro.rs", + "rust/documentation/rust-prune.rs", + "rust/documentation/rust-reach.rs", + "rust/documentation/rust-same-row.rs", + "tcl/documentation/tcl-continuation.tcl", + "tcl/documentation/tcl-crlf.tcl" + ], + "inputs_sha256": { + "javascript/documentation/js-body.js": "a5e15e2bc0d476e6ae49575831de83d0e770d1ac065b50af828fd84ac53d15b1", + "mozjs/documentation/js-body.js": "a5e15e2bc0d476e6ae49575831de83d0e770d1ac065b50af828fd84ac53d15b1", + "java/documentation/java-compact.java": "b50f0837e15282c120d0ed328b5592fcf5d475149bacc6e5a84ef94a38f419dd", + "java/documentation/java-empty.java": "dd44a099ad1ba4d52d55312703538293c4262590e2d918cf45b73d6e08e09804", + "java/documentation/java-record.java": "55af2656335587aa67ee87df26f4deb2734d3cae47a03ea8a50fc2738149e68f", + "java/documentation/java-selection.java": "c80633f20bac4f1743ecabf4d100a87345b08c28399c264d64e880d7ce4bdf08", + "rust/documentation/rust-attribute.rs": "aac39c7cc5bc121b5a806cc7e48af010226c50176197ef51fd62cef6ce0f45d5", + "rust/documentation/rust-crlf.rs": "83f241449672f5dbb9ecb0b0961f23f473df8ac788ceceac5e394752fa8fc010", + "rust/documentation/rust-empty.rs": "f56d4b84767ed81b9c2568781221b04c42c81a66ba6f49822a1be899f31bcc8f", + "rust/documentation/rust-eof.rs": "299d86d4b9a429931e8d6eb6c0aa8d871aab85f9f50c51e228654d6c16ebd0b6", + "rust/documentation/rust-macro.rs": "e094560ee4008e6e3786e7d16bbdea359f5c81175e9bfb9d9f33200a517df95b", + "rust/documentation/rust-prune.rs": "b8d8d20298f6b3023ffd32416783f0bbd2899805eeca4a87a6c1d652e19420d6", + "rust/documentation/rust-reach.rs": "65b64b7886b23fedb3af11962a5373804ee823f159894bf9b60b40be7de053c1", + "rust/documentation/rust-same-row.rs": "423b0558d5d6bdf5861948e8eca2fa195d643c23da844d8646e3e6f2ba07a525", + "tcl/documentation/tcl-continuation.tcl": "a9ad80721520286573efb3e5f009cf3c600371fc06b34af4aed66712ebe7fabc", + "tcl/documentation/tcl-crlf.tcl": "b5bf8060cbe824cdeeb02d5fa89267f19f5027e532e388d6988f8c479708d0eb", + "irules/documentation/irules-continuation.irule": "e9b51f618d96483e8baead435e0038b4d44e7385dc033fcd63414d2fca2d30eb", + "irules/documentation/irules-crlf.irule": "b0ba5c33f4490c1bdc37aef7b52a02d12a7d1f62b263dbe205045b4bc02b349b", + "c/documentation/doxygen-cdata.h": "a5b3d951f81a6a0e681cb93250a606d18bc60372e584c66b45c8620279bf5981", + "c/documentation/doxygen-quote.h": "952139d84a3aea4ce098dbc4ed0321592e03964ad6a3e74f367b60a9ad880de6", + "c/documentation/doxygen-quoted.h": "432df09aea4d1a8722954536844c625dfbbdad84dc1ad864b4ae24a46a0df769", + "cpp/documentation/doxygen-cdata.h": "a5b3d951f81a6a0e681cb93250a606d18bc60372e584c66b45c8620279bf5981", + "cpp/documentation/doxygen-quote.h": "952139d84a3aea4ce098dbc4ed0321592e03964ad6a3e74f367b60a9ad880de6", + "cpp/documentation/doxygen-quoted.h": "432df09aea4d1a8722954536844c625dfbbdad84dc1ad864b4ae24a46a0df769", + "mozcpp/documentation/doxygen-cdata.h": "a5b3d951f81a6a0e681cb93250a606d18bc60372e584c66b45c8620279bf5981", + "mozcpp/documentation/doxygen-quote.h": "952139d84a3aea4ce098dbc4ed0321592e03964ad6a3e74f367b60a9ad880de6", + "mozcpp/documentation/doxygen-quoted.h": "432df09aea4d1a8722954536844c625dfbbdad84dc1ad864b4ae24a46a0df769", + "objc/documentation/doxygen-cdata.h": "a5b3d951f81a6a0e681cb93250a606d18bc60372e584c66b45c8620279bf5981", + "objc/documentation/doxygen-quote.h": "952139d84a3aea4ce098dbc4ed0321592e03964ad6a3e74f367b60a9ad880de6", + "objc/documentation/doxygen-quoted.h": "432df09aea4d1a8722954536844c625dfbbdad84dc1ad864b4ae24a46a0df769", + "csharp/documentation/csharp-primary.cs": "246462b11e0d58ba09e63d8d1082b9132aaaac6f05004cbf17cbcfe719b3b75b", + "python/documentation/python-continuation.py": "1346cef54ffdf5bbf813c58b656a66148e2246f3f4f88790b798fabf64aa77eb", + "python/documentation/python-extras.py": "667e6f5a95f21845b96d11e9cf25be3131ec53f0c3e150356a0be4112f5db93d", + "python/documentation/python-named.py": "e9919ab5be0eb0ad4f619a2e07b432139c3e468007fa13ae84b3b371813d2a78", + "python/documentation/python-paren.py": "bebf97e9d342d0f3c74257479a915a7571a4d7c3952386fb0e4238f068dd46f6", + "python/documentation/python-runs.py": "17805a97dcf246a4c524a787d0761459b6aaa813a812a7e63a8c14fc25a92bf5", + "perl/documentation/perl-mixed.pl": "2b0bc4b726711a483bf374c961206cbe9fb23a8d5205ccce05ce1a492bac47b8", + "php/documentation/php-define.php": "91a2213e5ae0834b5b1399776f53445e0170a51a9ae9f2010be3c860d9aef378", + "groovy/documentation/groovy-spaces.groovy": "c0d05c5e26e9f1ff28bb9a44c74ab593c01d0cf3b016d24c6f283d506be29594" + }, + "grammar_pins": { + "tree-sitter": "=0.26.13", + "tree-sitter-bash": "=0.25.1", + "tree-sitter-c-sharp": "=0.23.5", + "tree-sitter-elixir": "=0.3.5", + "tree-sitter-go": "=0.25.0", + "dekobon-tree-sitter-groovy": "=0.6.0", + "tree-sitter-irules": "=0.2.0", + "tree-sitter-java": "=0.23.5", + "tree-sitter-javascript": "=0.25.0", + "tree-sitter-kotlin-ng": "=1.1.0", + "tree-sitter-lua": "=0.5.0", + "tree-sitter-objc": "=3.0.2", + "tree-sitter-perl": "=1.1.2", + "tree-sitter-php": "=0.25.1", + "tree-sitter-python": "=0.25.0", + "tree-sitter-ruby": "=0.23.1", + "tree-sitter-rust": "=0.24.2", + "tree-sitter-typescript": "=0.23.2", + "tree-sitter-cpp": "=0.23.4", + "tree-sitter-c": "=0.24.2", + "tree-sitter-ccomment": "=2.6.1", + "tree-sitter-mozcpp": "=2.6.1", + "tree-sitter-mozjs": "=2.6.1", + "tree-sitter-preproc": "=2.6.1", + "tree-sitter-tcl": "=2.6.1" + }, + "skipped_symlinks": [] +} \ No newline at end of file diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..86a51fb3e --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..189db1953 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..aef3f9ced --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..d2c981c0e --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..01316d6a4 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..1ddbf4571 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..f02526e32 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..c8d8e93a2 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..d811cc502 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..1fceb7b4e --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..5edf1332c --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..8c9a7ac3e --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..f3676bed0 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..cdbd0d0dc --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..cb6578cf4 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..d3e583eb4 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..b3d59bcd6 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..b50d863ca --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..7e0016fe7 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..7e9354749 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..d786c53de --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..ec73f95cb --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..0cad22a07 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..68a73fdce --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..d3a96b745 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..bae56c435 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..4c4751c89 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..5386e4b32 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..4ca82aaed --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..0b5b11ea1 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozcpp/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozcpp","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..8b77f32de --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..02a9147ab --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..af49ffc29 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..bcac1a4ec --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":4.5,"max":9,"min":0,"tokens":9},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":9.0,"max":9,"min":9,"tokens":9}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..93d01bea9 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..4d9c69da6 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..a61ea32d3 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..eea39bf23 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..8f2645af8 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":137.2560859464573,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":137.4860859464573,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..3df749c88 --- /dev/null +++ b/tests/fixtures/documentation/reference/mozjs/documentation/js-body.js.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"mozjs","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.2560859464573,"sei":172.22747946962977,"visual_studio":80.26671692775281}},"name":"tests/fixtures/documentation/sources/js-body.js","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.004471319041702271,"difficulty":2.5,"effort":49.12871113600807,"estimated_program_length":13.60964047443681,"length":7,"level":0.4,"purity_ratio":1.944234353490973,"time":2.7293728408893374,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":19.651484454403228},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":3,"ploc_average":3.0,"ploc_max":3,"ploc_min":3,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":137.4860859464573,"sei":172.4574794696298,"visual_studio":80.40121985172942}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/js-body.js","source_bytes":47} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..b9ff628ca --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b6f4d46aa --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..b5088896a --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..758c3a53b --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..9c5389e2b --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..dbd6706f5 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..fdd0ecdba --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..cd5926dd6 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..d3e204ac2 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..b05d269e4 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-cdata.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-cdata.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-cdata.h","source_bytes":42} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..69870779a --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..df6343093 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..150ba1542 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..a3b8cdad6 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":2.0,"max":2,"min":2,"tokens":2},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..28649f12a --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..41b068258 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..38d5c9c1c --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..e488c20ac --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..b1f37d56e --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..227989fd6 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quote.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":0.0,"length":0,"level":0.0,"purity_ratio":0.0,"time":0.0,"total_operands":0,"total_operators":0,"unique_operands":0,"unique_operators":0,"vocabulary":0,"volume":0.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":0.0,"sei":0.0,"visual_studio":0.0}},"name":"tests/fixtures/documentation/sources/doxygen-quote.h","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quote.h","source_bytes":30} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..2086841ac --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..8e4f444fc --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..767f01224 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..bce345891 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.0,"max":10,"min":6,"tokens":16},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..c85001f34 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..54a922c28 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..d83937b32 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..dcc4a5734 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..d67fe46b7 --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":131.55615143204844,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..7e803b6ec --- /dev/null +++ b/tests/fixtures/documentation/reference/objc/documentation/doxygen-quoted.h.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"objc","metrics":{"end_line":9,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":2.5,"cloc_max":5,"cloc_min":0,"dloc":5,"dloc_average":2.5,"dloc_max":5,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":4,"ploc_average":2.0,"ploc_max":4,"ploc_min":1,"sloc":9,"sloc_average":4.5,"sloc_max":9,"sloc_min":1},"mi":{"original":131.55615143204844,"sei":177.28984944775303,"visual_studio":76.9334218900868}},"name":"tests/fixtures/documentation/sources/doxygen-quoted.h","spaces":[{"end_line":9,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0057689982812296325,"difficulty":3.0,"effort":72.0,"estimated_program_length":17.509775004326936,"length":8,"level":0.3333333333333333,"purity_ratio":2.188721875540867,"time":4.0,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":6,"vocabulary":8,"volume":24.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.24412008219068,"sei":154.24412008219068,"visual_studio":90.20123981414659}},"name":"f","spaces":[],"start_line":9}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/doxygen-quoted.h","source_bytes":157} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..865d986af --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":4.5,"max":7,"min":2,"tokens":9}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..0775562b7 --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":194.50018936401395,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":4.5,"max":7,"min":2,"tokens":9}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..e7b3ff92f --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":4.5,"max":7,"min":2,"tokens":9}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..a21b1626b --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":194.50018936401395,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"tokens":{"average":4.5,"max":7,"min":2,"tokens":9}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..804447121 --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..88a744e02 --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":194.50018936401395,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..3dddb872c --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..aec92b2dd --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":194.50018936401395,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..d4cd5af46 --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..eb429663e --- /dev/null +++ b/tests/fixtures/documentation/reference/perl/documentation/perl-mixed.pl.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"perl","metrics":{"end_line":19,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":16,"cloc_average":8.0,"cloc_max":16,"cloc_min":0,"dloc":16,"dloc_average":8.0,"dloc_max":16,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":19,"sloc_average":9.5,"sloc_max":19,"sloc_min":1},"mi":{"original":145.0553692278485,"sei":194.50018936401395,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/perl-mixed.pl","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":156.51435355291963,"sei":156.51435355291963,"visual_studio":91.52886172685359}},"name":"f","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/perl-mixed.pl","source_bytes":121} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..4e5439561 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":169.61998214344317,"visual_studio":76.39032141765865},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":14.0,"max":18,"min":10,"tokens":28},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":18.0,"max":18,"min":18,"tokens":18}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b6dae6535 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":175.0840518305605,"visual_studio":76.39032141765865},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":14.0,"max":18,"min":10,"tokens":28},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":18.0,"max":18,"min":18,"tokens":18}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..fc9458cd1 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":169.61998214344317,"visual_studio":76.39032141765865},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":14.0,"max":18,"min":10,"tokens":28},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":18.0,"max":18,"min":18,"tokens":18}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..7cd49acb3 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":175.0840518305605,"visual_studio":76.39032141765865},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":14.0,"max":18,"min":10,"tokens":28},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":18.0,"max":18,"min":18,"tokens":18}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..17db0de8d --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":169.61998214344317,"visual_studio":76.39032141765865}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..9511371df --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":175.0840518305605,"visual_studio":76.39032141765865}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..2340ac4e7 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":169.61998214344317,"visual_studio":76.39032141765865}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..866e56b98 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":175.0840518305605,"visual_studio":76.39032141765865}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..851c9cf77 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":169.61998214344317,"visual_studio":76.39032141765865}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..a5012c8f9 --- /dev/null +++ b/tests/fixtures/documentation/reference/php/documentation/php-define.php.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"php","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.012910968936152529,"difficulty":3.4285714285714284,"effort":241.0572159246197,"estimated_program_length":35.161259458730164,"length":19,"level":0.2916666666666667,"purity_ratio":1.8505926030910613,"time":13.392067551367761,"total_operands":8,"total_operators":11,"unique_operands":7,"unique_operators":6,"vocabulary":13,"volume":70.30835464468075},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":3,"ploc_average":1.5,"ploc_max":3,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":130.6274496241963,"sei":175.0840518305605,"visual_studio":76.39032141765865}},"name":"tests/fixtures/documentation/sources/php-define.php","spaces":[{"end_line":4,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.008768493484667985,"difficulty":3.0,"effort":134.9178331268546,"estimated_program_length":27.11941547876375,"length":13,"level":0.3333333333333333,"purity_ratio":2.0861088829818266,"time":7.495435173714144,"total_operands":5,"total_operators":8,"unique_operands":5,"unique_operators":6,"vocabulary":11,"volume":44.97261104228487},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":150.97852096297217,"sei":200.96685418911233,"visual_studio":88.2915327268843}},"name":"f","spaces":[],"start_line":4}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/php-define.php","source_bytes":90} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..83aca80be --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":11,"min":2,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..c4b46d9db --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":11,"min":2,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":201.4760871474932,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..94adeeb87 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":11,"min":2,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..1dfd4af8b --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":11,"min":2,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":201.4760871474932,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..b2bee7dfc --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..e31dc27f3 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":201.4760871474932,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..822c8ac79 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..3d8defc21 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":201.4760871474932,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..016b3c13c --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..cb1fa3c2e --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-continuation.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":2,"blank_average":1.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":3,"lloc_average":1.5,"lloc_max":3,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":5},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-continuation.py","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":2,"blank_average":2.0,"blank_max":2,"blank_min":2,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":5,"sloc_average":5.0,"sloc_max":5,"sloc_min":5},"mi":{"original":159.95690398326485,"sei":201.4760871474932,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-continuation.py","source_bytes":65} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..ec3f3008a --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":189.5119714342127,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":7.0,"max":14,"min":0,"tokens":14},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":189.74197143421273,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":14.0,"max":14,"min":14,"tokens":14}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..5afcfb7a1 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":192.7344062521945,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":7.0,"max":14,"min":0,"tokens":14},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":192.96440625219452,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":14.0,"max":14,"min":14,"tokens":14}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..b987447f4 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":189.5119714342127,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":7.0,"max":14,"min":0,"tokens":14},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":189.74197143421273,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":14.0,"max":14,"min":14,"tokens":14}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..d238c2726 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":192.7344062521945,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":7.0,"max":14,"min":0,"tokens":14},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":192.96440625219452,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":14.0,"max":14,"min":14,"tokens":14}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..848d945e2 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":189.5119714342127,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":189.74197143421273,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..d0e769933 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":192.7344062521945,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":192.96440625219452,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..195b4967c --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":189.5119714342127,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":189.74197143421273,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..7dfca4d33 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":192.7344062521945,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":192.96440625219452,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..19dacd685 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":189.5119714342127,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":189.74197143421273,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..30a68f65c --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-extras.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":6,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":3.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.0553692278485,"sei":192.7344062521945,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-extras.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":4,"cloc_average":4.0,"cloc_max":4,"cloc_min":4,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":145.28536922784852,"sei":192.96440625219452,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-extras.py","source_bytes":60} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..823bf015a --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.0,"max":10,"min":0,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":145.28536922784852,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..a2066ef5b --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.0,"max":10,"min":0,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":184.27790174709537,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..375db4d08 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.0,"max":10,"min":0,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":145.28536922784852,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..992d08c28 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.0,"max":10,"min":0,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":184.27790174709537,"visual_studio":84.96220422681199},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..61840532f --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":145.28536922784852,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..e16ec67a6 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":184.27790174709537,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..214d3c22c --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":145.28536922784852,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..558f32952 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":184.27790174709537,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..3919d2d3b --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":145.0553692278485,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":145.28536922784852,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..9d39fd2ad --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-named.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":1.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":145.0553692278485,"sei":184.04790174709535,"visual_studio":84.82770130283538}},"name":"tests/fixtures/documentation/sources/python-named.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.003290806962640765,"difficulty":2.0,"effort":31.019550008653873,"estimated_program_length":10.0,"length":6,"level":0.5,"purity_ratio":1.6666666666666667,"time":1.723308333814104,"total_operands":2,"total_operators":4,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":15.509775004326936},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":145.28536922784852,"sei":184.27790174709537,"visual_studio":84.96220422681199}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-named.py","source_bytes":51} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..13c16f45b --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":13,"min":0,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":13.0,"max":13,"min":13,"tokens":13}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..10c415aa4 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":207.4059410076108,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":13,"min":0,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":207.63594100761082,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":13.0,"max":13,"min":13,"tokens":13}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..0bf131253 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":13,"min":0,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":13.0,"max":13,"min":13,"tokens":13}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..b65b0c6f3 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":207.4059410076108,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":6.5,"max":13,"min":0,"tokens":13},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":207.63594100761082,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":13.0,"max":13,"min":13,"tokens":13}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..5fe3b031d --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..5c4727f1b --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":207.4059410076108,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":207.63594100761082,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..3ac8c425d --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..f98d6e5b7 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":207.4059410076108,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":207.63594100761082,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..f87568c76 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..9d691a7fb --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-paren.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":3},"mi":{"original":159.72690398326483,"sei":207.4059410076108,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/python-paren.py","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":3.0,"sloc_max":3,"sloc_min":3},"mi":{"original":159.95690398326485,"sei":207.63594100761082,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-paren.py","source_bytes":43} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..382032a37 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":0.5,"assignments_max":1,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.5,"conditions_max":1,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":122.8653067569509,"visual_studio":71.85105658301222},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":13.0,"max":20,"min":6,"tokens":26},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":128.1160973335444,"visual_studio":74.92169434710198},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":20.0,"max":20,"min":20,"tokens":20}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..01e5866ec --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":0.5,"assignments_max":1,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.5,"conditions_max":1,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":164.38448992117924,"visual_studio":71.85105658301222},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":13.0,"max":20,"min":6,"tokens":26},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":167.10862985279124,"visual_studio":74.92169434710198},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":20.0,"max":20,"min":20,"tokens":20}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..89c0b2b2e --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":0.5,"assignments_max":1,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.5,"conditions_max":1,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":122.8653067569509,"visual_studio":71.85105658301222},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":13.0,"max":20,"min":6,"tokens":26},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":128.1160973335444,"visual_studio":74.92169434710198},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":20.0,"max":20,"min":20,"tokens":20}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..dd3b53052 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"abc":{"assignments":1,"assignments_average":0.5,"assignments_max":1,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.5,"conditions_max":1,"conditions_min":0,"magnitude":1.4142135623730951,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":164.38448992117924,"visual_studio":71.85105658301222},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":0,"total":1,"value":0},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":13.0,"max":20,"min":6,"tokens":26},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":167.10862985279124,"visual_studio":74.92169434710198},"nargs":{"average":1.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":1,"function_args_average":1.0,"function_args_max":1,"function_args_min":1,"total":1,"value":1},"nexits":{"average":2.0,"max":2,"min":2,"sum":2},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":20.0,"max":20,"min":20,"tokens":20}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..611acfad5 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":122.8653067569509,"visual_studio":71.85105658301222}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":128.1160973335444,"visual_studio":74.92169434710198}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..933ab4a9b --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":164.38448992117924,"visual_studio":71.85105658301222}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":167.10862985279124,"visual_studio":74.92169434710198}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..bbc04cc8a --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":122.8653067569509,"visual_studio":71.85105658301222}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":128.1160973335444,"visual_studio":74.92169434710198}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..11af9b9da --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":164.38448992117924,"visual_studio":71.85105658301222}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":167.10862985279124,"visual_studio":74.92169434710198}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..5c2300dbb --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":122.8653067569509,"visual_studio":71.85105658301222}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":128.1160973335444,"visual_studio":74.92169434710198}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..0a4c097d9 --- /dev/null +++ b/tests/fixtures/documentation/reference/python/documentation/python-runs.py.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"python","metrics":{"end_line":10,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.016278952490378522,"difficulty":5.6,"effort":341.288430068654,"estimated_program_length":31.26112492884004,"length":17,"level":0.17857142857142858,"purity_ratio":1.838889701696473,"time":18.960468337147447,"total_operands":8,"total_operators":9,"unique_operands":5,"unique_operators":7,"vocabulary":12,"volume":60.94436251225965},"loc":{"blank":1,"blank_average":0.5,"blank_max":1,"blank_min":0,"cloc":4,"cloc_average":2.0,"cloc_max":4,"cloc_min":2,"dloc":4,"dloc_average":2.0,"dloc_max":4,"dloc_min":2,"lloc":7,"lloc_average":3.5,"lloc_max":7,"lloc_min":5,"ploc":5,"ploc_average":2.5,"ploc_max":5,"ploc_min":4,"sloc":10,"sloc_average":5.0,"sloc_max":10,"sloc_min":6},"mi":{"original":122.8653067569509,"sei":164.38448992117924,"visual_studio":71.85105658301222}},"name":"tests/fixtures/documentation/sources/python-runs.py","spaces":[{"end_line":6,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.011749857421145992,"difficulty":4.5,"effort":209.2814699779038,"estimated_program_length":23.509775004326936,"length":14,"level":0.2222222222222222,"purity_ratio":1.6792696431662097,"time":11.626748332105768,"total_operands":6,"total_operators":8,"unique_operands":4,"unique_operators":6,"vocabulary":10,"volume":46.50699332842307},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":2,"dloc_average":2.0,"dloc_max":2,"dloc_min":2,"lloc":5,"lloc_average":5.0,"lloc_max":5,"lloc_min":5,"ploc":4,"ploc_average":4.0,"ploc_max":4,"ploc_min":4,"sloc":6,"sloc_average":6.0,"sloc_max":6,"sloc_min":6},"mi":{"original":128.1160973335444,"sei":167.10862985279124,"visual_studio":74.92169434710198}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/python-runs.py","source_bytes":115} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..905026fbb --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":139.70575871780346,"visual_studio":81.69927410397862},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.5,"max":11,"min":6,"tokens":17},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..0c281aad1 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":178.69829123705034,"visual_studio":81.69927410397862},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.5,"max":11,"min":6,"tokens":17},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..d8c413593 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":139.70575871780346,"visual_studio":81.69927410397862},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.5,"max":11,"min":6,"tokens":17},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..3b544d3a8 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":178.69829123705034,"visual_studio":81.69927410397862},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":8.5,"max":11,"min":6,"tokens":17},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..5e36d9055 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":139.70575871780346,"visual_studio":81.69927410397862}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..e0c61bdb7 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":178.69829123705034,"visual_studio":81.69927410397862}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..39c856785 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.93575871780345,"sei":139.93575871780345,"visual_studio":81.83377702795524}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..f34f90a9f --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.93575871780345,"sei":178.9282912370503,"visual_studio":81.83377702795524}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..16b49dbb5 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":139.70575871780346,"visual_studio":81.69927410397862}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..8ab60d652 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-attribute.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.00921258354248177,"difficulty":3.5,"effort":145.2961279827665,"estimated_program_length":27.651484454403228,"length":12,"level":0.2857142857142857,"purity_ratio":2.304290371200269,"time":8.072007110153695,"total_operands":4,"total_operators":8,"unique_operands":4,"unique_operators":7,"vocabulary":11,"volume":41.51317942364757},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":2,"ploc_average":1.0,"ploc_max":2,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":139.70575871780346,"sei":178.69829123705034,"visual_studio":81.69927410397862}},"name":"tests/fixtures/documentation/sources/rust-attribute.rs","spaces":[{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-attribute.rs","source_bytes":49} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..a6f641615 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..4cdf10a00 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":201.80827880557916,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..c39bfc07f --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..ddd6c2640 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":201.80827880557916,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..4daa8a0a2 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..be4e21402 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":201.80827880557916,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..0ef13a6bb --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":198.81584398759736,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..e7406bd3b --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":202.03827880557913,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..6ccd8f820 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..8d7dbdd3d --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-crlf.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":2,"cloc_average":1.0,"cloc_max":2,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":3,"sloc_average":1.5,"sloc_max":3,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":201.80827880557916,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-crlf.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-crlf.rs","source_bytes":44} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..c55e42f39 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":3.0,"max":6,"min":0,"tokens":6},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..75fdebbbf --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":204.18350618962904,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":3.0,"max":6,"min":0,"tokens":6},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..7596820d6 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":3.0,"max":6,"min":0,"tokens":6},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..28555c61b --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":204.18350618962904,"visual_studio":93.40754618904377},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":3.0,"max":6,"min":0,"tokens":6},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..d628d9213 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..d54f79721 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":204.18350618962904,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..ba8850d74 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..083d23ee0 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":204.18350618962904,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..87081e927 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":159.72690398326483,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..87bf0db3a --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-empty.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":159.72690398326483,"sei":204.18350618962904,"visual_studio":93.40754618904377}},"name":"tests/fixtures/documentation/sources/rust-empty.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":2}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-empty.rs","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..95e02f747 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..7426ad3d8 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..5cc66da66 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..63fb5bedf --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..cff684939 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..5ebcbc5af --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..c0f029b53 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":198.81584398759736,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..68be7f1c6 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":198.81584398759736,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..d3ab9bbed --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..ab2511942 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-eof.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":2,"sloc_average":1.0,"sloc_max":2,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-eof.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-eof.rs","source_bytes":28} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..f31a31308 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":144.48378569274678,"visual_studio":84.49344192558291},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..14b2c850b --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":188.940387899111,"visual_studio":84.49344192558291},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..92142ce8a --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":144.48378569274678,"visual_studio":84.49344192558291},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..d538a1b75 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":188.940387899111,"visual_studio":84.49344192558291},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..576b0fb7f --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":144.48378569274678,"visual_studio":84.49344192558291}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b96ff66de --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":188.940387899111,"visual_studio":84.49344192558291}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..4e36b8855 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":144.48378569274678,"visual_studio":84.49344192558291}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..0ecfd66aa --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":188.940387899111,"visual_studio":84.49344192558291}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..42dce1056 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":144.48378569274678,"visual_studio":84.49344192558291}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..0f4154390 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-macro.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":2,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":1,"dloc_average":1.0,"dloc_max":1,"dloc_min":1,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":2,"sloc_average":2.0,"sloc_max":2,"sloc_min":2},"mi":{"original":144.48378569274678,"sei":188.940387899111,"visual_studio":84.49344192558291}},"name":"tests/fixtures/documentation/sources/rust-macro.rs","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-macro.rs","source_bytes":26} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..bfcfb282a --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.5,"cloc_max":3,"cloc_min":0,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b7b306d30 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.5,"cloc_max":3,"cloc_min":0,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":202.8221700636377,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..88a9a54e9 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":8,"branches_average":1.6,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":8.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":9,"value":1},"sum":9,"value":1},"halstead":{"bugs":0.02823429369906876,"difficulty":4.875,"effort":779.5559202912946,"estimated_program_length":39.50977500432694,"length":42,"level":0.20512820512820512,"purity_ratio":0.940708928674451,"time":43.308662238405255,"total_operands":13,"total_operators":29,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":159.9089067264194},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":1.0,"cloc_max":5,"cloc_min":0,"dloc":3,"dloc_average":0.6,"dloc_max":3,"dloc_min":0,"lloc":4,"lloc_average":0.8,"lloc_max":4,"lloc_min":1,"ploc":8,"ploc_average":1.6,"ploc_max":8,"ploc_min":1,"sloc":13,"sloc_average":2.6,"sloc_max":13,"sloc_min":1},"mi":{"original":108.85510456004621,"sei":140.79059509289652,"visual_studio":63.65795588306796},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":4},"nom":{"average":0.8,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":4,"functions_average":0.8,"functions_max":1,"functions_min":0,"total":4},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":12.6,"max":19,"min":11,"tokens":63},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":5,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"removed","spaces":[],"start_line":5},{"end_line":8,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"plain","spaces":[],"start_line":8},{"end_line":11,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"inner","spaces":[],"start_line":11},{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..3de19cdfd --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":8,"branches_average":1.6,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":8.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":9,"value":1},"sum":9,"value":1},"halstead":{"bugs":0.02823429369906876,"difficulty":4.875,"effort":779.5559202912946,"estimated_program_length":39.50977500432694,"length":42,"level":0.20512820512820512,"purity_ratio":0.940708928674451,"time":43.308662238405255,"total_operands":13,"total_operators":29,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":159.9089067264194},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":1.0,"cloc_max":5,"cloc_min":0,"dloc":3,"dloc_average":0.6,"dloc_max":3,"dloc_min":0,"lloc":4,"lloc_average":0.8,"lloc_max":4,"lloc_min":1,"ploc":8,"ploc_average":1.6,"ploc_max":8,"ploc_min":1,"sloc":13,"sloc_average":2.6,"sloc_max":13,"sloc_min":1},"mi":{"original":108.85510456004621,"sei":149.83672049495848,"visual_studio":63.65795588306796},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":4},"nom":{"average":0.8,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":4,"functions_average":0.8,"functions_max":1,"functions_min":0,"total":4},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":12.6,"max":19,"min":11,"tokens":63},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":5,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"removed","spaces":[],"start_line":5},{"end_line":8,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"plain","spaces":[],"start_line":8},{"end_line":11,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"inner","spaces":[],"start_line":11},{"end_line":13,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..dbe6d8a26 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.5,"cloc_max":3,"cloc_min":0,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":198.58584398759737,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..63d89183f --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.5,"cloc_max":3,"cloc_min":0,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":202.8221700636377,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..8eedf7d27 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.5,"cloc_max":3,"cloc_min":0,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":198.81584398759736,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..25ab3a673 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":3,"cloc_average":1.5,"cloc_max":3,"cloc_min":0,"dloc":2,"dloc_average":1.0,"dloc_max":2,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":2.0,"sloc_max":4,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":203.0521700636377,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..1dc9dd9f2 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":9,"value":1},"sum":9,"value":1},"halstead":{"bugs":0.02823429369906876,"difficulty":4.875,"effort":779.5559202912946,"estimated_program_length":39.50977500432694,"length":42,"level":0.20512820512820512,"purity_ratio":0.940708928674451,"time":43.308662238405255,"total_operands":13,"total_operators":29,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":159.9089067264194},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":1.0,"cloc_max":5,"cloc_min":0,"dloc":3,"dloc_average":0.6,"dloc_max":3,"dloc_min":0,"lloc":4,"lloc_average":0.8,"lloc_max":4,"lloc_min":1,"ploc":8,"ploc_average":1.6,"ploc_max":8,"ploc_min":1,"sloc":13,"sloc_average":2.6,"sloc_max":13,"sloc_min":1},"mi":{"original":108.85510456004621,"sei":140.79059509289652,"visual_studio":63.65795588306796}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"removed","spaces":[],"start_line":5},{"end_line":8,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"plain","spaces":[],"start_line":8},{"end_line":11,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"inner","spaces":[],"start_line":11},{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..9f390573b --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-prune.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":13,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":9,"value":1},"sum":9,"value":1},"halstead":{"bugs":0.02823429369906876,"difficulty":4.875,"effort":779.5559202912946,"estimated_program_length":39.50977500432694,"length":42,"level":0.20512820512820512,"purity_ratio":0.940708928674451,"time":43.308662238405255,"total_operands":13,"total_operators":29,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":159.9089067264194},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":5,"cloc_average":1.0,"cloc_max":5,"cloc_min":0,"dloc":3,"dloc_average":0.6,"dloc_max":3,"dloc_min":0,"lloc":4,"lloc_average":0.8,"lloc_max":4,"lloc_min":1,"ploc":8,"ploc_average":1.6,"ploc_max":8,"ploc_min":1,"sloc":13,"sloc_average":2.6,"sloc_max":13,"sloc_min":1},"mi":{"original":108.85510456004621,"sei":149.83672049495848,"visual_studio":63.65795588306796}},"name":"tests/fixtures/documentation/sources/rust-prune.rs","spaces":[{"end_line":5,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"removed","spaces":[],"start_line":5},{"end_line":8,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"plain","spaces":[],"start_line":8},{"end_line":11,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"inner","spaces":[],"start_line":11},{"end_line":13,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"kept","spaces":[],"start_line":13}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-prune.rs","source_bytes":216} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..44767e735 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.3333333333333333,"conditions_max":1,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.5,"max":1,"min":0,"sum":1,"value":0},"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":12.0,"max":20,"min":6,"tokens":36},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..39fbc8b7a --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.3333333333333333,"conditions_max":1,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.5,"max":1,"min":0,"sum":1,"value":0},"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":12.0,"max":20,"min":6,"tokens":36},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..f5d638e3d --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.3333333333333333,"conditions_max":1,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.5,"max":1,"min":0,"sum":1,"value":0},"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":12.0,"max":20,"min":6,"tokens":36},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..8438a0c3c --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":0.3333333333333333,"conditions_max":1,"conditions_min":0,"magnitude":1.0,"value":0.0},"cognitive":{"average":0.5,"max":1,"min":0,"sum":1,"value":0},"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.6666666666666666,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":2,"functions_average":0.6666666666666666,"functions_max":1,"functions_min":0,"total":2},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":12.0,"max":20,"min":6,"tokens":36},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":1,"conditions_average":1.0,"conditions_max":1,"conditions_min":1,"magnitude":1.0,"value":1.0},"cognitive":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":10.0,"max":10,"min":10,"tokens":10}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":0,"branches_average":0.0,"branches_max":0,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":0.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":6.0,"max":6,"min":6,"tokens":6}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..4d6463004 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..428eb238e --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..50fcdda11 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..8ee18bc7f --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..4ecc0be5f --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..57e87b978 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-reach.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":3,"kind":"unit","metrics":{"cyclomatic":{"average":1.5,"max":2,"min":1,"modified":{"average":1.5,"max":2,"min":1,"sum":4,"value":1},"sum":4,"value":1},"halstead":{"bugs":0.013273647436602564,"difficulty":3.0,"effort":251.28542485580186,"estimated_program_length":39.50977500432694,"length":22,"level":0.3333333333333333,"purity_ratio":1.7958988638330426,"time":13.960301380877882,"total_operands":8,"total_operators":14,"unique_operands":8,"unique_operators":6,"vocabulary":14,"volume":83.76180828526729},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":0.3333333333333333,"lloc_max":1,"lloc_min":0,"ploc":3,"ploc_average":1.0,"ploc_max":3,"ploc_min":1,"sloc":3,"sloc_average":1.0,"sloc_max":3,"sloc_min":1},"mi":{"original":129.25699971644644,"sei":129.25699971644644,"visual_studio":75.5888887230681}},"name":"tests/fixtures/documentation/sources/rust-reach.rs","spaces":[{"end_line":2,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0036469818385629123,"difficulty":2.0,"effort":36.18947501009619,"estimated_program_length":10.0,"length":7,"level":0.5,"purity_ratio":1.4285714285714286,"time":2.0105263894497885,"total_operands":2,"total_operators":5,"unique_operands":2,"unique_operators":4,"vocabulary":6,"volume":18.094737505048094},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":155.48277001781787,"sei":155.48277001781787,"visual_studio":90.92559650164787}},"name":"helper","spaces":[],"start_line":2},{"end_line":3,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0017471609294725976,"difficulty":1.5,"effort":12.0,"estimated_program_length":4.754887502163468,"length":4,"level":0.6666666666666666,"purity_ratio":1.188721875540867,"time":0.6666666666666666,"total_operands":1,"total_operators":3,"unique_operands":1,"unique_operators":3,"vocabulary":4,"volume":8.0},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":0,"lloc_average":0.0,"lloc_max":0,"lloc_min":0,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":159.95690398326485,"sei":159.95690398326485,"visual_studio":93.54204911302038}},"name":"f","spaces":[],"start_line":3}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-reach.rs","source_bytes":74} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..53c594730 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":154.12924178123316,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..6bcb07270 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":204.11757500737332,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..576234c86 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":154.12924178123316,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..b80e717cf --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":1.0,"branches_max":2,"branches_min":0,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":0.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":204.11757500737332,"visual_studio":90.13405952118899},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":0.5,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":0.5,"functions_max":1,"functions_min":0,"total":1},"npa":{"cda":0.0,"class_attributes":0,"class_cda":0.0,"class_npa_sum":0,"interface_attributes":0,"interface_cda":0.0,"interface_npa_sum":0,"total":0,"total_attributes":0},"npm":{"class_coa":0.0,"class_methods":0,"class_npm_sum":0,"coa":0.0,"interface_coa":0.0,"interface_methods":0,"interface_npm_sum":0,"total":0,"total_methods":0},"tokens":{"average":5.5,"max":11,"min":0,"tokens":11},"wmc":{"class_wmc_sum":0,"interface_wmc_sum":0,"total":0}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":1.0,"max":1,"min":1,"sum":1},"nom":{"average":1.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":1,"functions_average":1.0,"functions_max":1,"functions_min":1,"total":1},"tokens":{"average":11.0,"max":11,"min":11,"tokens":11}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..e4aa4872d --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":154.12924178123316,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..771a974a5 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":204.11757500737332,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..d1c22e799 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..fb82bb0f7 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":2,"value":1},"sum":2,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":204.34757500737328,"visual_studio":90.26856244516559}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":1.0,"max":1,"min":1,"modified":{"average":1.0,"max":1,"min":1,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.58924178123317,"sei":154.58924178123317,"visual_studio":90.40306536914221}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..4ea93ce22 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":154.12924178123316,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..b257446d3 --- /dev/null +++ b/tests/fixtures/documentation/reference/rust/documentation/rust-same-row.rs.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"rust","metrics":{"end_line":1,"kind":"unit","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":3,"value":1},"sum":3,"value":1},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":1,"cloc_average":0.5,"cloc_max":1,"cloc_min":0,"dloc":1,"dloc_average":0.5,"dloc_max":1,"dloc_min":0,"lloc":1,"lloc_average":0.5,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":0.5,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":0.5,"sloc_max":1,"sloc_min":1},"mi":{"original":154.12924178123316,"sei":204.11757500737332,"visual_studio":90.13405952118899}},"name":"tests/fixtures/documentation/sources/rust-same-row.rs","spaces":[{"end_line":1,"kind":"function","metrics":{"cyclomatic":{"average":2.0,"max":2,"min":2,"modified":{"average":2.0,"max":2,"min":2,"sum":2,"value":2},"sum":2,"value":2},"halstead":{"bugs":0.0048876146417121315,"difficulty":2.5,"effort":56.14709844115208,"estimated_program_length":13.60964047443681,"length":8,"level":0.4,"purity_ratio":1.7012050593046013,"time":3.1192832467306713,"total_operands":2,"total_operators":6,"unique_operands":2,"unique_operators":5,"vocabulary":7,"volume":22.458839376460833},"loc":{"blank":0,"blank_average":0.0,"blank_max":0,"blank_min":0,"cloc":0,"cloc_average":0.0,"cloc_max":0,"cloc_min":0,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":1,"sloc_average":1.0,"sloc_max":1,"sloc_min":1},"mi":{"original":154.35924178123315,"sei":154.35924178123315,"visual_studio":90.26856244516559}},"name":"f","spaces":[],"start_line":1}],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/rust-same-row.rs","source_bytes":38} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..e5790d22e --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b52ad4bb8 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..d73174d37 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..f8f83779b --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":1,"branches_average":1.0,"branches_max":1,"branches_min":1,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":1.0,"value":1.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":5.0,"max":5,"min":5,"tokens":5}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..91e8a5437 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..2166f0c7f --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..5c7d71c20 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..a13f324cf --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..c7933afef --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..0ceabff9b --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-continuation.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":2,"cloc_average":2.0,"cloc_max":2,"cloc_min":2,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":1,"lloc_average":1.0,"lloc_max":1,"lloc_min":1,"ploc":1,"ploc_average":1.0,"ploc_max":1,"ploc_min":1,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":167.1656346610883,"sei":211.6222368674525,"visual_studio":97.75768108835572}},"name":"tests/fixtures/documentation/sources/tcl-continuation.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-continuation.tcl","source_bytes":16} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..7ce73f1d4 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..b10927cf3 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_false.txt new file mode 100644 index 000000000..57108d76c --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_true.txt new file mode 100644 index 000000000..521da847f --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"abc":{"assignments":0,"assignments_average":0.0,"assignments_max":0,"assignments_min":0,"branches":2,"branches_average":2.0,"branches_max":2,"branches_min":2,"conditions":0,"conditions_average":0.0,"conditions_max":0,"conditions_min":0,"magnitude":2.0,"value":2.0},"cognitive":{"average":0.0,"max":0,"min":0,"sum":0,"value":0},"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414},"nargs":{"average":0.0,"closure_args":0,"closure_args_average":0.0,"closure_args_max":0,"closure_args_min":0,"function_args":0,"function_args_average":0.0,"function_args_max":0,"function_args_min":0,"total":0,"value":0},"nexits":{"average":0.0,"max":0,"min":0,"sum":0},"nom":{"average":0.0,"closures":0,"closures_average":0.0,"closures_max":0,"closures_min":0,"functions":0,"functions_average":0.0,"functions_max":0,"functions_min":0,"total":0},"tokens":{"average":7.0,"max":7,"min":7,"tokens":7}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"all","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt new file mode 100644 index 000000000..1065c3903 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt new file mode 100644 index 000000000..100750a71 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt new file mode 100644 index 000000000..ba8de3a27 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt new file mode 100644 index 000000000..a1dc7901a --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":false,"exclude_tests":true,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt new file mode 100644 index 000000000..3515dc41e --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_false.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":false},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt new file mode 100644 index 000000000..ff1181e20 --- /dev/null +++ b/tests/fixtures/documentation/reference/tcl/documentation/tcl-crlf.tcl.verbatim_metrics_only_mi_mi_charges_docs_true.txt @@ -0,0 +1 @@ +{"lang":"tcl","metrics":{"end_line":4,"kind":"unit","metrics":{"cyclomatic":{"average":0.0,"max":0,"min":0,"modified":{"average":0.0,"max":0,"min":0,"sum":1,"value":1},"sum":1,"value":1},"halstead":{"bugs":0.0,"difficulty":0.0,"effort":0.0,"estimated_program_length":2.0,"length":2,"level":0.0,"purity_ratio":1.0,"time":0.0,"total_operands":2,"total_operators":0,"unique_operands":2,"unique_operators":0,"vocabulary":2,"volume":2.0},"loc":{"blank":1,"blank_average":1.0,"blank_max":1,"blank_min":1,"cloc":1,"cloc_average":1.0,"cloc_max":1,"cloc_min":1,"dloc":0,"dloc_average":0.0,"dloc_max":0,"dloc_min":0,"lloc":2,"lloc_average":2.0,"lloc_max":2,"lloc_min":2,"ploc":2,"ploc_average":2.0,"ploc_max":2,"ploc_min":2,"sloc":4,"sloc_average":4.0,"sloc_max":4,"sloc_min":4},"mi":{"original":155.93665033601718,"sei":190.90804385918966,"visual_studio":91.19102358831414}},"name":"tests/fixtures/documentation/sources/tcl-crlf.tcl","spaces":[],"start_line":1},"options":{"count_cyclomatic_try":true,"exclude_tests":false,"metrics":"mi","mi_charges_docs":true},"path":"tests/fixtures/documentation/sources/tcl-crlf.tcl","source_bytes":20} diff --git a/tests/fixtures/documentation/selection.json b/tests/fixtures/documentation/selection.json new file mode 100644 index 000000000..eae526d26 --- /dev/null +++ b/tests/fixtures/documentation/selection.json @@ -0,0 +1,41 @@ +[ + "c/documentation/doxygen-cdata.h", + "c/documentation/doxygen-quote.h", + "c/documentation/doxygen-quoted.h", + "cpp/documentation/doxygen-cdata.h", + "cpp/documentation/doxygen-quote.h", + "cpp/documentation/doxygen-quoted.h", + "csharp/documentation/csharp-primary.cs", + "groovy/documentation/groovy-spaces.groovy", + "irules/documentation/irules-continuation.irule", + "irules/documentation/irules-crlf.irule", + "java/documentation/java-compact.java", + "java/documentation/java-empty.java", + "java/documentation/java-record.java", + "java/documentation/java-selection.java", + "javascript/documentation/js-body.js", + "mozcpp/documentation/doxygen-cdata.h", + "mozcpp/documentation/doxygen-quote.h", + "mozcpp/documentation/doxygen-quoted.h", + "mozjs/documentation/js-body.js", + "objc/documentation/doxygen-cdata.h", + "objc/documentation/doxygen-quote.h", + "objc/documentation/doxygen-quoted.h", + "perl/documentation/perl-mixed.pl", + "php/documentation/php-define.php", + "python/documentation/python-continuation.py", + "python/documentation/python-extras.py", + "python/documentation/python-named.py", + "python/documentation/python-paren.py", + "python/documentation/python-runs.py", + "rust/documentation/rust-attribute.rs", + "rust/documentation/rust-crlf.rs", + "rust/documentation/rust-empty.rs", + "rust/documentation/rust-eof.rs", + "rust/documentation/rust-macro.rs", + "rust/documentation/rust-prune.rs", + "rust/documentation/rust-reach.rs", + "rust/documentation/rust-same-row.rs", + "tcl/documentation/tcl-continuation.tcl", + "tcl/documentation/tcl-crlf.tcl" +] diff --git a/tests/fixtures/documentation/sources/csharp-primary.cs b/tests/fixtures/documentation/sources/csharp-primary.cs new file mode 100644 index 000000000..5d8c86bf0 --- /dev/null +++ b/tests/fixtures/documentation/sources/csharp-primary.cs @@ -0,0 +1,2 @@ +/// type +class C(int x) { int F() { return x + 1; } } diff --git a/tests/fixtures/documentation/sources/doxygen-cdata.h b/tests/fixtures/documentation/sources/doxygen-cdata.h new file mode 100644 index 000000000..675ed452f --- /dev/null +++ b/tests/fixtures/documentation/sources/doxygen-cdata.h @@ -0,0 +1,2 @@ +/** */ +#include diff --git a/tests/fixtures/documentation/sources/doxygen-quote.h b/tests/fixtures/documentation/sources/doxygen-quote.h new file mode 100644 index 000000000..d0db1c701 --- /dev/null +++ b/tests/fixtures/documentation/sources/doxygen-quote.h @@ -0,0 +1,2 @@ +/** "@file" */ +#include diff --git a/tests/fixtures/documentation/sources/doxygen-quoted.h b/tests/fixtures/documentation/sources/doxygen-quoted.h new file mode 100644 index 000000000..e78c7d339 --- /dev/null +++ b/tests/fixtures/documentation/sources/doxygen-quoted.h @@ -0,0 +1,9 @@ +/** "@file" */ +#include +/** */ +#include +/** "x" @file */ +#include +/** first */ +/** second */ +int f(void) { return 1; } diff --git a/tests/fixtures/documentation/sources/groovy-spaces.groovy b/tests/fixtures/documentation/sources/groovy-spaces.groovy new file mode 100644 index 000000000..61581a88c --- /dev/null +++ b/tests/fixtures/documentation/sources/groovy-spaces.groovy @@ -0,0 +1,11 @@ +/** record */ +record R(int x) {} +/** type */ +class C { + /** ctor */ + C() {} + /** field */ + int x + /** method */ + def f() { return new C() } +} diff --git a/tests/fixtures/documentation/sources/helper-comment.c b/tests/fixtures/documentation/sources/helper-comment.c new file mode 100644 index 000000000..77b3caab6 --- /dev/null +++ b/tests/fixtures/documentation/sources/helper-comment.c @@ -0,0 +1 @@ +/**audit*/ \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/helper-preproc.h b/tests/fixtures/documentation/sources/helper-preproc.h new file mode 100644 index 000000000..a99c3ae1a --- /dev/null +++ b/tests/fixtures/documentation/sources/helper-preproc.h @@ -0,0 +1 @@ +#define X 1 diff --git a/tests/fixtures/documentation/sources/irules-continuation.irule b/tests/fixtures/documentation/sources/irules-continuation.irule new file mode 100644 index 000000000..d4d57fd20 --- /dev/null +++ b/tests/fixtures/documentation/sources/irules-continuation.irule @@ -0,0 +1,4 @@ +# c \ +\ + +set a 1 diff --git a/tests/fixtures/documentation/sources/irules-crlf.irule b/tests/fixtures/documentation/sources/irules-crlf.irule new file mode 100644 index 000000000..5dd605571 --- /dev/null +++ b/tests/fixtures/documentation/sources/irules-crlf.irule @@ -0,0 +1,4 @@ +# c \ +\ + +set a 1 diff --git a/tests/fixtures/documentation/sources/java-compact.java b/tests/fixtures/documentation/sources/java-compact.java new file mode 100644 index 000000000..d35c92669 --- /dev/null +++ b/tests/fixtures/documentation/sources/java-compact.java @@ -0,0 +1,2 @@ +/** Record doc */ +record R(int a) { R {} } diff --git a/tests/fixtures/documentation/sources/java-empty.java b/tests/fixtures/documentation/sources/java-empty.java new file mode 100644 index 000000000..21fc456c7 --- /dev/null +++ b/tests/fixtures/documentation/sources/java-empty.java @@ -0,0 +1,2 @@ +/**/ +class C {} diff --git a/tests/fixtures/documentation/sources/java-record.java b/tests/fixtures/documentation/sources/java-record.java new file mode 100644 index 000000000..6bbc61bf3 --- /dev/null +++ b/tests/fixtures/documentation/sources/java-record.java @@ -0,0 +1,2 @@ +/** Record doc */ +record R(int a) {} diff --git a/tests/fixtures/documentation/sources/java-selection.java b/tests/fixtures/documentation/sources/java-selection.java new file mode 100644 index 000000000..6121d64e2 --- /dev/null +++ b/tests/fixtures/documentation/sources/java-selection.java @@ -0,0 +1,5 @@ +/** a + * b + * c */ +/**/ +class C {} diff --git a/tests/fixtures/documentation/sources/js-body.js b/tests/fixtures/documentation/sources/js-body.js new file mode 100644 index 000000000..249abf506 --- /dev/null +++ b/tests/fixtures/documentation/sources/js-body.js @@ -0,0 +1,4 @@ +function f() { + /** note */ + return 1; +} diff --git a/tests/fixtures/documentation/sources/perl-mixed.pl b/tests/fixtures/documentation/sources/perl-mixed.pl new file mode 100644 index 000000000..9e35a391d --- /dev/null +++ b/tests/fixtures/documentation/sources/perl-mixed.pl @@ -0,0 +1,19 @@ +=head2 f + +Audit + +=begin comment + +not prose + +=end comment + +=cut + +sub f { return 1; } +__END__ +=head1 NAME + +Data docs + +=cut diff --git a/tests/fixtures/documentation/sources/php-define.php b/tests/fixtures/documentation/sources/php-define.php new file mode 100644 index 000000000..698d8ff86 --- /dev/null +++ b/tests/fixtures/documentation/sources/php-define.php @@ -0,0 +1,4 @@ +audit +class C {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.ex b/tests/fixtures/documentation/sources/primary.ex new file mode 100644 index 000000000..92eaae8df --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.ex @@ -0,0 +1,4 @@ +defmodule M do + @doc "audit" + def f(), do: :ok +end \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.go b/tests/fixtures/documentation/sources/primary.go new file mode 100644 index 000000000..30caa05bc --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.go @@ -0,0 +1,3 @@ +package p +// audit +func F() {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.groovy b/tests/fixtures/documentation/sources/primary.groovy new file mode 100644 index 000000000..0180c054d --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.groovy @@ -0,0 +1,2 @@ +/**audit*/ +class C {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.irule b/tests/fixtures/documentation/sources/primary.irule new file mode 100644 index 000000000..e38499719 --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.irule @@ -0,0 +1,3 @@ +# audit +when HTTP_REQUEST { +} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.java b/tests/fixtures/documentation/sources/primary.java new file mode 100644 index 000000000..21a96d200 --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.java @@ -0,0 +1,2 @@ +///audit +class C {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.js b/tests/fixtures/documentation/sources/primary.js new file mode 100644 index 000000000..2ec9120a2 --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.js @@ -0,0 +1,2 @@ +/**audit*/ +function f() {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.kt b/tests/fixtures/documentation/sources/primary.kt new file mode 100644 index 000000000..f27545208 --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.kt @@ -0,0 +1,2 @@ +/**audit*/ +fun f() {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.lua b/tests/fixtures/documentation/sources/primary.lua new file mode 100644 index 000000000..3afa9d09d --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.lua @@ -0,0 +1,3 @@ +module("m") +---audit +function f() end \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.m b/tests/fixtures/documentation/sources/primary.m new file mode 100644 index 000000000..d3c9f4619 --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.m @@ -0,0 +1,2 @@ +/**audit*/ +void f(void) {} \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/primary.php b/tests/fixtures/documentation/sources/primary.php new file mode 100644 index 000000000..c1accc26a --- /dev/null +++ b/tests/fixtures/documentation/sources/primary.php @@ -0,0 +1,3 @@ +; } \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/python-continuation.py b/tests/fixtures/documentation/sources/python-continuation.py new file mode 100644 index 000000000..d1a77eef2 --- /dev/null +++ b/tests/fixtures/documentation/sources/python-continuation.py @@ -0,0 +1,6 @@ +def f(): + \ + "primary" + \ + "additional" + return 1 diff --git a/tests/fixtures/documentation/sources/python-extras.py b/tests/fixtures/documentation/sources/python-extras.py new file mode 100644 index 000000000..db8a4f4fa --- /dev/null +++ b/tests/fixtures/documentation/sources/python-extras.py @@ -0,0 +1,6 @@ +def f(): + ( \ + \ + # c + """doc""" ) + return 1 diff --git a/tests/fixtures/documentation/sources/python-named.py b/tests/fixtures/documentation/sources/python-named.py new file mode 100644 index 000000000..214393b16 --- /dev/null +++ b/tests/fixtures/documentation/sources/python-named.py @@ -0,0 +1,3 @@ +def f(): + "\N{COMMERCIAL AT}audit" + return 1 diff --git a/tests/fixtures/documentation/sources/python-paren.py b/tests/fixtures/documentation/sources/python-paren.py new file mode 100644 index 000000000..579af210d --- /dev/null +++ b/tests/fixtures/documentation/sources/python-paren.py @@ -0,0 +1,3 @@ +def f(): + ("@au" # ordinary + "dit") diff --git a/tests/fixtures/documentation/sources/python-runs.py b/tests/fixtures/documentation/sources/python-runs.py new file mode 100644 index 000000000..71281e5c5 --- /dev/null +++ b/tests/fixtures/documentation/sources/python-runs.py @@ -0,0 +1,10 @@ +def f(value): + "" + "extra" + if value: + return value + 1 + return 0 + +#: setting +x = 1 +"attribute" diff --git a/tests/fixtures/documentation/sources/rust-attribute.rs b/tests/fixtures/documentation/sources/rust-attribute.rs new file mode 100644 index 000000000..85dda56d4 --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-attribute.rs @@ -0,0 +1,3 @@ +/// first +#[doc = r"second"] +fn f() { work()?; } diff --git a/tests/fixtures/documentation/sources/rust-crlf.rs b/tests/fixtures/documentation/sources/rust-crlf.rs new file mode 100644 index 000000000..f7979da7a --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-crlf.rs @@ -0,0 +1,3 @@ +/// kept +fn kept() { work()?; } +/// tail diff --git a/tests/fixtures/documentation/sources/rust-empty.rs b/tests/fixtures/documentation/sources/rust-empty.rs new file mode 100644 index 000000000..ee862fad8 --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-empty.rs @@ -0,0 +1,2 @@ +/*!*/ +fn f() {} diff --git a/tests/fixtures/documentation/sources/rust-eof.rs b/tests/fixtures/documentation/sources/rust-eof.rs new file mode 100644 index 000000000..b2d7dd2c1 --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-eof.rs @@ -0,0 +1,2 @@ +fn f() { work()?; } +/// tail \ No newline at end of file diff --git a/tests/fixtures/documentation/sources/rust-macro.rs b/tests/fixtures/documentation/sources/rust-macro.rs new file mode 100644 index 000000000..386763edf --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-macro.rs @@ -0,0 +1,2 @@ +m! { ///audit +fn f() {} } diff --git a/tests/fixtures/documentation/sources/rust-prune.rs b/tests/fixtures/documentation/sources/rust-prune.rs new file mode 100644 index 000000000..f2649541b --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-prune.rs @@ -0,0 +1,13 @@ +/// outer +#[test] +// between attributes +#[allow(dead_code)] +fn removed() { work()?; } +// plain prefix +#[test] +fn plain() { work()?; } +//! inner control +#[test] +fn inner() { work()?; } +/// kept +fn kept() { work()?; } diff --git a/tests/fixtures/documentation/sources/rust-reach.rs b/tests/fixtures/documentation/sources/rust-reach.rs new file mode 100644 index 000000000..b1403ca6d --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-reach.rs @@ -0,0 +1,3 @@ +#[consume] +#[doc = { #[cfg(test)] fn helper() { if a {} } "" }] +fn f() {} diff --git a/tests/fixtures/documentation/sources/rust-same-row.rs b/tests/fixtures/documentation/sources/rust-same-row.rs new file mode 100644 index 000000000..5bcc23770 --- /dev/null +++ b/tests/fixtures/documentation/sources/rust-same-row.rs @@ -0,0 +1 @@ +/*! a */ /*! b */ fn f() { work()?; } diff --git a/tests/fixtures/documentation/sources/tcl-continuation.tcl b/tests/fixtures/documentation/sources/tcl-continuation.tcl new file mode 100644 index 000000000..0b09e2900 --- /dev/null +++ b/tests/fixtures/documentation/sources/tcl-continuation.tcl @@ -0,0 +1,4 @@ +# c \ +\ + +puts x diff --git a/tests/fixtures/documentation/sources/tcl-crlf.tcl b/tests/fixtures/documentation/sources/tcl-crlf.tcl new file mode 100644 index 000000000..da32b6f50 --- /dev/null +++ b/tests/fixtures/documentation/sources/tcl-crlf.tcl @@ -0,0 +1,4 @@ +# c \ +\ + +puts x diff --git a/utils/documentation-characterization-perturb.json b/utils/documentation-characterization-perturb.json new file mode 100644 index 000000000..8c55a59fc --- /dev/null +++ b/utils/documentation-characterization-perturb.json @@ -0,0 +1,14 @@ +{ + "description": "Run on a clean tracked checkpoint. Focused AST and root targets include the mutated crate and dependent metric assertions; this is discrimination evidence, not a unique-guard claim. Parent performs full dependent reviews/sweeps.", + "cwd": ".", + "runner": "cargo", + "command": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation_"], + "cases": [ + {"name":"java-empty-marker-enters-legacy-selection","file":"big-code-analysis-ast/src/lang_helpers/doc_text.rs","old":"s.starts_with(b\"/**\") && s != b\"/**/\"","new":"s.starts_with(b\"/**\")","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"drop-rust-newline-discount","file":"src/metrics/loc/rust.rs","old":"(start, end.saturating_sub(1))","new":"(start, end)","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"charge-docs-in-both-mi-modes","file":"src/metrics/mi.rs","old":"let (comment_lines, physical_lines) = if charges_docs {","new":"let (comment_lines, physical_lines) = if charges_docs || loc.dloc() > 0 {","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"drop-python-named-extra-transparency","file":"big-code-analysis-ast/src/lang_helpers/python.rs","old":"Python::Comment | Python::LineContinuation","new":"Python::Comment","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"move-java-old-block-row-without-changing-count","file":"tests/fixtures/documentation/sources/java-selection.java","old":"/** a\n * b\n * c */\n/**/\nclass C {}\n","new":"\n/** a\n * b\n * c */\n/**/\nclass C {}\n","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"delete-rust-pruned-outer-doc","file":"tests/fixtures/documentation/sources/rust-prune.rs","old":"/// outer\n","new":"\n","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]} + ] +} diff --git a/utils/documentation-selection-perturb.json b/utils/documentation-selection-perturb.json new file mode 100644 index 000000000..16b9ec662 --- /dev/null +++ b/utils/documentation-selection-perturb.json @@ -0,0 +1,11 @@ +{ + "description":"Focused maintained-driver self-tests; no unique-guard claim. Run python3 -B utils/perturb.py utils/documentation-selection-perturb.json on clean tracked targets.", + "cwd":".", + "runner":"unittest", + "command":["python3","-B","-m","unittest","-q","utils/drift-oracle-test.py","utils/drift-compare-test.py"], + "cases":[ + {"name":"allow-untracked-selection","file":"utils/drift-oracle.py","old":"if tracked.returncode:","new":"if False:","expect":["utils.drift-oracle-test.DriftOracleTests.test_selection_rejects_empty_duplicate_missing_untracked_and_escape_keys"]}, + {"name":"omit-selected-view","file":"utils/drift-oracle.py","old":"selected_views = args.view or available_views","new":"selected_views = available_views","expect":["utils.drift-oracle-test.DriftOracleTests.test_explicit_selection_is_tracked_exact_and_can_force_a_dialect"]}, + {"name":"drop-relative-path-mode","file":"utils/drift-oracle.py","old":"if args.relative_paths:","new":"if False:","expect":["utils.drift-oracle-test.DriftOracleTests.test_relative_paths_reach_binary_without_output_rewriting"]} + ] +} diff --git a/utils/drift-oracle-test.py b/utils/drift-oracle-test.py index 3fd6ec49b..f1c7c88f3 100644 --- a/utils/drift-oracle-test.py +++ b/utils/drift-oracle-test.py @@ -19,6 +19,7 @@ import os import pathlib import stat +import subprocess import sys import tempfile import unittest @@ -225,6 +226,67 @@ def test_symlinks_are_skipped_and_logged(self) -> None: self.assertEqual(m["skipped_symlinks"], [str(self.fixtures / "link.rs")]) self.assertIn("skipped 1 symlink", err) + def test_explicit_selection_is_tracked_exact_and_can_force_a_dialect(self) -> None: + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "a.rs"], check=True) + selection = self.root / "selection.json" + selection.write_text(json.dumps(["mozcpp/fx/a.rs"])) + view = "verbatim_metrics_only_mi_mi_charges_docs_true" + rc, out, _, m = self._run("--selection", str(selection), "--verbatim", str(self.verbatim), "--view", view) + self.assertEqual(rc, 0) + self.assertEqual(m["keys"], ["mozcpp/fx/a.rs"]) + self.assertEqual(m["populations"], {"mozcpp": 1}) + self.assertEqual(m["views"], [view]) + self.assertEqual(m["cli_cmds"], {}) + self.assertEqual(m["outputs_per_file"], 1) + self.assertEqual(json.loads(out)["outputs"], 1) + self.assertEqual(m["metrics_options"], {view: ["--metrics-view", "--metrics", "mi", "--mi-charges-docs=true", "--"]}) + self.assertEqual(json.loads((self.out / f"mozcpp/fx/a.rs.{view}.txt").read_text()), + {"v": ["--metrics-view", "--metrics", "mi", "--mi-charges-docs=true", "--", "mozcpp", str(self.fixtures / "a.rs")]}) + + def test_selection_rejects_empty_duplicate_missing_untracked_and_escape_keys(self) -> None: + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "a.rs"], check=True) + selection = self.root / "selection.json" + for keys in [[], {}, [1], ["rust/fx/a.rs"] * 2, ["rust/fx/missing.rs"], + ["python/fx/b.py"], ["rust/fx/../a.rs"], ["rust/fx//a.rs"], + ["unknown/fx/a.rs"], ["rust/other/a.rs"]]: + with self.subTest(keys=keys): + selection.write_text(json.dumps(keys)) + rc, _, _, m = self._run("--selection", str(selection)) + self.assertNotEqual(rc, 0) + self.assertEqual(m, {}) + os.symlink(self.fixtures / "a.rs", self.fixtures / "link.rs") + selection.write_text('["rust/fx/link.rs"]') + rc, _, _, _ = self._run("--selection", str(selection)) + self.assertIn("symlink", str(rc)) + + def test_view_validation_and_requested_empty_population_fail(self) -> None: + for options in [("--view", "missing"), ("--view", "verbatim"), + ("--view", "metrics", "--view", "metrics")]: + rc, _, _, m = self._run("--lang", "rust", *options) + self.assertEqual(rc, "duplicate or unavailable --view") + self.assertEqual(m, {}) + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "a.rs"], check=True) + selection = self.root / "selection.json" + selection.write_text('["rust/fx/a.rs"]') + rc, _, _, m = self._run("--selection", str(selection), "--lang", "python") + self.assertEqual(rc, "population python is empty") + self.assertEqual(m, {}) + + def test_relative_paths_reach_binary_without_output_rewriting(self) -> None: + old = pathlib.Path.cwd() + try: + os.chdir(self.root) + rc, _, _, m = self._run("--lang", "rust", "--view", "metrics", "--relative-paths") + finally: + os.chdir(old) + self.assertEqual(rc, 0) + self.assertEqual(m["keys"], ["rust/fx/a.rs"]) + self.assertEqual((self.out / "rust/fx/a.rs.metrics.txt").read_bytes(), + b"metrics -O json --no-config --language rust -p fx/a.rs\n") + if __name__ == "__main__": unittest.main() diff --git a/utils/drift-oracle.py b/utils/drift-oracle.py index 650b96548..f9126b387 100755 --- a/utils/drift-oracle.py +++ b/utils/drift-oracle.py @@ -52,6 +52,13 @@ usage: drift-oracle.py --bca BIN [--verbatim BIN] --out DIR --root ID=PATH ... [--corpus PATH] [--lang L ...] [--jobs N] [--repo-toml Cargo.toml] + [--selection keys.json] [--view NAME ...] [--relative-paths] + +An explicit selection is a nonempty JSON array of language/root-id/relative-path +keys. Each selected input must be tracked by Git; selection bypasses extension +inference so dialects and helper inputs can be forced. --relative-paths passes +input paths relative to the current repository directory before execution. It +never rewrites returned output. Named views retain the existing option matrix. Self-tested by `utils/drift-oracle-test.py` (`make drift-oracle-test`), which stubs both binaries. Nothing lints `utils/*.py` today (#1477); @@ -63,6 +70,7 @@ import hashlib import json import pathlib +import subprocess import sys from concurrent.futures import ThreadPoolExecutor @@ -139,6 +147,9 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: ap.add_argument("--corpus", type=pathlib.Path, help="tests/repositories; omit for fixtures only") ap.add_argument("--lang", action="append", default=[], help="restrict to these populations") ap.add_argument("--jobs", type=int, default=8) + ap.add_argument("--selection", type=pathlib.Path, help="JSON array of exact language/root-id/relative-path keys; tracked files only") + ap.add_argument("--view", action="append", default=[], help="capture only this named view; repeatable") + ap.add_argument("--relative-paths", action="store_true", help="pass repository-relative input paths to binaries without rewriting output") ap.add_argument( "--repo-toml", type=pathlib.Path, @@ -184,6 +195,37 @@ def views(verbatim: bool) -> list[str]: return [*CLI_CMDS, *METRICS_OPTIONS, *(["verbatim", *VERBATIM_OPTIONS] if verbatim else [])] +def selected_inputs(selection: pathlib.Path, roots: dict[str, pathlib.Path]) -> list[tuple[str, str, pathlib.Path, pathlib.Path]]: + """Validate every explicit key before capture, including tracking and path containment.""" + keys = json.loads(selection.read_text()) + if not isinstance(keys, list) or not keys or any(not isinstance(k, str) for k in keys): + sys.exit("selection must be a nonempty JSON array of keys") + if len(set(keys)) != len(keys): + sys.exit("duplicate selection key") + jobs = [] + for key in keys: + parts = key.split("/") + if len(parts) < 3 or parts[0] not in POPULATIONS or parts[1] not in roots: + sys.exit(f"unknown language/root in selection key {key!r}") + if any(p in ("", ".", "..") or "\\" in p for p in parts): + sys.exit(f"invalid selection key {key!r}") + lang, rid, *relative = parts + root = roots[rid] + path = root.joinpath(*relative) + if any(p.is_symlink() for p in [path, *path.parents] if p.is_relative_to(root)): + sys.exit(f"symlink in selection key {key!r}") + if not path.is_file(): + sys.exit(f"missing selected input {key!r}") + tracked = subprocess.run( + ["git", "-C", str(root), "ls-files", "--error-unmatch", "--", "/".join(relative)], + capture_output=True, + ) + if tracked.returncode: + sys.exit(f"selected input is not tracked: {key!r}") + jobs.append((lang, key, root, path)) + return jobs + + def main(argv: list[str] | None = None) -> int: args = parse_args(argv) SKIPPED_LINKS.clear() @@ -206,6 +248,13 @@ def main(argv: list[str] | None = None) -> int: unknown = only - POPULATIONS.keys() if unknown: sys.exit(f"unknown language(s) {sorted(unknown)}") + available_views = views(args.verbatim is not None) + if len(set(args.view)) != len(args.view) or set(args.view) - set(available_views): + sys.exit("duplicate or unavailable --view") + selected_views = args.view or available_views + cli_cmds = {k: v for k, v in CLI_CMDS.items() if k in selected_views} + metric_options = {k: v for k, v in METRICS_OPTIONS.items() if k in selected_views} + verbatim_options = {k: v for k, v in VERBATIM_OPTIONS.items() if k in selected_views} # The corpus walk skips the snapshot submodule's own tree and git # metadata; a fixture root is walked whole. @@ -216,14 +265,22 @@ def main(argv: list[str] | None = None) -> int: inputs: dict[str, str] = {} out = args.out.resolve() destinations: set[pathlib.Path] = set() + explicit = selected_inputs(args.selection, roots) if args.selection else None for lang, exts in POPULATIONS.items(): if only and lang not in only: continue + if explicit is not None and not only and not any(job[0] == lang for job in explicit): + continue n = 0 for rid, root in roots.items(): if rid == "corpus" and lang in FIXTURE_ONLY: continue - for p in dc.walk(root, exts, corpus_skip if rid == "corpus" else (".git",), SKIPPED_LINKS): + paths = ( + [p for l, k, _, p in explicit if l == lang and k.split("/")[1] == rid] + if explicit is not None else + dc.walk(root, exts, corpus_skip if rid == "corpus" else (".git",), SKIPPED_LINKS) + ) + for p in paths: key = f"{lang}/{rid}/{p.relative_to(root)}" if key in keys: sys.exit(f"duplicate key {key}") @@ -233,6 +290,11 @@ def main(argv: list[str] | None = None) -> int: destinations.add(dst) keys.add(key) inputs[key] = sha256(p) + if args.relative_paths: + try: + p = p.relative_to(pathlib.Path.cwd()) + except ValueError: + sys.exit(f"selected input outside current directory: {p}") jobs.append((lang, key, root, p)) n += 1 if n == 0: @@ -248,10 +310,10 @@ def manifest(complete: bool) -> dict: failed_executions=len(FAILURES), bca={"path": str(args.bca), "sha256": sha256(args.bca)}, verbatim=None if args.verbatim is None else {"path": str(args.verbatim), "sha256": sha256(args.verbatim)}, - views=views(args.verbatim is not None), + views=selected_views, roots={k: str(v) for k, v in roots.items()}, - metrics_options={**METRICS_OPTIONS, **(VERBATIM_OPTIONS if args.verbatim is not None else {})}, - cli_cmds=CLI_CMDS, + metrics_options={**metric_options, **verbatim_options}, + cli_cmds=cli_cmds, populations=counts, keys=sorted(keys), inputs_sha256=inputs, @@ -270,13 +332,14 @@ def one(job: tuple[str, str, pathlib.Path, pathlib.Path]) -> None: dst.parent.mkdir(parents=True, exist_ok=True) base = [str(args.bca)] tail = ["--no-config", "--language", lang, "-p", str(p)] - for name, cmd in CLI_CMDS.items(): + for name, cmd in cli_cmds.items(): dst.with_name(dst.name + f".{name}.txt").write_bytes(run([*base, *cmd, *tail])) - for name, extra in METRICS_OPTIONS.items(): + for name, extra in metric_options.items(): dst.with_name(dst.name + f".{name}.txt").write_bytes(run([*base, "metrics", "-O", "json", *extra, *tail])) if args.verbatim is not None: - dst.with_name(dst.name + ".verbatim.jsonl").write_bytes(run([str(args.verbatim), lang, str(p)])) - for name, extra in VERBATIM_OPTIONS.items(): + if "verbatim" in selected_views: + dst.with_name(dst.name + ".verbatim.jsonl").write_bytes(run([str(args.verbatim), lang, str(p)])) + for name, extra in verbatim_options.items(): dst.with_name(dst.name + f".{name}.txt").write_bytes(run([str(args.verbatim), *extra, lang, str(p)])) with ThreadPoolExecutor(max_workers=args.jobs) as ex: From 324248ef071875575e639cfe282cda18fa224037 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:35:10 -0800 Subject: [PATCH 012/221] test(oracle): pin literal selection and equal-count row discrimination --- ...ocumentation-characterization-perturb.json | 1 + utils/drift-oracle-test.py | 21 +++++++++++++++++++ utils/drift-oracle.py | 4 ++-- 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/utils/documentation-characterization-perturb.json b/utils/documentation-characterization-perturb.json index 8c55a59fc..07ea9dce0 100644 --- a/utils/documentation-characterization-perturb.json +++ b/utils/documentation-characterization-perturb.json @@ -4,6 +4,7 @@ "runner": "cargo", "command": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation_"], "cases": [ + {"name":"shift-java-dloc-identity-preserving-whole-wire-values","file":"src/metrics/loc/shared.rs","old":".insert_range(member.start_row(), member.end_row());","new":".insert_range(member.start_row() + usize::from(code.starts_with(b\"/** a\\n * b\\n * c */\\n/**/\")), member.end_row() + usize::from(code.starts_with(b\"/** a\\n * b\\n * c */\\n/**/\")));","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"java-empty-marker-enters-legacy-selection","file":"big-code-analysis-ast/src/lang_helpers/doc_text.rs","old":"s.starts_with(b\"/**\") && s != b\"/**/\"","new":"s.starts_with(b\"/**\")","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"drop-rust-newline-discount","file":"src/metrics/loc/rust.rs","old":"(start, end.saturating_sub(1))","new":"(start, end)","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"charge-docs-in-both-mi-modes","file":"src/metrics/mi.rs","old":"let (comment_lines, physical_lines) = if charges_docs {","new":"let (comment_lines, physical_lines) = if charges_docs || loc.dloc() > 0 {","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, diff --git a/utils/drift-oracle-test.py b/utils/drift-oracle-test.py index f1c7c88f3..d757bfc3b 100644 --- a/utils/drift-oracle-test.py +++ b/utils/drift-oracle-test.py @@ -287,6 +287,27 @@ def test_relative_paths_reach_binary_without_output_rewriting(self) -> None: self.assertEqual((self.out / "rust/fx/a.rs.metrics.txt").read_bytes(), b"metrics -O json --no-config --language rust -p fx/a.rs\n") + def test_selected_filename_is_a_literal_git_pathspec(self) -> None: + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "a.rs"], check=True) + (self.fixtures / "*.rs").write_text("fn untracked() {}") + selection = self.root / "selection.json" + selection.write_text('["rust/fx/*.rs"]') + rc, _, _, m = self._run("--selection", str(selection)) + self.assertEqual(rc, "selected input is not tracked: 'rust/fx/*.rs'") + self.assertEqual(m, {}) + + def test_explicit_selection_keeps_root_identity_and_selected_helpers(self) -> None: + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "a.rs"], check=True) + selection = self.root / "selection.json" + selection.write_text('["rust/alias/a.rs", "ccomment/corpus/a.rs"]') + rc, _, _, m = self._run("--selection", str(selection), "--root", f"alias={self.fixtures}", + "--corpus", str(self.fixtures), "--view", "metrics") + self.assertEqual(rc, 0) + self.assertEqual(m["keys"], ["ccomment/corpus/a.rs", "rust/alias/a.rs"]) + self.assertEqual(m["populations"], {"rust": 1, "ccomment": 1}) + if __name__ == "__main__": unittest.main() diff --git a/utils/drift-oracle.py b/utils/drift-oracle.py index f9126b387..1532d6fbe 100755 --- a/utils/drift-oracle.py +++ b/utils/drift-oracle.py @@ -217,7 +217,7 @@ def selected_inputs(selection: pathlib.Path, roots: dict[str, pathlib.Path]) -> if not path.is_file(): sys.exit(f"missing selected input {key!r}") tracked = subprocess.run( - ["git", "-C", str(root), "ls-files", "--error-unmatch", "--", "/".join(relative)], + ["git", "--literal-pathspecs", "-C", str(root), "ls-files", "--error-unmatch", "--", "/".join(relative)], capture_output=True, ) if tracked.returncode: @@ -273,7 +273,7 @@ def main(argv: list[str] | None = None) -> int: continue n = 0 for rid, root in roots.items(): - if rid == "corpus" and lang in FIXTURE_ONLY: + if explicit is None and rid == "corpus" and lang in FIXTURE_ONLY: continue paths = ( [p for l, k, _, p in explicit if l == lang and k.split("/")[1] == rid] From b547a41f4e3b96f7ee4ad770afcfc48503588433 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:37:20 -0800 Subject: [PATCH 013/221] test(ast): preserve capture bytes and exercise outer-doc prune guard --- .gitattributes | 1 + utils/documentation-characterization-perturb.json | 1 + 2 files changed, 2 insertions(+) diff --git a/.gitattributes b/.gitattributes index 838032f02..5f50c2c17 100644 --- a/.gitattributes +++ b/.gitattributes @@ -36,3 +36,4 @@ fuzz/corpus/** -text -diff # Documentation characterization includes raw CRLF and missing-final-LF inputs. tests/fixtures/documentation/sources/** -text +tests/fixtures/documentation/reference/** -text diff --git a/utils/documentation-characterization-perturb.json b/utils/documentation-characterization-perturb.json index 07ea9dce0..22d8c1088 100644 --- a/utils/documentation-characterization-perturb.json +++ b/utils/documentation-characterization-perturb.json @@ -4,6 +4,7 @@ "runner": "cargo", "command": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation_"], "cases": [ + {"name":"stop-pruning-rust-outer-doc-run","file":"big-code-analysis-ast/src/checker/rust.rs","old":"if rust_attribute_run_start(node, code) {","new":"if rust_attribute_run_start(node, code) && !Self::is_doc_comment(node, code) {","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"shift-java-dloc-identity-preserving-whole-wire-values","file":"src/metrics/loc/shared.rs","old":".insert_range(member.start_row(), member.end_row());","new":".insert_range(member.start_row() + usize::from(code.starts_with(b\"/** a\\n * b\\n * c */\\n/**/\")), member.end_row() + usize::from(code.starts_with(b\"/** a\\n * b\\n * c */\\n/**/\")));","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"java-empty-marker-enters-legacy-selection","file":"big-code-analysis-ast/src/lang_helpers/doc_text.rs","old":"s.starts_with(b\"/**\") && s != b\"/**/\"","new":"s.starts_with(b\"/**\")","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"drop-rust-newline-discount","file":"src/metrics/loc/rust.rs","old":"(start, end.saturating_sub(1))","new":"(start, end)","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, From be4315a9ef12b607d8fef6fa777eeede6a46df6f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:43:21 -0800 Subject: [PATCH 014/221] test(ast): record characterization evidence and pin named capture options --- src/metrics/loc/documentation_tests.rs | 10 +++ .../fixtures/documentation/verification.json | 65 +++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 tests/fixtures/documentation/verification.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index dd1e01ff4..58b038669 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -90,6 +90,16 @@ fn documentation_legacy_whole_metrics() { serde_json::from_slice(&std::fs::read(path).expect("checked capture")) .expect("wire JSON"); let opt = &expected["options"]; + assert_eq!( + opt, + &json!({ + "mi_charges_docs": view.ends_with("_true"), + "exclude_tests": view.contains("exclude_tests"), + "count_cyclomatic_try": !view.contains("no_count_try"), + "metrics": if view.contains("only_mi") { "mi" } else { "all" }, + }), + "{key}/{view}: options must match the named view" + ); let excluded = opt["exclude_tests"].as_bool().expect("exclude_tests"); let mut options = MetricsOptions::default() .with_exclude_tests(excluded) diff --git a/tests/fixtures/documentation/verification.json b/tests/fixtures/documentation/verification.json new file mode 100644 index 000000000..459020f8e --- /dev/null +++ b/tests/fixtures/documentation/verification.json @@ -0,0 +1,65 @@ +{ + "implementation_checkpoint": "0a5b6e38d9d294209bd6e59c71a7b703dcbb9b46", + "selection_followup": "324248ef", + "perturbation_checkpoint": "b547a41f", + "review_base": "b47ea189ba51fe50d6362f876e77126c35d307d0", + "focused": { + "command": "cargo test -p big-code-analysis-ast -p big-code-analysis --all-features --lib --no-fail-fast documentation_", + "result": "7 passed (4 AST, 3 root, including 2 existing root tests)", + "clippy_command": "cargo clippy -p big-code-analysis-ast -p big-code-analysis --all-features --lib --tests -- -D warnings", + "clippy_result": "pass" + }, + "feature_isolation": { + "command_template": "cargo test -p PACKAGE --lib FEATURES documentation_", + "packages": ["big-code-analysis-ast", "big-code-analysis"], + "feature_arguments": [[], ["--all-features"], ["--no-default-features"], ["--no-default-features", "--features", "rust"], ["--no-default-features", "--features", "go"], ["--no-default-features", "--features", "java,python"]], + "ast_passed": [4,4,0,2,1,3], + "root_passed": [3,3,0,1,0,3], + "qualification": "Each package invoked separately. Zero documentation tests in no-language builds and root Go-only build confirms exclusion, not conformance. Batch initially timed out at 120 seconds while compiling root Rust-only; remaining root Rust/Go/Java+Python invocations rerun successfully." + }, + "gates": [ + {"command":"make check-test-lang-gates","result":"pass; 5117 gated test items"}, + {"command":"make check-test-lang-gates-compare COMPARE_REF=b47ea189","result":"pass; no test lost a build"}, + {"command":"make markdown-lint","result":"pass after removing existing .rumdl_cache"}, + {"command":"python3 -B -m unittest -q utils/drift-oracle-test.py utils/drift-compare-test.py","result":"30 passed"}, + {"command":"python3 -B -m unittest -q utils/drift_common-test.py utils/drift-oracle-test.py utils/drift-compare-test.py utils/recovery-oracle-test.py","result":"53 passed"} + ], + "replay": { + "commands": "README.md Replay block; exact capture argv also in provenance.json", + "keys_base":39,"keys_head":39,"outputs_compared":390,"differing":0,"key_problems":0,"views_uncompared":[], + "qualification":"Head-to-head replay using original captured binaries proves reproducible selection/bytes. Root tests separately recompute current production metrics. Semantic-base pins compared exactly with git show b47ea189:Cargo.toml; all 52 raw files equal their committed bytes." + }, + "perturbations": { + "rust_command":"python3 -B utils/perturb.py utils/documentation-characterization-perturb.json", + "rust_scope":"AST and root lib targets filtered by documentation_, --no-fail-fast; no unique-guard claim", + "rust_results":[ + {"name":"stop-pruning-rust-outer-doc-run","verdict":"caught","rc":101}, + {"name":"shift-java-dloc-identity-preserving-whole-wire-values","verdict":"caught","rc":101}, + {"name":"java-empty-marker-enters-legacy-selection","verdict":"caught","rc":101}, + {"name":"drop-rust-newline-discount","verdict":"caught","rc":101}, + {"name":"charge-docs-in-both-mi-modes","verdict":"caught","rc":101}, + {"name":"drop-python-named-extra-transparency","verdict":"caught","rc":101}, + {"name":"move-java-old-block-row-without-changing-count","verdict":"caught","rc":101}, + {"name":"delete-rust-pruned-outer-doc","verdict":"caught","rc":101} + ], + "rust_failures":"Every mutant failed metrics::loc::documentation_tests::documentation_legacy_whole_metrics. Python transparency also failed metrics::loc::tests::python_documentation_positions_follow_pep_257. No build/harness error; all expected guards present; targets restored.", + "python_command":"python3 -B utils/perturb.py utils/documentation-selection-perturb.json", + "python_results":[ + {"name":"allow-untracked-selection","verdict":"caught","rc":1,"failed":["test_selected_filename_is_a_literal_git_pathspec","test_selection_rejects_empty_duplicate_missing_untracked_and_escape_keys"]}, + {"name":"omit-selected-view","verdict":"caught","rc":1,"failed":["test_explicit_selection_is_tracked_exact_and_can_force_a_dialect"]}, + {"name":"drop-relative-path-mode","verdict":"caught","rc":1,"failed":["test_relative_paths_reach_binary_without_output_rewriting"]} + ], + "python_failure_prefix":"utils.drift-oracle-test.DriftOracleTests." + }, + "pending_parent_work":["ordered simplify-rust -> rust-optimize -> audit-tests", "seven scheduled independent reviews including prose", "optional broad repository corpus captures", "issue evidence/publication/merge"], + "not_triggered":["scaling and chain-audit (no production traversal change)", "fuzz (no fuzz files changed)", "metric snapshot submodule/baseline refresh (no metric semantics changed)"], + "full_gate": { + "command":"make pre-commit > unique-mktemp-log 2>&1; read ^BCA_GATE: from log", + "first_verdict":"BCA_GATE: pass (gate=pre-commit)", + "workspace_tests_passed":7462,"workspace_tests_skipped":4, + "doctests_passed":68,"doctests_ignored":1, + "python_tests_passed":413,"python_tests_xfailed":1, + "unavailable":"patchelf: non-failing maturin wheel rpath warning, twice; no gate stage skipped", + "qualification":"Final rerun pending after adding the named-view/options consistency assertion." + } +} From 06d482667c765593d0fbefb49dd76071fac63df5 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:45:51 -0800 Subject: [PATCH 015/221] test(ast): record final characterization validation gate --- tests/fixtures/documentation/verification.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/fixtures/documentation/verification.json b/tests/fixtures/documentation/verification.json index 459020f8e..68ac6ccf8 100644 --- a/tests/fixtures/documentation/verification.json +++ b/tests/fixtures/documentation/verification.json @@ -56,10 +56,12 @@ "full_gate": { "command":"make pre-commit > unique-mktemp-log 2>&1; read ^BCA_GATE: from log", "first_verdict":"BCA_GATE: pass (gate=pre-commit)", + "final_verified_revision":"be4315a9ef12b607d8fef6fa777eeede6a46df6f", + "final_verdict":"BCA_GATE: pass (gate=pre-commit)", "workspace_tests_passed":7462,"workspace_tests_skipped":4, "doctests_passed":68,"doctests_ignored":1, "python_tests_passed":413,"python_tests_xfailed":1, "unavailable":"patchelf: non-failing maturin wheel rpath warning, twice; no gate stage skipped", - "qualification":"Final rerun pending after adding the named-view/options consistency assertion." + "qualification":"Final rerun passed after the named-view/options consistency assertion. Only this evidence record changes afterwards; ordered cleanup and independent reviews remain parent work." } } From 22c42bf70d0b6d46dc841e516f38044392abe10c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:53:22 -0800 Subject: [PATCH 016/221] test(docs): guard characterization coverage and positive projection --- .../src/test_support/documentation.rs | 6 +++++ src/metrics/loc/documentation_tests.rs | 25 +++++++++++++++++++ ...ocumentation-characterization-perturb.json | 5 +++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/big-code-analysis-ast/src/test_support/documentation.rs b/big-code-analysis-ast/src/test_support/documentation.rs index 0e9960327..19778fefa 100644 --- a/big-code-analysis-ast/src/test_support/documentation.rs +++ b/big-code-analysis-ast/src/test_support/documentation.rs @@ -170,6 +170,7 @@ mod tests { ); for lang in LANG::into_enum_iter().filter(LANG::is_enabled) { let entry = &inventory[lang.to_string()]; + assert_eq!(entry["path"], primary(lang), "{lang}: fixture routing"); let source = source(primary(lang)); let mut comments = Vec::new(); let mut owners = Vec::new(); @@ -225,12 +226,17 @@ mod tests { } ran += 1; } + assert_eq!(ran, LANG::into_enum_iter().filter(LANG::is_enabled).count()); assert!(ran > 0); } #[cfg(feature = "rust")] #[test] fn documentation_conformance_rejects_absent_adapter_and_wrong_identity() { + assert_primary_extraction( + LANG::Rust, + Ok(serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"text":"audit"}])), + ); for result in [ Err("Unsupported"), Err("NoDeclarationModel"), diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 58b038669..844517e78 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -33,6 +33,30 @@ fn documentation_legacy_whole_metrics() { "../../../tests/fixtures/documentation/selection.json" )) .expect("selected keys"); + let keys = selection.as_array().expect("keys"); + assert_eq!(keys.len(), 39); + assert_eq!( + keys.iter() + .map(|key| key.as_str().expect("key")) + .collect::>() + .len(), + keys.len(), + "each selected language/input key is unique" + ); + let expected_runs = keys + .iter() + .filter(|key| { + key.as_str() + .expect("key") + .split('/') + .next() + .expect("language") + .parse::() + .expect("known LANG") + .is_enabled() + }) + .count() + * 10; assert_eq!(manifest["keys"], selection); assert_eq!(manifest["complete"], true); assert_eq!( @@ -208,5 +232,6 @@ fn documentation_legacy_whole_metrics() { ran += 1; } } + assert_eq!(ran, expected_runs, "every enabled key and view was checked"); assert!(ran > 0); } diff --git a/utils/documentation-characterization-perturb.json b/utils/documentation-characterization-perturb.json index 22d8c1088..37d8fc9c7 100644 --- a/utils/documentation-characterization-perturb.json +++ b/utils/documentation-characterization-perturb.json @@ -11,6 +11,9 @@ {"name":"charge-docs-in-both-mi-modes","file":"src/metrics/mi.rs","old":"let (comment_lines, physical_lines) = if charges_docs {","new":"let (comment_lines, physical_lines) = if charges_docs || loc.dloc() > 0 {","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"drop-python-named-extra-transparency","file":"big-code-analysis-ast/src/lang_helpers/python.rs","old":"Python::Comment | Python::LineContinuation","new":"Python::Comment","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"move-java-old-block-row-without-changing-count","file":"tests/fixtures/documentation/sources/java-selection.java","old":"/** a\n * b\n * c */\n/**/\nclass C {}\n","new":"\n/** a\n * b\n * c */\n/**/\nclass C {}\n","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, - {"name":"delete-rust-pruned-outer-doc","file":"tests/fixtures/documentation/sources/rust-prune.rs","old":"/// outer\n","new":"\n","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]} + {"name":"delete-rust-pruned-outer-doc","file":"tests/fixtures/documentation/sources/rust-prune.rs","old":"/// outer\n","new":"\n","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"conformance-helper-compares-against-null","file":"big-code-analysis-ast/src/test_support/documentation.rs","old":"let expected = &inventory()[lang.to_string()];","new":"let expected = &serde_json::Value::Null;","expect":["test_support::documentation::tests::documentation_conformance_rejects_absent_adapter_and_wrong_identity"]}, + {"name":"legacy-selection-loop-visits-only-first-key","file":"src/metrics/loc/documentation_tests.rs","old":"for key in selection.as_array().expect(\"keys\") {","new":"for key in selection.as_array().expect(\"keys\").iter().take(1) {","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, + {"name":"primary-recognition-loop-visits-only-first-language","file":"big-code-analysis-ast/src/test_support/documentation.rs","old":"for lang in LANG::into_enum_iter().filter(LANG::is_enabled) {","new":"for lang in LANG::into_enum_iter().filter(LANG::is_enabled).take(1) {","expect":["test_support::documentation::tests::documentation_primary_recognition"]} ] } From 97432fbb086245db9846088fa70203faf940f3c1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 11:58:26 -0800 Subject: [PATCH 017/221] test(docs): record ordered audit and perturbation evidence --- .../fixtures/documentation/verification.json | 44 ++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/tests/fixtures/documentation/verification.json b/tests/fixtures/documentation/verification.json index 68ac6ccf8..ebb33aec9 100644 --- a/tests/fixtures/documentation/verification.json +++ b/tests/fixtures/documentation/verification.json @@ -51,7 +51,49 @@ ], "python_failure_prefix":"utils.drift-oracle-test.DriftOracleTests." }, - "pending_parent_work":["ordered simplify-rust -> rust-optimize -> audit-tests", "seven scheduled independent reviews including prose", "optional broad repository corpus captures", "issue evidence/publication/merge"], + "ordered_skill_review": { + "reviewed_range": "b47ea189ba51fe50d6362f876e77126c35d307d0..06d482667c765593d0fbefb49dd76071fac63df5", + "order": ["simplify-rust", "rust-optimize", "audit-tests"], + "simplify_rust": "No justified Rust cleanup; no edits. Reused the verified be4315a9 full gate because 06d48266 changes evidence only.", + "rust_optimize": "No justified behavior-preserving reduction; no edits. cargo clippy -p big-code-analysis-ast -p big-code-analysis-bench --all-features --all-targets -- -W clippy::pedantic passed without warnings.", + "capture_scope": "Verified the exact 39-key by 10-view reference file set (390 records), drawn from 29 sources across 15 LANG variants; 52 raw fixtures and 25 independent LANG inventory entries overall. The other 10 LANG variants have primary inventory requirements, not selected whole-metric captures. Existing replay is same-binary reproducibility, not independently rebuilt base/head corpus parity. Current root tests recompute metrics against these references. Capture input hashes match the committed raw sources and grammar pins match b47ea189.", + "test_audit": { + "tests_audited": 22, + "fix_checkpoint": "22c42bf70d0b6d46dc841e516f38044392abe10c", + "findings": [ + {"name":"negative-only conformance assertion", "severity":"weak-assertion", "probe":"conformance-helper-compares-against-null", "before":"UNCAUGHT rc=0 failed=[]", "fix":"Added an independently written successful Rust projection before the rejected results."}, + {"name":"legacy loop accepts partial selection", "severity":"weak-assertion", "probe":"legacy-selection-loop-visits-only-first-key", "before":"UNCAUGHT rc=0 failed=[]", "fix":"Assert 39 unique selected keys and the exact enabled-key times ten-view execution count."}, + {"name":"primary recognition accepts partial LANG sweep", "severity":"weak-assertion", "probe":"primary-recognition-loop-visits-only-first-language", "before":"UNCAUGHT rc=0 failed=[]", "fix":"Assert the exact enabled LANG execution count and inventory/source routing consistency."} + ], + "probe_manifest": "utils/documentation-characterization-perturb.json", + "post_fix_probes": { + "command_template": "TMPDIR=/tmp/opencode python3 -B utils/perturb.py MANIFEST", + "manifests": [ + {"path":"utils/documentation-characterization-perturb.json", "caught":11, "rc_each":101}, + {"path":"utils/documentation-oracle-rust-perturb.json", "caught":6, "rc_each":101}, + {"path":"utils/documentation-selection-perturb.json", "caught":3, "rc_each":1}, + {"path":"utils/documentation-oracle-perturb.json", "caught":3, "rc_each":1} + ], + "result": "All 23 caught by their expected guards; no build errors, harness errors, bad anchors or missing guards. The three previously uncaught audit probes now fail their named tests. All mutation targets restored." + }, + "post_fix_feature_isolation": { + "command_template": "cargo test -p PACKAGE --lib --no-default-features [--features FEATURE] documentation_", + "features": ["rust", "go", "none"], + "ast_passed": [2,1,0], + "root_passed": [1,0,0], + "qualification": "Each package tested separately. Zero tests confirms intentional feature exclusion, not extraction conformance." + }, + "qualification": "Only characterization assertions and maintained perturbation cases changed. The successful projection checks the future-adapter assertion itself, not an implemented extractor. No unique-guard claim. Captures, raw sources, production metrics and capture provenance are unchanged. Post-fix perturbation and full-gate results are recorded separately below." + }, + "tools_unavailable": ["read-only subagent dispatch", "Serena symbols/memory"], + "focused_commands": [ + {"command":"cargo test -p big-code-analysis-ast -p big-code-analysis --all-features --lib --no-fail-fast documentation_", "result":"7 passed after fixes (4 AST, 3 root including 2 existing root tests)"}, + {"command":"cargo test -p big-code-analysis-bench --lib", "result":"68 passed before assertion-only fixes"}, + {"command":"python3 -B -m unittest -q utils/drift_common-test.py utils/drift-oracle-test.py utils/drift-compare-test.py utils/recovery-oracle-test.py", "result":"53 passed; Python code unchanged"}, + {"command":"cargo clippy -p big-code-analysis-ast -p big-code-analysis --all-features --lib --tests -- -D warnings", "result":"pass after fixes"} + ] + }, + "pending_parent_work":["seven scheduled independent reviews including prose", "optional broad repository corpus captures", "issue evidence/publication/merge"], "not_triggered":["scaling and chain-audit (no production traversal change)", "fuzz (no fuzz files changed)", "metric snapshot submodule/baseline refresh (no metric semantics changed)"], "full_gate": { "command":"make pre-commit > unique-mktemp-log 2>&1; read ^BCA_GATE: from log", From 7128a4430b3a6ee1282a04e6d34b26774d1c84b7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:01:20 -0800 Subject: [PATCH 018/221] test(docs): record post-audit full gate pass --- tests/fixtures/documentation/verification.json | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/fixtures/documentation/verification.json b/tests/fixtures/documentation/verification.json index ebb33aec9..b749f44ab 100644 --- a/tests/fixtures/documentation/verification.json +++ b/tests/fixtures/documentation/verification.json @@ -98,12 +98,13 @@ "full_gate": { "command":"make pre-commit > unique-mktemp-log 2>&1; read ^BCA_GATE: from log", "first_verdict":"BCA_GATE: pass (gate=pre-commit)", - "final_verified_revision":"be4315a9ef12b607d8fef6fa777eeede6a46df6f", + "pre_audit_verified_revision":"be4315a9ef12b607d8fef6fa777eeede6a46df6f", + "final_verified_revision":"97432fbb086245db9846088fa70203faf940f3c1", "final_verdict":"BCA_GATE: pass (gate=pre-commit)", "workspace_tests_passed":7462,"workspace_tests_skipped":4, "doctests_passed":68,"doctests_ignored":1, "python_tests_passed":413,"python_tests_xfailed":1, "unavailable":"patchelf: non-failing maturin wheel rpath warning, twice; no gate stage skipped", - "qualification":"Final rerun passed after the named-view/options consistency assertion. Only this evidence record changes afterwards; ordered cleanup and independent reviews remain parent work." + "qualification":"Final rerun passed after the ordered skill audit and three assertion fixes. Only this evidence record changes afterwards. All gate stages ran; scheduled independent reviews remain parent work." } } From 435ad1fbcc1a0401ff0a887ea65ff4343c5f3bbe Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:36:04 -0800 Subject: [PATCH 019/221] fix(docs): remediate D28 characterization review findings --- .../src/test_support/documentation.rs | 164 ++++++++++++++++-- src/metrics/loc/documentation_tests.rs | 73 ++++++-- tests/fixtures/documentation/README.md | 79 ++++++--- tests/fixtures/documentation/forms.json | 3 + tests/fixtures/documentation/inventory.json | 25 +++ tests/fixtures/documentation/legacy.json | 8 +- tests/fixtures/documentation/provenance.json | 12 +- .../documentation/sources/lua-first-file.lua | 2 + .../sources/python-chained-comment.py | 2 + .../documentation/sources/python-chained.py | 2 + ...ocumentation-characterization-perturb.json | 6 +- utils/documentation-package-check.py | 58 +++++++ utils/documentation-selection-perturb.json | 8 +- utils/drift-compare-test.py | 17 ++ utils/drift-compare.py | 2 +- utils/drift-oracle-test.py | 64 +++++++ utils/drift-oracle.py | 13 +- 17 files changed, 470 insertions(+), 68 deletions(-) create mode 100644 tests/fixtures/documentation/sources/lua-first-file.lua create mode 100644 tests/fixtures/documentation/sources/python-chained-comment.py create mode 100644 tests/fixtures/documentation/sources/python-chained.py create mode 100644 utils/documentation-package-check.py diff --git a/big-code-analysis-ast/src/test_support/documentation.rs b/big-code-analysis-ast/src/test_support/documentation.rs index 19778fefa..dd3a338b6 100644 --- a/big-code-analysis-ast/src/test_support/documentation.rs +++ b/big-code-analysis-ast/src/test_support/documentation.rs @@ -2,25 +2,31 @@ //! //! These describe required source extraction, not current adapter capabilities. //! Current recognition is tested separately against the production Checker. +//! Fixture readers require the repository checkout at runtime; packaged builds +//! can compile this module without the checkout's external fixture directory. use crate::LANG; /// Independent primary expectations, including legacy syntax observations. /// /// # Panics -/// If the checked inventory is not valid JSON. +/// If the checkout-only inventory is missing, unreadable, or not valid JSON. #[must_use] pub fn inventory() -> serde_json::Value { - serde_json::from_str(include_str!( - "../../../tests/fixtures/documentation/inventory.json" - )) - .expect("independent documentation inventory") + let bytes = std::fs::read( + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../tests/fixtures/documentation/inventory.json"), + ) + .expect("documentation inventory requires a repository checkout"); + serde_json::from_slice(&bytes).expect("independent documentation inventory") } /// Compare a future adapter's primary result with the independent requirement. /// -/// The adapter projects its result to ordered records with `fragments`, `owner` -/// and `text` keys. Helpers must report `NoDeclarationModel`. Disabled languages +/// The adapter projects its result to ordered records with `fragments`, `owner`, +/// `owner_kind` and `text` keys. `owner_kind` is the selected declaration's syntax +/// kind, not every node sharing its byte range. Helpers must report +/// `NoDeclarationModel`. Disabled languages /// are checked separately by the adapter's feature tests, never as positives. /// This harness does not call or claim an implemented extraction API. /// @@ -35,10 +41,12 @@ pub fn assert_primary_extraction(lang: LANG, result: Result { + let actual = result.expect("source adapter must produce declaration text"); assert_eq!( - result.expect("source adapter must produce declaration text"), + actual, serde_json::json!([{ - "fragments": expected["fragments"], "owner": expected["owner"], "text": expected["text"] + "fragments": expected["fragments"], "owner": expected["owner"], + "owner_kind": expected["selected_owner_kind"], "text": expected["text"] }]) ); } @@ -89,7 +97,7 @@ pub const fn requirement(lang: LANG) -> Requirement { /// Raw source for a named fixture. Never uses the normalizing file loader. /// /// # Panics -/// If the tracked fixture is missing or unreadable. +/// If the checkout-only fixture is missing or unreadable. #[must_use] pub fn source(path: &str) -> Vec { std::fs::read( @@ -97,7 +105,7 @@ pub fn source(path: &str) -> Vec { .join("../tests/fixtures/documentation/sources") .join(path), ) - .expect("tracked raw documentation fixture") + .expect("raw documentation fixtures require a repository checkout") } /// One primary input per LANG variant, including explicit helper controls. @@ -218,10 +226,18 @@ mod tests { "{lang}: declaration syntax" ); assert!(!owners.is_empty(), "missing declaration for {lang}"); + assert!( + owners.contains( + &entry["selected_owner_kind"] + .as_str() + .expect("selected declaration kind") + ) + ); } Requirement::NoDeclarationModel => { assert_eq!(entry["profile"], "NoDeclarationModel"); assert!(entry["owner"].is_null()); + assert!(entry["selected_owner_kind"].is_null()); } } ran += 1; @@ -235,15 +251,23 @@ mod tests { fn documentation_conformance_rejects_absent_adapter_and_wrong_identity() { assert_primary_extraction( LANG::Rust, - Ok(serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"text":"audit"}])), + Ok( + serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"owner_kind":"function_item","text":"audit"}]), + ), ); for result in [ Err("Unsupported"), Err("NoDeclarationModel"), Ok(serde_json::json!([])), - Ok(serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"text":""}])), - Ok(serde_json::json!([{"fragments":[[1,9]],"owner":[9,18],"text":"audit"}])), - Ok(serde_json::json!([{"fragments":[[0,8]],"owner":[0,18],"text":"audit"}])), + Ok( + serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"owner_kind":"function_item","text":""}]), + ), + Ok( + serde_json::json!([{"fragments":[[1,9]],"owner":[9,18],"owner_kind":"function_item","text":"audit"}]), + ), + Ok( + serde_json::json!([{"fragments":[[0,8]],"owner":[0,18],"owner_kind":"function_item","text":"audit"}]), + ), ] { assert!( std::panic::catch_unwind(|| assert_primary_extraction(LANG::Rust, result)).is_err() @@ -251,6 +275,36 @@ mod tests { } } + #[cfg(feature = "python")] + #[test] + fn documentation_python_conformance_distinguishes_same_span_root() { + assert_primary_extraction( + LANG::Python, + Ok( + serde_json::json!([{"fragments":[[13,20]],"owner":[0,29],"owner_kind":"function_definition","text":"audit"}]), + ), + ); + assert!(std::panic::catch_unwind(|| assert_primary_extraction( + LANG::Python, + Ok(serde_json::json!([{"fragments":[[13,20]],"owner":[0,29],"owner_kind":"module","text":"audit"}])), + )).is_err()); + } + + #[cfg(feature = "tcl")] + #[test] + fn documentation_tcl_conformance_distinguishes_same_span_root() { + assert_primary_extraction( + LANG::Tcl, + Ok( + serde_json::json!([{"fragments":[[12,19]],"owner":[0,28],"owner_kind":"procedure","text":"audit"}]), + ), + ); + assert!(std::panic::catch_unwind(|| assert_primary_extraction( + LANG::Tcl, + Ok(serde_json::json!([{"fragments":[[12,19]],"owner":[0,28],"owner_kind":"source_file","text":"audit"}])), + )).is_err()); + } + #[cfg(feature = "java")] #[test] fn documentation_record_header_and_compact_constructor_are_distinct_nodes() { @@ -287,4 +341,84 @@ mod tests { }); assert_eq!(extras, [(15, 17, true), (21, 23, true)]); } + + #[cfg(feature = "lua")] + #[test] + fn documentation_lua_first_file_run_needs_no_declaration() { + let source = source("lua-first-file.lua"); + let mut comments = Vec::new(); + super::super::for_each_node_with_sibling_cache::( + &source, + |node, ancestors| { + if crate::LuaCode::is_comment(node) { + let next = ancestors + .siblings_after(node) + .next() + .expect("function after comment"); + assert_eq!(next.kind(), "function_declaration"); + assert_eq!( + &source[next.start_byte()..next.end_byte()], + b"function f() end" + ); + comments.push(( + node.start_byte(), + node.end_byte(), + crate::LuaCode::is_doc_run_opener(node, Some(&next), &source, ancestors), + crate::LuaCode::is_doc_run_opener(node, None, &source, ancestors), + )); + } + }, + ); + assert_eq!(comments, [(0, 8, true, true)]); + } + + #[cfg(feature = "python")] + #[test] + fn documentation_python_chained_forms_are_recognized_without_owner_claims() { + use crate::lang_helpers::python::{ + python_documentation_string_run, python_sphinx_doc_comment, + }; + for (file, offset, expected_strings, expected_comments) in [ + ("python-chained.py", 0, vec![(1, 1)], vec![]), + ("python-chained-comment.py", 9, vec![], vec![(0, 0)]), + ] { + let source = source(file); + let mut targets = Vec::new(); + let mut strings = Vec::new(); + let mut comments = Vec::new(); + super::super::for_each_node_with_sibling_cache::( + &source, + |node, ancestors| { + if node.kind() == "assignment" { + let left = node.child_by_field_name("left").expect("assignment target"); + targets.push(( + left.start_byte(), + left.end_byte(), + &source[left.start_byte()..left.end_byte()], + )); + } + if crate::PythonCode::is_string(node) { + python_documentation_string_run(node, &source, ancestors, |start, end| { + strings.push((start, end)); + }); + } + if crate::PythonCode::is_comment(node) { + python_sphinx_doc_comment(node, &source, ancestors, |start, end| { + comments.push((start, end)); + }); + } + }, + ); + assert_eq!( + targets, + [ + (offset, offset + 1, b"x".as_slice()), + (offset + 4, offset + 5, b"y".as_slice()) + ], + "{file}" + ); + assert_eq!(strings, expected_strings, "{file}"); + assert_eq!(comments, expected_comments, "{file}"); + } + } } diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 844517e78..d149ab041 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -166,24 +166,7 @@ fn documentation_legacy_whole_metrics() { .collect(); assert_eq!(json!(rows), anchor["dloc_rows"], "{key}/{view}"); assert_eq!(rows.len() as u64, loc.dloc()); - if matches!(lang, LANG::Tcl | LANG::Irules) { - let ploc: Vec<_> = (0..source.len()) - .filter(|row| loc.ploc.lines.contains(*row)) - .collect(); - let cloc: Vec<_> = (0..source.len()) - .filter(|row| { - loc.cloc.only_comment_line_starts.contains(*row) - || loc.cloc.code_comment_line_starts.contains(*row) - }) - .collect(); - let (want_code, want_comment) = if file.contains("crlf") { - (vec![1, 3], vec![0]) - } else { - (vec![3], vec![0, 1]) - }; - assert_eq!(ploc, want_code, "{key}: exact code rows"); - assert_eq!(cloc, want_comment, "{key}: exact comment rows"); - } + assert_optional_rows(loc, source.len(), anchor); let mut nested = Vec::new(); let mut stack: Vec<_> = space.spaces.iter().rev().collect(); while let Some(child) = stack.pop() { @@ -235,3 +218,57 @@ fn documentation_legacy_whole_metrics() { assert_eq!(ran, expected_runs, "every enabled key and view was checked"); assert!(ran > 0); } + +fn assert_optional_rows(loc: &super::Stats, source_len: usize, anchor: &Value) { + if let Some(expected) = anchor.get("ploc_rows") { + let rows: Vec<_> = (0..source_len) + .filter(|row| loc.ploc.lines.contains(*row)) + .collect(); + assert_eq!(json!(rows), *expected, "exact code rows"); + } + if let Some(expected) = anchor.get("cloc_rows") { + let rows: Vec<_> = (0..source_len) + .filter(|row| { + loc.cloc.only_comment_line_starts.contains(*row) + || loc.cloc.code_comment_line_starts.contains(*row) + }) + .collect(); + assert_eq!(json!(rows), *expected, "exact comment rows"); + } +} + +#[cfg(feature = "tcl")] +#[test] +fn documentation_optional_rows_follow_anchors_not_filenames() { + let source = documentation::source("tcl-crlf.tcl"); + let space = analyze( + Source::new(LANG::Tcl, &source).with_name(Some("renamed.tcl".into())), + MetricsOptions::default(), + ) + .expect("renamed fixture"); + assert_optional_rows( + &space.metrics.loc, + source.len(), + &json!({"ploc_rows":[1,3],"cloc_rows":[0]}), + ); + let source = b"proc unrelated {} {}\n"; + let space = analyze( + Source::new(LANG::Tcl, source).with_name(Some("unrelated-crlf.tcl".into())), + MetricsOptions::default(), + ) + .expect("unrelated fixture"); + assert_optional_rows(&space.metrics.loc, source.len(), &json!({})); + assert_optional_rows( + &space.metrics.loc, + source.len(), + &json!({"ploc_rows":[0],"cloc_rows":[]}), + ); + assert!( + std::panic::catch_unwind(|| assert_optional_rows( + &space.metrics.loc, + source.len(), + &json!({"ploc_rows":[1,3],"cloc_rows":[0]}) + )) + .is_err() + ); +} diff --git a/tests/fixtures/documentation/README.md b/tests/fixtures/documentation/README.md index 681ae4a6d..4fae9912f 100644 --- a/tests/fixtures/documentation/README.md +++ b/tests/fixtures/documentation/README.md @@ -5,35 +5,57 @@ changing an adapter. They assume the distinction between source attachment and d counting in the [extraction contract](../../../docs/development/documentation_extraction.md#recognition). `sources/` contains raw inputs. Read them as bytes: several omit the final newline or contain CRLF. -The directory's Git attributes disable newline conversion. AST test-support provides the same raw -reader to AST recognition tests and root metric tests. +The directory's [Git attributes](https://git-scm.com/docs/gitattributes) disable newline conversion. +AST test-support provides the same raw reader to AST recognition tests and root metric tests. ## Requirements and observations - `inventory.json` records the contract's primary owner, fragment ranges, profile and nonempty text - for every source dialect. Helper grammars explicitly require `NoDeclarationModel`. + for every source dialect. `selected_owner_kind` names the required declaration's syntax kind; + `owner_kinds` separately records every observed node sharing its range. Helper grammars require + `NoDeclarationModel`, with null owner and selected kind. - `forms.json` records additional source requirements and qualifications. The [complete form inventory](../../../docs/development/documentation_extraction_cases.md#ownership) remains authoritative for later adapter work. Text and attachment requirements are independently specified; they are not generated from runtime capabilities. - `legacy.json` anchors integer LOC values, physical documentation rows and ordered nested spaces. Rows are zero-based. An absent `excluded` entry means the `included` expectation applies in both - pruning modes. These expectations preserve existing behavior, including named limitations. -- `reference/` holds selected whole-metric wire records from the maintained `verbatim-oracle`. - `selection.json` fixes the exact language/input keys. Its manifest records input hashes, binary - hashes, grammar pins and views. `provenance.json` records revisions and reference evidence. + pruning modes. Optional `ploc_rows` and `cloc_rows` arrays belong to that anchor, independent of + the filename. These expectations preserve existing behavior, including named limitations. +- `reference/` holds selected whole-metric wire records from the maintained + [`verbatim-oracle`](../../../big-code-analysis-bench/src/bin/verbatim_oracle.rs). + `selection.json` fixes the exact language/input keys. `reference/manifest.json` records input + hashes, binary hashes, grammar pins and views. `provenance.json` records revisions, the relationship + between the D01 baseline and semantic base, and reference evidence. Extraction is not implemented here. `assert_primary_extraction` is the shared assertion for future -adapters. It rejects unsupported or empty results for source languages. Current tests run production -parsing, recognition and metrics; they do not claim extraction conformance. +adapters. It rejects unsupported or empty results and wrong selected kinds for source languages. +For example, Python's primary projection is: -Rust outer docs and comments inside pruned attribute runs disappear with the item. Plain prefixes -and inner docs survive. The attribute-value reach case preserves the documented -[#1786 limitation](https://github.com/dekobon/big-code-analysis/issues/1786). -Java's empty block has a source requirement distinct from the older block billed by legacy DLOC. -Mixed Perl POD bills comment-only subregions inside a documentation token, although they are not -source prose. Tcl/iRules CRLF continuation cases preserve -[#1802](https://github.com/dekobon/big-code-analysis/issues/1802). +```json +[{"fragments":[[13,20]],"owner":[0,29],"owner_kind":"function_definition","text":"audit"}] +``` + +The module root shares that range but is the wrong owner. Current tests run production parsing, +recognition and metrics; they do not claim extraction conformance. Lua first-file and Python chained +assignment controls add raw requirements and recognition tests without extending `selection.json`. +Their source associations remain requirements for future adapters. + +- Rust outer docs and comments inside pruned attribute runs disappear with the item. Plain prefixes + and inner docs survive, as described by the [legacy pruning contract][recognition]. The + attribute-value reach case preserves the [#1786 limitation][rust-reach]. +- Java's empty block has a [source requirement][text] distinct from the older block billed by legacy + DLOC (documentation lines of code). +- Mixed Perl POD bills comment-only subregions inside a documentation token, although the + [source profile][profiles] excludes them from prose. +- Tcl/iRules CRLF continuation cases preserve [#1802][tcl-crlf]. The [ownership requirements][profiles] + remain independent of those legacy row counts. + +[recognition]: ../../../docs/development/documentation_extraction.md#recognition +[text]: ../../../docs/development/documentation_extraction.md#text +[profiles]: ../../../docs/development/documentation_extraction.md#profiles +[rust-reach]: https://github.com/dekobon/big-code-analysis/issues/1786 +[tcl-crlf]: https://github.com/dekobon/big-code-analysis/issues/1802 ## Replay @@ -46,7 +68,7 @@ cargo test -p big-code-analysis-ast --all-features --lib documentation_ cargo test -p big-code-analysis --all-features --lib documentation_ python3 -B -m unittest -q utils/drift-oracle-test.py utils/drift-compare-test.py cargo build -p big-code-analysis-cli -p big-code-analysis-bench --bin bca --bin verbatim-oracle -out=$(mktemp -d /tmp/opencode/bca-documentation-replay.XXXXXX) +out=$(mktemp -d "${TMPDIR:-/tmp}/bca-documentation-replay.XXXXXX") views=( verbatim_metrics_mi_charges_docs_false verbatim_metrics_mi_charges_docs_true @@ -69,11 +91,26 @@ python3 -B utils/drift-oracle.py --bca target/debug/bca \ python3 -B utils/drift-compare.py tests/fixtures/documentation/reference "$out" ``` -The selected capture exercises both MI documentation modes with all metrics and MI-only dependency -closure, pruning, and the combined pruning/try-count choice. The root test checks whole serialized -space trees as well as integer and row anchors. No external documentation generator runs in CI. +The selected capture exercises both [maintainability index][mi] (MI) documentation modes, pruning, +and the combined pruning/try-count choice. MI depends on LOC, cyclomatic and Halstead metrics. An MI-only +request therefore computes and serializes those dependencies too; this is its dependency closure. +The root test checks whole serialized space trees as well as integer and row anchors. No external +documentation generator runs in CI. + +[mi]: https://learn.microsoft.com/en-us/visualstudio/code-quality/code-metrics-maintainability-index-range-and-meaning + +See [metric selection](../../../big-code-analysis-book/src/library/selecting-metrics.md) for the +library's dependency rules. + +AST fixture readers require a repository checkout at runtime. The test-support feature still +compiles without external fixtures. When unpublished grammar versions block package verification, +run `python3 -B utils/documentation-package-check.py` for an isolated all-features build and rustdoc +check. This preserves workspace manifests and local grammar sources; it does not verify registry +resolution or the normalized package manifest. `--baseline REV` substitutes the helper from that +revision to demonstrate the old compile-time dependency on the omitted fixture. To extend the fixtures, specify source outcomes from the contract or a versioned reference first. Add raw source and independent legacy anchors, select the input explicitly, then review its capture. Use `utils/perturb.py` with the tracked characterization manifests to verify decision-bearing guards -on a clean checkpoint. The manifests state their sweep scope; they do not claim unique guards. +on a clean checkpoint. Each mutation must fail its expected tests. Other tests can catch the same +mutation, and these focused sweeps do not establish that a guard is unique across dependent crates. diff --git a/tests/fixtures/documentation/forms.json b/tests/fixtures/documentation/forms.json index 674e01029..96d10a9d2 100644 --- a/tests/fixtures/documentation/forms.json +++ b/tests/fixtures/documentation/forms.json @@ -4,6 +4,9 @@ "status": "independent requirements; extraction is not implemented or claimed conformant", "range_notation": "Half-open bytes; spelling ranges refer to the exact occurrence in the raw file. Comment terminators exclude LF/CRLF. Owner ranges include the entire declaration unless a slot is named.", "cases": [ + {"path":"lua-first-file.lua","profile":"LDoc","documents":[{"fragments":[[0,8]],"owner":"file","text":"audit"}],"excluded_owners":["f"],"legacy":"Recognized documentation run; no attachment API exists. Recognition is tested with and without a following candidate; whole-metric capture is not extended."}, + {"path":"python-chained.py","profile":"Pep257Pep258Sphinx","documents":[{"fragments":[[10,17]],"owner":"x binding","text":"audit","role":"attribute-binding"}],"excluded_owners":["y binding"],"legacy":"String run credits row 1. Raw assignment targets and recognition are tested, not source associations; whole-metric capture is not extended."}, + {"path":"python-chained-comment.py","profile":"Pep257Pep258Sphinx","documents":[{"fragments":[[0,8]],"owners":["x binding","y binding"],"text":"audit","role":"Sphinx"}],"legacy":"Sphinx comment credits row 0. Raw assignment targets and recognition are tested, not source associations; whole-metric capture is not extended."}, {"path":"python-extras.py","documents":[{"fragment_spelling":"\"\"\"doc\"\"\"","owner":"f","text":"doc","role":"primary"}],"legacy":"Named line_continuation extras and ordinary comment are read past for recognition; rows 1,4 DLOC, rows 1,2,3,4 CLOC."}, {"path":"java-selection.java","profile":"Jdk25Source","documents":[{"fragments":[[19,23]],"owner":[24,34],"text":"","availability":"complete"}],"superseded":[[0,18]],"legacy":"Rows 0,1,2 only; empty block on row 3 is not a legacy marker."}, {"path":"java-empty.java","profile":"Jdk25Source","documents":[{"fragments":[[0,4]],"owner":[5,15],"text":"","availability":"complete"}],"reference_deviation":"JDK 25.0.5 returns slash; BCA delimiter cleanup intentionally returns empty."}, diff --git a/tests/fixtures/documentation/inventory.json b/tests/fixtures/documentation/inventory.json index 7a4760304..1acdf1675 100644 --- a/tests/fixtures/documentation/inventory.json +++ b/tests/fixtures/documentation/inventory.json @@ -1,6 +1,7 @@ { "rust": { "path": "primary.rs", + "selected_owner_kind": "function_item", "profile": "RustCompiler", "fragments": [ [ @@ -26,6 +27,7 @@ }, "python": { "path": "primary.py", + "selected_owner_kind": "function_definition", "profile": "Pep257Pep258Sphinx", "fragments": [ [ @@ -46,6 +48,7 @@ }, "java": { "path": "primary.java", + "selected_owner_kind": "class_declaration", "profile": "Jdk25Source", "fragments": [ [ @@ -71,6 +74,7 @@ }, "kotlin": { "path": "primary.kt", + "selected_owner_kind": "function_declaration", "profile": "KDoc", "fragments": [ [ @@ -96,6 +100,7 @@ }, "groovy": { "path": "primary.groovy", + "selected_owner_kind": "class_declaration", "profile": "Groovydoc", "fragments": [ [ @@ -121,6 +126,7 @@ }, "csharp": { "path": "primary.cs", + "selected_owner_kind": "class_declaration", "profile": "CsharpXml", "fragments": [ [ @@ -146,6 +152,7 @@ }, "php": { "path": "primary.php", + "selected_owner_kind": "function_definition", "profile": "BcaPhpSource", "fragments": [ [ @@ -171,6 +178,7 @@ }, "javascript": { "path": "primary.js", + "selected_owner_kind": "function_declaration", "profile": "JsDoc", "fragments": [ [ @@ -196,6 +204,7 @@ }, "mozjs": { "path": "primary.js", + "selected_owner_kind": "function_declaration", "profile": "JsDoc", "fragments": [ [ @@ -221,6 +230,7 @@ }, "typescript": { "path": "primary.ts", + "selected_owner_kind": "function_declaration", "profile": "BcaTypescriptSource", "fragments": [ [ @@ -246,6 +256,7 @@ }, "tsx": { "path": "primary.tsx", + "selected_owner_kind": "function_declaration", "profile": "BcaTypescriptSource", "fragments": [ [ @@ -271,6 +282,7 @@ }, "c": { "path": "primary.c", + "selected_owner_kind": "function_definition", "profile": "Doxygen", "fragments": [ [ @@ -296,6 +308,7 @@ }, "cpp": { "path": "primary.cpp", + "selected_owner_kind": "function_definition", "profile": "Doxygen", "fragments": [ [ @@ -321,6 +334,7 @@ }, "mozcpp": { "path": "primary.cpp", + "selected_owner_kind": "function_definition", "profile": "Doxygen", "fragments": [ [ @@ -346,6 +360,7 @@ }, "objc": { "path": "primary.m", + "selected_owner_kind": "function_definition", "profile": "Doxygen", "fragments": [ [ @@ -371,6 +386,7 @@ }, "go": { "path": "primary.go", + "selected_owner_kind": "function_declaration", "profile": "GoDoc", "fragments": [ [ @@ -396,6 +412,7 @@ }, "ruby": { "path": "primary.rb", + "selected_owner_kind": "method", "profile": "Yard", "fragments": [ [ @@ -421,6 +438,7 @@ }, "lua": { "path": "primary.lua", + "selected_owner_kind": "function_declaration", "profile": "LDoc", "fragments": [ [ @@ -446,6 +464,7 @@ }, "perl": { "path": "primary.pl", + "selected_owner_kind": "function_definition", "profile": "PodUniqueHeading", "fragments": [ [ @@ -471,6 +490,7 @@ }, "elixir": { "path": "primary.ex", + "selected_owner_kind": "call", "profile": "ElixirCompiler", "fragments": [ [ @@ -490,6 +510,7 @@ }, "bash": { "path": "primary.bash", + "selected_owner_kind": "function_definition", "profile": "Shdoc", "fragments": [ [ @@ -515,6 +536,7 @@ }, "tcl": { "path": "primary.tcl", + "selected_owner_kind": "procedure", "profile": "StaticRuff304", "fragments": [ [ @@ -542,6 +564,7 @@ }, "irules": { "path": "primary.irule", + "selected_owner_kind": "when_event", "profile": "BcaIrules", "fragments": [ [ @@ -568,6 +591,7 @@ }, "ccomment": { "path": "helper-comment.c", + "selected_owner_kind": null, "profile": "NoDeclarationModel", "fragments": [], "owner": null, @@ -583,6 +607,7 @@ }, "preproc": { "path": "helper-preproc.h", + "selected_owner_kind": null, "profile": "NoDeclarationModel", "fragments": [], "owner": null, diff --git a/tests/fixtures/documentation/legacy.json b/tests/fixtures/documentation/legacy.json index 407aed00c..f5835ffb9 100644 --- a/tests/fixtures/documentation/legacy.json +++ b/tests/fixtures/documentation/legacy.json @@ -27,8 +27,8 @@ "doxygen-cdata.h": {"included":{"loc":[2,1,0,1,0,0],"dloc_rows":[],"spaces":[]}}, "perl-mixed.pl": {"included":{"loc":[19,2,1,16,1,16],"dloc_rows":[0,1,2,3,4,5,6,7,8,9,10,14,15,16,17,18],"spaces":[["f","function",13,13,[]]]}}, "groovy-spaces.groovy": {"included":{"loc":[11,6,1,5,0,5],"dloc_rows":[0,2,4,6,8],"spaces":[["R","class",2,2,[]],["R","function",2,2,[]],["C","class",4,11,[4,6,8]],["C","function",6,6,[]],["f","function",10,10,[]]]}}, - "tcl-continuation.tcl": {"included":{"loc":[4,1,1,2,1,0],"dloc_rows":[],"spaces":[]}}, - "tcl-crlf.tcl": {"included":{"loc":[4,2,2,1,1,0],"dloc_rows":[],"spaces":[]}}, - "irules-continuation.irule": {"included":{"loc":[4,1,1,2,1,0],"dloc_rows":[],"spaces":[]}}, - "irules-crlf.irule": {"included":{"loc":[4,2,2,1,1,0],"dloc_rows":[],"spaces":[]}} + "tcl-continuation.tcl": {"included":{"loc":[4,1,1,2,1,0],"dloc_rows":[],"ploc_rows":[3],"cloc_rows":[0,1],"spaces":[]}}, + "tcl-crlf.tcl": {"included":{"loc":[4,2,2,1,1,0],"dloc_rows":[],"ploc_rows":[1,3],"cloc_rows":[0],"spaces":[]}}, + "irules-continuation.irule": {"included":{"loc":[4,1,1,2,1,0],"dloc_rows":[],"ploc_rows":[3],"cloc_rows":[0,1],"spaces":[]}}, + "irules-crlf.irule": {"included":{"loc":[4,2,2,1,1,0],"dloc_rows":[],"ploc_rows":[1,3],"cloc_rows":[0],"spaces":[]}} } diff --git a/tests/fixtures/documentation/provenance.json b/tests/fixtures/documentation/provenance.json index 27ec8b3f5..57ec30beb 100644 --- a/tests/fixtures/documentation/provenance.json +++ b/tests/fixtures/documentation/provenance.json @@ -1,6 +1,16 @@ { "date": "2026-11-18", "semantic_base": "b47ea189ba51fe50d6362f876e77126c35d307d0", + "d01_baseline_relationship": { + "baseline": "91087f52f5d4a58e31ae320851351990f1436411", + "semantic_base": "b47ea189ba51fe50d6362f876e77126c35d307d0", + "ancestor_command": "git merge-base --is-ancestor 91087f52f5d4a58e31ae320851351990f1436411 b47ea189ba51fe50d6362f876e77126c35d307d0", + "ancestor_exit": 0, + "equal_paths": ["Cargo.toml", "Cargo.lock", "src/metrics", "big-code-analysis-ast/src/checker", "big-code-analysis-ast/src/lang_helpers", "big-code-analysis-ast/src/roles", "src/spaces", "src/options.rs"], + "comparison_command": "git diff --stat 91087f52f5d4a58e31ae320851351990f1436411 b47ea189ba51fe50d6362f876e77126c35d307d0 -- Cargo.toml Cargo.lock src/metrics big-code-analysis-ast/src/checker big-code-analysis-ast/src/lang_helpers big-code-analysis-ast/src/roles src/spaces src/options.rs big-code-analysis-ast/src/parser.rs big-code-analysis-ast/src/node.rs big-code-analysis-ast/src/node", + "changed_parser_paths": ["big-code-analysis-ast/src/parser.rs", "big-code-analysis-ast/src/node.rs", "big-code-analysis-ast/src/node/parser_cache.rs"], + "qualification": "D01 baseline is an ancestor of the semantic base. Dependency manifests/lockfile (including grammar pins), metric code and recognition paths listed above are byte-identical. Parser provenance handling changed between them. This source comparison does not establish independently rebuilt clean-base metric parity; the capture build qualifications below still apply." + }, "oracle_build_revision": "3c25db8e3224abcb6e41fde3c2d011655c868149", "oracle_portion": "a776c9d4a4927c016413c94596d9cd12925c5b0c", "build_worktree_changes": "New test-support module routing, cfg(test) root routing and raw fixtures present during build. No shipping metric, Checker, Getter, role or shared binding changes. Capture driver selection additions run from this checkpoint's source.", @@ -23,7 +33,7 @@ "revision": "42d39ad8cb854536e432dcce164fb7392121cccb", "sources": ["docs/development/documentation_extraction.md", "docs/development/documentation_extraction_cases.md"], "reference_record": "https://gist.github.com/dekobon/acb5b4fd9ada1c2b63f86ae0f0514524", - "qualification": "Source expectations copied from accepted D01, not generated from extractor output. Primary LANG inventory requires declaration-associated nonempty text for each source variant, with explicit helper exceptions. Future extraction conformance remains unimplemented." + "qualification": "Source expectations copied from accepted D01, not generated from extractor output. Primary LANG inventory requires declaration-associated nonempty text and an explicit selected declaration kind for each source variant, with null helper kinds. owner_kinds separately records every observed same-span node. Lua first-file and Python chained-assignment raw controls extend requirements and production recognition tests only; the selected whole-metric capture is unchanged. Future extraction conformance remains unimplemented." }, "references": [ {"tool":"Zulu OpenJDK","version":"25.0.5.0.3+1-LTS","evidence":"Prior D01 executed observation, not rerun here","configuration":"JavacTask.parse, -proc:none, logical C.java; DocTrees.getDocComment/getDocCommentTree","command":"jshell --feedback concise; complete source and exact commands in reference_record","reference":"https://docs.oracle.com/en/java/javase/25/docs/specs/javadoc/doc-comment-spec.html","qualification":"BCA empty-block local cleanup intentionally differs from returned slash."}, diff --git a/tests/fixtures/documentation/sources/lua-first-file.lua b/tests/fixtures/documentation/sources/lua-first-file.lua new file mode 100644 index 000000000..4a5df01e5 --- /dev/null +++ b/tests/fixtures/documentation/sources/lua-first-file.lua @@ -0,0 +1,2 @@ +---audit +function f() end diff --git a/tests/fixtures/documentation/sources/python-chained-comment.py b/tests/fixtures/documentation/sources/python-chained-comment.py new file mode 100644 index 000000000..157b8dd84 --- /dev/null +++ b/tests/fixtures/documentation/sources/python-chained-comment.py @@ -0,0 +1,2 @@ +#: audit +x = y = 1 diff --git a/tests/fixtures/documentation/sources/python-chained.py b/tests/fixtures/documentation/sources/python-chained.py new file mode 100644 index 000000000..3f741d211 --- /dev/null +++ b/tests/fixtures/documentation/sources/python-chained.py @@ -0,0 +1,2 @@ +x = y = 1 +"audit" diff --git a/utils/documentation-characterization-perturb.json b/utils/documentation-characterization-perturb.json index 37d8fc9c7..c9fbb9081 100644 --- a/utils/documentation-characterization-perturb.json +++ b/utils/documentation-characterization-perturb.json @@ -14,6 +14,10 @@ {"name":"delete-rust-pruned-outer-doc","file":"tests/fixtures/documentation/sources/rust-prune.rs","old":"/// outer\n","new":"\n","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, {"name":"conformance-helper-compares-against-null","file":"big-code-analysis-ast/src/test_support/documentation.rs","old":"let expected = &inventory()[lang.to_string()];","new":"let expected = &serde_json::Value::Null;","expect":["test_support::documentation::tests::documentation_conformance_rejects_absent_adapter_and_wrong_identity"]}, {"name":"legacy-selection-loop-visits-only-first-key","file":"src/metrics/loc/documentation_tests.rs","old":"for key in selection.as_array().expect(\"keys\") {","new":"for key in selection.as_array().expect(\"keys\").iter().take(1) {","expect":["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"]}, - {"name":"primary-recognition-loop-visits-only-first-language","file":"big-code-analysis-ast/src/test_support/documentation.rs","old":"for lang in LANG::into_enum_iter().filter(LANG::is_enabled) {","new":"for lang in LANG::into_enum_iter().filter(LANG::is_enabled).take(1) {","expect":["test_support::documentation::tests::documentation_primary_recognition"]} + {"name":"primary-recognition-loop-visits-only-first-language","file":"big-code-analysis-ast/src/test_support/documentation.rs","old":"for lang in LANG::into_enum_iter().filter(LANG::is_enabled) {","new":"for lang in LANG::into_enum_iter().filter(LANG::is_enabled).take(1) {","expect":["test_support::documentation::tests::documentation_primary_recognition"]}, + {"name":"bypass-selected-owner-kind","file":"big-code-analysis-ast/src/test_support/documentation.rs","old":"\"owner_kind\": expected[\"selected_owner_kind\"]","new":"\"owner_kind\": actual[0][\"owner_kind\"]","expect":["test_support::documentation::tests::documentation_python_conformance_distinguishes_same_span_root","test_support::documentation::tests::documentation_tcl_conformance_distinguishes_same_span_root"]}, + {"name":"drop-lua-first-file-recognition","file":"big-code-analysis-ast/src/checker/lua.rs","old":"|| lua_first_ldoc_block(first, code, ancestors))","new":"|| (false && lua_first_ldoc_block(first, code, ancestors)))","expect":["test_support::documentation::tests::documentation_lua_first_file_run_needs_no_declaration"]}, + {"name":"drop-python-chained-string-recognition","file":"big-code-analysis-ast/src/lang_helpers/python.rs","old":"return attributes.documented_by(&sibling, code).then_some(first);","new":"return (attributes.documented_by(&sibling, code) && !code.starts_with(b\"x = y =\")).then_some(first);","expect":["test_support::documentation::tests::documentation_python_chained_forms_are_recognized_without_owner_claims"]}, + {"name":"drop-python-chained-comment-recognition","file":"big-code-analysis-ast/src/lang_helpers/python.rs","old":"if documents {\n credit_block(comment, code, ancestors, &mut credit);","new":"if documents && !code.starts_with(b\"#: audit\\nx = y =\") {\n credit_block(comment, code, ancestors, &mut credit);","expect":["test_support::documentation::tests::documentation_python_chained_forms_are_recognized_without_owner_claims"]} ] } diff --git a/utils/documentation-package-check.py b/utils/documentation-package-check.py new file mode 100644 index 000000000..56ba40020 --- /dev/null +++ b/utils/documentation-package-check.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Compile AST test-support without checkout-only documentation fixtures. + +Fallback when unpublished grammar dependencies prevent cargo package verification. +Copies tracked sources (plus current edits) and workspace manifests to a temporary +directory, retaining local grammar dependencies but omitting documentation fixtures. +Runs all-features check and rustdoc. --baseline REV substitutes only the old +documentation helper, proving that its external include fails across this boundary. +This does not verify registry resolution or Cargo's normalized package manifest. +""" + +import argparse +import os +from pathlib import Path +import shutil +import subprocess +import tempfile + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--baseline") + args = parser.parse_args() + root = Path(__file__).resolve().parent.parent + files = subprocess.check_output(["git", "ls-files", "-z"], cwd=root).split(b"\0") + with tempfile.TemporaryDirectory(prefix="bca-documentation-package-") as directory: + isolated = Path(directory) + for raw in files: + if not raw: + continue + relative = Path(os.fsdecode(raw)) + if relative.is_relative_to("tests/fixtures/documentation"): + continue + source = root / relative + if not source.is_file(): + continue + target = isolated / relative + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, target) + assert not (isolated / "tests/fixtures/documentation").exists() + if args.baseline: + helper = "big-code-analysis-ast/src/test_support/documentation.rs" + old = subprocess.check_output(["git", "show", f"{args.baseline}:{helper}"], cwd=root) + (isolated / helper).write_bytes(old) + env = {**os.environ, "CARGO_TARGET_DIR": str(root / "target/documentation-package-check"), + "RUSTDOCFLAGS": "-D warnings"} + for action in ("check", "doc"): + command = ["cargo", action, "--offline", "--locked", "-p", "big-code-analysis-ast", "--all-features"] + command += ["--lib"] if action == "check" else ["--no-deps"] + print("+", " ".join(command), flush=True) + result = subprocess.run(command, cwd=isolated, env=env) + if result.returncode: + return result.returncode + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/utils/documentation-selection-perturb.json b/utils/documentation-selection-perturb.json index 16b9ec662..6928e95e3 100644 --- a/utils/documentation-selection-perturb.json +++ b/utils/documentation-selection-perturb.json @@ -4,8 +4,12 @@ "runner":"unittest", "command":["python3","-B","-m","unittest","-q","utils/drift-oracle-test.py","utils/drift-compare-test.py"], "cases":[ - {"name":"allow-untracked-selection","file":"utils/drift-oracle.py","old":"if tracked.returncode:","new":"if False:","expect":["utils.drift-oracle-test.DriftOracleTests.test_selection_rejects_empty_duplicate_missing_untracked_and_escape_keys"]}, + {"name":"allow-untracked-selection","file":"utils/drift-oracle.py","old":"if tracked.returncode or set(tracked.stdout.split(b\"\\0\")[:-1]) != {os.fsencode(\"/\".join(relative))}:","new":"if False:","expect":["utils.drift-oracle-test.DriftOracleTests.test_selection_rejects_empty_duplicate_missing_untracked_and_escape_keys"]}, {"name":"omit-selected-view","file":"utils/drift-oracle.py","old":"selected_views = args.view or available_views","new":"selected_views = available_views","expect":["utils.drift-oracle-test.DriftOracleTests.test_explicit_selection_is_tracked_exact_and_can_force_a_dialect"]}, - {"name":"drop-relative-path-mode","file":"utils/drift-oracle.py","old":"if args.relative_paths:","new":"if False:","expect":["utils.drift-oracle-test.DriftOracleTests.test_relative_paths_reach_binary_without_output_rewriting"]} + {"name":"drop-relative-path-mode","file":"utils/drift-oracle.py","old":"if args.relative_paths:","new":"if False:","expect":["utils.drift-oracle-test.DriftOracleTests.test_relative_paths_reach_binary_without_output_rewriting"]}, + {"name":"tracking-status-without-exact-path","file":"utils/drift-oracle.py","old":"if tracked.returncode or set(tracked.stdout.split(b\"\\0\")[:-1]) != {os.fsencode(\"/\".join(relative))}:","new":"if tracked.returncode:","expect":["utils.drift-oracle-test.DriftOracleTests.test_selection_rejects_directory_prefix_impostor"]}, + {"name":"drop-leading-hyphen-disambiguation","file":"utils/drift-oracle.py","old":"path_arg = f\"./{p}\" if str(p).startswith(\"-\") else str(p)","new":"path_arg = str(p)","expect":["utils.drift-oracle-test.DriftOracleTests.test_leading_hyphen_relative_path_is_disambiguated_for_every_binary"]}, + {"name":"unfiltered-one-sided-cli-options","file":"utils/drift-compare.py","old":"compared_options(mb[\"cli_cmds\"]) != compared_options(mh[\"cli_cmds\"])","new":"mb[\"cli_cmds\"] != mh[\"cli_cmds\"]","expect":["utils.drift-compare-test.DriftCompareTests.test_shared_views_filter_cli_and_metrics_but_check_shared_argv"]}, + {"name":"ignore-shared-cli-argv-change","file":"utils/drift-compare.py","old":"compared_options(mb[\"cli_cmds\"]) != compared_options(mh[\"cli_cmds\"])","new":"False","expect":["utils.drift-compare-test.DriftCompareTests.test_shared_views_filter_cli_and_metrics_but_check_shared_argv"]} ] } diff --git a/utils/drift-compare-test.py b/utils/drift-compare-test.py index 106cab81c..de1099282 100644 --- a/utils/drift-compare-test.py +++ b/utils/drift-compare-test.py @@ -173,6 +173,23 @@ def test_no_shared_view_is_refused(self) -> None: self.assertEqual(rc, 2) self.assertIn("no view on both sides", text) + def test_shared_views_filter_cli_and_metrics_but_check_shared_argv(self) -> None: + base = _capture(self.root / "base", verbatim=False) + head = _capture(self.root / "head", verbatim=False) + self._edit(base, views=["ops", "dump"], metrics_options={}) + self._edit(head, views=["ops", "metrics"], cli_cmds={"ops": ["ops"]}) + rc, _, summary = self._run(base, head, "--only-shared-views") + self.assertEqual(rc, 0) + self.assertEqual(summary["views_compared"], ["ops"]) + self.assertEqual(summary["views_uncompared"], ["dump", "metrics"]) + self.assertEqual(summary["outputs_compared"], 2) + self.assertEqual(summary["key_problems"], 0) + self._edit(head, cli_cmds={"ops": ["ops", "-O", "json"]}) + rc, _, summary = self._run(base, head, "--only-shared-views") + self.assertEqual(rc, 1) + self.assertEqual(summary["differing"], 0) + self.assertEqual(summary["key_problems"], 1) + def test_empty_key_sets_are_refused_even_without_a_filter(self) -> None: base = _capture(self.root / "base", verbatim=True, keys=[]) head = _capture(self.root / "head", verbatim=True, keys=[]) diff --git a/utils/drift-compare.py b/utils/drift-compare.py index a51da7373..4f49c2165 100755 --- a/utils/drift-compare.py +++ b/utils/drift-compare.py @@ -134,7 +134,7 @@ def main(argv: list[str] | None = None) -> int: def compared_options(matrix: dict) -> dict: return {name: argv for name, argv in matrix.items() if not args.only_shared_views or name not in one_sided} - if compared_options(mb["metrics_options"]) != compared_options(mh["metrics_options"]) or mb["cli_cmds"] != mh["cli_cmds"]: + if compared_options(mb["metrics_options"]) != compared_options(mh["metrics_options"]) or compared_options(mb["cli_cmds"]) != compared_options(mh["cli_cmds"]): print("option matrix or command set differs between captures") problems += 1 compared = 0 diff --git a/utils/drift-oracle-test.py b/utils/drift-oracle-test.py index d757bfc3b..73f5c9313 100644 --- a/utils/drift-oracle-test.py +++ b/utils/drift-oracle-test.py @@ -23,6 +23,7 @@ import sys import tempfile import unittest +from unittest.mock import patch UTILS_DIR = pathlib.Path(__file__).resolve().parent @@ -72,6 +73,11 @@ def _stub(path: pathlib.Path, body: str) -> pathlib.Path: class DriftOracleTests(unittest.TestCase): def setUp(self) -> None: + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull) + self._git_env = patch.dict(os.environ, env, clear=True) + self._git_env.start() + self.addCleanup(self._git_env.stop) self._tmp = tempfile.TemporaryDirectory() self.root = pathlib.Path(self._tmp.name) self.bca = _stub(self.root / "bca", "sys.stdout.write(' '.join(sys.argv[1:]) + '\\n')") @@ -297,6 +303,64 @@ def test_selected_filename_is_a_literal_git_pathspec(self) -> None: self.assertEqual(rc, "selected input is not tracked: 'rust/fx/*.rs'") self.assertEqual(m, {}) + def test_selection_rejects_directory_prefix_impostor(self) -> None: + directory = self.fixtures / "dir" + directory.mkdir() + child = directory / "child.rs" + child.write_text("fn child() {}") + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "dir/child.rs"], check=True) + child.unlink() + directory.rmdir() + directory.write_text("fn impostor() {}") + selection = self.root / "selection.json" + selection.write_text('["rust/fx/dir"]') + rc, _, _, m = self._run("--selection", str(selection), "--view", "metrics") + self.assertEqual(rc, "selected input is not tracked: 'rust/fx/dir'") + self.assertEqual(m, {}) + + def test_selection_accepts_exact_odd_paths_in_nested_root(self) -> None: + _stub(self.bca, "import json; print(json.dumps(sys.argv[1:]))") + subprocess.run(["git", "init", "-q", str(self.root)], check=True) + names = ["*.rs", ":(glob)*.rs", "quote\"\tline\n.rs", "café.rs"] + if os.name == "posix": + names.append(os.fsdecode(b"nonutf8-\xff.rs")) + for name in names: + (self.fixtures / name).write_text("fn exact() {}") + subprocess.run(["git", "-C", str(self.root), "add", "fx"], check=True) + selection = self.root / "selection.json" + keys = [f"rust/fx/{name}" for name in names] + selection.write_text(json.dumps(keys)) + rc, _, err, m = self._run("--selection", str(selection), "--view", "metrics") + self.assertEqual(rc, 0, err) + self.assertEqual(m["keys"], sorted(keys)) + for name in names: + args = json.loads((self.out / f"rust/fx/{name}.metrics.txt").read_text()) + self.assertEqual(os.fsencode(args[-1]), os.fsencode(self.fixtures / name)) + + def test_leading_hyphen_relative_path_is_disambiguated_for_every_binary(self) -> None: + _stub(self.bca, "import json; print(json.dumps(sys.argv[1:]))") + (self.fixtures / "--help").write_text("fn f() {}") + subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) + subprocess.run(["git", "-C", str(self.fixtures), "add", "--", "--help"], check=True) + selection = self.root / "selection.json" + selection.write_text('["rust/fx/--help"]') + with contextlib.chdir(self.fixtures): + rc, _, _, m = self._run("--selection", str(selection), "--relative-paths", + "--verbatim", str(self.verbatim)) + self.assertEqual(rc, 0) + self.assertTrue(m["complete"]) + for view in m["views"]: + suffix = ".verbatim.jsonl" if view == "verbatim" else f".{view}.txt" + args = json.loads((self.out / f"rust/fx/--help{suffix}").read_text()) + if view.startswith("verbatim"): + args = args["v"] + expected = [*oracle.VERBATIM_OPTIONS.get(view, []), "rust", "./--help"] + else: + head = oracle.CLI_CMDS.get(view, ["metrics", "-O", "json", *EXPECTED_METRICS_OPTIONS.get(view, [])]) + expected = [*head, "--no-config", "--language", "rust", "-p", "./--help"] + self.assertEqual(args, expected, view) + def test_explicit_selection_keeps_root_identity_and_selected_helpers(self) -> None: subprocess.run(["git", "init", "-q", str(self.fixtures)], check=True) subprocess.run(["git", "-C", str(self.fixtures), "add", "a.rs"], check=True) diff --git a/utils/drift-oracle.py b/utils/drift-oracle.py index 1532d6fbe..b89e4b380 100755 --- a/utils/drift-oracle.py +++ b/utils/drift-oracle.py @@ -69,6 +69,7 @@ import argparse import hashlib import json +import os import pathlib import subprocess import sys @@ -217,10 +218,11 @@ def selected_inputs(selection: pathlib.Path, roots: dict[str, pathlib.Path]) -> if not path.is_file(): sys.exit(f"missing selected input {key!r}") tracked = subprocess.run( - ["git", "--literal-pathspecs", "-C", str(root), "ls-files", "--error-unmatch", "--", "/".join(relative)], + ["git", "--literal-pathspecs", "-C", str(root), "ls-files", "-z", "--error-unmatch", "--", "/".join(relative)], capture_output=True, ) - if tracked.returncode: + # Unmerged index stages may repeat a path; a tracked descendant is not this file. + if tracked.returncode or set(tracked.stdout.split(b"\0")[:-1]) != {os.fsencode("/".join(relative))}: sys.exit(f"selected input is not tracked: {key!r}") jobs.append((lang, key, root, path)) return jobs @@ -331,16 +333,17 @@ def one(job: tuple[str, str, pathlib.Path, pathlib.Path]) -> None: dst = out / key dst.parent.mkdir(parents=True, exist_ok=True) base = [str(args.bca)] - tail = ["--no-config", "--language", lang, "-p", str(p)] + path_arg = f"./{p}" if str(p).startswith("-") else str(p) + tail = ["--no-config", "--language", lang, "-p", path_arg] for name, cmd in cli_cmds.items(): dst.with_name(dst.name + f".{name}.txt").write_bytes(run([*base, *cmd, *tail])) for name, extra in metric_options.items(): dst.with_name(dst.name + f".{name}.txt").write_bytes(run([*base, "metrics", "-O", "json", *extra, *tail])) if args.verbatim is not None: if "verbatim" in selected_views: - dst.with_name(dst.name + ".verbatim.jsonl").write_bytes(run([str(args.verbatim), lang, str(p)])) + dst.with_name(dst.name + ".verbatim.jsonl").write_bytes(run([str(args.verbatim), lang, path_arg])) for name, extra in verbatim_options.items(): - dst.with_name(dst.name + f".{name}.txt").write_bytes(run([str(args.verbatim), *extra, lang, str(p)])) + dst.with_name(dst.name + f".{name}.txt").write_bytes(run([str(args.verbatim), *extra, lang, path_arg])) with ThreadPoolExecutor(max_workers=args.jobs) as ex: list(ex.map(one, jobs)) From dae737d09bb58c878de8ad463103d9b8e1ec60e7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:36:17 -0800 Subject: [PATCH 020/221] test(docs): retain verbatim option mutation after path fix --- utils/documentation-oracle-perturb.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/documentation-oracle-perturb.json b/utils/documentation-oracle-perturb.json index ac7057689..02b72e5ba 100644 --- a/utils/documentation-oracle-perturb.json +++ b/utils/documentation-oracle-perturb.json @@ -17,8 +17,8 @@ { "name": "drop-verbatim-metric-options", "file": "utils/drift-oracle.py", - "old": "[str(args.verbatim), *extra, lang, str(p)]", - "new": "[str(args.verbatim), lang, str(p)]", + "old": "[str(args.verbatim), *extra, lang, path_arg]", + "new": "[str(args.verbatim), lang, path_arg]", "expect": [ "utils.drift-oracle-test.DriftOracleTests.test_mi_matrix_and_every_argv_are_symmetric_and_explicit", "utils.drift-oracle-test.DriftOracleTests.test_a_failed_mi_verbatim_view_is_not_a_baseline" From 9a3dc192b9fc7e0146760050bce5d4e699f6a0f7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:45:04 -0800 Subject: [PATCH 021/221] test(docs): record cycle-one regression and mutation evidence --- .../fixtures/documentation/verification.json | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/tests/fixtures/documentation/verification.json b/tests/fixtures/documentation/verification.json index b749f44ab..34b37a9db 100644 --- a/tests/fixtures/documentation/verification.json +++ b/tests/fixtures/documentation/verification.json @@ -1,4 +1,54 @@ { + "remediation_cycle1": { + "reviewed_from": "7128a4430b3a6ee1282a04e6d34b26774d1c84b7", + "implementation_checkpoint": "dae737d09bb58c878de8ad463103d9b8e1ec60e7", + "scope": "Confirmed D28 findings only; no production metric/recognition change or snapshot reblessing. Parent owns independent remediation review and integration.", + "pre_fix_failures": { + "python_command": "python3 -B -m unittest -q utils/drift-oracle-test.py utils/drift-compare-test.py", + "python_result": "New tests on old implementation: hyphen argv, directory-prefix impostor, and asymmetric shared CLI views failed. An initial odd-path positive also failed because the text-printing stub could not encode a surrogate filename; changing that stub to JSON preserved exact bytes and passed.", + "package_command": "TMPDIR=/tmp/opencode python3 -B utils/documentation-package-check.py --baseline 7128a443", + "package_result": "exit 101: couldn't read big-code-analysis-ast/src/test_support/../../../tests/fixtures/documentation/inventory.json; No such file or directory. Isolated copy omits that fixture tree while retaining workspace manifests and local grammar dependencies." + }, + "package_boundary": { + "package_command": "cargo package -p big-code-analysis-ast --all-features --offline --allow-dirty", + "package_result": "unavailable: registry cache offers bca-tree-sitter-ccomment 2.3.1, not required =2.6.1; exit 101 before package verification", + "fallback_command": "TMPDIR=/tmp/opencode python3 -B utils/documentation-package-check.py", + "fallback_result": "pass: cargo check --offline --locked -p big-code-analysis-ast --all-features --lib; RUSTDOCFLAGS='-D warnings' cargo doc --offline --locked -p big-code-analysis-ast --all-features --no-deps", + "qualification": "All-features includes test-support. This verifies compilation without checkout-only fixtures, not registry resolution, Cargo's normalized package manifest, or docs.rs hosting. Production docs.rs feature settings unchanged." + }, + "focused": [ + {"command":"cargo test -p big-code-analysis-ast -p big-code-analysis --all-features --lib --no-fail-fast documentation_", "result":"12 passed: 8 AST, 4 root (including 2 existing root tests)"}, + {"command":"cargo clippy -p big-code-analysis-ast -p big-code-analysis --all-features --lib --tests -- -D warnings", "result":"pass after correcting two semicolon lint failures"}, + {"command":"python3 -B -m unittest -q utils/drift_common-test.py utils/drift-oracle-test.py utils/drift-compare-test.py utils/recovery-oracle-test.py", "result":"57 passed"}, + {"command":"python3 -B -m unittest -q utils/perturb-test.py", "result":"59 passed"}, + {"command":"make check-test-lang-gates", "result":"pass: 5122 gated test items"}, + {"command":"make check-test-lang-gates-compare COMPARE_REF=b47ea189", "result":"pass: no test lost a build"}, + {"command":"make markdown-lint (after clearing inspected .rumdl_cache); rumdl check tests/fixtures/documentation/README.md", "result":"pass; local links and pinned fragment anchors checked separately"} + ], + "actual_cli_controls": { + "command_template": "python3 -B WORKSPACE/utils/drift-oracle.py --bca WORKSPACE/target/debug/bca --repo-toml WORKSPACE/Cargo.toml --out OUT --root fx=. --selection SELECTION --relative-paths --view metrics --jobs 1", + "setup": "Isolated scratch Git repositories with GIT_* environment removed, GIT_CONFIG_NOSYSTEM=1 and GIT_CONFIG_GLOBAL=/dev/null. Hyphen: track --help containing '/// audit\\nfn f() {}\\n'. Impostor: track dir/child.rs, remove its directory and replace it by an untracked regular file dir. Select rust/fx/--help or rust/fx/dir respectively.", + "hyphen_result": "exit 0, complete:true, one output, unit name ./--help", + "impostor_result": "exit 1, selected input is not tracked: 'rust/fx/dir'; no manifest or capture created" + }, + "fixture_dimensions": {"raw_files":55,"inventory_LANG_entries":25,"selected_keys":39,"views_per_key":10,"reference_records":390,"reference_changes":0}, + "perturbations": { + "tested_revision":"dae737d09bb58c878de8ad463103d9b8e1ec60e7", + "command_template":"TMPDIR=/tmp/opencode python3 -B utils/perturb.py MANIFEST", + "manifests":[ + {"path":"utils/documentation-characterization-perturb.json","caught":15,"rc_each":101}, + {"path":"utils/documentation-oracle-rust-perturb.json","caught":6,"rc_each":101}, + {"path":"utils/documentation-selection-perturb.json","caught":7,"rc_each":1}, + {"path":"utils/documentation-oracle-perturb.json","caught":3,"rc_each":1} + ], + "result":"All 31 caught by expected guards; original 23 cases retained. No bad anchors, missing guards, build errors, or harness errors; mutation targets restored.", + "owner_kind_discrimination":"bypass-selected-owner-kind substitutes actual[0][owner_kind] for the independently expected kind. Both Python and Tcl same-span-root tests then fail; the tests also reject a helper that compares against null. Valid independently written projections pass normally.", + "new_raw_controls":"Dropping Lua first-file recognition fails its no-following-candidate assertion. Suppressing each Python chained recognition path separately fails the chained-forms test. These are recognition guards, not extraction-association guards.", + "qualification":"Focused AST/root documentation filters, whole bench lib, and driver unittest targets; no unique-guard claim. verification.json was the only unrelated dirty file during the sweeps." + }, + "fixture_qualification": "All 55 raw files equal their committed bytes; -text Git attribute applies to the three added controls. All selected input hashes still match reference/manifest.json. Lua first-file and Python chained forms have raw production recognition tests and independently specified future owner requirements, not an extraction implementation or new metric capture.", + "prose_review": "Self-review corrected link targets, added Git/MI references, explained MI dependency closure and non-unique mutation guards, and separated language-specific limitations into a linked list. No new findings on final reread; independent review remains parent work." + }, "implementation_checkpoint": "0a5b6e38d9d294209bd6e59c71a7b703dcbb9b46", "selection_followup": "324248ef", "perturbation_checkpoint": "b547a41f", From 2808850c572848bab1381a3242803456287633c9 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:49:02 -0800 Subject: [PATCH 022/221] test(docs): record passing cycle-one gate and reference replay --- .../fixtures/documentation/verification.json | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/tests/fixtures/documentation/verification.json b/tests/fixtures/documentation/verification.json index 34b37a9db..ab11a59e6 100644 --- a/tests/fixtures/documentation/verification.json +++ b/tests/fixtures/documentation/verification.json @@ -29,9 +29,33 @@ "command_template": "python3 -B WORKSPACE/utils/drift-oracle.py --bca WORKSPACE/target/debug/bca --repo-toml WORKSPACE/Cargo.toml --out OUT --root fx=. --selection SELECTION --relative-paths --view metrics --jobs 1", "setup": "Isolated scratch Git repositories with GIT_* environment removed, GIT_CONFIG_NOSYSTEM=1 and GIT_CONFIG_GLOBAL=/dev/null. Hyphen: track --help containing '/// audit\\nfn f() {}\\n'. Impostor: track dir/child.rs, remove its directory and replace it by an untracked regular file dir. Select rust/fx/--help or rust/fx/dir respectively.", "hyphen_result": "exit 0, complete:true, one output, unit name ./--help", + "hyphen_all_views_command":"Same scratch setup and driver argv with --verbatim WORKSPACE/target/debug/verbatim-oracle and no --view restriction, freshly rebuilt binaries at 9a3dc192", + "hyphen_all_views_result":"exit 0, complete:true, all 34 CLI/verbatim views, zero failed executions", "impostor_result": "exit 1, selected input is not tracked: 'rust/fx/dir'; no manifest or capture created" }, "fixture_dimensions": {"raw_files":55,"inventory_LANG_entries":25,"selected_keys":39,"views_per_key":10,"reference_records":390,"reference_changes":0}, + "feature_isolation": { + "command_template":"cargo test -p PACKAGE --lib --no-default-features [--features FEATURE] documentation_", + "packages":["big-code-analysis-ast","big-code-analysis"], + "features":["none","rust","go","python","tcl","lua","irules"], + "ast_passed":[0,2,1,4,2,2,1], + "root_passed":[0,1,0,3,2,0,1], + "qualification":"Each package invoked separately at implementation dae737d0; only verification evidence changed during execution. Zero tests denotes feature exclusion, not conformance. All invocations exit 0." + }, + "replay": { + "tested_revision":"9a3dc192b9fc7e0146760050bce5d4e699f6a0f7", + "build_command":"cargo build -p big-code-analysis-cli -p big-code-analysis-bench --bin bca --bin verbatim-oracle", + "capture_command":"README.md Replay block, exact view argv in provenance.json; output written to a unique mktemp directory", + "compare_command":"python3 -B utils/drift-compare.py tests/fixtures/documentation/reference OUT", + "keys_base":39,"keys_head":39,"outputs_compared":390,"differing":0,"key_problems":0,"views_uncompared":[], + "base_bca_sha256_prefix":"dbe4ea4892f8","head_bca_sha256_prefix":"a325f7522e7d", + "qualification":"Freshly rebuilt current binaries versus original checked reference; both captures complete. Reproduces every selected record without updating references. The original reference build qualifications remain in provenance.json; this is not independently rebuilt D01/base corpus parity." + }, + "shared_view_reference_control": { + "setup":"Copy checked reference twice to scratch; add an ops view, matching cli_cmds entry, outputs_per_file increment and one-sided dummy ops records to head only.", + "command":"python3 -B utils/drift-compare.py BASE_COPY HEAD_COPY --only-shared-views", + "result":"exit 0; outputs_compared=390, differing=0, key_problems=0, views_uncompared=[ops]. Synthetic view-selection control, not another production capture." + }, "perturbations": { "tested_revision":"dae737d09bb58c878de8ad463103d9b8e1ec60e7", "command_template":"TMPDIR=/tmp/opencode python3 -B utils/perturb.py MANIFEST", @@ -47,6 +71,19 @@ "qualification":"Focused AST/root documentation filters, whole bench lib, and driver unittest targets; no unique-guard claim. verification.json was the only unrelated dirty file during the sweeps." }, "fixture_qualification": "All 55 raw files equal their committed bytes; -text Git attribute applies to the three added controls. All selected input hashes still match reference/manifest.json. Lua first-file and Python chained forms have raw production recognition tests and independently specified future owner requirements, not an extraction implementation or new metric capture.", + "full_gate": { + "tested_revision":"9a3dc192b9fc7e0146760050bce5d4e699f6a0f7", + "command":"log=$(mktemp /tmp/opencode/bca-cycle1-pre-commit.XXXXXX.log); make pre-commit >\"$log\" 2>&1; read the single ^BCA_GATE: line", + "verdict":"BCA_GATE: pass (gate=pre-commit)", + "exit":0, + "workspace_tests_passed":7467,"workspace_tests_skipped":4, + "doctests_passed":68,"doctests_ignored":1, + "python_tests_passed":413,"python_tests_xfailed":1, + "python_test_runtime":"Python 3.14.8 in bindings venv; standalone driver checks used Python 3.14.3", + "skipped_stages":[], + "unavailable":"patchelf: non-failing maturin wheel rpath warning twice; pytest and stubtest both passed", + "qualification":"All gate stages completed. Only verification.json evidence changed during and after this run. No metric behavior, reference records, raw inputs, or test code changed after the tested revision. D28 remains unintegrated pending parent remediation review." + }, "prose_review": "Self-review corrected link targets, added Git/MI references, explained MI dependency closure and non-unique mutation guards, and separated language-specific limitations into a linked list. No new findings on final reread; independent review remains parent work." }, "implementation_checkpoint": "0a5b6e38d9d294209bd6e59c71a7b703dcbb9b46", From f1f45d6aedc2dc82ffa8ba8cb9447a4439122fe3 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:31:25 -0800 Subject: [PATCH 023/221] refactor(ast): retain marker evidence and stream legacy LOC decisions Implement D03 marker binding evidence with independent source candidates, native profile hooks, final-member selection and canonical raw occurrences. Migrate shared and Rust LOC atomically to ordered legacy events. Validate exact row/timing/cache counters, Doxygen gathering and conditional siblings, nested and macro source context. Selected replay: 390 outputs, zero drift. All 140 scaling probes pass; make pre-commit reports BCA_GATE: pass. Tracked perturbation manifest supports the clean-checkpoint sweep. --- .bca-baseline.toml | 34 +- big-code-analysis-ast/src/checker.rs | 31 + .../src/checker/doxygen_doc_binding.rs | 15 + big-code-analysis-ast/src/checker/java.rs | 21 + .../src/checker/js_doc_binding.rs | 11 + big-code-analysis-ast/src/checker/kotlin.rs | 2 + big-code-analysis-ast/src/checker/php.rs | 2 + big-code-analysis-ast/src/checker/rust.rs | 21 +- .../src/documentation/source.rs | 6 + .../src/documentation/streaming.rs | 32 +- .../src/documentation/streaming/markers.rs | 292 +++++++ .../documentation/streaming/markers/tests.rs | 820 ++++++++++++++++++ .../src/lang_helpers/doc_comment.rs | 119 ++- .../src/node/ancestors/folds.rs | 8 +- src/metrics/loc/documentation_tests.rs | 50 ++ src/metrics/loc/rust.rs | 23 +- src/metrics/loc/shared.rs | 70 +- utils/documentation-markers-perturb.json | 77 ++ 18 files changed, 1532 insertions(+), 102 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/streaming/markers.rs create mode 100644 big-code-analysis-ast/src/documentation/streaming/markers/tests.rs create mode 100644 utils/documentation-markers-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index ab0959a82..e536d2f73 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -215,7 +215,13 @@ value = 5.0 path = "big-code-analysis-ast/src/checker.rs" qualified = "" metric = "loc.sloc" -value = 1288.0 +value = 1319.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::select" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/getter.rs" @@ -253,6 +259,12 @@ qualified = "RubyCode::get_op_type" metric = "halstead.effort" value = 101217.532578918 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_gathered" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "bind_leading" @@ -263,7 +275,7 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "bound_doc_run" metric = "halstead.effort" -value = 74870.34845140431 +value = 55726.365295548676 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -271,12 +283,30 @@ qualified = "bound_doc_run" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_stretch" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "joined_run" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "select_bound" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/elixir_decisions.rs" qualified = "elixir_pair_section" diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 90f2bc818..4be823048 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -409,6 +409,37 @@ pub trait Checker { fn is_doc_comment(_: &Node, _code: &[u8]) -> bool { false } + /// Native source marker before selection, independent of the legacy gate. + #[must_use] + fn is_source_doc_comment(node: &Node, code: &[u8]) -> bool { + Self::is_doc_comment(node, code) + } + /// Native source binding, before owner normalization or publication policy. + #[must_use] + fn source_doc_binding() -> Option { + Self::DOC_BINDING + } + /// Whether a marker can document locally without a following target. + const SOURCE_LOCAL_DOCS: bool = false; + /// Source target through the shared role/context inventory. + #[must_use] + fn is_source_doc_target<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + Self::is_doc_target(node, code, ancestors) + } + /// Uncertainty in a local source marker, before owner normalization. + #[must_use] + fn source_doc_uncertainty<'a>( + node: &Node<'a>, + _: &[u8], + _: Ancestors<'a, '_>, + ) -> Option { + node.is_error() + .then_some(crate::documentation::UnresolvedReason::GrammarBoundary) + } /// Whether a doc comment inside a function or closure body is still /// documentation. `false` where it is better read as a working note, /// so a note spelled `/// …` stays a charged comment: rustc lints one diff --git a/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs b/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs index d0721fb03..098e9f3d2 100644 --- a/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs +++ b/big-code-analysis-ast/src/checker/doxygen_doc_binding.rs @@ -17,6 +17,8 @@ // conditionals" with no bytes. macro_rules! impl_doxygen_doc_binding { () => { + const SOURCE_LOCAL_DOCS: bool = true; + const DOC_BINDING: Option = Some(DocBinding { skips: $crate::lang_helpers::doxygen::doxygen_skips::, forward: $crate::lang_helpers::doxygen::doxygen_binds_forward::, @@ -31,6 +33,19 @@ macro_rules! impl_doxygen_doc_binding { fn is_doc_target<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { $crate::lang_helpers::doxygen::doxygen_target::(node, code, ancestors) } + + fn source_doc_uncertainty<'a>( + node: &Node<'a>, + _: &[u8], + _: Ancestors<'a, '_>, + ) -> Option<$crate::documentation::UnresolvedReason> { + use $crate::documentation::UnresolvedReason; + if $crate::lang_helpers::doxygen::preproc_conditional::(node) { + Some(UnresolvedReason::Conditional) + } else { + node.is_error().then_some(UnresolvedReason::GrammarBoundary) + } + } }; } diff --git a/big-code-analysis-ast/src/checker/java.rs b/big-code-analysis-ast/src/checker/java.rs index e1f942d1c..a8a863338 100644 --- a/big-code-analysis-ast/src/checker/java.rs +++ b/big-code-analysis-ast/src/checker/java.rs @@ -18,6 +18,27 @@ impl Checker for JavaCode { impl_comment_from_rows!(java); impl_doc_comment_from_row!(java); + fn is_source_doc_comment(node: &Node, code: &[u8]) -> bool { + Self::is_comment(node) + && matches!( + node_bytes(node, code), + [b'/', b'*', b'*', ..] | [b'/', b'/', b'/', ..] + ) + } + + fn is_source_doc_target<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + // Package publication depends on explicit filename metadata, not the + // following type. Source attachment retains the package in either case. + // role-bypass: allow(DocTarget) — package source attachment drops only the legacy filename-shape approximation. + crate::roles::java::doc_target::lists_kind(node.kind_id()) + && (node.kind_id() == Java::PackageDeclaration + || Self::is_doc_target(node, code, ancestors)) + } + // javac's `Token::docComment` gives a declaration the last doc comment // before its first token, its annotations and modifiers included, and // its dangling-doc-comments lint names every earlier one; blank rows diff --git a/big-code-analysis-ast/src/checker/js_doc_binding.rs b/big-code-analysis-ast/src/checker/js_doc_binding.rs index 8ff94981f..deb2fff13 100644 --- a/big-code-analysis-ast/src/checker/js_doc_binding.rs +++ b/big-code-analysis-ast/src/checker/js_doc_binding.rs @@ -30,6 +30,17 @@ macro_rules! impl_js_family_doc_binding { }) }); + fn source_doc_binding() -> Option<$crate::lang_helpers::DocBinding> { + Self::DOC_BINDING.map(|binding| $crate::lang_helpers::DocBinding { + forward: |comment, code, _| { + !$standalone($crate::lang_helpers::doc_comment::node_bytes(comment, code)) + }, + ..binding + }) + } + + const SOURCE_LOCAL_DOCS: bool = true; + fn is_doc_target<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { $target(node, code, ancestors) } diff --git a/big-code-analysis-ast/src/checker/kotlin.rs b/big-code-analysis-ast/src/checker/kotlin.rs index 8eca6db7d..c1192fdd2 100644 --- a/big-code-analysis-ast/src/checker/kotlin.rs +++ b/big-code-analysis-ast/src/checker/kotlin.rs @@ -10,6 +10,8 @@ impl Checker for KotlinCode { impl_comment_from_rows!(kotlin); impl_doc_comment_from_row!(kotlin); + const SOURCE_LOCAL_DOCS: bool = true; + // Kotlin's parser closes each declaration with // `PrecedingDocCommentsBinder`, which pulls in the last KDoc of the // comments before it and leaves the earlier ones outside, whatever diff --git a/big-code-analysis-ast/src/checker/php.rs b/big-code-analysis-ast/src/checker/php.rs index 39a0f20b3..9a8818eb3 100644 --- a/big-code-analysis-ast/src/checker/php.rs +++ b/big-code-analysis-ast/src/checker/php.rs @@ -60,6 +60,8 @@ impl Checker for PhpCode { impl_comment_from_rows!(php); impl_doc_comment_from_row!(php); + const SOURCE_LOCAL_DOCS: bool = true; + // phpDocumentor gives an element PHP-Parser's `getDocComment`: the // last DocBlock among the comments before the node's first token, so // plain comments in between are read past and only the last of several diff --git a/big-code-analysis-ast/src/checker/rust.rs b/big-code-analysis-ast/src/checker/rust.rs index dffa4e55e..4e52e64d1 100644 --- a/big-code-analysis-ast/src/checker/rust.rs +++ b/big-code-analysis-ast/src/checker/rust.rs @@ -35,7 +35,12 @@ fn rust_doc_binds_forward<'a>( ancestors: Ancestors<'a, '_>, ) -> bool { let inner = rust_inner_doc(node_bytes(comment, code)); - let in_macro = ancestors.parent(comment).is_some_and(|parent| { + let in_macro = rust_doc_in_macro(comment, ancestors); + !inner && !in_macro +} + +fn rust_doc_in_macro<'a>(comment: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { + ancestors.parent(comment).is_some_and(|parent| { // role-bypass: allow(DocTarget) — a comment *inside* a macro definition's // token trees documents what the expansion makes of it; binding context // over the parent, not whether the definition is a target @@ -48,8 +53,7 @@ fn rust_doc_binds_forward<'a>( | Rust::TokenRepetitionPattern | Rust::MacroDefinition ) - }); - !inner && !in_macro + }) } impl Checker for RustCode { @@ -59,6 +63,17 @@ impl Checker for RustCode { impl_comment_from_rows!(rust); impl_doc_comment_from_row!(rust); + const SOURCE_LOCAL_DOCS: bool = true; + + fn source_doc_uncertainty<'a>( + node: &Node<'a>, + _: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> Option { + rust_doc_in_macro(node, ancestors) + .then_some(crate::documentation::UnresolvedReason::Expansion) + } + // rustc lints a doc comment on a statement or expression as unused and // rustdoc renders no item nested in a body, so a body holds its doc // comments (the default `holds_doc_comment_in_body`) — except the diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index e004d58d9..df9455995 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -60,6 +60,12 @@ pub struct SourceContext<'s> { } impl<'s> SourceContext<'s> { + /// The actual parsed bytes borrowed by this request. + #[must_use] + pub fn bytes(&self) -> &'s [u8] { + self.bytes + } + /// Bind the actual parsed source to its tree. This does not reparse or /// infer completion; adopted/raw inputs retain the caller's precondition. #[must_use] diff --git a/big-code-analysis-ast/src/documentation/streaming.rs b/big-code-analysis-ast/src/documentation/streaming.rs index b6d632be9..dd8f92ccb 100644 --- a/big-code-analysis-ast/src/documentation/streaming.rs +++ b/big-code-analysis-ast/src/documentation/streaming.rs @@ -4,6 +4,33 @@ use crate::Node; +pub mod markers; + +/// Stream the original marker/placement decision before the final-member binding +/// callbacks. This path needs no source context and constructs no source evidence. +pub fn marker_comment<'t, T: crate::Checker>( + node: &Node<'t>, + code: &[u8], + ancestors: crate::Ancestors<'t, '_>, + mut sink: impl FnMut(LegacyEvent<'t>), +) { + use crate::lang_helpers::doc_comment::{ + bound_doc_run, documents_unbound, documents_where_it_sits, + }; + let marker = markers::legacy_marker::(node, code, ancestors); + let by_placement = marker + && documents_unbound::(node, code, ancestors) + && documents_where_it_sits::(node, code, ancestors); + sink(LegacyEvent::Comment { + node: *node, + marker, + by_placement, + }); + bound_doc_run::(node, code, ancestors, |member| { + sink(LegacyEvent::BoundComment(*member)); + }); +} + /// A legacy recognition/coverage event, emitted at the original callback point. /// Root LOC retains row sets, physical space attribution and aggregation. #[derive(Clone, Copy, Debug)] @@ -48,9 +75,8 @@ pub enum CoverageKind { SphinxComment, } -// The marker/positional migrations wire these private requests into the shared -// scan. Keeping the lazy sink concrete here pins zero extra materialization -// without changing existing callbacks before their atomic root migration. +// Generic request/key primitives for positional adapters. Marker streaming uses +// the typed SourceRequest and separate visited-node slots in `markers`. #[allow(dead_code)] pub(crate) mod evidence { use super::super::{Convention, NodeEvidence}; diff --git a/big-code-analysis-ast/src/documentation/streaming/markers.rs b/big-code-analysis-ast/src/documentation/streaming/markers.rs new file mode 100644 index 000000000..7a3bbb2f8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/markers.rs @@ -0,0 +1,292 @@ +//! Native marker selection over borrowed traversal context. These are binding +//! candidates for owner adapters, not a declaration index or resolved owners. + +use crate::lang_helpers::doc_comment::{self, DocBinding, StretchEnd}; +use crate::node::WordSlot; +use crate::{Ancestors, Checker, Node}; + +use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces}; + +// Separate slots are necessary even on one visited node: Java's empty marker +// answers differently before the same Last selector runs. +#[derive(Clone, Copy)] +pub(crate) enum CandidateView { + Legacy, + Source, +} + +impl CandidateView { + pub(crate) fn marker(self, node: &Node, code: &[u8], ancestors: Ancestors) -> bool { + let slot = match self { + Self::Legacy => WordSlot::LegacyDocMarker, + Self::Source => WordSlot::SourceDocMarker, + }; + ancestors.classified(slot, node, || { + marker_reads::record(); + u8::from(match self { + Self::Legacy => T::is_doc_comment(node, code), + Self::Source => T::is_source_doc_comment(node, code), + }) + }) != 0 + } + + pub(crate) fn target<'t, T: Checker>( + self, + node: &Node<'t>, + code: &[u8], + ancestors: Ancestors<'t, '_>, + ) -> bool { + match self { + Self::Legacy => T::is_doc_target(node, code, ancestors), + Self::Source => T::is_source_doc_target(node, code, ancestors), + } + } +} + +pub(crate) fn legacy_marker(node: &Node, code: &[u8], ancestors: Ancestors) -> bool { + CandidateView::Legacy.marker::(node, code, ancestors) +} + +// The result cannot reveal extra marker reads or evidence built then discarded. +crate::observation::counter!(marker_reads, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(evidence_built, cfg(any(test, feature = "test-support"))); +pub use doc_comment::stretches_collected; + +/// Explicit source-only request for a language's native marker binding profile. +/// The caller visits comments once in source order, with its walk's caches. +/// Superseded and unattached candidates are retained only when requested. +pub struct SourceRequest<'r, 's> { + /// Exact tree/source context, prepared by the source consumer alone. + pub context: &'r SourceContext<'s>, + /// Retain rejected and superseded candidates in addition to selected ones. + pub retain_unbound: bool, + /// Receives each completed stretch once, on its final comment visit. + pub sink: &'r mut dyn FnMut(MarkerRun<'s>), +} + +/// A completed native marker stretch. All node fields are canonical source +/// evidence; a target is a binding candidate, never a resolved semantic owner. +#[derive(Debug)] +pub struct MarkerRun<'s> { + /// Recognized occurrences in source order, without repeated gatherers. + pub members: Vec>, + /// Following target wrapper, possibly a conditional or recovery node. + pub target: Option>, + /// Conditional/recovery evidence, not a set of simultaneously resolved owners. + pub target_uncertainty: Option, + /// Immediate containing syntax; owner adapters refine this context. + pub containing: Option>, + /// Preceding code retained for after-code placement decisions. + pub code_before: Option>, +} + +/// One physical source marker and its selection result. +#[derive(Debug)] +pub struct MarkerMember<'s> { + /// Exact syntax node, including any grammar-owned newline. + pub node: NodeEvidence<'s>, + /// Included spelling, excluding a line comment's LF/CRLF terminator. + pub source: SourcePieces<'s>, + /// Selection within this profile, independent of legacy billing. + pub selection: MarkerSelection, + /// Binding direction/context, still requiring the language's owner adapter. + pub placement: MarkerPlacement<'s>, + /// Known source uncertainty; no semantic owner is inferred from macro tokens. + pub uncertainty: Option, +} + +/// Native profile selection of a recognized marker. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MarkerSelection { + /// Contributes to forward or local source documentation. + Selected, + /// Another candidate of the stretch replaced this forward marker. + Superseded, + /// No target was selected, including after-code and rejected trivia. + Unattached, +} + +struct RunSelection<'t> { + kept: Vec>, + target: Option>, + gatherer: Option>, +} + +impl<'t> RunSelection<'t> { + fn select( + stretch: &[Node<'t>], + code_before: Option>, + end: StretchEnd<'t>, + binding: DocBinding, + input: (&[u8], Ancestors<'t, '_>), + ) -> Self { + let (code, ancestors) = input; + let marker = |n: &Node<'t>| CandidateView::Source.marker::(n, code, ancestors); + let forward = |n: &Node<'t>| marker(n) && (binding.forward)(n, code, ancestors); + if let StretchEnd::AtTarget { next, target } = end { + return Self { + kept: doc_comment::select_bound::( + stretch, + code, + binding.kept, + (code_before, next, target), + forward, + ), + target: Some(target), + gatherer: None, + }; + } + let result = binding.gathers.map(|gathers| { + let gatherer = stretch + .iter() + .rfind(|n| marker(n) && gathers(n, code)) + .copied(); + ( + doc_comment::bind_gathered(stretch, code, gathers, marker, forward), + gatherer, + ) + }); + let (kept, gatherer) = result.unwrap_or_default(); + Self { + kept, + target: None, + gatherer, + } + } + + fn members( + &self, + stretch: &[Node<'t>], + binding: DocBinding, + ancestors: Ancestors<'t, '_>, + request: &SourceRequest<'_, 't>, + ) -> Result>, SourceError> { + // bca: suppress(halstead) -- one ordered merge pairs selected nodes with retained source evidence. + let code = request.context.bytes(); + let mut selected = self.kept.iter().peekable(); + let mut members = Vec::new(); + for node in stretch + .iter() + .filter(|n| CandidateView::Source.marker::(n, code, ancestors)) + { + let kept = selected.peek().is_some_and(|n| n.id() == node.id()); + if kept { + selected.next(); + } + let forward = (binding.forward)(node, code, ancestors); + let selection = if kept || !forward { + MarkerSelection::Selected + } else if self.target.is_some() && !self.kept.is_empty() { + MarkerSelection::Superseded + } else { + MarkerSelection::Unattached + }; + if selection != MarkerSelection::Selected && !request.retain_unbound { + continue; + } + let placement = match (forward, kept, self.gatherer) { + (false, _, _) if binding.gathers.is_some_and(|gathers| gathers(node, code)) => { + MarkerPlacement::Gatherer + } + (false, _, _) => MarkerPlacement::Local, + (true, true, Some(gatherer)) => { + MarkerPlacement::Gathered(request.context.node(gatherer.as_tree_sitter())?) + } + _ => MarkerPlacement::Forward, + }; + let mut member = member(request.context, node, selection, placement)?; + member.uncertainty = T::source_doc_uncertainty(node, code, ancestors); + members.push(member); + } + Ok(members) + } +} + +/// Structural placement, deliberately not a semantic owner claim. Local macro +/// tokens and conditional targets retain uncertainty until an adapter resolves it. +#[derive(Clone, Copy, Debug)] +pub enum MarkerPlacement<'s> { + /// Candidate for the following target wrapper. + Forward, + /// Inner, trailing, signature, structural or expansion-local documentation. + Local, + /// A structural comment with its own document, retained once even when it + /// also gathers preceding forward markers. + Gatherer, + /// Contributes to this structural comment's document. + Gathered(NodeEvidence<'s>), +} + +/// Recognize native source markers at a comment visit. Uses the same stretch +/// boundaries and selection algorithms as legacy binding, with separate +/// pre-selection predicates. A deferred member never collects its prefix. +/// +/// # Errors +/// Propagates source identity/range failures; no successful partial run is emitted. +pub fn source_comment<'s, T: Checker>( + comment: &Node<'s>, + ancestors: Ancestors<'s, '_>, + request: &mut SourceRequest<'_, 's>, +) -> Result<(), SourceError> { + // bca: suppress(nexits, halstead) -- early deferral and source identity failures propagate before any sink call. + let Some(binding) = T::source_doc_binding() else { + return Ok(()); + }; + let code = request.context.bytes(); + let view = CandidateView::Source; + let end = doc_comment::stretch_end::(comment, code, ancestors, binding.skips, view); + if matches!(end, StretchEnd::Undecided) { + return Ok(()); + } + if matches!(end, StretchEnd::Elsewhere) + && !request.retain_unbound + && !T::SOURCE_LOCAL_DOCS + && binding.gathers.is_none() + { + return Ok(()); + } + let (stretch, code_before) = + doc_comment::collect_stretch::(comment, code, ancestors, binding.skips, view); + let selection = + RunSelection::select::(&stretch, code_before, end, binding, (code, ancestors)); + let members = selection.members::(&stretch, binding, ancestors, request)?; + if !members.is_empty() { + let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); + (request.sink)(MarkerRun { + members, + target: selection.target.map(canonical).transpose()?, + target_uncertainty: selection + .target + .and_then(|node| T::source_doc_uncertainty(&node, code, ancestors)), + containing: ancestors.parent(comment).map(canonical).transpose()?, + code_before: code_before.map(canonical).transpose()?, + }); + } + Ok(()) +} + +fn member<'s>( + context: &SourceContext<'s>, + node: &Node<'s>, + selection: MarkerSelection, + placement: MarkerPlacement<'s>, +) -> Result, SourceError> { + evidence_built::record(); + let bytes = doc_comment::node_bytes(node, context.bytes()); + let end = if bytes.starts_with(b"//") { + let line = bytes.strip_suffix(b"\n").unwrap_or(bytes); + node.start_byte() + line.strip_suffix(b"\r").unwrap_or(line).len() + } else { + node.end_byte() + }; + Ok(MarkerMember { + node: context.node(node.as_tree_sitter())?, + source: context.pieces(node.start_byte()..end)?, + selection, + placement, + uncertainty: None, + }) +} + +#[cfg(test)] +mod tests; diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs new file mode 100644 index 000000000..83923b5a6 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs @@ -0,0 +1,820 @@ +#![allow(clippy::single_range_in_vec_init)] + +use super::*; +use crate::{AnyParser, LANG, Search}; + +#[cfg(feature = "java")] +#[test] +fn java_source_selects_empty_new_block_before_legacy_selection() { + use crate::JavaCode; + let source = b"/** a\n * b\n * c */\n/**/\nclass C {}\n"; + let parser = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + let mut legacy = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if JavaCode::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + super::super::marker_comment::(node, source, ancestors, |event| { + legacy.push(event); + }); + } + }); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].target.unwrap().node().byte_range(), 24..34); + assert_eq!( + runs[0] + .members + .iter() + .map(|m| (m.node.node().byte_range(), m.selection)) + .collect::>(), + [ + (0..18, MarkerSelection::Superseded), + (19..23, MarkerSelection::Selected), + ] + ); + assert_eq!( + legacy + .iter() + .filter_map(|e| match e { + super::super::LegacyEvent::BoundComment(n) => Some(n.as_tree_sitter().byte_range()), + _ => None, + }) + .collect::>(), + [0..18] + ); + assert!(matches!( + legacy[0], + super::super::LegacyEvent::Comment { + marker: true, + by_placement: false, + .. + } + )); + assert!(matches!( + legacy[1], + super::super::LegacyEvent::Comment { + marker: false, + by_placement: false, + .. + } + )); + assert!(matches!( + legacy[2], + super::super::LegacyEvent::BoundComment(_) + )); + assert_eq!(legacy.len(), 3); +} + +#[cfg(feature = "java")] +#[test] +fn divergent_marker_queries_share_real_cache_in_both_orders() { + use crate::{FoldCache, JavaCode, SiblingCache}; + for source_first in [false, true] { + let source = b"/**/\nclass C {}"; + let parser = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + let root = parser.root_node(); + let comment = root.children().next().unwrap(); + let cache = FoldCache::default(); + let siblings = SiblingCache::default(); + let chain = [root]; + let ancestors = Ancestors::for_walk(&chain, &comment, &cache, &siblings); + let order = if source_first { + [CandidateView::Source, CandidateView::Legacy] + } else { + [CandidateView::Legacy, CandidateView::Source] + }; + let before = marker_reads::observed(); + for view in order.into_iter().cycle().take(6) { + assert_eq!( + view.marker::(&comment, source, ancestors), + matches!(view, CandidateView::Source) + ); + } + // expected: each distinct view computes once for this visited node. + assert_eq!(marker_reads::observed() - before, 2); + + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let cache = FoldCache::default(); + let ancestors = Ancestors::for_walk(&chain, &comment, &cache, &siblings); + let before = marker_reads::observed(); + let scans = stretches_collected::observed(); + let mut runs = Vec::new(); + let mut events = Vec::new(); + for view in order { + match view { + CandidateView::Source => source_comment::( + &comment, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(), + CandidateView::Legacy => { + super::super::marker_comment::( + &comment, + source, + ancestors, + |event| { + events.push(event); + }, + ); + } + } + } + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].node.node().byte_range(), 0..4); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Selected); + assert_eq!(events.len(), 1); + assert!(matches!( + events[0], + super::super::LegacyEvent::Comment { + marker: false, + by_placement: false, + .. + } + )); + // expected: two distinct questions computed once; one final-member scan per view. + assert_eq!(marker_reads::observed() - before, 2); + assert_eq!(stretches_collected::observed() - scans, 2); + } +} + +#[cfg(feature = "java")] +#[test] +fn legacy_deferrals_rejections_and_eof_build_no_source_evidence() { + use crate::JavaCode; + for (source, expected_scans, expected_bound) in [ + ("/**a*/\n/**b*/\nclass C {}", 1, vec![7..13]), + ("/**a*/\n/**b*/", 0, vec![]), + ( + "class C { void f() { /**a*/\n/**b*/\nclass N {} } }", + 0, + vec![], + ), + ] { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let built = evidence_built::observed(); + let scans = stretches_collected::observed(); + let mut bound = Vec::new(); + let mut visits = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if JavaCode::is_comment(node) { + visits += 1; + super::super::marker_comment::(node, parser.code(), ancestors, |event| { + if let super::super::LegacyEvent::BoundComment(n) = event { + assert_eq!(visits, 2); + bound.push(n.as_tree_sitter().byte_range()); + } + }); + if visits == 1 { + assert_eq!(stretches_collected::observed() - scans, 0); + } + } + }); + assert_eq!(visits, 2); + assert_eq!(bound, expected_bound); + assert_eq!(stretches_collected::observed() - scans, expected_scans); + assert_eq!(evidence_built::observed() - built, 0); + } +} + +#[cfg(any( + feature = "rust", + feature = "java", + feature = "kotlin", + feature = "groovy", + feature = "csharp", + feature = "php", + feature = "javascript", + feature = "mozjs", + feature = "typescript", + feature = "c", + feature = "cpp", + feature = "mozcpp", + feature = "objc" +))] +fn selections( + source: &str, +) -> (Vec<(usize, MarkerSelection)>, Vec) { + let parser = AnyParser::parse(T::lang(), source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut selected = Vec::new(); + let mut billed = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |run| { + selected.extend( + run.members + .iter() + .map(|m| (m.node.node().start_position().row, m.selection)), + ); + }, + }, + ) + .unwrap(); + super::super::marker_comment::( + node, + parser.code(), + ancestors, + |event| match event { + super::super::LegacyEvent::Comment { + node, + by_placement: true, + .. + } + | super::super::LegacyEvent::BoundComment(node) => { + billed.push(node.start_row()); + } + _ => {} + }, + ); + } + }); + (selected, billed) +} + +#[cfg(feature = "rust")] +#[test] +fn rust_all_crosses_plain_comments_attributes_and_blank_rows() { + assert_eq!( + selections::("///a\n// plain\n#[inline]\n\n///b\nfn f() {}"), + ( + vec![ + (0, MarkerSelection::Selected), + (4, MarkerSelection::Selected) + ], + vec![0, 4] + ) + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_last_joins_markdown_and_accepts_four_slashes() { + assert_eq!( + selections::("///old\n\n///new\n////\nclass C {}"), + ( + vec![ + (0, MarkerSelection::Superseded), + (2, MarkerSelection::Selected), + (3, MarkerSelection::Selected) + ], + vec![2] + ) + ); +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_last_reads_across_plain_comments() { + assert_eq!( + selections::("/**old*/\n// plain\n/**new*/\nfun f() {}"), + ( + vec![ + (0, MarkerSelection::Superseded), + (2, MarkerSelection::Selected) + ], + vec![2] + ) + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_nearest_plain_comment_detaches() { + assert_eq!( + selections::("/**old*/\n// plain\nclass C {}"), + (vec![(0, MarkerSelection::Unattached)], vec![]) + ); + assert_eq!( + selections::("/**old*/\n/* hidden */ class C {}"), + (vec![(0, MarkerSelection::Selected)], vec![0]) + ); + assert_eq!( + selections::("/**old*/\npackage p\nclass C {}"), + (vec![(0, MarkerSelection::Selected)], vec![0]) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_leading_joins_but_hidden_plain_breaks_composition() { + assert_eq!( + selections::("///old\n// plain\n///a\n///b\nclass C {}"), + ( + vec![ + (0, MarkerSelection::Superseded), + (2, MarkerSelection::Selected), + (3, MarkerSelection::Selected) + ], + vec![2, 3] + ) + ); + assert_eq!( + selections::("///a\n#region R\n///b\nclass C {}\n#endregion"), + ( + vec![ + (0, MarkerSelection::Superseded), + (2, MarkerSelection::Selected) + ], + vec![2] + ) + ); +} + +#[cfg(feature = "php")] +#[test] +fn php_leading_keeps_last_and_qualified_define_grouping() { + assert_eq!( + selections::( + "("/**old*/\n// plain\n/**new*/\nfunction f() {}"), + ( + vec![ + (0, MarkerSelection::Superseded), + (2, MarkerSelection::Selected) + ], + vec![2] + ) + ); + assert_eq!( + selections::( + "function outer() {\n/**inner*/\nfunction inner() {}\n/**note*/\nreturn 1;\n}" + ), + ( + vec![ + (1, MarkerSelection::Selected), + (3, MarkerSelection::Unattached) + ], + vec![1, 3] + ) + ); +} + +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_leading_keeps_last() { + assert_eq!( + selections::("/**old*/\n// plain\n/**new*/\nfunction f() {}"), + ( + vec![ + (0, MarkerSelection::Superseded), + (2, MarkerSelection::Selected) + ], + vec![2] + ) + ); + assert_eq!( + selections::( + "function outer() {\n/**inner*/\nfunction inner() {}\n/**note*/\nreturn 1;\n}" + ), + ( + vec![ + (1, MarkerSelection::Selected), + (3, MarkerSelection::Unattached) + ], + vec![1, 3] + ) + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_after_code_is_unattached() { + assert_eq!( + selections::("const x = 1; /**doc*/\nfunction f() {}"), + (vec![(0, MarkerSelection::Unattached)], vec![]) + ); + assert_eq!( + selections::( + "function outer() {\n/**inner*/\nfunction inner() {}\n/**note*/\nreturn 1;\n}" + ), + ( + vec![ + (1, MarkerSelection::Selected), + (3, MarkerSelection::Unattached) + ], + vec![1, 3] + ) + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn tsx_after_code_is_unattached() { + assert_eq!( + selections::("const x = 1; /**doc*/\nfunction f() {}"), + (vec![(0, MarkerSelection::Unattached)], vec![]) + ); + assert_eq!( + selections::( + "function outer() {\n/**inner*/\nfunction inner() {}\n/**note*/\nreturn 1;\n}" + ), + ( + vec![ + (1, MarkerSelection::Selected), + (3, MarkerSelection::Unattached) + ], + vec![1, 3] + ) + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_source_context_keeps_nested_and_package_candidates() { + assert_eq!( + selections::("class C { void f() {\n/**nested*/\nclass N {}\n} }"), + (vec![(1, MarkerSelection::Selected)], vec![]) + ); + assert_eq!( + selections::("/**pkg*/\npackage p;\nclass C {}"), + (vec![(0, MarkerSelection::Selected)], vec![]) + ); +} + +#[cfg(feature = "java")] +#[test] +fn unbound_retention_is_lazy_on_the_real_source_path() { + use crate::JavaCode; + for (source, retain_unbound, expected) in [ + ("/**old*/\n/**new*/\nclass C {}", false, 1), + ("/**old*/\n/**new*/\nclass C {}", true, 2), + ("/**dangling*/", false, 0), + ("/**dangling*/", true, 1), + ] { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let before = evidence_built::observed(); + let scans = stretches_collected::observed(); + let mut members = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if JavaCode::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound, + sink: &mut |run| members += run.members.len(), + }, + ) + .unwrap(); + } + }); + assert_eq!(members, expected); + assert_eq!(evidence_built::observed() - before, expected); + assert_eq!( + stretches_collected::observed() - scans, + usize::from(expected != 0) + ); + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn gathering() { + assert_eq!( + selections::("/**a*/\n/**b*/\n/**@file*/\n/**dangling*/"), + ( + vec![ + (0, MarkerSelection::Selected), + (1, MarkerSelection::Selected), + (2, MarkerSelection::Selected), + (3, MarkerSelection::Unattached) + ], + vec![2, 0, 1] + ) + ); + assert_eq!( + selections::("/**a*/\n/** text \"@file\" */\nvoid f();"), + ( + vec![ + (0, MarkerSelection::Selected), + (1, MarkerSelection::Selected) + ], + vec![0, 1] + ) + ); +} + +#[cfg(feature = "rust")] +#[test] +fn rust_nested_inner_and_macro_evidence_keeps_exact_source_spelling() { + use crate::{RustCode, documentation::UnresolvedReason}; + for (source, range, target, local, uncertainty, billed) in [ + ("/*!*/\nfn f() {}\n", 0..5, Some(6..15), true, None, vec![0]), + ( + "fn outer() {\n///inner\nfn inner() {}\n}", + 13..21, + Some(22..35), + false, + None, + vec![], + ), + ( + "m! { ///audit\nfn f() {} }\n", + 5..13, + None, + true, + Some(UnresolvedReason::Expansion), + vec![0], + ), + ( + "///audit\r\nfn f() {}", + 0..8, + Some(10..19), + false, + None, + vec![0], + ), + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if RustCode::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: false, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + } + }); + assert_eq!(runs.len(), 1, "{source}"); + let run = &runs[0]; + assert_eq!(run.members.len(), 1); + let member = &run.members[0]; + assert_eq!(member.source.pieces()[0].range(), range, "{source}"); + assert_eq!(member.source.pieces().len(), 1); + assert_eq!(member.selection, MarkerSelection::Selected); + assert_eq!(matches!(member.placement, MarkerPlacement::Local), local); + assert_eq!(member.uncertainty, uncertainty); + assert_eq!( + run.target.map(|n| n.node().byte_range()), + target, + "{source}" + ); + assert_eq!(selections::(source).1, billed); + } +} + +#[cfg(feature = "rust")] +#[test] +fn rust_macro_context_is_not_recovered_from_a_known_empty_chain() { + use crate::{RustCode, documentation::UnresolvedReason}; + let parser = AnyParser::parse( + LANG::Rust, + b"m! { ///audit\nfn f() {} }".to_vec(), + None, + None, + ) + .unwrap(); + let mut comments = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if RustCode::is_comment(node) { + comments += 1; + assert_eq!( + RustCode::source_doc_uncertainty(node, parser.code(), ancestors), + Some(UnresolvedReason::Expansion) + ); + assert_eq!( + RustCode::source_doc_uncertainty(node, parser.code(), Ancestors::known(&[])), + None + ); + } + }); + assert_eq!(comments, 1); +} + +#[cfg(feature = "rust")] +#[test] +fn source_rust_pruned_runs_remain_available_and_defer_once() { + use crate::RustCode; + let source = "///outer\n#[test]\nfn test_f() {}\n///kept\nfn f() {}"; + assert_eq!( + selections::(source), + ( + vec![ + (0, MarkerSelection::Selected), + (3, MarkerSelection::Selected) + ], + vec![0, 3] + ) + ); + for width in [4, 64, 256] { + let source = format!( + "{}fn f() {{}}", + "///doc\n// plain\n#[inline]\n".repeat(width) + ); + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let scans = stretches_collected::observed(); + let built = evidence_built::observed(); + let derived = crate::node::child_chains_derived::observed(); + let mut visits = 0; + let mut emitted = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if RustCode::is_comment(node) { + visits += 1; + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: false, + sink: &mut |run| { + assert_eq!(visits, 2 * width); + assert_eq!(run.members.len(), width); + emitted += 1; + }, + }, + ) + .unwrap(); + assert_eq!( + stretches_collected::observed() - scans, + usize::from(visits == 2 * width) + ); + } + }); + assert_eq!((visits, emitted), (2 * width, 1)); + // expected: one final-member scan, one source record per doc, no derived chains. + assert_eq!(stretches_collected::observed() - scans, 1); + assert_eq!(evidence_built::observed() - built, width); + assert_eq!(crate::node::child_chains_derived::observed() - derived, 0); + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn conditional_and_gathered_evidence() { + // bca: suppress(halstead) -- independent gathering and conditional fixtures share the four grammar adapters. + use crate::documentation::UnresolvedReason; + let source = b"/**a*/\n/**b*/\n/**@file*/\n/**dangling*/"; + let parser = AnyParser::parse(T::lang(), source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + } + }); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 4); + for member in &runs[0].members[..2] { + let MarkerPlacement::Gathered(gatherer) = member.placement else { + panic!("gathered predecessor") + }; + assert_eq!(gatherer.node().byte_range(), 14..24); + } + assert!(matches!( + runs[0].members[2].placement, + MarkerPlacement::Gatherer + )); + assert_eq!(runs[0].members[3].selection, MarkerSelection::Unattached); + for declares in [false, true] { + const DEPTH: usize = 12; + let source = format!( + "{}{}{}", + "/**doc*/\n#if A\n".repeat(DEPTH), + if declares { + "void f();\n" + } else { + "#include \n" + }, + "#endif\n".repeat(DEPTH) + ); + let parser = AnyParser::parse(T::lang(), source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + let before = crate::lang_helpers::doxygen::conditionals_read::observed(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + super::super::marker_comment::(node, parser.code(), ancestors, |_| {}); + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + } + }); + assert_eq!(runs.len(), DEPTH); + assert_eq!( + crate::lang_helpers::doxygen::conditionals_read::observed() - before, + DEPTH + ); + for run in runs { + assert_eq!(run.members.len(), 1); + assert_eq!(run.target.is_some(), declares); + assert_eq!( + run.target_uncertainty, + declares.then_some(UnresolvedReason::Conditional) + ); + assert_eq!( + run.members[0].selection, + if declares { + MarkerSelection::Selected + } else { + MarkerSelection::Unattached + } + ); + } + } +} + +#[cfg(feature = "c")] +#[test] +fn c_conditional_and_gathering_context() { + conditional_and_gathered_evidence::(); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_conditional_and_gathering_context() { + conditional_and_gathered_evidence::(); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_conditional_and_gathering_context() { + conditional_and_gathered_evidence::(); +} +#[cfg(feature = "objc")] +#[test] +fn objc_conditional_and_gathering_context() { + conditional_and_gathered_evidence::(); +} + +#[cfg(feature = "c")] +#[test] +fn c_gatherer_and_predecessors_once() { + gathering::(); +} + +#[cfg(feature = "cpp")] +#[test] +fn cpp_gatherer_and_predecessors_once() { + gathering::(); +} + +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_gatherer_and_predecessors_once() { + gathering::(); +} + +#[cfg(feature = "objc")] +#[test] +fn objc_gatherer_and_predecessors_once() { + gathering::(); +} diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 8d3669fd6..eba2dcd34 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -10,6 +10,7 @@ pub(crate) use super::doc_text::{ ruby_magic_comment, tsdoc_block, tsdoc_module, }; use crate::checker::Checker; +use crate::documentation::streaming::markers::CandidateView; use crate::node::{Ancestors, FoldLane, Node}; /// How a language's tool attaches a doc comment to the declaration after @@ -287,7 +288,8 @@ pub fn bound_doc_run<'a, T: Checker>( let Some(binding) = T::DOC_BINDING else { return; }; - let end = match stretch_end::(comment, code, ancestors, binding.skips) { + let view = CandidateView::Legacy; + let end = match stretch_end::(comment, code, ancestors, binding.skips, view) { // A later member decides. StretchEnd::Undecided => return, // Nothing documents, and no block gathers the stretch either. @@ -297,21 +299,47 @@ pub fn bound_doc_run<'a, T: Checker>( if !documents_where_it_sits::(comment, code, ancestors) { return; } - let (stretch, code_before) = collect_stretch::(comment, code, ancestors, binding.skips); - let forward = - |n: &Node<'a>| T::is_doc_comment(n, code) && (binding.forward)(n, code, ancestors); + let (stretch, code_before) = + collect_stretch::(comment, code, ancestors, binding.skips, view); + let forward = |n: &Node<'a>| { + view.marker::(n, code, ancestors) && (binding.forward)(n, code, ancestors) + }; let StretchEnd::AtTarget { next, target } = end else { if let Some(gathers) = binding.gathers { - bind_gathered::(&stretch, code, gathers, forward) - .iter() - .for_each(&mut credit); + bind_gathered( + &stretch, + code, + gathers, + |n| view.marker::(n, code, ancestors), + forward, + ) + .iter() + .for_each(&mut credit); } return; }; - let kept = match binding.kept { + let kept = select_bound::( + &stretch, + code, + binding.kept, + (code_before, next, target), + forward, + ); + kept.iter().for_each(&mut credit); +} + +pub(crate) fn select_bound<'a, T: Checker>( + stretch: &[Node<'a>], + code: &[u8], + kept: KeptDocs, + boundaries: (Option>, Node<'a>, Node<'a>), + forward: impl Fn(&Node<'a>) -> bool, +) -> Vec> { + let (code_before, next, target) = boundaries; + match kept { KeptDocs::All => stretch.iter().copied().filter(forward).collect(), - KeptDocs::Last { joins } => bind_last::(&stretch, code, joins, forward), - KeptDocs::Nearest { hidden } => bind_nearest::(&stretch, next, hidden, forward) + KeptDocs::Last { joins } => bind_last::(stretch, code, joins, forward), + KeptDocs::Nearest { hidden } => bind_nearest::(stretch, next, hidden, forward) .into_iter() .collect(), KeptDocs::Leading { @@ -326,14 +354,14 @@ pub fn bound_doc_run<'a, T: Checker>( .filter(|_| !after_code(&target)) .map(|before| before.end_row()); let attaches = |n: &Node<'a>| forward(n) && Some(n.start_row()) != after_code_row; - bind_leading::(&stretch, code, hidden, joins, attaches) + bind_leading::(stretch, code, hidden, joins, attaches) } - }; - kept.iter().for_each(&mut credit); + } } /// Where a stretch of comments ends, asked of its last comment. -enum StretchEnd<'a> { +#[derive(Clone, Copy)] +pub(crate) enum StretchEnd<'a> { /// A later comment of the stretch decides. Undecided, /// At `target`, an [`Checker::is_doc_target`] or a parse error holding @@ -351,21 +379,24 @@ enum StretchEnd<'a> { /// whether it is read past, and only once the binding's own `skips` and /// [`Checker::is_doc_target`] have passed on it, so a binding that decides /// errors itself (Doxygen's) keeps its reading. -fn stretch_end<'a, T: Checker>( +pub(crate) fn stretch_end<'a, T: Checker>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, skips: for<'b> fn(&Node<'a>, Ancestors<'a, 'b>) -> bool, + view: CandidateView, ) -> StretchEnd<'a> { let mut after = ancestors.siblings_after(comment).peekable(); let Some(&next) = after.peek() else { return StretchEnd::Elsewhere; }; - match after.find(|n| !skips(n, ancestors) && !read_past_error::(n, code, ancestors)) { + match after.find(|n| !skips(n, ancestors) && !read_past_error_in::(n, code, ancestors, view)) + { Some(target) if T::is_comment(&target) => StretchEnd::Undecided, Some(target) - if T::is_doc_target(&target, code, ancestors) - || (target.is_error() && error_holds_target::(&target, code, ancestors)) => + if view.target::(&target, code, ancestors) + || (target.is_error() + && error_holds_target_in::(&target, code, ancestors, view)) => { StretchEnd::AtTarget { next, target } } @@ -381,12 +412,14 @@ fn stretch_end<'a, T: Checker>( /// `safe` of a `safe fn` is between the item's doc comments and its /// first token, not that token. An error the scan does not read past — /// one holding a target — ends the stretch and is the sibling before it. -fn collect_stretch<'a, T: Checker>( +pub(crate) fn collect_stretch<'a, T: Checker>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, skips: for<'b> fn(&Node<'a>, Ancestors<'a, 'b>) -> bool, + view: CandidateView, ) -> (Vec>, Option>) { + stretches_collected::record(); let mut stretch = vec![*comment]; let mut before = None; // An error read past is no member of the stretch: neither a comment @@ -396,7 +429,7 @@ fn collect_stretch<'a, T: Checker>( // above it instead of the one the tool attaches. for sibling in ancestors .siblings_before(comment) - .filter(|sibling| !read_past_error::(sibling, code, ancestors)) + .filter(|sibling| !read_past_error_in::(sibling, code, ancestors, view)) { if T::is_comment(&sibling) || skips(&sibling, ancestors) { stretch.push(sibling); @@ -415,14 +448,15 @@ fn collect_stretch<'a, T: Checker>( /// error between the item's doc comment and the rest of it. Given the /// benefit of the doubt, as Doxygen's binding gives one (`doxygen_skips`), /// rather than dropping the doc comment on a parse failure. -fn read_past_error<'a, T: Checker>( +fn read_past_error_in<'a, T: Checker>( node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, + view: CandidateView, ) -> bool { node.is_error() - && !T::is_doc_target(node, code, ancestors) - && !error_holds_target::(node, code, ancestors) + && !view.target::(node, code, ancestors) + && !error_holds_target_in::(node, code, ancestors, view) } /// Whether a child of the parse error `error` is a doc target: a @@ -435,34 +469,39 @@ fn read_past_error<'a, T: Checker>( /// chain the children are judged with none, which a target test that /// climbs pays for at `O(depth)`; every production walk lends one, so /// only a test reaches that fallback. -fn error_holds_target<'a, T: Checker>( +fn error_holds_target_in<'a, T: Checker>( error: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, + view: CandidateView, ) -> bool { let under = ancestors.of_children(error); let inside = under.get(); error .children() - .any(|child| child.is_named() && T::is_doc_target(&child, code, inside)) + .any(|child| child.is_named() && view.target::(&child, code, inside)) } +// Output alone cannot reveal repeated prefix collection or rejected-path work. +crate::observation::counter!( + stretches_collected, + cfg(any(test, feature = "test-support")) +); + /// What a stretch that ends at no target documents: what its last /// gathering comment ([`DocBinding::gathers`]) takes — the forward doc /// comments before it, and the line doc comments on the rows directly /// below it, which a line-comment tool reads as one block with it. The /// gathering comment does not bind forward, so `forward` drops it; it /// documents where it sits. -fn bind_gathered<'a, T: Checker>( +pub(crate) fn bind_gathered<'a>( stretch: &[Node<'a>], code: &[u8], gathers: fn(&Node, &[u8]) -> bool, + marker: impl Fn(&Node<'a>) -> bool, forward: impl Fn(&Node<'a>) -> bool, ) -> Vec> { - let Some(gatherer) = stretch - .iter() - .rposition(|n| T::is_doc_comment(n, code) && gathers(n, code)) - else { + let Some(gatherer) = stretch.iter().rposition(|n| marker(n) && gathers(n, code)) else { return Vec::new(); }; let line = |n: &Node| node_bytes(n, code).starts_with(b"//"); @@ -473,7 +512,7 @@ fn bind_gathered<'a, T: Checker>( while let Some(below) = stretch.get(last + 1) && gathers_below && line(below) - && T::is_doc_comment(below, code) + && marker(below) && below.start_row() == stretch[last].end_row().saturating_add(1) { last += 1; @@ -700,6 +739,24 @@ pub(crate) fn lua_group_head_above<'a, T: Checker>( mod tests { use super::*; + #[cfg(feature = "c")] + fn read_past_error<'a, T: Checker>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + read_past_error_in::(node, code, ancestors, CandidateView::Legacy) + } + + #[cfg(feature = "java")] + fn error_holds_target<'a, T: Checker>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + error_holds_target_in::(node, code, ancestors, CandidateView::Legacy) + } + /// Every language's `DOC_BINDING` spreads `..DocBinding::new(kept)` /// and relies on its defaults: nothing skipped, every doc comment /// binding forward, no gathering comment. Each const is evaluated at diff --git a/big-code-analysis-ast/src/node/ancestors/folds.rs b/big-code-analysis-ast/src/node/ancestors/folds.rs index 025564905..ce0617b00 100644 --- a/big-code-analysis-ast/src/node/ancestors/folds.rs +++ b/big-code-analysis-ast/src/node/ancestors/folds.rs @@ -669,14 +669,18 @@ pub(crate) enum WordSlot { ElixirCallTarget, /// Tcl: what a `command`'s leading `simple_word` spells. TclCommandWord, + /// Legacy documentation marker for the visited comment. + LegacyDocMarker, + /// Native source-profile marker, which can disagree with the legacy marker. + SourceDocMarker, } impl WordSlot { /// How many slots a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 2; + const COUNT: usize = 4; } -const _: () = assert!(WordSlot::TclCommandWord as usize + 1 == WordSlot::COUNT); +const _: () = assert!(WordSlot::SourceDocMarker as usize + 1 == WordSlot::COUNT); /// Answers that are a fact of one node, memoised for one walk and keyed /// by node id, which is unique within a tree. Most are about the node's diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index d149ab041..38aad8aeb 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -5,6 +5,56 @@ use serde_json::{Value, json}; use crate::{LANG, Metric, MetricsOptions, Source, analyze}; +#[cfg(all(feature = "java", feature = "rust"))] +#[test] +fn documentation_marker_stream_preserves_rows_without_source_materialization() { + use big_code_analysis_ast::documentation::streaming::markers::{ + evidence_built, stretches_collected, + }; + for (lang, source, excluded, rows, scans) in [ + ( + LANG::Java, + "/** a\n * b\n * c */\n/**/\nclass C {}\n", + false, + vec![0, 1, 2], + 1, + ), + ( + LANG::Java, + "class C { void f() { /**a*/\n/**b*/\nclass N {} } }", + false, + vec![], + 0, + ), + (LANG::Java, "/**a*/\n/**b*/", false, vec![], 0), + (LANG::Rust, "/*!*/\nfn f() {}\n", false, vec![0], 1), + ( + LANG::Rust, + "/// outer\n#[test]\nfn test_f() {}\n\n/// kept\nfn f() {}\n", + true, + vec![4], + 1, + ), + ] { + let built = evidence_built::observed(); + let collected = stretches_collected::observed(); + let space = analyze( + Source::new(lang, source.as_bytes()), + MetricsOptions::default().with_exclude_tests(excluded), + ) + .unwrap(); + assert_eq!( + (0..source.len()) + .filter(|row| space.metrics.loc.dloc.lines.contains(*row)) + .collect::>(), + rows, + "{source}" + ); + assert_eq!(evidence_built::observed() - built, 0); + assert_eq!(stretches_collected::observed() - collected, scans); + } +} + #[cfg(any( feature = "c", feature = "cpp", diff --git a/src/metrics/loc/rust.rs b/src/metrics/loc/rust.rs index 521021955..9a00d1bec 100644 --- a/src/metrics/loc/rust.rs +++ b/src/metrics/loc/rust.rs @@ -12,7 +12,7 @@ )] use super::*; -use crate::lang_helpers::bound_doc_run; +use big_code_analysis_ast::documentation::streaming::{LegacyEvent, marker_comment}; /// The rows a Rust comment renders on. tree-sitter-rust's /// `process_line_doc_content` (see `src/scanner.c` in the pinned grammar @@ -74,13 +74,20 @@ impl Loc for RustCode { // it is asked once here and its answer handed down; a member // `bound_doc_run` credits has already passed that test. BlockComment | LineComment => { - let doc = Self::is_doc_comment(node, code); - let (first, last) = rendered_rows(node, doc); - let documentation = doc && documents_by_placement::(node, code, ancestors); - add_comment_rows(stats, first, last, documentation); - bound_doc_run::(node, code, ancestors, |member| { - let (first, last) = rendered_rows(member, true); - stats.dloc.lines.insert_range(first, last); + marker_comment::(node, code, ancestors, |event| match event { + LegacyEvent::Comment { + node, + marker, + by_placement, + } => { + let (first, last) = rendered_rows(&node, marker); + add_comment_rows(stats, first, last, by_placement); + } + LegacyEvent::BoundComment(member) => { + let (first, last) = rendered_rows(&member, true); + stats.dloc.lines.insert_range(first, last); + } + _ => {} }); } Statement diff --git a/src/metrics/loc/shared.rs b/src/metrics/loc/shared.rs index 95528393d..e65d32dc1 100644 --- a/src/metrics/loc/shared.rs +++ b/src/metrics/loc/shared.rs @@ -54,9 +54,8 @@ use super::continuation::BareRowIndex; use super::*; -use crate::lang_helpers::{ - bound_doc_run, documents_unbound, documents_where_it_sits, leading_doc_run, -}; +use crate::lang_helpers::leading_doc_run; +use big_code_analysis_ast::documentation::streaming::{LegacyEvent, marker_comment}; #[inline] pub(crate) fn init(node: &Node, stats: &mut Stats, is_func_space: bool) -> usize { @@ -170,8 +169,8 @@ pub(crate) fn add_leading_doc_run<'a, T: Checker>( } #[inline] -// Bills a comment node's rows, as documentation when `is_documentation` -// says so. Every language's comment arm routes here — Rust's comment +// Bills a comment node's rows from the AST's ordered legacy stream. +// Every language's comment arm routes here — Rust's comment // arm bills through `add_comment_rows` itself, since its // `Checker::is_doc_comment` answer also sizes its row span — so "which // comments are documentation" is answered in one place per language, in @@ -186,54 +185,19 @@ pub(crate) fn add_comment_lines<'a, T: Checker>( ancestors: Ancestors<'a, '_>, stats: &mut Stats, ) { - let documentation = is_documentation::(node, code, ancestors); - add_comment_rows(stats, node.start_row(), node.end_row(), documentation); - add_bound_doc_run::(node, code, ancestors, stats); -} - -// Whether a comment is documentation by where it sits: spelled as a doc -// comment (`Checker::is_doc_comment`), not one a `Checker::DOC_BINDING` -// attaches forward (`documents_unbound`; `add_bound_doc_run` bills -// those), and, per `documents_where_it_sits`, not a working note in a -// function body (#1597, #1613). -fn is_documentation<'a, T: Checker>( - node: &Node<'a>, - code: &[u8], - ancestors: Ancestors<'a, '_>, -) -> bool { - T::is_doc_comment(node, code) && documents_by_placement::(node, code, ancestors) -} - -// The placement half of `is_documentation`, for a caller that already -// holds the `Checker::is_doc_comment` answer (Rust's comment arm). -pub(crate) fn documents_by_placement<'a, T: Checker>( - node: &Node<'a>, - code: &[u8], - ancestors: Ancestors<'a, '_>, -) -> bool { - documents_unbound::(node, code, ancestors) - && documents_where_it_sits::(node, code, ancestors) -} - -#[inline] -// Bills as `dloc` the doc comments a bound language's tool attaches to -// the declaration after them, once `node` ends their stretch -// (`bound_doc_run`, #1613). Each member's rows are the ones its own -// comment arm billed to `cloc`, so `dloc() <= cloc()` still holds; every -// member is a sibling of `node`, so they were billed to this space's -// `stats`. Rust's arm, whose `///` rows are not its node's, calls -// `bound_doc_run` itself. -fn add_bound_doc_run<'a, T: Checker>( - node: &Node<'a>, - code: &[u8], - ancestors: Ancestors<'a, '_>, - stats: &mut Stats, -) { - bound_doc_run::(node, code, ancestors, |member| { - stats - .dloc - .lines - .insert_range(member.start_row(), member.end_row()); + marker_comment::(node, code, ancestors, |event| match event { + LegacyEvent::Comment { + node, by_placement, .. + } => { + add_comment_rows(stats, node.start_row(), node.end_row(), by_placement); + } + LegacyEvent::BoundComment(member) => { + stats + .dloc + .lines + .insert_range(member.start_row(), member.end_row()); + } + _ => {} }); } diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json new file mode 100644 index 000000000..b620b5b0d --- /dev/null +++ b/utils/documentation-markers-perturb.json @@ -0,0 +1,77 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], + "cases": [ + { + "name": "source-marker-must-not-reuse-legacy-slot", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "Self::Source => WordSlot::SourceDocMarker,", + "new": "Self::Source => WordSlot::LegacyDocMarker,", + "expect": ["documentation::streaming::markers::tests::divergent_marker_queries_share_real_cache_in_both_orders"] + }, + { + "name": "source-candidates-precede-last-selection", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "Self::Source => T::is_source_doc_comment(node, code),", + "new": "Self::Source => T::is_doc_comment(node, code),", + "expect": ["documentation::streaming::markers::tests::java_source_selects_empty_new_block_before_legacy_selection"] + }, + { + "name": "source-prefixes-must-defer", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "if matches!(end, StretchEnd::Undecided) {", + "new": "if false && matches!(end, StretchEnd::Undecided) {", + "expect": ["documentation::streaming::markers::tests::source_rust_pruned_runs_remain_available_and_defer_once"] + }, + { + "name": "legacy-rejected-placement-exits-before-collection", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "if !documents_where_it_sits::(comment, code, ancestors) {", + "new": "if false && !documents_where_it_sits::(comment, code, ancestors) {", + "expect": ["documentation::streaming::markers::tests::legacy_deferrals_rejections_and_eof_build_no_source_evidence", "metrics::loc::documentation_tests::documentation_marker_stream_preserves_rows_without_source_materialization"] + }, + { + "name": "gatherer-retained-alongside-predecessors", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "let selection = if kept || !forward {", + "new": "let selection = if kept {", + "expect": ["documentation::streaming::markers::tests::c_gatherer_and_predecessors_once", "documentation::streaming::markers::tests::cpp_gatherer_and_predecessors_once", "documentation::streaming::markers::tests::mozcpp_gatherer_and_predecessors_once", "documentation::streaming::markers::tests::objc_gatherer_and_predecessors_once"] + }, + { + "name": "legacy-bound-callbacks-remain-source-ordered", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "kept.iter().for_each(&mut credit);", + "new": "kept.iter().rev().for_each(&mut credit);", + "expect": ["documentation::streaming::markers::tests::rust_all_crosses_plain_comments_attributes_and_blank_rows"] + }, + { + "name": "after-code-placement-must-be-read", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": ".filter(|_| !after_code(&target))", + "new": ".filter(|_| false && !after_code(&target))", + "expect": ["documentation::streaming::markers::tests::typescript_after_code_is_unattached", "documentation::streaming::markers::tests::tsx_after_code_is_unattached"] + }, + { + "name": "rust-attribute-skips-remain-in-the-run", + "file": "big-code-analysis-ast/src/checker/rust.rs", + "old": "skips: |node, _| node.kind_id() == Rust::AttributeItem,", + "new": "skips: |node, _| false && node.kind_id() == Rust::AttributeItem,", + "expect": ["documentation::streaming::markers::tests::rust_all_crosses_plain_comments_attributes_and_blank_rows"] + }, + { + "name": "conditional-target-is-not-a-resolved-owner", + "file": "big-code-analysis-ast/src/checker/doxygen_doc_binding.rs", + "old": "Some(UnresolvedReason::Conditional)", + "new": "None", + "expect": ["documentation::streaming::markers::tests::c_conditional_and_gathering_context", "documentation::streaming::markers::tests::cpp_conditional_and_gathering_context", "documentation::streaming::markers::tests::mozcpp_conditional_and_gathering_context", "documentation::streaming::markers::tests::objc_conditional_and_gathering_context"] + }, + { + "name": "rust-legacy-row-correction-uses-marker-not-placement", + "file": "src/metrics/loc/rust.rs", + "old": "let (first, last) = rendered_rows(&node, marker);", + "new": "let (first, last) = rendered_rows(&node, marker && by_placement);", + "expect": ["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"] + } + ] +} From 648efb0e4f907c66638cd3635c76982625e2ec37 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:39:37 -0800 Subject: [PATCH 024/221] test(documentation): guard retained marker context evidence --- .../documentation/streaming/markers/tests.rs | 45 +++++++++++++++++++ utils/documentation-markers-perturb.json | 14 ++++++ 2 files changed, 59 insertions(+) diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs index 83923b5a6..e07fa18aa 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs @@ -598,6 +598,51 @@ fn rust_nested_inner_and_macro_evidence_keeps_exact_source_spelling() { } } +#[cfg(feature = "rust")] +#[test] +fn source_run_retains_containing_and_preceding_nodes() { + use crate::RustCode; + let source = b"fn outer() {\nlet x = 0;\n///doc\nfn inner() {}\n}"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if RustCode::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: false, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + } + }); + assert_eq!(runs.len(), 1); + let run = &runs[0]; + let containing = run.containing.unwrap().node(); + assert_eq!( + (containing.kind(), containing.byte_range()), + ("block", 11..46) + ); + let before = run.code_before.unwrap().node(); + assert_eq!( + (before.kind(), before.byte_range()), + ("let_declaration", 13..23) + ); + let target = run.target.unwrap().node(); + assert_eq!( + (target.kind(), target.byte_range()), + ("function_item", 31..44) + ); + assert_eq!(run.members.len(), 1); + assert_eq!(run.members[0].source.pieces()[0].range(), 24..30); + assert_eq!(run.members[0].selection, MarkerSelection::Selected); + assert!(matches!(run.members[0].placement, MarkerPlacement::Forward)); +} + #[cfg(feature = "rust")] #[test] fn rust_macro_context_is_not_recovered_from_a_known_empty_chain() { diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index b620b5b0d..0c2a6f2e4 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -3,6 +3,20 @@ "runner": "cargo", "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], "cases": [ + { + "name": "source-containing-context-must-be-retained", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "containing: ancestors.parent(comment).map(canonical).transpose()?,", + "new": "containing: None,", + "expect": ["documentation::streaming::markers::tests::source_run_retains_containing_and_preceding_nodes"] + }, + { + "name": "source-preceding-code-must-be-retained", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "code_before: code_before.map(canonical).transpose()?,", + "new": "code_before: None,", + "expect": ["documentation::streaming::markers::tests::source_run_retains_containing_and_preceding_nodes"] + }, { "name": "source-marker-must-not-reuse-legacy-slot", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", From a4d6b4cdd8a072b6fdc37d1e41a4996ac5820209 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:37:30 -0800 Subject: [PATCH 025/221] fix(documentation): respect source gaps and preserve rejection evidence --- .bca-baseline.toml | 30 +- CHANGELOG.md | 4 + big-code-analysis-ast/src/checker.rs | 11 + big-code-analysis-ast/src/checker/php.rs | 91 ++-- big-code-analysis-ast/src/checker/rust.rs | 4 + .../src/documentation/owners.rs | 2 + .../src/documentation/source.rs | 62 +++ .../src/documentation/streaming/markers.rs | 178 +++++-- .../streaming/markers/regressions.rs | 455 ++++++++++++++++++ .../documentation/streaming/markers/tests.rs | 9 +- .../src/lang_helpers/doc_comment.rs | 152 ++++-- utils/documentation-markers-perturb.json | 68 ++- 12 files changed, 939 insertions(+), 127 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs diff --git a/.bca-baseline.toml b/.bca-baseline.toml index e536d2f73..f8523076d 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -215,13 +215,19 @@ value = 5.0 path = "big-code-analysis-ast/src/checker.rs" qualified = "" metric = "loc.sloc" -value = 1319.0 +value = 1330.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" -qualified = "RunSelection<'t>::select" -metric = "nargs" -value = 5.0 +path = "big-code-analysis-ast/src/checker.rs" +qualified = "Checker" +metric = "nom" +value = 29.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock" +metric = "halstead.effort" +value = 72819.97333517869 [[entry]] path = "big-code-analysis-ast/src/getter.rs" @@ -259,6 +265,12 @@ qualified = "RubyCode::get_op_type" metric = "halstead.effort" value = 101217.532578918 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "" +metric = "loc.ploc" +value = 531.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "bind_gathered" @@ -275,7 +287,7 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "bound_doc_run" metric = "halstead.effort" -value = 55726.365295548676 +value = 56178.08004602712 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -301,6 +313,12 @@ qualified = "select_bound" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end" +metric = "halstead.effort" +value = 63070.7256524501 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "stretch_end" diff --git a/CHANGELOG.md b/CHANGELOG.md index f46595328..edfb6d29b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ for historical reference. ### Added +- Added unstable AST-crate source-marker `Checker` hooks and streaming requests + that retain selection, source pieces and attachment uncertainty. The separate + legacy event stream preserves existing metric behavior. (#1658) + - Added unstable `big-code-analysis-ast::documentation` fact, source and owner primitives, plus retained `Complete` / `Cancelled` / `Adopted` parse provenance on `Parser` and `AnyParser`. The root library's documentation facade follows diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 4be823048..3a4ec34de 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -419,6 +419,17 @@ pub trait Checker { fn source_doc_binding() -> Option { Self::DOC_BINDING } + /// Source-only direction test. Overrides must respect included-range barriers + /// when inspecting comments beyond the current continuous spelling. + #[must_use] + fn source_doc_binds_forward<'a>( + node: &Node<'a>, + context: &crate::documentation::SourceContext<'a>, + ancestors: Ancestors<'a, '_>, + ) -> bool { + Self::source_doc_binding() + .is_some_and(|binding| (binding.forward)(node, context.bytes(), ancestors)) + } /// Whether a marker can document locally without a following target. const SOURCE_LOCAL_DOCS: bool = false; /// Source target through the shared role/context inventory. diff --git a/big-code-analysis-ast/src/checker/php.rs b/big-code-analysis-ast/src/checker/php.rs index 9a8818eb3..9452c3681 100644 --- a/big-code-analysis-ast/src/checker/php.rs +++ b/big-code-analysis-ast/src/checker/php.rs @@ -2,6 +2,7 @@ #![allow(clippy::wildcard_imports, clippy::enum_glob_use)] use super::*; +use crate::documentation::streaming::markers::CandidateView; use crate::lang_helpers::doc_comment::never_joins; /// A top-level node phpDocumentor's `createFileDocBlock` passes over @@ -22,18 +23,36 @@ fn php_file_preamble(node: &Node) -> bool { /// DocBlock among them is the file's, and otherwise it is only when exactly /// two DocBlocks precede it. The backward test stops at the previous /// DocBlock, so only the file's first one scans forward. -fn php_file_docblock<'a>(comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - let preamble_or_plain = |n: Node| { - php_file_preamble(&n) || (PhpCode::is_comment(&n) && !PhpCode::is_doc_comment(&n, code)) +fn php_file_docblock<'a>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView, +) -> bool { + let marker = |n: &Node| match view { + CandidateView::Legacy => PhpCode::is_doc_comment(n, code), + CandidateView::Source(_) => view.marker::(n, code, ancestors), }; + let preamble_or_plain = + |n: Node| php_file_preamble(&n) || (PhpCode::is_comment(&n) && !marker(&n)); + let mut boundary = comment.start_byte(); if !ancestors.parent_has_kind(comment, Php::Program as u16) - || !ancestors.siblings_before(comment).all(preamble_or_plain) + || !ancestors.siblings_before(comment).all(|n| { + let continuous = view.covers(n.start_byte()..boundary); + boundary = n.start_byte(); + continuous && preamble_or_plain(n) + }) { return false; } let mut docs = 1_usize; + let mut boundary = comment.end_byte(); for node in ancestors.siblings_after(comment) { - if PhpCode::is_doc_comment(&node, code) { + if !view.covers(boundary..node.end_byte()) { + return false; + } + boundary = node.end_byte(); + if marker(&node) { docs += 1; } else if !PhpCode::is_comment(&node) && !php_file_preamble(&node) { return docs == 2 @@ -54,6 +73,24 @@ fn php_file_docblock<'a>(comment: &Node<'a>, code: &[u8], ancestors: Ancestors<' true } +fn php_doc_in_signature<'a>(comment: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { + ancestors.parent(comment).is_some_and(|parent| { + let kind = parent.kind_id(); + // role-bypass: allow(DocTarget) — signature placement excludes define expression statements. + let declaration = + crate::roles::php::doc_target::lists_kind(kind) && kind != Php::ExpressionStatement; + // role-bypass: allow(Closure) — signature holders beyond declaration owners. + let signature_holder = matches!( + kind.into(), + Php::AnonymousFunction + | Php::ArrowFunction + | Php::FormalParameters + | Php::PropertyPromotionParameter + ); + declaration || signature_holder + }) +} + impl Checker for PhpCode { // The `Comment` and `DocComment` rows of `roles/php.rs` (#1699): // the one comment kind, a DocBlock under PHP's marker. @@ -62,6 +99,20 @@ impl Checker for PhpCode { const SOURCE_LOCAL_DOCS: bool = true; + fn source_doc_binds_forward<'a>( + node: &Node<'a>, + context: &crate::documentation::SourceContext<'a>, + ancestors: Ancestors<'a, '_>, + ) -> bool { + !php_doc_in_signature(node, ancestors) + && !php_file_docblock( + node, + context.bytes(), + ancestors, + CandidateView::Source(context), + ) + } + // phpDocumentor gives an element PHP-Parser's `getDocComment`: the // last DocBlock among the comments before the node's first token, so // plain comments in between are read past and only the last of several @@ -74,34 +125,8 @@ impl Checker for PhpCode { // each is a declaration here like a method. const DOC_BINDING: Option = Some(DocBinding { forward: |comment, code, ancestors| { - let in_signature = ancestors.parent(comment).is_some_and(|parent| { - let kind = parent.kind_id(); - // The declarations are the `DocTarget` row's kind table, - // less the `define()` statement: a DocBlock among an - // expression statement's children sits after its - // expression, where PHP-Parser gives it to the token - // after it, as `/** d */ $x = 1;` does (#1646). Beside - // the declarations the closures, a parameter list and a - // promoted parameter, which hold a DocBlock in a - // signature without being targets themselves. - // role-bypass: allow(DocTarget) — the row's declaration owners, which hold - // their DocBlock as a child after `#[…]` attributes; the statement owner - // holds no declaration children, so it is left out of the signature set - let declaration = crate::roles::php::doc_target::lists_kind(kind) - && kind != Php::ExpressionStatement; - // role-bypass: allow(Closure) — a DocBlock *inside* a closure is in - // its signature; where a declaration's children end is a binding - // question, not membership - let signature_holder = matches!( - kind.into(), - Php::AnonymousFunction - | Php::ArrowFunction - | Php::FormalParameters - | Php::PropertyPromotionParameter - ); - declaration || signature_holder - }); - !in_signature && !php_file_docblock(comment, code, ancestors) + !php_doc_in_signature(comment, ancestors) + && !php_file_docblock(comment, code, ancestors, CandidateView::Legacy) }, ..DocBinding::new(KeptDocs::Leading { hidden: |node, code| !Self::is_doc_comment(node, code), diff --git a/big-code-analysis-ast/src/checker/rust.rs b/big-code-analysis-ast/src/checker/rust.rs index 4e52e64d1..276eb06d3 100644 --- a/big-code-analysis-ast/src/checker/rust.rs +++ b/big-code-analysis-ast/src/checker/rust.rs @@ -72,6 +72,10 @@ impl Checker for RustCode { ) -> Option { rust_doc_in_macro(node, ancestors) .then_some(crate::documentation::UnresolvedReason::Expansion) + .or_else(|| { + node.is_error() + .then_some(crate::documentation::UnresolvedReason::GrammarBoundary) + }) } // rustc lints a doc comment on a statement or expression as unused and diff --git a/big-code-analysis-ast/src/documentation/owners.rs b/big-code-analysis-ast/src/documentation/owners.rs index dac119be2..adba85d2e 100644 --- a/big-code-analysis-ast/src/documentation/owners.rs +++ b/big-code-analysis-ast/src/documentation/owners.rs @@ -104,6 +104,8 @@ pub enum UnresolvedReason { Expansion, /// Recovery or known grammar boundaries are insufficient. GrammarBoundary, + /// Excluded source bytes prevent recognizing a continuous spelling or attachment. + ExcludedGap, } /// Known publication eligibility under a convention, separate from attachment. diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index df9455995..e68955aee 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -57,6 +57,7 @@ pub struct SourceContext<'s> { tree: &'s tree_sitter::Tree, bytes: &'s [u8], included: Vec, + continuous: Vec>, } impl<'s> SourceContext<'s> { @@ -72,10 +73,21 @@ impl<'s> SourceContext<'s> { pub fn new(tree: &'s tree_sitter::Tree, bytes: &'s [u8]) -> Self { let mut included = tree.included_ranges(); included.retain(|range| range.start_byte < range.end_byte); + let mut continuous: Vec> = Vec::new(); + for range in &included { + if let Some(last) = continuous.last_mut() + && last.end == range.start_byte + { + last.end = range.end_byte; + } else { + continuous.push(range.start_byte..range.end_byte); + } + } Self { tree, bytes, included, + continuous, } } @@ -118,6 +130,23 @@ impl<'s> SourceContext<'s> { }) } + /// Whether the whole interval is available, without joining across a gap. + pub(crate) fn covers(&self, span: Range) -> bool { + if span.start > span.end || span.end > self.bytes.len() { + return false; + } + if span.is_empty() { + return true; + } + let first = self + .continuous + .partition_point(|range| range.end <= span.start); + included_range_visits::record(); + self.continuous + .get(first) + .is_some_and(|range| range.start <= span.start && range.end >= span.end) + } + /// Record a node reached canonically by a collector cursor. The caller /// supplies canonical traversal context; foreign trees are rejected here. /// Later validation compares against this retained value without parent walks. @@ -132,6 +161,39 @@ impl<'s> SourceContext<'s> { } } +#[cfg(all(test, feature = "rust"))] +mod coverage_tests { + use super::*; + + #[test] + fn coverage_seeks_to_late_ranges_and_stops_at_the_first_gap() { + let source = b"a ".repeat(256); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&crate::LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + let ranges: Vec<_> = (0..256) + .map(|i| tree_sitter::Range { + start_byte: i * 2, + end_byte: i * 2 + 1, + start_point: tree_sitter::Point::new(0, i * 2), + end_point: tree_sitter::Point::new(0, i * 2 + 1), + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(&source, None).unwrap(); + let context = SourceContext::new(&tree, &source); + let before = included_range_visits::observed(); + assert!(context.covers(510..511)); + // expected: the last range only; earlier ranges are binary-searched past. + assert_eq!(included_range_visits::observed() - before, 1); + let before = included_range_visits::observed(); + assert!(!context.covers(0..511)); + // expected: the first continuous interval cannot contain the whole request. + assert_eq!(included_range_visits::observed() - before, 1); + } +} + /// A safe borrowed canonical value; raw pointers are only compared transiently. /// This retains the tree-sitter node's `Send + Sync` guarantees. #[derive(Clone, Copy, Debug)] diff --git a/big-code-analysis-ast/src/documentation/streaming/markers.rs b/big-code-analysis-ast/src/documentation/streaming/markers.rs index 7a3bbb2f8..c706daf98 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers.rs @@ -10,22 +10,32 @@ use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces}; // Separate slots are necessary even on one visited node: Java's empty marker // answers differently before the same Last selector runs. #[derive(Clone, Copy)] -pub(crate) enum CandidateView { +pub(crate) enum CandidateView<'s> { Legacy, - Source, + Source(&'s SourceContext<'s>), } -impl CandidateView { +impl CandidateView<'_> { + pub(crate) fn covers(self, span: std::ops::Range) -> bool { + match self { + Self::Legacy => true, + Self::Source(context) => context.covers(span), + } + } + pub(crate) fn marker(self, node: &Node, code: &[u8], ancestors: Ancestors) -> bool { + if !self.covers(node.start_byte()..node.end_byte()) { + return false; + } let slot = match self { Self::Legacy => WordSlot::LegacyDocMarker, - Self::Source => WordSlot::SourceDocMarker, + Self::Source(_) => WordSlot::SourceDocMarker, }; ancestors.classified(slot, node, || { marker_reads::record(); u8::from(match self { Self::Legacy => T::is_doc_comment(node, code), - Self::Source => T::is_source_doc_comment(node, code), + Self::Source(_) => T::is_source_doc_comment(node, code), }) }) != 0 } @@ -38,7 +48,10 @@ impl CandidateView { ) -> bool { match self { Self::Legacy => T::is_doc_target(node, code, ancestors), - Self::Source => T::is_source_doc_target(node, code, ancestors), + Self::Source(_) => { + self.covers(node.start_byte()..node.end_byte()) + && T::is_source_doc_target(node, code, ancestors) + } } } } @@ -50,7 +63,7 @@ pub(crate) fn legacy_marker(node: &Node, code: &[u8], ancestors: Anc // The result cannot reveal extra marker reads or evidence built then discarded. crate::observation::counter!(marker_reads, cfg(any(test, feature = "test-support"))); crate::observation::counter!(evidence_built, cfg(any(test, feature = "test-support"))); -pub use doc_comment::stretches_collected; +pub use doc_comment::{gatherer_probes, stretches_collected}; /// Explicit source-only request for a language's native marker binding profile. /// The caller visits comments once in source order, with its walk's caches. @@ -68,7 +81,8 @@ pub struct SourceRequest<'r, 's> { /// evidence; a target is a binding candidate, never a resolved semantic owner. #[derive(Debug)] pub struct MarkerRun<'s> { - /// Recognized occurrences in source order, without repeated gatherers. + /// Source occurrences in order, including explicitly unknown gap-spanning + /// comments when requested, without repeated gatherers. pub members: Vec>, /// Following target wrapper, possibly a conditional or recovery node. pub target: Option>, @@ -80,7 +94,7 @@ pub struct MarkerRun<'s> { pub code_before: Option>, } -/// One physical source marker and its selection result. +/// One physical source marker or uncertain comment and its selection result. #[derive(Debug)] pub struct MarkerMember<'s> { /// Exact syntax node, including any grammar-owned newline. @@ -110,6 +124,8 @@ struct RunSelection<'t> { kept: Vec>, target: Option>, gatherer: Option>, + bound: Option>, + gap: bool, } impl<'t> RunSelection<'t> { @@ -118,39 +134,47 @@ impl<'t> RunSelection<'t> { code_before: Option>, end: StretchEnd<'t>, binding: DocBinding, - input: (&[u8], Ancestors<'t, '_>), + context: &SourceContext<'t>, + ancestors: Ancestors<'t, '_>, ) -> Self { - let (code, ancestors) = input; - let marker = |n: &Node<'t>| CandidateView::Source.marker::(n, code, ancestors); - let forward = |n: &Node<'t>| marker(n) && (binding.forward)(n, code, ancestors); + // bca: suppress(nargs) -- the stretch, boundaries, policy and borrowed traversal inputs are independent selector inputs. + let code = context.bytes(); + let marker = |n: &Node<'t>| CandidateView::Source(context).marker::(n, code, ancestors); + let forward = + |n: &Node<'t>| marker(n) && T::source_doc_binds_forward(n, context, ancestors); if let StretchEnd::AtTarget { next, target } = end { + let mut bound = doc_comment::select_bound::( + stretch, + code, + binding.kept, + doc_comment::StretchBounds { + code_before, + next, + target, + }, + forward, + ); return Self { - kept: doc_comment::select_bound::( - stretch, - code, - binding.kept, - (code_before, next, target), - forward, - ), + kept: std::mem::take(&mut bound.nodes), target: Some(target), gatherer: None, + bound: Some(bound), + gap: false, }; } - let result = binding.gathers.map(|gathers| { - let gatherer = stretch - .iter() - .rfind(|n| marker(n) && gathers(n, code)) - .copied(); - ( - doc_comment::bind_gathered(stretch, code, gathers, marker, forward), - gatherer, - ) + let result = binding + .gathers + .map(|gathers| doc_comment::bind_gathered(stretch, code, gathers, marker, forward)); + let doc_comment::Gathered { kept, gatherer } = result.unwrap_or(doc_comment::Gathered { + kept: Vec::new(), + gatherer: None, }); - let (kept, gatherer) = result.unwrap_or_default(); Self { kept, target: None, gatherer, + bound: None, + gap: matches!(end, StretchEnd::ExcludedGap), } } @@ -161,22 +185,40 @@ impl<'t> RunSelection<'t> { ancestors: Ancestors<'t, '_>, request: &SourceRequest<'_, 't>, ) -> Result>, SourceError> { - // bca: suppress(halstead) -- one ordered merge pairs selected nodes with retained source evidence. + // bca: suppress(halstead, cognitive, cyclomatic, abc) -- one ordered merge preserves selection, uncertain tokens and lazy evidence without rescanning the stretch. let code = request.context.bytes(); let mut selected = self.kept.iter().peekable(); let mut members = Vec::new(); - for node in stretch - .iter() - .filter(|n| CandidateView::Source.marker::(n, code, ancestors)) - { + for (index, node) in stretch.iter().enumerate() { + if !request.context.covers(node.start_byte()..node.end_byte()) { + if request.retain_unbound && T::is_comment(node) { + let mut evidence = member( + request.context, + node, + MarkerSelection::Unattached, + MarkerPlacement::Unknown, + )?; + evidence.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); + members.push(evidence); + } + continue; + } + if !CandidateView::Source(request.context).marker::(node, code, ancestors) { + continue; + } let kept = selected.peek().is_some_and(|n| n.id() == node.id()); if kept { selected.next(); } - let forward = (binding.forward)(node, code, ancestors); + let forward = T::source_doc_binds_forward(node, request.context, ancestors); let selection = if kept || !forward { MarkerSelection::Selected - } else if self.target.is_some() && !self.kept.is_empty() { + } else if self + .bound + .as_ref() + .is_some_and(|bound| bound.eligible(index, stretch, code)) + && !self.kept.is_empty() + { MarkerSelection::Superseded } else { MarkerSelection::Unattached @@ -196,6 +238,9 @@ impl<'t> RunSelection<'t> { }; let mut member = member(request.context, node, selection, placement)?; member.uncertainty = T::source_doc_uncertainty(node, code, ancestors); + if self.gap && forward && !kept { + member.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); + } members.push(member); } Ok(members) @@ -206,6 +251,8 @@ impl<'t> RunSelection<'t> { /// tokens and conditional targets retain uncertainty until an adapter resolves it. #[derive(Clone, Copy, Debug)] pub enum MarkerPlacement<'s> { + /// A gap-spanning comment whose native marker and direction are unknown. + Unknown, /// Candidate for the following target wrapper. Forward, /// Inner, trailing, signature, structural or expansion-local documentation. @@ -218,8 +265,8 @@ pub enum MarkerPlacement<'s> { } /// Recognize native source markers at a comment visit. Uses the same stretch -/// boundaries and selection algorithms as legacy binding, with separate -/// pre-selection predicates. A deferred member never collects its prefix. +/// selection algorithms as legacy binding, with separate pre-selection predicates +/// and source-only gap barriers. A deferred member never collects its prefix. /// /// # Errors /// Propagates source identity/range failures; no successful partial run is emitted. @@ -233,12 +280,13 @@ pub fn source_comment<'s, T: Checker>( return Ok(()); }; let code = request.context.bytes(); - let view = CandidateView::Source; + request.context.node(comment.as_tree_sitter())?; + let view = CandidateView::Source(request.context); let end = doc_comment::stretch_end::(comment, code, ancestors, binding.skips, view); if matches!(end, StretchEnd::Undecided) { return Ok(()); } - if matches!(end, StretchEnd::Elsewhere) + if matches!(end, StretchEnd::Elsewhere | StretchEnd::ExcludedGap) && !request.retain_unbound && !T::SOURCE_LOCAL_DOCS && binding.gathers.is_none() @@ -247,8 +295,14 @@ pub fn source_comment<'s, T: Checker>( } let (stretch, code_before) = doc_comment::collect_stretch::(comment, code, ancestors, binding.skips, view); - let selection = - RunSelection::select::(&stretch, code_before, end, binding, (code, ancestors)); + let selection = RunSelection::select::( + &stretch, + code_before, + end, + binding, + request.context, + ancestors, + ); let members = selection.members::(&stretch, binding, ancestors, request)?; if !members.is_empty() { let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); @@ -273,12 +327,12 @@ fn member<'s>( ) -> Result, SourceError> { evidence_built::record(); let bytes = doc_comment::node_bytes(node, context.bytes()); - let end = if bytes.starts_with(b"//") { - let line = bytes.strip_suffix(b"\n").unwrap_or(bytes); - node.start_byte() + line.strip_suffix(b"\r").unwrap_or(line).len() - } else { - node.end_byte() - }; + let end = + if bytes.starts_with(b"//") && context.covers(node.start_byte()..node.start_byte() + 2) { + line_spelling_end(context, node) + } else { + node.end_byte() + }; Ok(MarkerMember { node: context.node(node.as_tree_sitter())?, source: context.pieces(node.start_byte()..end)?, @@ -288,5 +342,31 @@ fn member<'s>( }) } +fn line_spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { + let code = context.bytes(); + let end = node.end_byte(); + let lf = if code.get(end - 1) == Some(&b'\n') { + end - 1 + } else { + end + }; + if code.get(lf) == Some(&b'\n') && context.covers(lf..lf + 1) { + if code.get(lf - 1) == Some(&b'\r') && context.covers(lf - 1..lf + 1) { + return lf - 1; + } + return lf; + } + // Some grammars exclude CR from the node even when no included LF follows it. + if code.get(end) == Some(&b'\r') + && context.covers(end..end + 1) + && !(code.get(end + 1) == Some(&b'\n') && context.covers(end + 1..end + 2)) + { + return end + 1; + } + end +} + +#[cfg(test)] +mod regressions; #[cfg(test)] mod tests; diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs new file mode 100644 index 000000000..8caf28386 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs @@ -0,0 +1,455 @@ +#![allow(clippy::single_range_in_vec_init)] + +use super::*; +use crate::documentation::SourcePiece; +use crate::{AnyParser, LANG, Search, documentation::UnresolvedReason}; +use std::ops::Range; + +#[cfg(any( + feature = "java", + feature = "rust", + feature = "typescript", + feature = "groovy", + feature = "c", + feature = "cpp", + feature = "mozcpp", + feature = "objc", + feature = "csharp", + feature = "php" +))] +fn runs(parser: &AnyParser, retain_unbound: bool) -> Vec> { + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + } + }); + runs +} + +#[cfg(any( + feature = "java", + feature = "rust", + feature = "csharp", + feature = "php" +))] +#[allow(clippy::naive_bytecount)] +fn restricted(lang: LANG, source: &[u8], included: &[Range]) -> AnyParser { + let point = |at| { + let prefix = &source[..at]; + tree_sitter::Point::new( + prefix.iter().filter(|&&b| b == b'\n').count(), + prefix + .iter() + .rposition(|&b| b == b'\n') + .map_or(at, |pos| at - pos - 1), + ) + }; + let ranges: Vec<_> = included + .iter() + .map(|r| tree_sitter::Range { + start_byte: r.start, + end_byte: r.end, + start_point: point(r.start), + end_point: point(r.end), + }) + .collect(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&lang.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + assert!( + !tree.root_node().has_error(), + "{}", + tree.root_node().to_sexp() + ); + AnyParser::from_tree(lang, tree, source.to_vec()).unwrap() +} + +#[cfg(feature = "java")] +#[test] +fn excluded_marker_cannot_supersede_genuine_documentation() { + let source = b"/**old*/\n///fake\nclass C {}"; + let parser = restricted(LANG::Java, source, &[0..11, 12..source.len()]); + assert!(runs::(&parser, false).is_empty()); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 2); + let members: Vec<_> = runs.iter().flat_map(|r| &r.members).collect(); + assert_eq!(members.len(), 2); + assert!(runs.iter().all(|r| r.target.is_none())); + assert_eq!(members[0].node.node().byte_range(), 0..8); + assert_eq!(members[0].source.pieces()[0].bytes(), b"/**old*/"); + assert_eq!( + members[1] + .source + .pieces() + .iter() + .map(SourcePiece::range) + .collect::>(), + [9..11, 12..16] + ); + assert!(matches!(members[1].placement, MarkerPlacement::Unknown)); + for member in members { + assert_eq!(member.selection, MarkerSelection::Unattached); + assert_eq!(member.uncertainty, Some(UnresolvedReason::ExcludedGap)); + } + let mut bound = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if crate::JavaCode::is_comment(node) { + super::super::marker_comment::(node, source, ancestors, |event| { + if let super::super::LegacyEvent::BoundComment(n) = event { + bound.push(n.as_tree_sitter().byte_range()); + } + }); + } + }); + assert_eq!(bound, [9..16]); +} + +#[cfg(feature = "java")] +#[test] +fn excluded_marker_byte_never_becomes_a_native_marker() { + let source = b"///doc\nclass C {}"; + let parser = restricted(LANG::Java, source, &[0..2, 3..source.len()]); + assert!(runs::(&parser, false).is_empty()); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 1); + let member = &runs[0].members[0]; + assert_eq!(member.selection, MarkerSelection::Unattached); + assert!(matches!(member.placement, MarkerPlacement::Unknown)); + assert_eq!(member.uncertainty, Some(UnresolvedReason::ExcludedGap)); + assert_eq!( + member + .source + .pieces() + .iter() + .map(SourcePiece::range) + .collect::>(), + [0..2, 3..6] + ); + assert!(member.source.has_excluded_gap()); +} + +#[cfg(feature = "java")] +#[test] +fn excluded_attachment_and_target_bytes_are_barriers() { + for (source, included) in [ + (b"/**doc*/\nXX\nclass C {}".as_slice(), vec![0..9, 12..22]), + (b"/**doc*/\nclass C {}".as_slice(), vec![0..16, 17..19]), + ] { + let parser = restricted(LANG::Java, source, &included); + assert!(runs::(&parser, false).is_empty()); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + assert!(runs[0].target.is_none()); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Unattached); + assert_eq!( + runs[0].members[0].uncertainty, + Some(UnresolvedReason::ExcludedGap) + ); + assert_eq!(runs[0].members[0].source.pieces()[0].range(), 0..8); + assert!(!runs[0].members[0].source.has_excluded_gap()); + } +} + +#[cfg(feature = "java")] +#[test] +fn excluded_code_keeps_unrelated_later_docs_and_splits_comment_runs() { + let source = b"/**old*/\nclass X {}\n/**new*/\nclass C {}"; + let later = source.windows(8).position(|b| b == b"/**new*/").unwrap(); + let parser = restricted(LANG::Java, source, &[0..9, later..source.len()]); + for retain in [false, true] { + let runs = runs::(&parser, retain); + assert_eq!(runs.len(), if retain { 2 } else { 1 }); + let last = runs.last().unwrap(); + assert_eq!(last.members.len(), 1); + assert_eq!(last.members[0].source.pieces()[0].bytes(), b"/**new*/"); + assert_eq!(last.members[0].selection, MarkerSelection::Selected); + assert_eq!(last.members[0].uncertainty, None); + assert_eq!( + last.target.unwrap().node().byte_range(), + later + 9..source.len() + ); + if retain { + assert_eq!(runs[0].members[0].selection, MarkerSelection::Unattached); + assert_eq!( + runs[0].members[0].uncertainty, + Some(UnresolvedReason::ExcludedGap) + ); + } + } +} + +#[cfg(feature = "php")] +#[test] +fn php_file_scan_cannot_read_a_gap_spanning_marker() { + let source = b"(&parser, retain); + let members: Vec<_> = runs.iter().flat_map(|r| &r.members).collect(); + assert_eq!( + members.len(), + if retain { 3 } else { 1 }, + "{} {runs:?}", + parser.ts_tree().root_node().to_sexp() + ); + let last = members.last().unwrap(); + assert_eq!(last.source.pieces()[0].bytes(), b"/** later */"); + assert_eq!(last.selection, MarkerSelection::Selected); + assert!(matches!(last.placement, MarkerPlacement::Forward)); + if retain { + assert_eq!(members[0].selection, MarkerSelection::Unattached); + assert_eq!(members[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); + assert!(matches!(members[1].placement, MarkerPlacement::Unknown)); + } + } +} + +#[cfg(feature = "java")] +#[test] +fn many_included_ranges_do_not_rescan_comment_prefixes() { + for width in [4, 64, 256] { + let source = "/**doc*/X\n".repeat(width); + let included: Vec<_> = (0..width).map(|n| n * 10..n * 10 + 8).collect(); + let parser = restricted(LANG::Java, source.as_bytes(), &included); + let before = stretches_collected::observed(); + let built = evidence_built::observed(); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), width); + // expected: each gap-delimited comment is its own final member. + assert_eq!(stretches_collected::observed() - before, width); + assert_eq!(evidence_built::observed() - built, width); + assert!( + runs.iter() + .all(|r| r.members.len() == 1 && r.target.is_none()) + ); + } +} + +#[cfg(feature = "java")] +#[test] +fn foreign_source_context_fails_without_partial_emission() { + let source = b"/**a*/\n/**b*/\nclass C {}"; + let parser = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + let other = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(other.ts_tree(), source); + let mut visits = 0; + let mut emitted = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if crate::JavaCode::is_comment(node) { + visits += 1; + assert_eq!( + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |_| emitted += 1, + } + ), + Err(SourceError::ForeignTree) + ); + } + }); + assert_eq!(visits, 2); + assert_eq!(emitted, 0); +} + +#[cfg(feature = "typescript")] +fn mixed_rejections() { + for (source, expected) in [ + ( + "const x = 1; /**a*/\n/**b*/\nfunction f() {}", + [MarkerSelection::Unattached, MarkerSelection::Selected], + ), + ( + "class C {\n/**a*/\n@dec\n/**b*/\nm() {}\n}", + [MarkerSelection::Selected, MarkerSelection::Unattached], + ), + ] { + let parser = AnyParser::parse(T::lang(), source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error()); + for retain in [false, true] { + let runs = runs::(&parser, retain); + let members: Vec<_> = runs.iter().flat_map(|r| &r.members).collect(); + assert_eq!( + members.iter().map(|m| m.selection).collect::>(), + expected + .into_iter() + .filter(|s| retain || *s == MarkerSelection::Selected) + .collect::>(), + "{source}" + ); + } + } +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_mixed_rejections_are_not_superseded() { + mixed_rejections::(); +} + +#[cfg(feature = "typescript")] +#[test] +fn tsx_mixed_rejections_are_not_superseded() { + mixed_rejections::(); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_hidden_doc_is_unattached_beside_selected_doc() { + let parser = AnyParser::parse( + LANG::Groovy, + b"/**a*/\n/**b*/ class C {}".to_vec(), + None, + None, + ) + .unwrap(); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + assert_eq!( + runs[0] + .members + .iter() + .map(|m| m.selection) + .collect::>(), + [MarkerSelection::Selected, MarkerSelection::Unattached] + ); +} + +#[cfg(any(feature = "rust", feature = "java", feature = "csharp"))] +fn terminators() { + for (source, bytes) in [ + (b"///audit\n".as_slice(), b"///audit".as_slice()), + (b"///audit\r\n", b"///audit"), + (b"///audit\r", b"///audit\r"), + ] { + let parser = AnyParser::parse(T::lang(), source.to_vec(), None, None).unwrap(); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].source.pieces().len(), 1); + assert_eq!(runs[0].members[0].source.pieces()[0].bytes(), bytes); + } + let source = b"///audit\r\n"; + for included in [vec![0..9], vec![0..9, 9..10], vec![0..8, 9..10]] { + let parser = restricted(T::lang(), source, &included); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + let member = &runs[0].members[0]; + let bytes: Vec<_> = member + .source + .pieces() + .iter() + .flat_map(SourcePiece::bytes) + .copied() + .collect(); + assert_eq!( + bytes, + if included == [0..9] { + b"///audit\r".as_slice() + } else { + b"///audit" + } + ); + } +} + +#[cfg(feature = "rust")] +#[test] +fn rust_verbatim_line_terminators() { + terminators::(); +} +#[cfg(feature = "java")] +#[test] +fn java_verbatim_line_terminators() { + terminators::(); +} +#[cfg(feature = "csharp")] +#[test] +fn csharp_verbatim_line_terminators() { + terminators::(); +} + +#[cfg(any(feature = "rust", feature = "java"))] +fn recovery(source: &[u8]) { + let parser = AnyParser::parse(T::lang(), source.to_vec(), None, None).unwrap(); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1, "{}", parser.ts_tree().root_node().to_sexp()); + assert!(runs[0].target.unwrap().node().is_error()); + assert_eq!( + runs[0].target_uncertainty, + Some(UnresolvedReason::GrammarBoundary) + ); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Selected); +} + +#[cfg(feature = "rust")] +#[test] +fn rust_recovery_target_retains_grammar_uncertainty() { + recovery::(b"///audit\n{ fn f() {}"); + recovery::(b"/// d\n1 fn f() {} 2\n"); +} + +#[cfg(feature = "java")] +#[test] +fn java_recovery_target_retains_default_uncertainty() { + recovery::(b"/**doc*/\nclass {\npackage a;\n@ "); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn gatherer_search() { + for width in [4, 64, 256] { + let source = format!("/**lead*/\n/**@file*/\n{}", "/**dangling*/\n".repeat(width)); + let parser = AnyParser::parse(T::lang(), source.as_bytes().to_vec(), None, None).unwrap(); + let before = doc_comment::gatherer_probes::observed(); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), width + 2); + assert!(matches!( + runs[0].members[0].placement, + MarkerPlacement::Gathered(_) + )); + // expected: the dangling suffix plus its one gatherer, searched once. + assert_eq!(doc_comment::gatherer_probes::observed() - before, width + 1); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_gatherer_search_is_once_per_stretch() { + gatherer_search::(); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_gatherer_search_is_once_per_stretch() { + gatherer_search::(); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_gatherer_search_is_once_per_stretch() { + gatherer_search::(); +} +#[cfg(feature = "objc")] +#[test] +fn objc_gatherer_search_is_once_per_stretch() { + gatherer_search::(); +} diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs index e07fa18aa..758741bfe 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs @@ -82,6 +82,7 @@ fn divergent_marker_queries_share_real_cache_in_both_orders() { for source_first in [false, true] { let source = b"/**/\nclass C {}"; let parser = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), parser.code()); let root = parser.root_node(); let comment = root.children().next().unwrap(); let cache = FoldCache::default(); @@ -89,15 +90,15 @@ fn divergent_marker_queries_share_real_cache_in_both_orders() { let chain = [root]; let ancestors = Ancestors::for_walk(&chain, &comment, &cache, &siblings); let order = if source_first { - [CandidateView::Source, CandidateView::Legacy] + [CandidateView::Source(&context), CandidateView::Legacy] } else { - [CandidateView::Legacy, CandidateView::Source] + [CandidateView::Legacy, CandidateView::Source(&context)] }; let before = marker_reads::observed(); for view in order.into_iter().cycle().take(6) { assert_eq!( view.marker::(&comment, source, ancestors), - matches!(view, CandidateView::Source) + matches!(view, CandidateView::Source(_)) ); } // expected: each distinct view computes once for this visited node. @@ -112,7 +113,7 @@ fn divergent_marker_queries_share_real_cache_in_both_orders() { let mut events = Vec::new(); for view in order { match view { - CandidateView::Source => source_comment::( + CandidateView::Source(_) => source_comment::( &comment, ancestors, &mut SourceRequest { diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index eba2dcd34..1c81b1971 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -313,6 +313,7 @@ pub fn bound_doc_run<'a, T: Checker>( |n| view.marker::(n, code, ancestors), forward, ) + .kept .iter() .for_each(&mut credit); } @@ -322,23 +323,72 @@ pub fn bound_doc_run<'a, T: Checker>( &stretch, code, binding.kept, - (code_before, next, target), + StretchBounds { + code_before, + next, + target, + }, forward, ); - kept.iter().for_each(&mut credit); + kept.nodes.iter().for_each(&mut credit); +} + +#[derive(Clone, Copy)] +pub(crate) struct StretchBounds<'a> { + pub(crate) code_before: Option>, + pub(crate) next: Node<'a>, + pub(crate) target: Node<'a>, +} + +pub(crate) struct BoundSelection<'a> { + pub(crate) nodes: Vec>, + eligible_end: usize, + after_code_row: Option, + policy: KeptDocs, + next: Node<'a>, +} + +impl BoundSelection<'_> { + pub(crate) fn eligible(&self, index: usize, stretch: &[Node], code: &[u8]) -> bool { + let node = &stretch[index]; + index < self.eligible_end + && Some(node.start_row()) != self.after_code_row + && match self.policy { + KeptDocs::Nearest { hidden } => { + !hidden(node, stretch.get(index + 1).unwrap_or(&self.next)) + } + KeptDocs::Leading { hidden, .. } => !hidden(node, code), + _ => true, + } + } } pub(crate) fn select_bound<'a, T: Checker>( stretch: &[Node<'a>], code: &[u8], kept: KeptDocs, - boundaries: (Option>, Node<'a>, Node<'a>), + boundaries: StretchBounds<'a>, forward: impl Fn(&Node<'a>) -> bool, -) -> Vec> { - let (code_before, next, target) = boundaries; - match kept { +) -> BoundSelection<'a> { + let StretchBounds { + code_before, + next, + target, + } = boundaries; + let mut selection = BoundSelection { + nodes: Vec::new(), + eligible_end: stretch.len(), + after_code_row: None, + policy: kept, + next, + }; + selection.nodes = match kept { KeptDocs::All => stretch.iter().copied().filter(forward).collect(), - KeptDocs::Last { joins } => bind_last::(stretch, code, joins, forward), + KeptDocs::Last { joins } => { + let (nodes, eligible_end) = bind_last::(stretch, code, joins, forward); + selection.eligible_end = eligible_end; + nodes + } KeptDocs::Nearest { hidden } => bind_nearest::(stretch, next, hidden, forward) .into_iter() .collect(), @@ -350,13 +400,17 @@ pub(crate) fn select_bound<'a, T: Checker>( // A member on the row the code before the stretch ends on is // after that code, where a scan from the next line break does // not reach. - let after_code_row = code_before + selection.after_code_row = code_before .filter(|_| !after_code(&target)) .map(|before| before.end_row()); - let attaches = |n: &Node<'a>| forward(n) && Some(n.start_row()) != after_code_row; - bind_leading::(stretch, code, hidden, joins, attaches) + let attaches = + |n: &Node<'a>| forward(n) && Some(n.start_row()) != selection.after_code_row; + let (nodes, eligible_end) = bind_leading::(stretch, code, hidden, joins, attaches); + selection.eligible_end = eligible_end; + nodes } - } + }; + selection } /// Where a stretch of comments ends, asked of its last comment. @@ -371,6 +425,8 @@ pub(crate) enum StretchEnd<'a> { /// At a statement, a closing brace, the end of the file — anything /// that documents nothing. Elsewhere, + /// Excluded bytes interrupt the source stretch or target spelling. + ExcludedGap, } /// Where the stretch `comment` belongs to ends. The scan stops at the @@ -388,10 +444,23 @@ pub(crate) fn stretch_end<'a, T: Checker>( ) -> StretchEnd<'a> { let mut after = ancestors.siblings_after(comment).peekable(); let Some(&next) = after.peek() else { - return StretchEnd::Elsewhere; + return if view.covers(comment.start_byte()..comment.end_byte()) { + StretchEnd::Elsewhere + } else { + StretchEnd::ExcludedGap + }; }; - match after.find(|n| !skips(n, ancestors) && !read_past_error_in::(n, code, ancestors, view)) - { + let mut boundary = comment.start_byte(); + let mut continuous = true; + let target = after.find(|n| { + continuous = view.covers(boundary..n.end_byte()); + boundary = n.end_byte(); + !continuous || (!skips(n, ancestors) && !read_past_error_in::(n, code, ancestors, view)) + }); + if !continuous { + return StretchEnd::ExcludedGap; + } + match target { Some(target) if T::is_comment(&target) => StretchEnd::Undecided, Some(target) if view.target::(&target, code, ancestors) @@ -422,15 +491,21 @@ pub(crate) fn collect_stretch<'a, T: Checker>( stretches_collected::record(); let mut stretch = vec![*comment]; let mut before = None; + let mut boundary = comment.end_byte(); // An error read past is no member of the stretch: neither a comment // nor the first token a binder stops at. Left in, a binder that keeps // the last doc comment before the first token (tsc's, JSDoc's, // javac's) would read the error as that token and keep the comment // above it instead of the one the tool attaches. - for sibling in ancestors - .siblings_before(comment) - .filter(|sibling| !read_past_error_in::(sibling, code, ancestors, view)) - { + for sibling in ancestors.siblings_before(comment) { + if !view.covers(sibling.start_byte()..boundary) { + before = Some(sibling); + break; + } + boundary = sibling.start_byte(); + if read_past_error_in::(&sibling, code, ancestors, view) { + continue; + } if T::is_comment(&sibling) || skips(&sibling, ancestors) { stretch.push(sibling); } else { @@ -494,15 +569,28 @@ crate::observation::counter!( /// below it, which a line-comment tool reads as one block with it. The /// gathering comment does not bind forward, so `forward` drops it; it /// documents where it sits. +pub(crate) struct Gathered<'a> { + pub(crate) kept: Vec>, + pub(crate) gatherer: Option>, +} + +crate::observation::counter!(gatherer_probes, cfg(any(test, feature = "test-support"))); + pub(crate) fn bind_gathered<'a>( stretch: &[Node<'a>], code: &[u8], gathers: fn(&Node, &[u8]) -> bool, marker: impl Fn(&Node<'a>) -> bool, forward: impl Fn(&Node<'a>) -> bool, -) -> Vec> { - let Some(gatherer) = stretch.iter().rposition(|n| marker(n) && gathers(n, code)) else { - return Vec::new(); +) -> Gathered<'a> { + let Some(gatherer) = stretch.iter().rposition(|n| { + gatherer_probes::record(); + marker(n) && gathers(n, code) + }) else { + return Gathered { + kept: Vec::new(), + gatherer: None, + }; }; let line = |n: &Node| node_bytes(n, code).starts_with(b"//"); // Only a line-comment gatherer reads the line doc comments below it @@ -517,7 +605,10 @@ pub(crate) fn bind_gathered<'a>( { last += 1; } - stretch[..=last].iter().copied().filter(forward).collect() + Gathered { + kept: stretch[..=last].iter().copied().filter(forward).collect(), + gatherer: Some(stretch[gatherer]), + } } /// [`KeptDocs::Last`] over a stretch in source order: the last doc @@ -528,16 +619,19 @@ fn bind_last<'a, T: Checker>( code: &[u8], joins: fn(&Node, &Node, &[u8]) -> bool, forward: impl Fn(&Node<'a>) -> bool, -) -> Vec> { +) -> (Vec>, usize) { let split = stretch .iter() .position(|n| !T::is_comment(n)) .unwrap_or(stretch.len()); let (before, after) = stretch.split_at(split); let Some(last) = before.iter().rposition(&forward) else { - return after.iter().copied().find(forward).into_iter().collect(); + return ( + after.iter().copied().find(forward).into_iter().collect(), + stretch.len(), + ); }; - joined_run(before, last, code, joins, forward) + (joined_run(before, last, code, joins, forward), split) } /// [`KeptDocs::Leading`] over a stretch in source order: the members @@ -550,19 +644,19 @@ fn bind_leading<'a, T: Checker>( hidden: fn(&Node, &[u8]) -> bool, joins: fn(&Node, &Node, &[u8]) -> bool, forward: impl Fn(&Node<'a>) -> bool, -) -> Vec> { +) -> (Vec>, usize) { let first_token = stretch .iter() .position(|n| !T::is_comment(n) && !hidden(n, code)) .unwrap_or(stretch.len()); let before = &stretch[..first_token]; let Some(last) = before.iter().rposition(|n| !hidden(n, code)) else { - return Vec::new(); + return (Vec::new(), first_token); }; if !forward(&before[last]) { - return Vec::new(); + return (Vec::new(), first_token); } - joined_run(before, last, code, joins, forward) + (joined_run(before, last, code, joins, forward), first_token) } /// `before[last]` with the doc comments directly before it that it diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index 0c2a6f2e4..26edfd0fa 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -20,15 +20,15 @@ { "name": "source-marker-must-not-reuse-legacy-slot", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "Self::Source => WordSlot::SourceDocMarker,", - "new": "Self::Source => WordSlot::LegacyDocMarker,", + "old": "Self::Source(_) => WordSlot::SourceDocMarker,", + "new": "Self::Source(_) => WordSlot::LegacyDocMarker,", "expect": ["documentation::streaming::markers::tests::divergent_marker_queries_share_real_cache_in_both_orders"] }, { "name": "source-candidates-precede-last-selection", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "Self::Source => T::is_source_doc_comment(node, code),", - "new": "Self::Source => T::is_doc_comment(node, code),", + "old": "Self::Source(_) => T::is_source_doc_comment(node, code),", + "new": "Self::Source(_) => T::is_doc_comment(node, code),", "expect": ["documentation::streaming::markers::tests::java_source_selects_empty_new_block_before_legacy_selection"] }, { @@ -55,8 +55,8 @@ { "name": "legacy-bound-callbacks-remain-source-ordered", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "kept.iter().for_each(&mut credit);", - "new": "kept.iter().rev().for_each(&mut credit);", + "old": "kept.nodes.iter().for_each(&mut credit);", + "new": "kept.nodes.iter().rev().for_each(&mut credit);", "expect": ["documentation::streaming::markers::tests::rust_all_crosses_plain_comments_attributes_and_blank_rows"] }, { @@ -86,6 +86,62 @@ "old": "let (first, last) = rendered_rows(&node, marker);", "new": "let (first, last) = rendered_rows(&node, marker && by_placement);", "expect": ["metrics::loc::documentation_tests::documentation_legacy_whole_metrics"] + }, + { + "name": "source-included-byte-barriers-precede-selection", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "Self::Source(context) => context.covers(span),", + "new": "Self::Source(_context) => true,", + "expect": ["documentation::streaming::markers::regressions::excluded_marker_cannot_supersede_genuine_documentation", "documentation::streaming::markers::regressions::excluded_attachment_and_target_bytes_are_barriers", "documentation::streaming::markers::regressions::excluded_code_keeps_unrelated_later_docs_and_splits_comment_runs"] + }, + { + "name": "opaque-token-retains-unknown-evidence", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "if request.retain_unbound && T::is_comment(node) {", + "new": "if false && request.retain_unbound && T::is_comment(node) {", + "expect": ["documentation::streaming::markers::regressions::excluded_marker_byte_never_becomes_a_native_marker"] + }, + { + "name": "rejected-placement-is-not-supersession", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": ".is_some_and(|bound| bound.eligible(index, stretch, code))", + "new": ".is_some_and(|bound| true || bound.eligible(index, stretch, code))", + "expect": ["documentation::streaming::markers::regressions::typescript_mixed_rejections_are_not_superseded", "documentation::streaming::markers::regressions::tsx_mixed_rejections_are_not_superseded", "documentation::streaming::markers::regressions::groovy_hidden_doc_is_unattached_beside_selected_doc"] + }, + { + "name": "lone-cr-is-source-content", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "let lf = if code.get(end - 1) == Some(&b'\\n') {", + "new": "let lf = if code.get(end - 1) == Some(&b'\\r') { return end - 1; } else if code.get(end - 1) == Some(&b'\\n') {", + "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] + }, + { + "name": "excluded-lf-does-not-strip-included-cr", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "if code.get(lf) == Some(&b'\\n') && context.covers(lf..lf + 1) {", + "new": "if code.get(lf) == Some(&b'\\n') {", + "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] + }, + { + "name": "rust-recovery-keeps-default-uncertainty", + "file": "big-code-analysis-ast/src/checker/rust.rs", + "old": "node.is_error()\n .then_some(crate::documentation::UnresolvedReason::GrammarBoundary)", + "new": "None", + "expect": ["documentation::streaming::markers::regressions::rust_recovery_target_retains_grammar_uncertainty"] + }, + { + "name": "gatherer-search-must-not-repeat", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": ".map(|gathers| doc_comment::bind_gathered(stretch, code, gathers, marker, forward));", + "new": ".map(|gathers| { let _ = doc_comment::bind_gathered(stretch, code, gathers, marker, forward); doc_comment::bind_gathered(stretch, code, gathers, marker, forward) });", + "expect": ["documentation::streaming::markers::regressions::c_gatherer_search_is_once_per_stretch", "documentation::streaming::markers::regressions::cpp_gatherer_search_is_once_per_stretch", "documentation::streaming::markers::regressions::mozcpp_gatherer_search_is_once_per_stretch", "documentation::streaming::markers::regressions::objc_gatherer_search_is_once_per_stretch"] + }, + { + "name": "php-source-direction-keeps-range-context", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": "CandidateView::Source(context),", + "new": "CandidateView::Legacy,", + "expect": ["documentation::streaming::markers::regressions::php_file_scan_cannot_read_a_gap_spanning_marker"] } ] } From 07cded2bd775204e8d2561ab3abfb244951fea70 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:53:54 -0800 Subject: [PATCH 026/221] test(documentation): strengthen terminator mutation and sibling controls --- .../streaming/markers/regressions.rs | 50 ++++++++++++++++++- utils/documentation-markers-perturb.json | 4 +- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs index 8caf28386..8cf355f93 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs @@ -41,7 +41,11 @@ fn runs(parser: &AnyParser, retain_unbound: bool) -> Vec]) -> AnyParser { @@ -334,7 +338,15 @@ fn groovy_hidden_doc_is_unattached_beside_selected_doc() { ); } -#[cfg(any(feature = "rust", feature = "java", feature = "csharp"))] +#[cfg(any( + feature = "rust", + feature = "java", + feature = "csharp", + feature = "c", + feature = "cpp", + feature = "mozcpp", + feature = "objc" +))] fn terminators() { for (source, bytes) in [ (b"///audit\n".as_slice(), b"///audit".as_slice()), @@ -376,6 +388,19 @@ fn terminators() { #[test] fn rust_verbatim_line_terminators() { terminators::(); + for (source, expected) in [ + (b"//!audit\r".as_slice(), b"//!audit\r".as_slice()), + (b"//!audit\r\n", b"//!audit"), + (b"//!audit\n", b"//!audit"), + ] { + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let runs = runs::(&parser, false); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Selected); + assert_eq!(runs[0].members[0].source.pieces().len(), 1); + assert_eq!(runs[0].members[0].source.pieces()[0].bytes(), expected); + } } #[cfg(feature = "java")] #[test] @@ -388,6 +413,27 @@ fn csharp_verbatim_line_terminators() { terminators::(); } +#[cfg(feature = "c")] +#[test] +fn c_verbatim_line_terminators() { + terminators::(); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_verbatim_line_terminators() { + terminators::(); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_verbatim_line_terminators() { + terminators::(); +} +#[cfg(feature = "objc")] +#[test] +fn objc_verbatim_line_terminators() { + terminators::(); +} + #[cfg(any(feature = "rust", feature = "java"))] fn recovery(source: &[u8]) { let parser = AnyParser::parse(T::lang(), source.to_vec(), None, None).unwrap(); diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index 26edfd0fa..9b754945d 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -118,8 +118,8 @@ { "name": "excluded-lf-does-not-strip-included-cr", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "if code.get(lf) == Some(&b'\\n') && context.covers(lf..lf + 1) {", - "new": "if code.get(lf) == Some(&b'\\n') {", + "old": "if code.get(lf) == Some(&b'\\n') && context.covers(lf..lf + 1) {\n if code.get(lf - 1) == Some(&b'\\r') && context.covers(lf - 1..lf + 1) {", + "new": "if code.get(lf) == Some(&b'\\n') {\n if code.get(lf - 1) == Some(&b'\\r') {", "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] }, { From 0bb4ee700090202f49df2be2b3b315ae1af075c0 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 18:48:39 -0800 Subject: [PATCH 027/221] fix(documentation): preserve unknown prefix-gap binding decisions --- .bca-baseline.toml | 38 +++- big-code-analysis-ast/src/checker.rs | 11 +- big-code-analysis-ast/src/checker/php.rs | 59 +++--- .../src/documentation/streaming/markers.rs | 59 ++++-- .../streaming/markers/regressions.rs | 168 ++++++++++++++++++ .../src/lang_helpers/doc_comment.rs | 34 +++- utils/documentation-markers-perturb.json | 42 +++++ 7 files changed, 358 insertions(+), 53 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index f8523076d..e3e98f929 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -215,7 +215,7 @@ value = 5.0 path = "big-code-analysis-ast/src/checker.rs" qualified = "" metric = "loc.sloc" -value = 1330.0 +value = 1333.0 [[entry]] path = "big-code-analysis-ast/src/checker.rs" @@ -226,8 +226,32 @@ value = 29.0 [[entry]] path = "big-code-analysis-ast/src/checker/php.rs" qualified = "php_file_docblock" +metric = "cognitive" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock" +metric = "halstead.effort" +value = 85764.10672424761 + +[[entry]] +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::select" metric = "halstead.effort" -value = 72819.97333517869 +value = 55859.38834242588 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::select" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/getter.rs" @@ -269,7 +293,7 @@ value = 101217.532578918 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "" metric = "loc.ploc" -value = 531.0 +value = 554.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -287,7 +311,7 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "bound_doc_run" metric = "halstead.effort" -value = 56178.08004602712 +value = 57703.76052754793 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -295,6 +319,12 @@ qualified = "bound_doc_run" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_stretch" +metric = "halstead.effort" +value = 56431.32292303746 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "collect_stretch" diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 3a4ec34de..9243d2118 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -420,15 +420,18 @@ pub trait Checker { Self::DOC_BINDING } /// Source-only direction test. Overrides must respect included-range barriers - /// when inspecting comments beyond the current continuous spelling. + /// when inspecting comments beyond the current continuous spelling. `None` + /// means an excluded gap prevents deciding between forward and local binding. #[must_use] fn source_doc_binds_forward<'a>( node: &Node<'a>, context: &crate::documentation::SourceContext<'a>, ancestors: Ancestors<'a, '_>, - ) -> bool { - Self::source_doc_binding() - .is_some_and(|binding| (binding.forward)(node, context.bytes(), ancestors)) + ) -> Option { + Some( + Self::source_doc_binding() + .is_some_and(|binding| (binding.forward)(node, context.bytes(), ancestors)), + ) } /// Whether a marker can document locally without a following target. const SOURCE_LOCAL_DOCS: bool = false; diff --git a/big-code-analysis-ast/src/checker/php.rs b/big-code-analysis-ast/src/checker/php.rs index 9452c3681..2d2dc2ca2 100644 --- a/big-code-analysis-ast/src/checker/php.rs +++ b/big-code-analysis-ast/src/checker/php.rs @@ -22,13 +22,14 @@ fn php_file_preamble(node: &Node) -> bool { /// node is not a class, function, constant, interface or trait, the first /// DocBlock among them is the file's, and otherwise it is only when exactly /// two DocBlocks precede it. The backward test stops at the previous -/// DocBlock, so only the file's first one scans forward. +/// DocBlock, so only the file's first one scans forward. A source gap reached +/// by either scan leaves the file decision unknown; the legacy view has no gaps. fn php_file_docblock<'a>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, view: CandidateView, -) -> bool { +) -> Option { let marker = |n: &Node| match view { CandidateView::Legacy => PhpCode::is_doc_comment(n, code), CandidateView::Source(_) => view.marker::(n, code, ancestors), @@ -36,26 +37,33 @@ fn php_file_docblock<'a>( let preamble_or_plain = |n: Node| php_file_preamble(&n) || (PhpCode::is_comment(&n) && !marker(&n)); let mut boundary = comment.start_byte(); - if !ancestors.parent_has_kind(comment, Php::Program as u16) - || !ancestors.siblings_before(comment).all(|n| { - let continuous = view.covers(n.start_byte()..boundary); - boundary = n.start_byte(); - continuous && preamble_or_plain(n) - }) - { - return false; + if !ancestors.parent_has_kind(comment, Php::Program as u16) { + return Some(false); + } + for node in ancestors.siblings_before(comment) { + if !view.covers(node.start_byte()..boundary) { + return None; + } + boundary = node.start_byte(); + if !preamble_or_plain(node) { + return Some(false); + } + } + if !view.covers(0..boundary) { + return None; } let mut docs = 1_usize; let mut boundary = comment.end_byte(); for node in ancestors.siblings_after(comment) { if !view.covers(boundary..node.end_byte()) { - return false; + return None; } boundary = node.end_byte(); if marker(&node) { docs += 1; } else if !PhpCode::is_comment(&node) && !php_file_preamble(&node) { - return docs == 2 + return Some( + docs == 2 // role-bypass: allow(DocTarget, FuncOpener, Container, Member) — the subset // of targets `createFileDocBlock` treats as the file's first element: a // selection policy over the row, not membership @@ -67,15 +75,18 @@ fn php_file_docblock<'a>( | Php::ConstDeclaration2 | Php::InterfaceDeclaration | Php::TraitDeclaration - ); + ), + ); } } - true + view.covers(boundary..code.len()).then_some(true) } fn php_doc_in_signature<'a>(comment: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { ancestors.parent(comment).is_some_and(|parent| { let kind = parent.kind_id(); + // A DocBlock after an expression inside its statement belongs to the + // following token, rather than documenting that expression's signature. // role-bypass: allow(DocTarget) — signature placement excludes define expression statements. let declaration = crate::roles::php::doc_target::lists_kind(kind) && kind != Php::ExpressionStatement; @@ -103,14 +114,17 @@ impl Checker for PhpCode { node: &Node<'a>, context: &crate::documentation::SourceContext<'a>, ancestors: Ancestors<'a, '_>, - ) -> bool { - !php_doc_in_signature(node, ancestors) - && !php_file_docblock( - node, - context.bytes(), - ancestors, - CandidateView::Source(context), - ) + ) -> Option { + if php_doc_in_signature(node, ancestors) { + return Some(false); + } + php_file_docblock( + node, + context.bytes(), + ancestors, + CandidateView::Source(context), + ) + .map(|file| !file) } // phpDocumentor gives an element PHP-Parser's `getDocComment`: the @@ -127,6 +141,7 @@ impl Checker for PhpCode { forward: |comment, code, ancestors| { !php_doc_in_signature(comment, ancestors) && !php_file_docblock(comment, code, ancestors, CandidateView::Legacy) + .unwrap_or(false) }, ..DocBinding::new(KeptDocs::Leading { hidden: |node, code| !Self::is_doc_comment(node, code), diff --git a/big-code-analysis-ast/src/documentation/streaming/markers.rs b/big-code-analysis-ast/src/documentation/streaming/markers.rs index c706daf98..b77673bff 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers.rs @@ -100,6 +100,8 @@ pub struct MarkerMember<'s> { /// Exact syntax node, including any grammar-owned newline. pub node: NodeEvidence<'s>, /// Included spelling, excluding a line comment's LF/CRLF terminator. + /// May extend one byte beyond `node` to preserve an included lone CR that + /// the grammar left outside the comment node. pub source: SourcePieces<'s>, /// Selection within this profile, independent of legacy billing. pub selection: MarkerSelection, @@ -126,23 +128,35 @@ struct RunSelection<'t> { gatherer: Option>, bound: Option>, gap: bool, + prefix_gap_row: Option, } impl<'t> RunSelection<'t> { fn select( - stretch: &[Node<'t>], - code_before: Option>, + collected: &doc_comment::CollectedStretch<'t>, end: StretchEnd<'t>, binding: DocBinding, context: &SourceContext<'t>, ancestors: Ancestors<'t, '_>, ) -> Self { - // bca: suppress(nargs) -- the stretch, boundaries, policy and borrowed traversal inputs are independent selector inputs. + let stretch = &collected.members; + let code_before = collected.code_before; let code = context.bytes(); let marker = |n: &Node<'t>| CandidateView::Source(context).marker::(n, code, ancestors); - let forward = - |n: &Node<'t>| marker(n) && T::source_doc_binds_forward(n, context, ancestors); + let forward = |n: &Node<'t>| { + marker(n) && T::source_doc_binds_forward(n, context, ancestors) == Some(true) + }; if let StretchEnd::AtTarget { next, target } = end { + // Only a leading-trivia policy that rejects after-code comments + // needs the missing prefix; later rows already have a line break. + let prefix_gap_row = match binding.kept { + doc_comment::KeptDocs::Leading { after_code, .. } + if collected.prefix_gap && !after_code(&target) => + { + stretch.first().map(Node::start_row) + } + _ => None, + }; let mut bound = doc_comment::select_bound::( stretch, code, @@ -160,6 +174,7 @@ impl<'t> RunSelection<'t> { gatherer: None, bound: Some(bound), gap: false, + prefix_gap_row, }; } let result = binding @@ -175,6 +190,7 @@ impl<'t> RunSelection<'t> { gatherer, bound: None, gap: matches!(end, StretchEnd::ExcludedGap), + prefix_gap_row: None, } } @@ -210,7 +226,20 @@ impl<'t> RunSelection<'t> { if kept { selected.next(); } - let forward = T::source_doc_binds_forward(node, request.context, ancestors); + let Some(forward) = T::source_doc_binds_forward(node, request.context, ancestors) + else { + if request.retain_unbound { + let mut evidence = member( + request.context, + node, + MarkerSelection::Unattached, + MarkerPlacement::Unknown, + )?; + evidence.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); + members.push(evidence); + } + continue; + }; let selection = if kept || !forward { MarkerSelection::Selected } else if self @@ -238,7 +267,7 @@ impl<'t> RunSelection<'t> { }; let mut member = member(request.context, node, selection, placement)?; member.uncertainty = T::source_doc_uncertainty(node, code, ancestors); - if self.gap && forward && !kept { + if forward && ((self.gap && !kept) || self.prefix_gap_row == Some(node.start_row())) { member.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); } members.push(member); @@ -251,7 +280,7 @@ impl<'t> RunSelection<'t> { /// tokens and conditional targets retain uncertainty until an adapter resolves it. #[derive(Clone, Copy, Debug)] pub enum MarkerPlacement<'s> { - /// A gap-spanning comment whose native marker and direction are unknown. + /// Excluded source prevents recognizing the marker or deciding its direction. Unknown, /// Candidate for the following target wrapper. Forward, @@ -293,17 +322,11 @@ pub fn source_comment<'s, T: Checker>( { return Ok(()); } - let (stretch, code_before) = + let collected = doc_comment::collect_stretch::(comment, code, ancestors, binding.skips, view); - let selection = RunSelection::select::( - &stretch, - code_before, - end, - binding, - request.context, - ancestors, - ); - let members = selection.members::(&stretch, binding, ancestors, request)?; + let code_before = collected.code_before; + let selection = RunSelection::select::(&collected, end, binding, request.context, ancestors); + let members = selection.members::(&collected.members, binding, ancestors, request)?; if !members.is_empty() { let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); (request.sink)(MarkerRun { diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs index 8cf355f93..33bb34099 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs @@ -42,6 +42,7 @@ fn runs(parser: &AnyParser, retain_unbound: bool) -> Vec(); } + +#[cfg(all(test, feature = "typescript"))] +fn source_prefix_gap() { + for (source, included, expected_runs, span, target) in [ + ( + b"/**a*/ /**b*/\nfunction f() {}".as_slice(), + vec![0..6, 7..29], + 2, + 7..13, + 14..29, + ), + ( + b"XXXXXX /**b*/\nfunction f() {}".as_slice(), + vec![7..29], + 1, + 7..13, + 14..29, + ), + ] { + let parser = restricted(T::lang(), source, &included); + for retain in [false, true] { + let runs = runs::(&parser, retain); + assert_eq!(runs.len(), if retain { expected_runs } else { 1 }); + if retain && expected_runs == 2 { + assert!(runs[0].code_before.is_none()); + assert!(runs[0].target.is_none()); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].source.pieces()[0].range(), 0..6); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Unattached); + assert_eq!( + runs[0].members[0].uncertainty, + Some(UnresolvedReason::ExcludedGap) + ); + } + let run = runs.last().unwrap(); + assert!(run.code_before.is_none()); + assert_eq!(run.target.unwrap().node().byte_range(), target); + assert_eq!(run.members.len(), 1); + let member = &run.members[0]; + assert_eq!(member.node.node().byte_range(), span); + assert_eq!(member.source.pieces().len(), 1); + assert_eq!(member.source.pieces()[0].range(), span); + assert_eq!(member.source.pieces()[0].bytes(), b"/**b*/"); + assert_eq!(member.selection, MarkerSelection::Selected); + assert!(matches!(member.placement, MarkerPlacement::Forward)); + assert_eq!(member.uncertainty, Some(UnresolvedReason::ExcludedGap)); + } + } + let parser = AnyParser::parse( + T::lang(), + b"/**a*/ /**b*/\nfunction f() {}".to_vec(), + None, + None, + ) + .unwrap(); + let runs = runs::(&parser, false); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].node.node().byte_range(), 7..13); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Selected); + assert_eq!(runs[0].members[0].uncertainty, None); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_source_prefix_gap_is_not_preceding_code() { + source_prefix_gap::(); +} + +#[cfg(feature = "typescript")] +#[test] +fn tsx_source_prefix_gap_is_not_preceding_code() { + source_prefix_gap::(); +} + +#[cfg(feature = "php")] +#[test] +fn php_source_prefix_gap_keeps_unknown_direction_out_of_selection() { + for (source, included) in [ + ( + b"(&parser, retain); + assert_eq!(runs.len(), 1); + let run = &runs[0]; + assert_eq!( + run.code_before.map(|n| n.node().byte_range()), + if included == [3..37] { + Some(3..8) + } else { + None + } + ); + assert_eq!(run.target.unwrap().node().byte_range(), 27..37); + assert_eq!(run.members.len(), if retain { 2 } else { 1 }); + let b = run.members.last().unwrap(); + assert_eq!(b.source.pieces().len(), 1); + assert_eq!(b.source.pieces()[0].range(), 18..26); + assert_eq!(b.source.pieces()[0].bytes(), b"/** b */"); + assert_eq!(b.selection, MarkerSelection::Selected); + assert!(matches!(b.placement, MarkerPlacement::Forward)); + assert_eq!(b.uncertainty, None); + if retain { + let a = &run.members[0]; + assert_eq!(a.source.pieces().len(), 1); + assert_eq!(a.source.pieces()[0].range(), 9..17); + assert_eq!(a.source.pieces()[0].bytes(), b"/** a */"); + assert_eq!(a.selection, MarkerSelection::Unattached); + assert!(matches!(a.placement, MarkerPlacement::Unknown)); + assert_eq!(a.uncertainty, Some(UnresolvedReason::ExcludedGap)); + } + } + } + let parser = AnyParser::parse( + LANG::Php, + b"(&parser, false); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 2); + assert!(matches!( + runs[0].members[0].placement, + MarkerPlacement::Local + )); + assert!(matches!( + runs[0].members[1].placement, + MarkerPlacement::Forward + )); + assert!( + runs[0] + .members + .iter() + .all(|m| m.selection == MarkerSelection::Selected && m.uncertainty.is_none()) + ); +} + +#[cfg(feature = "php")] +#[test] +fn php_source_prefix_gap_cannot_select_unknown_define_documentation() { + let source = b"(&parser, false).is_empty()); + let runs = runs::(&parser, true); + assert_eq!(runs.len(), 1); + let run = &runs[0]; + assert!(run.code_before.is_none()); + assert_eq!(run.target.unwrap().node().byte_range(), 18..source.len()); + assert_eq!(run.members.len(), 1); + let member = &run.members[0]; + assert_eq!(member.source.pieces()[0].range(), 9..17); + assert_eq!(member.source.pieces().len(), 1); + assert_eq!(member.selection, MarkerSelection::Unattached); + assert!(matches!(member.placement, MarkerPlacement::Unknown)); + assert_eq!(member.uncertainty, Some(UnresolvedReason::ExcludedGap)); +} diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 1c81b1971..e7b699fc6 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -299,8 +299,11 @@ pub fn bound_doc_run<'a, T: Checker>( if !documents_where_it_sits::(comment, code, ancestors) { return; } - let (stretch, code_before) = - collect_stretch::(comment, code, ancestors, binding.skips, view); + let CollectedStretch { + members: stretch, + code_before, + .. + } = collect_stretch::(comment, code, ancestors, binding.skips, view); let forward = |n: &Node<'a>| { view.marker::(n, code, ancestors) && (binding.forward)(n, code, ancestors) }; @@ -481,16 +484,23 @@ pub(crate) fn stretch_end<'a, T: Checker>( /// `safe` of a `safe fn` is between the item's doc comments and its /// first token, not that token. An error the scan does not read past — /// one holding a target — ends the stretch and is the sibling before it. +pub(crate) struct CollectedStretch<'a> { + pub(crate) members: Vec>, + pub(crate) code_before: Option>, + pub(crate) prefix_gap: bool, +} + pub(crate) fn collect_stretch<'a, T: Checker>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, skips: for<'b> fn(&Node<'a>, Ancestors<'a, 'b>) -> bool, view: CandidateView, -) -> (Vec>, Option>) { +) -> CollectedStretch<'a> { stretches_collected::record(); let mut stretch = vec![*comment]; let mut before = None; + let mut prefix_gap = false; let mut boundary = comment.end_byte(); // An error read past is no member of the stretch: neither a comment // nor the first token a binder stops at. Left in, a binder that keeps @@ -499,7 +509,7 @@ pub(crate) fn collect_stretch<'a, T: Checker>( // above it instead of the one the tool attaches. for sibling in ancestors.siblings_before(comment) { if !view.covers(sibling.start_byte()..boundary) { - before = Some(sibling); + prefix_gap = true; break; } boundary = sibling.start_byte(); @@ -513,8 +523,22 @@ pub(crate) fn collect_stretch<'a, T: Checker>( break; } } + if matches!(view, CandidateView::Source(_)) && before.is_none() && !prefix_gap { + let start = if ancestors.depth() == Some(1) { + 0 + } else { + ancestors + .parent(comment) + .map_or(0, |parent| parent.start_byte()) + }; + prefix_gap = !view.covers(start..boundary); + } stretch.reverse(); - (stretch, before) + CollectedStretch { + members: stretch, + code_before: before, + prefix_gap, + } } /// Whether a stretch reads past `node`: a parse error that is no doc diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index 9b754945d..2dafdded7 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -142,6 +142,48 @@ "old": "CandidateView::Source(context),", "new": "CandidateView::Legacy,", "expect": ["documentation::streaming::markers::regressions::php_file_scan_cannot_read_a_gap_spanning_marker"] + }, + { + "name": "prefix-gap-is-not-preceding-code", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "prefix_gap = true;\n break;", + "new": "prefix_gap = true;\n before = Some(sibling);\n break;", + "expect": ["documentation::streaming::markers::regressions::typescript_source_prefix_gap_is_not_preceding_code", "documentation::streaming::markers::regressions::tsx_source_prefix_gap_is_not_preceding_code", "documentation::streaming::markers::regressions::php_source_prefix_gap_keeps_unknown_direction_out_of_selection"] + }, + { + "name": "selected-prefix-gap-remains-uncertain", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "self.prefix_gap_row == Some(node.start_row())", + "new": "(!kept && self.prefix_gap_row == Some(node.start_row()))", + "expect": ["documentation::streaming::markers::regressions::typescript_source_prefix_gap_is_not_preceding_code", "documentation::streaming::markers::regressions::tsx_source_prefix_gap_is_not_preceding_code"] + }, + { + "name": "first-source-token-keeps-excluded-prefix", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "prefix_gap = !view.covers(start..boundary);", + "new": "prefix_gap = false && !view.covers(start..boundary);", + "expect": ["documentation::streaming::markers::regressions::typescript_source_prefix_gap_is_not_preceding_code", "documentation::streaming::markers::regressions::tsx_source_prefix_gap_is_not_preceding_code"] + }, + { + "name": "unknown-php-direction-is-not-forward", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": ".map(|file| !file)", + "new": ".or(Some(false)).map(|file| !file)", + "expect": ["documentation::streaming::markers::regressions::php_source_prefix_gap_keeps_unknown_direction_out_of_selection", "documentation::streaming::markers::regressions::php_source_prefix_gap_cannot_select_unknown_define_documentation"] + }, + { + "name": "unknown-php-direction-is-not-local", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": ".map(|file| !file)", + "new": ".or(Some(true)).map(|file| !file)", + "expect": ["documentation::streaming::markers::regressions::php_source_prefix_gap_keeps_unknown_direction_out_of_selection", "documentation::streaming::markers::regressions::php_source_prefix_gap_cannot_select_unknown_define_documentation"] + }, + { + "name": "php-file-scan-checks-before-first-node", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": "if !view.covers(0..boundary) {", + "new": "if false && !view.covers(0..boundary) {", + "expect": ["documentation::streaming::markers::regressions::php_source_prefix_gap_keeps_unknown_direction_out_of_selection"] } ] } From 481d7e5334d40e8e94bf5eaa05e3e2eab4c4a81d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:55:11 -0800 Subject: [PATCH 028/221] refactor(ast): expose positional documentation run evidence --- .bca-baseline.toml | 42 +- CHANGELOG.md | 4 + big-code-analysis-ast/src/checker.rs | 21 + big-code-analysis-ast/src/checker/go.rs | 2 + big-code-analysis-ast/src/checker/lua.rs | 115 +++- big-code-analysis-ast/src/checker/ruby.rs | 67 +- .../src/documentation/streaming.rs | 19 + .../src/documentation/streaming/markers.rs | 6 +- .../streaming/markers/regressions.rs | 21 + .../src/documentation/streaming/positional.rs | 274 ++++++++ .../streaming/positional/tests.rs | 638 ++++++++++++++++++ .../src/lang_helpers/doc_comment.rs | 163 +++-- .../src/lang_helpers/ruby.rs | 26 +- .../src/node/ancestors/folds.rs | 4 +- src/metrics/loc.rs | 2 +- src/metrics/loc/dloc.rs | 2 +- src/metrics/loc/documentation_tests.rs | 170 +++++ src/metrics/loc/go.rs | 3 +- src/metrics/loc/lua.rs | 3 +- src/metrics/loc/ruby.rs | 3 +- src/metrics/loc/shared.rs | 30 +- utils/documentation-positional-perturb.json | 63 ++ 22 files changed, 1578 insertions(+), 100 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/streaming/positional.rs create mode 100644 big-code-analysis-ast/src/documentation/streaming/positional/tests.rs create mode 100644 utils/documentation-positional-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index e3e98f929..fe7916aff 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -211,17 +211,29 @@ qualified = "step_raw_string" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/checker.rs" +qualified = "" +metric = "loc.ploc" +value = 525.0 + [[entry]] path = "big-code-analysis-ast/src/checker.rs" qualified = "" metric = "loc.sloc" -value = 1333.0 +value = 1354.0 [[entry]] path = "big-code-analysis-ast/src/checker.rs" qualified = "Checker" metric = "nom" -value = 29.0 +value = 32.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_in" +metric = "nexits" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/checker/php.rs" @@ -253,6 +265,24 @@ qualified = "RunSelection<'t>::select" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceDecision<'t>::new" +metric = "halstead.effort" +value = 48196.811018362634 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "source_comment" +metric = "halstead.effort" +value = 47971.63551728485 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional/tests.rs" +qualified = "work" +metric = "halstead.effort" +value = 53704.58403901065 + [[entry]] path = "big-code-analysis-ast/src/getter.rs" qualified = "Getter::is_braced_literal_slot" @@ -293,7 +323,7 @@ value = 101217.532578918 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "" metric = "loc.ploc" -value = 554.0 +value = 626.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -337,6 +367,12 @@ qualified = "joined_run" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "positional_run" +metric = "halstead.effort" +value = 49504.66878343322 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "select_bound" diff --git a/CHANGELOG.md b/CHANGELOG.md index edfb6d29b..ef6ed321f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,10 @@ for historical reference. ### Added +- Added unstable AST positional-run evidence for Go, Ruby and Lua, including + ordered comments, directive members, candidate targets and opener reasons. + Marker and positional runs retain excluded-prefix composition metadata. (#1659) + - Added unstable AST-crate source-marker `Checker` hooks and streaming requests that retain selection, source pieces and attachment uncertainty. The separate legacy event stream preserves existing metric behavior. (#1658) diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index 9243d2118..c9c172a18 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -578,6 +578,27 @@ pub trait Checker { fn is_doc_run_directive(_: &Node, _code: &[u8]) -> bool { false } + /// Whether the native source profile uses positional comment runs. + const SOURCE_POSITIONAL_DOCS: bool = false; + /// Whether bare adjacency suffices, independently of an explicit opener. + const SOURCE_POSITIONAL_TARGETS: bool = false; + /// Source opener evidence from the completed run, before owner normalization. + /// + /// # Errors + /// Returns uncertainty when excluded source prevents the content decision. + fn source_doc_run_opener<'a>( + run: &crate::documentation::streaming::positional::RunContext<'_, 'a>, + ancestors: Ancestors<'a, '_>, + ) -> Result< + Option, + crate::documentation::UnresolvedReason, + > { + Ok(run + .members + .first() + .filter(|first| Self::is_doc_run_opener(first, run.below.as_ref(), run.code, ancestors)) + .map(|_| crate::documentation::streaming::positional::OpenerReason::Explicit)) + } /// Whether `node` opens a space by its kind alone: a function, /// closure, or one of the containers (class, struct, trait, impl, /// namespace, interface). diff --git a/big-code-analysis-ast/src/checker/go.rs b/big-code-analysis-ast/src/checker/go.rs index aa152264c..46eeedd5e 100644 --- a/big-code-analysis-ast/src/checker/go.rs +++ b/big-code-analysis-ast/src/checker/go.rs @@ -4,6 +4,8 @@ use super::*; impl Checker for GoCode { + const SOURCE_POSITIONAL_DOCS: bool = true; + const SOURCE_POSITIONAL_TARGETS: bool = true; // The `Comment`, `DocTarget` and `DocRunDirective` rows of // `roles/go.rs` (#1699): go/doc's targets under the function-body // scope gate, read with the node's own chain; a directive by its diff --git a/big-code-analysis-ast/src/checker/lua.rs b/big-code-analysis-ast/src/checker/lua.rs index b74966d95..8fc6397f7 100644 --- a/big-code-analysis-ast/src/checker/lua.rs +++ b/big-code-analysis-ast/src/checker/lua.rs @@ -19,19 +19,25 @@ struct LdocText { tag: bool, } -fn lua_block_text<'a>(first: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> LdocText { - let mut found = LdocText::default(); - let mut member = *first; - let mut after = ancestors.siblings_after(first); - loop { - for line in node_bytes(&member, code).split(|&byte| byte == b'\n') { +impl LdocText { + fn read(&mut self, member: &Node<'_>, code: &[u8]) { + for line in node_bytes(member, code).split(|&byte| byte == b'\n') { let body = ldoc_line_body(line); - found.text |= body.iter().any(|&byte| { + self.text |= body.iter().any(|&byte| { !matches!(byte, b'-' | b'[' | b']' | b'=') && !byte.is_ascii_whitespace() }); - found.tag |= + self.tag |= matches!(body.trim_ascii_start(), [b'@', tag, ..] if tag.is_ascii_alphanumeric()); } + } +} + +fn lua_block_text<'a>(first: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> LdocText { + let mut found = LdocText::default(); + let mut member = *first; + let mut after = ancestors.siblings_after(first); + loop { + found.read(&member, code); match after.next() { Some(next) if run_continues_to::(&member, &next, code) => member = next, _ => return found, @@ -57,6 +63,16 @@ fn ldoc_line_body(line: &[u8]) -> &[u8] { /// and every block that reaches it qualifies, so the scans of a file cover /// disjoint stretches and cost `O(siblings)` in all. fn lua_first_ldoc_block<'a>(first: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { + lua_first_block_in(first, code, ancestors, None).unwrap_or(false) +} + +fn lua_first_block_in<'a>( + first: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: Option<&crate::documentation::SourceContext<'a>>, +) -> Result { + // bca: suppress(halstead) -- the same reverse first-block decision serves legacy and source, with source-only gap barriers. // A fast path, not a separate rule: every other container opens with a // token (`if`, `do`, `{`), and the grammar parks a comment above a // body's first statement after it, so the first-token test below would @@ -67,11 +83,21 @@ fn lua_first_ldoc_block<'a>(first: &Node<'a>, code: &[u8], ancestors: Ancestors< .parent(first) .is_none_or(|parent| parent.kind_id() != Lua::Chunk) { - return false; + return Ok(false); } let mut earliest = *first; let mut before = ancestors.siblings_before(first).peekable(); while let Some(sibling) = before.next() { + if source.is_some_and(|source| !source.covers(sibling.start_byte()..earliest.end_byte())) { + return Err(crate::documentation::UnresolvedReason::ExcludedGap); + } + if source.is_some_and(|source| { + before + .peek() + .is_some_and(|above| !source.covers(above.start_byte()..sibling.end_byte())) + }) { + return Err(crate::documentation::UnresolvedReason::ExcludedGap); + } // `run_continues_to` asks only whether `sibling` continues a run // from `above`, so a comment directly under code needs the // comment test too: it opens its run. @@ -85,13 +111,19 @@ fn lua_first_ldoc_block<'a>(first: &Node<'a>, code: &[u8], ancestors: Ancestors< && ldoc_opener(node_bytes(&sibling, code)) && lua_block_text(&sibling, code, ancestors).text { - return false; + return Ok(false); } earliest = sibling; } + if source.is_some_and(|source| !source.covers(0..earliest.start_byte())) { + return Err(crate::documentation::UnresolvedReason::ExcludedGap); + } // role-bypass: allow(Comment) — whether the file opens with a comment or // a shebang, LDoc's first-token rule; traversal, not membership - matches!(earliest.kind_id().into(), Lua::Comment | Lua::HashBangLine) + Ok(matches!( + earliest.kind_id().into(), + Lua::Comment | Lua::HashBangLine + )) } /// The first statement of a `block`, which stands for it: the grammar parks @@ -104,6 +136,67 @@ fn lua_block_first_statement<'a>(node: &Node<'a>) -> Option> { } impl Checker for LuaCode { + const SOURCE_POSITIONAL_DOCS: bool = true; + + fn is_source_doc_target<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + if let Some(item) = lua_block_first_statement(node) { + crate::roles::lua::doc_target::owns(&item, code, ancestors.of_children(node).get()) + } else { + crate::roles::lua::doc_target::owns(node, code, ancestors) + } + } + + fn source_doc_run_opener<'a>( + run: &crate::documentation::streaming::positional::RunContext<'_, 'a>, + ancestors: Ancestors<'a, '_>, + ) -> Result< + Option, + crate::documentation::UnresolvedReason, + > { + // bca: suppress(nexits, halstead) -- retain unknown prefix context before selecting file, tagged or following-item documentation. + use crate::documentation::streaming::positional::OpenerReason; + if run.members.first().is_some_and(|first| { + ancestors + .siblings_before(first) + .next() + .is_some_and(|above| { + Self::is_comment(&above) + && run.source.is_some_and(|source| { + !source.covers(above.start_byte()..first.end_byte()) + }) + }) + }) { + return Err(crate::documentation::UnresolvedReason::ExcludedGap); + } + let Some(first) = run + .members + .first() + .filter(|first| crate::roles::lua::doc_run_opener::owns(first, run.code, ancestors)) + else { + return Ok(None); + }; + let mut text = LdocText::default(); + for member in run.members { + text.read(member, run.code); + } + if !text.text { + return Ok(None); + } + if lua_first_block_in(first, run.code, ancestors, run.source)? { + return Ok(Some(OpenerReason::FirstFile)); + } + if text.tag { + return Ok(Some(OpenerReason::Tagged)); + } + Ok(run + .below + .filter(|next| Self::is_source_doc_target(next, run.code, ancestors)) + .map(|_| OpenerReason::FollowingItem)) + } // The `Comment` row of `roles/lua.rs` (#1699); no `DocComment`. impl_comment_from_rows!(lua); diff --git a/big-code-analysis-ast/src/checker/ruby.rs b/big-code-analysis-ast/src/checker/ruby.rs index 459dd89bd..8505f9950 100644 --- a/big-code-analysis-ast/src/checker/ruby.rs +++ b/big-code-analysis-ast/src/checker/ruby.rs @@ -2,7 +2,7 @@ #![allow(clippy::wildcard_imports, clippy::enum_glob_use)] use super::*; -use crate::lang_helpers::ruby::{YardScope, ruby_yard_reads}; +use crate::lang_helpers::ruby::{YardScope, ruby_source_yard_reads, ruby_yard_reads}; /// The statement a comment run directly above `node` documents: `node` /// itself, or the statement a wrapper stands for. A statement modifier @@ -58,7 +58,59 @@ fn ruby_then_first_statement<'a>(node: &Node<'a>) -> Option> { .flatten() } +fn ruby_doc_target<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: bool, +) -> bool { + let (statement, chain) = match ruby_then_first_statement(node) { + Some(first) => (first, Some(ancestors.of_children(node))), + None => (*node, None), + }; + let statement_chain = chain.as_ref().map_or(ancestors, ChildAncestors::get); + ruby_documented_core(&statement, statement_chain).is_some_and(|(core, core_chain)| { + let core_chain = core_chain + .as_ref() + .map_or(statement_chain, ChildAncestors::get); + let reads = if source { + ruby_source_yard_reads + } else { + ruby_yard_reads + }; + crate::roles::ruby::doc_target::owns(&core, code, core_chain) + && reads(YardScope::of(&core), node, ancestors) + }) +} + impl Checker for RubyCode { + const SOURCE_POSITIONAL_DOCS: bool = true; + const SOURCE_POSITIONAL_TARGETS: bool = true; + + fn is_source_doc_target<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + ruby_doc_target(node, code, ancestors, true) + } + + fn source_doc_run_opener<'a>( + run: &crate::documentation::streaming::positional::RunContext<'_, 'a>, + ancestors: Ancestors<'a, '_>, + ) -> Result< + Option, + crate::documentation::UnresolvedReason, + > { + Ok(run + .members + .first() + .filter(|first| { + crate::roles::ruby::doc_run_opener::owns(first, run.code, ancestors) + && ruby_source_yard_reads(YardScope::Namespace, first, ancestors) + }) + .map(|_| crate::documentation::streaming::positional::OpenerReason::Explicit)) + } // The `Comment` row of `roles/ruby.rs` (#1699); no `DocComment`. impl_comment_from_rows!(ruby); @@ -74,18 +126,7 @@ impl Checker for RubyCode { // node's chain, where the comment sits. The candidate test goes // first, so the scope fold runs only for one. fn is_doc_target<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> bool { - let (statement, chain) = match ruby_then_first_statement(node) { - Some(first) => (first, Some(ancestors.of_children(node))), - None => (*node, None), - }; - let statement_chain = chain.as_ref().map_or(ancestors, ChildAncestors::get); - ruby_documented_core(&statement, statement_chain).is_some_and(|(core, core_chain)| { - let core_chain = core_chain - .as_ref() - .map_or(statement_chain, ChildAncestors::get); - crate::roles::ruby::doc_target::owns(&core, code, core_chain) - && ruby_yard_reads(YardScope::of(&core), node, ancestors) - }) + ruby_doc_target(node, code, ancestors, false) } fn doc_target_start_row(node: &Node) -> usize { diff --git a/big-code-analysis-ast/src/documentation/streaming.rs b/big-code-analysis-ast/src/documentation/streaming.rs index dd8f92ccb..2014c14ed 100644 --- a/big-code-analysis-ast/src/documentation/streaming.rs +++ b/big-code-analysis-ast/src/documentation/streaming.rs @@ -5,6 +5,25 @@ use crate::Node; pub mod markers; +pub mod positional; + +/// Stream a positional comment and its completed run's original inclusive rows. +/// Coverage follows the current comment's billing and excludes directive members. +pub fn positional_comment<'t, T: crate::Checker>( + node: &Node<'t>, + code: &[u8], + ancestors: crate::Ancestors<'t, '_>, + mut sink: impl FnMut(LegacyEvent<'t>), +) { + marker_comment::(node, code, ancestors, &mut sink); + crate::lang_helpers::leading_doc_run::(node, code, ancestors, |first, last| { + sink(LegacyEvent::Coverage { + kind: CoverageKind::LeadingRun, + first, + last, + }); + }); +} /// Stream the original marker/placement decision before the final-member binding /// callbacks. This path needs no source context and constructs no source evidence. diff --git a/big-code-analysis-ast/src/documentation/streaming/markers.rs b/big-code-analysis-ast/src/documentation/streaming/markers.rs index b77673bff..a1a9ee27c 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers.rs @@ -92,6 +92,9 @@ pub struct MarkerRun<'s> { pub containing: Option>, /// Preceding code retained for after-code placement decisions. pub code_before: Option>, + /// Excluded source precedes this stretch. Composition may be incomplete even + /// when only selected members were requested and their attachment is known. + pub prefix_gap: bool, } /// One physical source marker or uncertain comment and its selection result. @@ -337,6 +340,7 @@ pub fn source_comment<'s, T: Checker>( .and_then(|node| T::source_doc_uncertainty(&node, code, ancestors)), containing: ancestors.parent(comment).map(canonical).transpose()?, code_before: code_before.map(canonical).transpose()?, + prefix_gap: collected.prefix_gap, }); } Ok(()) @@ -365,7 +369,7 @@ fn member<'s>( }) } -fn line_spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { +pub(super) fn line_spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { let code = context.bytes(); let end = node.end_byte(); let lf = if code.get(end - 1) == Some(&b'\n') { diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs index 33bb34099..3949ceaa2 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs @@ -182,6 +182,8 @@ fn excluded_code_keeps_unrelated_later_docs_and_splits_comment_runs() { assert_eq!(runs.len(), if retain { 2 } else { 1 }); let last = runs.last().unwrap(); assert_eq!(last.members.len(), 1); + assert!(last.prefix_gap); + assert!(last.code_before.is_none()); assert_eq!(last.members[0].source.pieces()[0].bytes(), b"/**new*/"); assert_eq!(last.members[0].selection, MarkerSelection::Selected); assert_eq!(last.members[0].uncertainty, None); @@ -199,6 +201,25 @@ fn excluded_code_keeps_unrelated_later_docs_and_splits_comment_runs() { } } +#[cfg(feature = "rust")] +#[test] +fn selected_join_all_run_reports_missing_prefix_for_composition() { + let source = b"///old\nXXXX\n///new\nfn f() {}"; + let parser = restricted(LANG::Rust, source, &[0..7, 12..source.len()]); + for retain in [false, true] { + let result = runs::(&parser, retain); + assert_eq!(result.len(), if retain { 2 } else { 1 }); + let last = result.last().unwrap(); + assert!(last.prefix_gap); + assert!(last.code_before.is_none()); + assert_eq!(last.members.len(), 1); + assert_eq!(last.members[0].selection, MarkerSelection::Selected); + assert_eq!(last.members[0].source.pieces()[0].bytes(), b"///new"); + assert_eq!(last.target.unwrap().node().kind(), "function_item"); + assert_eq!(last.target.unwrap().node().byte_range(), 19..28); + } +} + #[cfg(feature = "php")] #[test] fn php_file_scan_cannot_read_a_gap_spanning_marker() { diff --git a/big-code-analysis-ast/src/documentation/streaming/positional.rs b/big-code-analysis-ast/src/documentation/streaming/positional.rs new file mode 100644 index 000000000..bce41e895 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/positional.rs @@ -0,0 +1,274 @@ +//! Positional run evidence over the same final-member scan as legacy LOC. + +use crate::lang_helpers::doc_comment::{self, PositionalRun}; +use crate::{Ancestors, Checker, Node}; + +use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces, UnresolvedReason}; +use super::markers::CandidateView; + +pub use doc_comment::{positional_predecessors, positional_runs_collected}; +crate::observation::counter!(evidence_built, cfg(any(test, feature = "test-support"))); + +/// Why the final comment cannot defer to another member. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RunEnd { + /// Another non-comment token follows, including missing and ERROR tokens. + Token, + /// A blank source row separates this run from the next sibling. + BlankLine, + /// The language's long-comment terminator ends the run. + Terminator, + /// No further sibling exists in this containing scope. + EndOfScope, + /// Excluded bytes interrupt the run or the following token. + ExcludedGap, +} + +/// Content-based selection, independent of a concrete declaration owner. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OpenerReason { + /// An explicit directive opens documentation without requiring a target. + Explicit, + /// LDoc's first qualifying file block is module documentation. + FirstFile, + /// A tagged LDoc block supplies its own structural evidence. + Tagged, + /// A marked LDoc block precedes a supported item. + FollowingItem, +} + +/// Selection of a positional run under the native source convention. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RunSelection { + /// An ordinary run precedes a supported candidate. + FollowingTarget, + /// The opener, rather than bare adjacency, makes this documentation. + Opener(OpenerReason), + /// No native attachment was established. + Unattached, +} + +/// Completed run context for language content predicates. All members are +/// siblings on the caller's actual chain, in source order. +pub struct RunContext<'r, 't> { + /// Complete ordered comment run, before directive filtering. + pub members: &'r [Node<'t>], + /// Immediate next-row sibling, before candidate classification. + pub below: Option>, + /// Actual parsed buffer. + pub code: &'r [u8], + /// Source-only included-range context; absent on the legacy path. + pub source: Option<&'r SourceContext<'t>>, +} + +/// A source request. Rejected runs and directive-only members are independently +/// opt-in; the legacy path constructs neither this request nor source evidence. +pub struct SourceRequest<'r, 's> { + /// Exact borrowed parse context. + pub context: &'r SourceContext<'s>, + /// Retain runs that have no native attachment. + pub retain_unbound: bool, + /// Retain recognized non-prose directives in their original order. + pub retain_directives: bool, + /// Receives a completed run at its final comment visit. + pub sink: &'r mut dyn FnMut(SourceRun<'s>), +} + +/// Positional binding evidence; owner normalization remains language-specific. +#[derive(Debug)] +pub struct SourceRun<'s> { + /// Retained physical occurrences, in source order. + pub members: Vec>, + /// Native selection reason, never a concrete owner assertion. + pub selection: RunSelection, + /// Following supported candidate, even when an opener selects a virtual or + /// file document instead. Adapters must inspect `selection` before binding. + pub target: Option>, + /// Immediate following sibling, including a non-target or recovery token. + pub following: Option>, + /// Immediate lexical container from the walk's chain. + pub containing: Option>, + /// Preceding token when known. Never fabricated across excluded source. + pub code_before: Option>, + /// Excluded source before this run may make composition incomplete. + pub prefix_gap: bool, + /// Why the run ended. + pub end: RunEnd, + /// An excluded gap or recovery boundary prevented a certain decision. + pub uncertainty: Option, +} + +/// A comment occurrence; raw bytes need not be valid UTF-8. +#[derive(Debug)] +pub struct RunMember<'s> { + /// Exact canonical syntax identity and grammar-owned span. + pub node: NodeEvidence<'s>, + /// Included comment spelling, without a line-comment LF/CRLF terminator. + pub source: SourcePieces<'s>, + /// Whether the language excludes this member from documentation prose. + pub directive: bool, + /// Whether this occurrence contributes prose under the native selection. + /// Trailing prefixes and directives remain evidence only. + pub selected: bool, +} + +/// Stream native positional evidence at a comment visit. Ordinary extras that +/// are comments join; every other token, including an extra ERROR, stops a run. +/// No generic leading-comment inference is enabled here. +/// +/// # Errors +/// Rejects foreign parse context or invalid source ranges before emitting a run. +pub fn source_comment<'s, T: Checker>( + comment: &Node<'s>, + ancestors: Ancestors<'s, '_>, + request: &mut SourceRequest<'_, 's>, +) -> Result<(), SourceError> { + // bca: suppress(nexits) -- defer or reject before canonicalizing a complete run; every identity failure precedes the sink. + if !T::SOURCE_POSITIONAL_DOCS { + return Ok(()); + } + request.context.node(comment.as_tree_sitter())?; + let code = request.context.bytes(); + let Some(run) = doc_comment::positional_run::( + comment, + code, + ancestors, + CandidateView::Source(request.context), + ) else { + return Ok(()); + }; + let decision = SourceDecision::new::(&run, ancestors, request.context); + if decision.selection == RunSelection::Unattached && !request.retain_unbound { + return Ok(()); + } + let members = source_members::(&run, decision.selection, request)?; + if !members.is_empty() { + let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); + (request.sink)(SourceRun { + members, + selection: decision.selection, + target: decision.target.map(canonical).transpose()?, + following: run.next.map(canonical).transpose()?, + containing: ancestors.parent(comment).map(canonical).transpose()?, + code_before: run.code_before.map(canonical).transpose()?, + prefix_gap: run.prefix_gap, + end: run.end, + uncertainty: decision.uncertainty, + }); + } + Ok(()) +} + +struct SourceDecision<'t> { + selection: RunSelection, + target: Option>, + uncertainty: Option, +} + +impl<'t> SourceDecision<'t> { + fn new( + run: &PositionalRun<'t>, + ancestors: Ancestors<'t, '_>, + source: &SourceContext<'t>, + ) -> Self { + let mut decision = Self { + selection: RunSelection::Unattached, + target: None, + uncertainty: None, + }; + if !continuous_placement(run, source) { + decision.uncertainty = Some(UnresolvedReason::ExcludedGap); + return decision; + } + decision.target = run + .below + .filter(|n| T::is_source_doc_target(n, source.bytes(), ancestors)); + if run.trailing_members == run.members.len() { + return decision; + } + let context = RunContext { + members: &run.members[run.trailing_members..], + below: run.below, + code: source.bytes(), + source: Some(source), + }; + match T::source_doc_run_opener(&context, ancestors) { + Ok(Some(reason)) => decision.selection = RunSelection::Opener(reason), + Ok(None) if T::SOURCE_POSITIONAL_TARGETS && decision.target.is_some() => { + decision.selection = RunSelection::FollowingTarget; + } + Ok(None) => {} + Err(reason) => decision.uncertainty = Some(reason), + } + if decision.uncertainty.is_none() { + decision.uncertainty = run + .next + .filter(|n| n.has_error() || n.is_missing()) + .map(|_| UnresolvedReason::GrammarBoundary); + } + decision + } +} + +fn continuous_placement(run: &PositionalRun<'_>, source: &SourceContext<'_>) -> bool { + let Some(first) = run.members.first() else { + return false; + }; + if run.end == RunEnd::ExcludedGap || !source.covers(first.start_byte()..first.end_byte()) { + return false; + } + if !run.prefix_gap { + return true; + } + let start = first + .start_byte() + .saturating_sub(first.as_tree_sitter().start_position().column); + source.covers(start..first.start_byte()) + && source.bytes()[start..first.start_byte()] + .iter() + .all(u8::is_ascii_whitespace) +} + +fn source_members<'s, T: Checker>( + run: &PositionalRun<'s>, + selection: RunSelection, + request: &SourceRequest<'_, 's>, +) -> Result>, SourceError> { + let mut members = Vec::new(); + for (index, node) in run.members.iter().enumerate() { + let trailing = index < run.trailing_members; + if trailing && !request.retain_unbound { + continue; + } + let directive = request.context.covers(node.start_byte()..node.end_byte()) + && T::is_doc_run_directive(node, request.context.bytes()); + if directive && !request.retain_directives { + continue; + } + evidence_built::record(); + members.push(RunMember { + node: request.context.node(node.as_tree_sitter())?, + source: request + .context + .pieces(node.start_byte()..spelling_end(request.context, node))?, + directive, + selected: !trailing && !directive && selection != RunSelection::Unattached, + }); + } + Ok(members) +} + +fn spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { + let bytes = doc_comment::node_bytes(node, context.bytes()); + if bytes.starts_with(b"//") + || bytes.starts_with(b"#") + || (bytes.starts_with(b"--") && !doc_comment::lua_long_comment(bytes)) + { + super::markers::line_spelling_end(context, node) + } else { + node.end_byte() + } +} + +#[cfg(test)] +mod tests; diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs new file mode 100644 index 000000000..d2d84f7ed --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs @@ -0,0 +1,638 @@ +#![allow(clippy::single_range_in_vec_init)] + +use super::*; +use crate::{AnyParser, LANG, Search}; +use std::ops::Range; + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn runs(parser: &AnyParser, retain: bool, directives: bool) -> Vec> { + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut result = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: retain, + retain_directives: directives, + sink: &mut |run| result.push(run), + }, + ) + .unwrap(); + } + }); + result +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn parse(lang: LANG, source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(lang, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{}", + parser.ts_tree().root_node().to_sexp() + ); + parser +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn identity(node: NodeEvidence<'_>, kind: &str, range: Range) { + assert_eq!(node.node().kind(), kind); + assert_eq!(node.node().byte_range(), range); + node.validate(node.node()).unwrap(); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn members(run: &SourceRun<'_>, expected: &[(Range, &[u8], bool)]) { + assert_eq!(run.members.len(), expected.len()); + for (member, (range, bytes, directive)) in run.members.iter().zip(expected) { + identity(member.node, "comment", range.clone()); + assert_eq!(member.source.pieces().len(), 1); + assert_eq!(member.source.pieces()[0].range(), *range); + assert_eq!(member.source.pieces()[0].bytes(), *bytes); + assert_eq!(member.directive, *directive); + assert_eq!( + member.selected, + !directive && run.selection != RunSelection::Unattached + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_order_directives_and_candidate_are_independent() { + let parser = parse( + LANG::Go, + b"package p\n// audit\n//go:generate tool\n// more\nfunc F() {}", + ); + let run = runs::(&parser, false, true).pop().unwrap(); + members( + &run, + &[ + (10..18, b"// audit", false), + (19..37, b"//go:generate tool", true), + (38..45, b"// more", false), + ], + ); + identity(run.target.unwrap(), "function_declaration", 46..57); + identity(run.following.unwrap(), "function_declaration", 46..57); + identity(run.code_before.unwrap(), "package_clause", 0..9); + identity(run.containing.unwrap(), "source_file", 0..57); + assert_eq!(run.selection, RunSelection::FollowingTarget); + assert_eq!(run.uncertainty, None); + assert_eq!(run.end, RunEnd::Token); + assert!(!run.prefix_gap); + let before = evidence_built::observed(); + let filtered = runs::(&parser, false, false); + assert_eq!(evidence_built::observed() - before, 2); + members( + &filtered[0], + &[(10..18, b"// audit", false), (38..45, b"// more", false)], + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_wrappers_magic_and_virtual_opener_keep_distinct_evidence() { + let parser = parse( + LANG::Ruby, + b"#!/ruby\n# frozen_string_literal: true\n# audit\nprivate def f; end", + ); + let result = runs::(&parser, false, true); + assert_eq!(result.len(), 1); + members( + &result[0], + &[ + (0..7, b"#!/ruby", true), + (8..37, b"# frozen_string_literal: true", true), + (38..45, b"# audit", false), + ], + ); + identity(result[0].target.unwrap(), "call", 46..64); + assert_eq!(result[0].selection, RunSelection::FollowingTarget); + assert_eq!(result[0].uncertainty, None); + let parser = parse(LANG::Ruby, b"# @!method ghost\n# audit\ndef ghost; end"); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 1); + assert_eq!( + result[0].selection, + RunSelection::Opener(OpenerReason::Explicit) + ); + identity(result[0].target.unwrap(), "method", 27..41); + members( + &result[0], + &[ + (0..16, b"# @!method ghost", false), + (17..26, b"# audit", false), + ], + ); +} + +#[cfg(feature = "lua")] +#[test] +fn lua_plain_marked_first_file_and_later_contexts() { + for (source, selection, target) in [ + ( + "---audit\nfunction f() end", + RunSelection::Opener(OpenerReason::FirstFile), + 9..25, + ), + ( + "module(\"m\")\n---audit\nfunction f() end", + RunSelection::Opener(OpenerReason::FollowingItem), + 21..37, + ), + ( + "module(\"m\")\n-- audit\nfunction f() end", + RunSelection::Unattached, + 21..37, + ), + ( + "x = 1\nmodule(\"m\")\n---audit\nfunction f() end", + RunSelection::Opener(OpenerReason::FollowingItem), + 27..43, + ), + ] { + let parser = parse(LANG::Lua, source.as_bytes()); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 1, "{source}"); + assert_eq!(result[0].selection, selection, "{source}"); + identity(result[0].target.unwrap(), "function_declaration", target); + assert_eq!(result[0].uncertainty, None); + let selected = runs::(&parser, false, false); + assert_eq!( + selected.len(), + usize::from(selection != RunSelection::Unattached) + ); + } + let parser = parse(LANG::Lua, b"module(\"m\")\n---audit\n-- @function ghost"); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 1); + assert_eq!( + result[0].selection, + RunSelection::Opener(OpenerReason::Tagged) + ); + assert!(result[0].target.is_none()); + members( + &result[0], + &[ + (12..20, b"---audit", false), + (21..39, b"-- @function ghost", false), + ], + ); + assert_eq!(result[0].end, RunEnd::EndOfScope); +} + +#[cfg(feature = "go")] +#[test] +fn go_source_blank_comment_blank_trailing_and_same_row() { + for (source, counts, selected, end) in [ + ( + "package p\n// a\n\n// b\nfunc F() {}", + vec![1, 1], + vec![false, true], + RunEnd::Token, + ), + ( + "package p\n// a\n//\n// b\nfunc F() {}", + vec![3], + vec![true], + RunEnd::Token, + ), + ( + "package p\n/*a*/ /*b*/\nfunc F() {}", + vec![2], + vec![true], + RunEnd::Token, + ), + ( + "package p\nfunc F() {} // a", + vec![1], + vec![false], + RunEnd::EndOfScope, + ), + ("package p\n// a", vec![1], vec![false], RunEnd::EndOfScope), + ( + "package p\n// a\nvar x = 1", + vec![1], + vec![true], + RunEnd::Token, + ), + ] { + let parser = parse(LANG::Go, source.as_bytes()); + let result = runs::(&parser, true, true); + assert_eq!( + result.iter().map(|r| r.members.len()).collect::>(), + counts, + "{source}" + ); + assert_eq!( + result + .iter() + .map(|r| r.selection != RunSelection::Unattached) + .collect::>(), + selected, + "{source}" + ); + assert_eq!(result.last().unwrap().end, end); + if result.len() == 2 { + assert_eq!(result[0].end, RunEnd::BlankLine); + } + } +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_yard_scope_uses_actual_wrapper_context() { + for (source, expected) in [ + ( + "class C\n# audit\nX = 1 unless false\nend", + RunSelection::FollowingTarget, + ), + ("foo do\n# audit\ndef f; end\nend", RunSelection::Unattached), + ("def outer\n# audit\nX = 1\nend", RunSelection::Unattached), + ( + "if true\n# audit\ndef f; end\nend", + RunSelection::FollowingTarget, + ), + ("# audit\nputs 1", RunSelection::Unattached), + ("# audit", RunSelection::Unattached), + ("##\n# audit", RunSelection::Opener(OpenerReason::Explicit)), + ] { + let parser = parse(LANG::Ruby, source.as_bytes()); + let result = runs::(&parser, true, true); + assert_eq!(result.len(), 1, "{source}"); + assert_eq!(result[0].selection, expected, "{source}"); + assert_eq!(result[0].uncertainty, None); + if source.starts_with("if") { + identity(result[0].target.unwrap(), "then", 15..26); + } + } +} + +#[cfg(feature = "lua")] +#[test] +fn lua_long_terminator_and_body_notes_do_not_merge() { + let parser = parse(LANG::Lua, b"--[[-audit]]\n-- note\nfunction f() end"); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 2); + assert_eq!(result[0].end, RunEnd::Terminator); + assert_eq!( + result[0].selection, + RunSelection::Opener(OpenerReason::FirstFile) + ); + assert_eq!(result[1].selection, RunSelection::Unattached); + let parser = parse(LANG::Lua, b"function f()\n---audit\nlocal x = 1\nend"); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert_eq!(result[0].uncertainty, None); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +#[allow(clippy::naive_bytecount)] +fn restricted(lang: LANG, source: &[u8], included: &[Range]) -> AnyParser { + let point = |at| { + tree_sitter::Point::new( + source[..at].iter().filter(|&&b| b == b'\n').count(), + source[..at] + .iter() + .rposition(|&b| b == b'\n') + .map_or(at, |b| at - b - 1), + ) + }; + let ranges: Vec<_> = included + .iter() + .map(|r| tree_sitter::Range { + start_byte: r.start, + end_byte: r.end, + start_point: point(r.start), + end_point: point(r.end), + }) + .collect(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&lang.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + AnyParser::from_tree(lang, tree, source.to_vec()).unwrap() +} + +#[cfg(feature = "go")] +#[test] +fn go_gaps_split_runs_before_selection_and_keep_composition_metadata() { + let source = b"package p\n// old\nXXXX\n// new\nfunc F() {}"; + let parser = restricted(LANG::Go, source, &[0..17, 22..source.len()]); + for retain in [false, true] { + let result = runs::(&parser, retain, true); + assert_eq!(result.len(), if retain { 2 } else { 1 }); + let last = result.last().unwrap(); + assert!(last.prefix_gap); + assert!(last.code_before.is_none()); + assert_eq!(last.selection, RunSelection::FollowingTarget); + assert_eq!(last.uncertainty, None); + identity(last.target.unwrap(), "function_declaration", 29..40); + if retain { + assert_eq!(result[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); + } + } + for (source, included) in [ + (b"XX// a\npackage p".as_slice(), vec![2..16]), + (b"// a\npackage p".as_slice(), vec![0..2, 3..14]), + (b"// a\npackage p".as_slice(), vec![0..4, 5..14]), + ] { + let parser = restricted(LANG::Go, source, &included); + assert!(runs::(&parser, false, false).is_empty()); + let result = runs::(&parser, true, true); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert_eq!(result[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); + } +} + +#[cfg(feature = "lua")] +#[test] +fn lua_gap_never_fabricates_first_file_context() { + let source = b"XXXX\n---audit\nfunction f() end"; + let parser = restricted(LANG::Lua, source, &[5..source.len()]); + assert!(runs::(&parser, false, false).is_empty()); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 1); + assert!(result[0].prefix_gap); + assert!(result[0].code_before.is_none()); + assert_eq!(result[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn work(prefix: &str, comment: &str, target: &str) { + for width in [4, 64, 256] { + let source = format!("{prefix}{}{target}", comment.repeat(width)); + let parser = parse(T::lang(), source.as_bytes()); + let before = positional_runs_collected::observed(); + let probes = positional_predecessors::observed(); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].members.len(), width); + // expected: one final-member scan, width-1 members and the one prefix token. + assert_eq!(positional_runs_collected::observed() - before, 1); + assert_eq!(positional_predecessors::observed() - probes, width); + let before = evidence_built::observed(); + let scans = positional_runs_collected::observed(); + let probes = positional_predecessors::observed(); + let mut rows = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + super::super::positional_comment::( + node, + source.as_bytes(), + ancestors, + |event| { + if let super::super::LegacyEvent::Coverage { kind, first, last } = event { + assert_eq!(kind, super::super::CoverageKind::LeadingRun); + rows.push((first, last)); + } + }, + ); + } + }); + assert_eq!(rows, (1..=width).map(|row| (row, row)).collect::>()); + assert_eq!(evidence_built::observed() - before, 0); + assert_eq!(positional_runs_collected::observed() - scans, 1); + assert_eq!(positional_predecessors::observed() - probes, width); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_completed_run_is_scanned_once() { + work::("package p\n", "// audit\n", "func F() {}"); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_completed_run_is_scanned_once() { + work::("X = 1\n", "# audit\n", "def f; end"); +} +#[cfg(feature = "lua")] +#[test] +fn lua_completed_run_is_scanned_once() { + work::("module(\"m\")\n", "---audit\n", "function f() end"); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn raw(source: &[u8], range: Range) { + let parser = parse(T::lang(), source); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].members.len(), 1); + assert_eq!( + result[0].members[0].source.pieces()[0].range(), + range.clone() + ); + assert_eq!( + result[0].members[0].source.pieces()[0].bytes(), + &source[range] + ); + assert_eq!(result[0].uncertainty, None); +} + +#[cfg(feature = "go")] +#[test] +fn go_invalid_bytes_and_crlf_are_raw() { + raw::(b"// \xff\r\npackage p", 0..4); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_invalid_bytes_and_crlf_are_raw() { + raw::(b"# \xff\r\ndef f; end", 0..3); +} +#[cfg(feature = "lua")] +#[test] +fn lua_invalid_bytes_and_crlf_are_raw() { + raw::(b"---\xff\r\nfunction f() end", 0..4); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_gap_after_code_does_not_hide_incomplete_composition() { + let source = b"X = 1\n# old\nXXXX\n# new\ndef f; end"; + let parser = restricted(LANG::Ruby, source, &[0..12, 17..source.len()]); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::FollowingTarget); + assert!(result[0].prefix_gap); + assert!(result[0].code_before.is_none()); + assert_eq!(result[0].uncertainty, None); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_source_and_legacy_scope_caches_disagree_in_both_orders() { + let source = b"foo do\n# audit\ndef f; end\nend"; + let parser = parse(LANG::Ruby, source); + for source_first in [false, true] { + let context = SourceContext::new(parser.ts_tree(), source); + let mut result = Vec::new(); + let mut credited = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if !crate::RubyCode::is_comment(node) { + return; + } + for is_source in [source_first, !source_first] { + if is_source { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: true, + retain_directives: false, + sink: &mut |run| result.push(run), + }, + ) + .unwrap(); + } else { + super::super::positional_comment::( + node, + source, + ancestors, + |event| { + if let super::super::LegacyEvent::Coverage { first, last, .. } = event { + credited.push((first, last)); + } + }, + ); + } + } + }); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert!(result[0].target.is_none()); + assert_eq!(credited, [(1, 1)]); + } +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn recovery(source: &[u8]) { + let parser = AnyParser::parse(T::lang(), source.to_vec(), None, None).unwrap(); + let mut errors = 0; + parser.root_node().act_on_node(&mut |node, _| { + if node.is_error() && node.is_extra() { + errors += 1; + } + }); + assert!(errors > 0, "{}", parser.ts_tree().root_node().to_sexp()); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 2, "{result:?}"); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert_eq!( + result[0].uncertainty, + Some(UnresolvedReason::GrammarBoundary) + ); + assert!(result[0].target.is_none()); + assert!(result[0].following.unwrap().node().is_error()); + assert_eq!(result[0].members.len(), 1); + assert_eq!(result[1].members.len(), 1); +} + +#[cfg(feature = "go")] +#[test] +fn go_extra_error_is_a_boundary() { + recovery::(b"package p\n// a\n@\n// b\nfunc F() {}"); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_extra_error_is_a_boundary() { + recovery::(b"# a\n@\n# b\ndef f; end"); +} +#[cfg(feature = "lua")] +#[test] +fn lua_extra_error_is_a_boundary() { + recovery::(b"module(\"m\")\n-- a\n@\n---b\nfunction f() end"); +} + +#[cfg(feature = "go")] +#[test] +fn go_trailing_prefix_is_retained_without_seeding_documentation() { + let parser = parse( + LANG::Go, + b"package p\nfunc A() {} /* t */ /* u */\n// b\nfunc B() {}", + ); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 1); + assert_eq!( + result[0] + .members + .iter() + .map(|m| m.selected) + .collect::>(), + [false, false, true] + ); + let selected = runs::(&parser, false, false); + assert_eq!(selected.len(), 1); + assert_eq!(selected[0].members.len(), 1); + assert_eq!(selected[0].members[0].source.pieces()[0].bytes(), b"// b"); +} + +#[cfg(feature = "go")] +#[test] +fn go_missing_target_retains_uncertain_canonical_candidate() { + let source = b"package p\n// audit\nfunc F( {}"; + let parser = AnyParser::parse(LANG::Go, source.to_vec(), None, None).unwrap(); + assert!(parser.root_node().preorder().any(|n| n.is_missing())); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 1); + assert_eq!( + result[0].uncertainty, + Some(UnresolvedReason::GrammarBoundary) + ); + assert!(result[0].following.unwrap().node().has_error()); + assert_eq!(result[0].members.len(), 1); + identity(result[0].members[0].node, "comment", 10..18); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn lazy(source: &[u8]) { + let parser = parse(T::lang(), source); + let before = evidence_built::observed(); + assert!(runs::(&parser, false, false).is_empty()); + assert_eq!(evidence_built::observed() - before, 0); + let result = runs::(&parser, true, true); + assert_eq!(result.len(), 1); + assert_eq!(result[0].members.len(), 1); + assert_eq!(evidence_built::observed() - before, 1); + assert_eq!(result[0].selection, RunSelection::Unattached); +} + +#[cfg(feature = "go")] +#[test] +fn go_unattached_evidence_is_lazy() { + lazy::(b"package p\n// note"); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_unattached_evidence_is_lazy() { + lazy::(b"# note"); +} +#[cfg(feature = "lua")] +#[test] +fn lua_unattached_evidence_is_lazy() { + lazy::(b"-- note"); +} + +#[cfg(feature = "go")] +#[test] +fn go_directive_only_evidence_is_lazy_and_not_prose() { + let parser = parse(LANG::Go, b"//go:generate tool\npackage p"); + let before = evidence_built::observed(); + assert!(runs::(&parser, false, false).is_empty()); + assert_eq!(evidence_built::observed() - before, 0); + let result = runs::(&parser, false, true); + assert_eq!(result.len(), 1); + assert_eq!(result[0].members.len(), 1); + assert!(result[0].members[0].directive); + assert!(!result[0].members[0].selected); + identity(result[0].target.unwrap(), "package_clause", 19..28); +} diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index e7b699fc6..7cec10437 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -749,28 +749,20 @@ pub fn leading_doc_run<'a, T: Checker>( ancestors: Ancestors<'a, '_>, mut credit: impl FnMut(usize, usize), ) { - let next = ancestors.siblings_after(comment).next(); - if next - .as_ref() - .is_some_and(|n| run_continues_to::(comment, n, code)) - { - // A later member decides. + let Some(run) = positional_run::(comment, code, ancestors, CandidateView::Legacy) else { return; - } - let Some(first) = run_first_member::(comment, code, ancestors) else { + }; + let Some(first) = run.members.get(run.trailing_members) else { return; }; - // `next` is `comment`'s sibling, so `ancestors` is its chain too. - let below = next.filter(|n| T::doc_target_start_row(n) == comment.end_row().saturating_add(1)); - let documents = below.is_some_and(|n| T::is_doc_target(&n, code, ancestors)) - || T::is_doc_run_opener(&first, below.as_ref(), code, ancestors); + let documents = run + .below + .is_some_and(|n| T::is_doc_target(&n, code, ancestors)) + || T::is_doc_run_opener(first, run.below.as_ref(), code, ancestors); if !documents { return; } - for member in std::iter::once(first).chain(ancestors.siblings_after(&first)) { - if member.start_byte() > comment.start_byte() { - break; - } + for member in run.members.into_iter().skip(run.trailing_members) { if !T::is_doc_run_directive(&member, code) { credit(member.start_row(), member.end_row()); } @@ -791,48 +783,117 @@ pub(crate) fn run_continues_to(comment: &Node, next: &Node, code: &[ && !T::ends_doc_run(comment, code))) } -/// The first member of the run `comment` ends: the comment siblings -/// before it on consecutive rows that hold nothing but comments, so two -/// comments sharing a row (`/* a */ /* b */`) are one row of the run. -/// `None` when code precedes `comment` on its own row: a trailing -/// comment belongs to no run, and a row where code precedes its -/// comments ends the run below it. One backward pass over one sibling -/// iterator. -fn run_first_member<'a, T: Checker>( +/// Ordered members and boundaries from the completed positional run. Trailing +/// rows are rejected for billing but retained when source evidence is requested. +pub(crate) struct PositionalRun<'a> { + pub(crate) members: Vec>, + pub(crate) next: Option>, + pub(crate) below: Option>, + pub(crate) code_before: Option>, + pub(crate) prefix_gap: bool, + pub(crate) trailing_members: usize, + pub(crate) end: crate::documentation::streaming::positional::RunEnd, +} + +crate::observation::counter!( + positional_runs_collected, + cfg(any(test, feature = "test-support")) +); +crate::observation::counter!( + positional_predecessors, + cfg(any(test, feature = "test-support")) +); + +pub(crate) fn positional_run<'a, T: Checker>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, -) -> Option> { - // `row_first` is the earliest comment found on the row being scanned; - // `first` is the first member of the earliest row known to be clean. - // Each step moves `row_first` to the sibling just before it, so one - // iterator walks the whole run. - let mut before = ancestors.siblings_before(comment); - let mut first = None; + view: CandidateView<'_>, +) -> Option> { + use crate::documentation::streaming::positional::RunEnd; + let next = ancestors.siblings_after(comment).next(); + let continuous = + view.covers(comment.start_byte()..next.map_or(comment.end_byte(), |n| n.end_byte())); + if continuous && next.is_some_and(|n| run_continues_to::(comment, &n, code)) { + return None; + } + let below = next.filter(|n| T::doc_target_start_row(n) == comment.end_row().saturating_add(1)); + let end = if !continuous { + RunEnd::ExcludedGap + } else if T::ends_doc_run(comment, code) { + RunEnd::Terminator + } else if next.is_none() { + RunEnd::EndOfScope + } else if below.is_none() && next.is_some_and(|n| n.start_row() > comment.end_row()) { + RunEnd::BlankLine + } else { + RunEnd::Token + }; + let mut run = collect_positional_prefix::(comment, code, ancestors, view); + run.next = next; + run.below = below.filter(|_| continuous); + run.end = end; + Some(run) +} + +fn collect_positional_prefix<'a, T: Checker>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, +) -> PositionalRun<'a> { + // bca: suppress(cognitive, halstead) -- one reverse state machine preserves clean rows, same-row comments, trailing rows and excluded boundaries. + positional_runs_collected::record(); + let mut run = PositionalRun { + members: vec![*comment], + next: None, + below: None, + code_before: None, + prefix_gap: false, + trailing_members: 0, + end: crate::documentation::streaming::positional::RunEnd::EndOfScope, + }; + let mut clean_members = 0; let mut row_first = *comment; - loop { - match before.next() { - // Another token on this row: a comment extends the row, and - // code before it makes every comment on the row a trailing one. - Some(prev) if prev.end_row() >= row_first.start_row() => { - if !T::is_comment(&prev) { - return first; - } - row_first = prev; - } - // A comment ending on the row above: this row is clean, and - // the run continues upward unless that comment ends a run. - Some(prev) - if T::is_comment(&prev) - && prev.end_row().saturating_add(1) == row_first.start_row() - && !T::ends_doc_run(&prev, code) => - { - first = Some(row_first); - row_first = prev; + let mut stopped = false; + for prev in ancestors.siblings_before(comment) { + positional_predecessors::record(); + if !view.covers(prev.start_byte()..row_first.end_byte()) { + run.prefix_gap = true; + stopped = true; + break; + } + if !T::is_comment(&prev) { + run.code_before = Some(prev); + if prev.end_row() >= row_first.start_row() { + run.trailing_members = run.members.len() - clean_members; } - _ => return Some(row_first), + stopped = true; + break; } + if !run_continues_to::(&prev, &row_first, code) { + run.code_before = Some(prev); + stopped = true; + break; + } + if prev.end_row() < row_first.start_row() { + clean_members = run.members.len(); + } + run.members.push(prev); + row_first = prev; + } + if !stopped && matches!(view, CandidateView::Source(_)) { + let start = if ancestors.depth() == Some(1) { + 0 + } else { + ancestors + .parent(comment) + .map_or(0, |parent| parent.start_byte()) + }; + run.prefix_gap = !view.covers(start..row_first.start_byte()); } + run.members.reverse(); + run } /// The trailing comment that heads `first`'s LDoc group, when `first` sits diff --git a/big-code-analysis-ast/src/lang_helpers/ruby.rs b/big-code-analysis-ast/src/lang_helpers/ruby.rs index 9675215b5..ee7849a1a 100644 --- a/big-code-analysis-ast/src/lang_helpers/ruby.rs +++ b/big-code-analysis-ast/src/lang_helpers/ruby.rs @@ -128,6 +128,23 @@ pub(crate) fn ruby_yard_reads<'a>( needs: YardScope, scope: &Node<'a>, ancestors: Ancestors<'a, '_>, +) -> bool { + yard_reads(needs, scope, ancestors, false) +} + +pub(crate) fn ruby_source_yard_reads<'a>( + needs: YardScope, + scope: &Node<'a>, + ancestors: Ancestors<'a, '_>, +) -> bool { + yard_reads(needs, scope, ancestors, true) +} + +fn yard_reads<'a>( + needs: YardScope, + scope: &Node<'a>, + ancestors: Ancestors<'a, '_>, + source: bool, ) -> bool { // Read upward, the rule is: the nearest namespace admits the // statement; a method body met first rejects it if it needs a @@ -142,11 +159,16 @@ pub(crate) fn ruby_yard_reads<'a>( let reads = ancestors.fold_down( scope, 0, - FoldLane::DocScope, + if source { + FoldLane::SourceDocScope + } else { + FoldLane::DocScope + }, BOTH, // Where YARD reads a doc comment, not whether a node opens a space: // each arm below that names a space opener is exempt for that. - |above, ancestor, _, _| match ancestor.kind_id().into() { + |above, ancestor, outer, _| match ancestor.kind_id().into() { + _ if source && crate::roles::ruby::closure::owns(ancestor, &[], outer) => 0, // role-bypass: allow(Container) — the file, where YARD reads Ruby::Program => BOTH, // Each opens a namespace only where one already reads it. For a diff --git a/big-code-analysis-ast/src/node/ancestors/folds.rs b/big-code-analysis-ast/src/node/ancestors/folds.rs index ce0617b00..48c1ec550 100644 --- a/big-code-analysis-ast/src/node/ancestors/folds.rs +++ b/big-code-analysis-ast/src/node/ancestors/folds.rs @@ -453,6 +453,8 @@ pub(crate) enum FoldLane { /// Ruby's YARD namespace. One lane serves both because a walk parses /// one language. DocScope, + /// Source YARD scope excludes call blocks retained by legacy metrics. + SourceDocScope, /// Python: the climb from a node through the parentheses above it to /// a bare string statement (#1610). BareStringClimb, @@ -479,7 +481,7 @@ pub(crate) enum FoldLane { impl FoldLane { /// How many lanes a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 11; + const COUNT: usize = 12; } // A lane past `COUNT` would index out of the array at run time, on the diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index ad7dce7e6..bd89a645e 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -1103,7 +1103,7 @@ impl Stats { self.sloc() ); // Every documentation row is a cloc row (#1597) — `add_comment_rows` - // bills both, `add_leading_doc_run` re-bills billed comment rows — + // bills both, `add_positional_comment` re-bills billed comment rows — // and MI's subtractions rely on it. Compared as sets, not counts: a // stray row would grow the union while leaving `dloc() <= cloc()`. #[cfg(debug_assertions)] diff --git a/src/metrics/loc/dloc.rs b/src/metrics/loc/dloc.rs index fc961d110..5f9f1b7a3 100644 --- a/src/metrics/loc/dloc.rs +++ b/src/metrics/loc/dloc.rs @@ -14,7 +14,7 @@ use super::min_or_zero; /// docstring are the constructs recorded here, and their rows are /// exactly the rows the same arms also record as comment lines, so /// `dloc() <= cloc()` holds by construction — `add_comment_rows` inserts -/// into both, and `add_leading_doc_run` (Go, Ruby, Lua), +/// into both, and `add_positional_comment` (Go, Ruby, Lua), /// `add_bound_doc_run` (the doc comments Rust, Java, Kotlin, Groovy, C#, /// PHP and the JS family attach to the declaration after them, #1613) /// and Python's diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 38aad8aeb..ef6113af0 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -5,6 +5,176 @@ use serde_json::{Value, json}; use crate::{LANG, Metric, MetricsOptions, Source, analyze}; +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +#[derive(Clone, Copy)] +struct PositionalRows<'a> { + loc: [u64; 6], + docs: &'a [usize], + code: &'a [usize], + comments: &'a [usize], + scans: usize, +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +#[allow(clippy::arithmetic_side_effects)] +fn positional_rows(lang: LANG, source: &[u8], expected: PositionalRows<'_>) { + use big_code_analysis_ast::documentation::streaming::positional::{ + evidence_built, positional_runs_collected, + }; + let before = evidence_built::observed(); + let scans = positional_runs_collected::observed(); + let intersections = big_code_analysis_ast::documentation::included_range_visits::observed(); + let space = analyze( + Source::new(lang, source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + expected.loc + ); + assert_eq!( + (0..source.len()) + .filter(|row| loc.dloc.lines.contains(*row)) + .collect::>(), + expected.docs + ); + assert_optional_rows( + loc, + source.len(), + &json!({"ploc_rows": expected.code, "cloc_rows": expected.comments}), + ); + assert_eq!(evidence_built::observed() - before, 0); + assert_eq!( + big_code_analysis_ast::documentation::included_range_visits::observed() - intersections, + 0 + ); + assert_eq!( + positional_runs_collected::observed() - scans, + expected.scans + ); + assert_eq!(space.spaces.len(), 1); + assert_eq!(space.spaces[0].metrics.loc.dloc(), 0); +} + +#[cfg(feature = "go")] +#[test] +fn documentation_go_positional_exact_rows() { + // Eight physical rows: package/function code, five comment rows, one source blank. + positional_rows( + LANG::Go, + b"package p\n// a\n//go:generate tool\n//\n/* b */ /* c */\n\n// d\nfunc F() {}", + PositionalRows { + loc: [8, 2, 0, 5, 1, 1], + docs: &[6], + code: &[0, 7], + comments: &[1, 2, 3, 4, 6], + scans: 2, + }, + ); + positional_rows( + LANG::Go, + b"package p\n// a\n//go:generate tool\n//\n/* b */ /* c */\nfunc F() {}", + PositionalRows { + loc: [6, 2, 0, 4, 0, 3], + docs: &[1, 3, 4], + code: &[0, 5], + comments: &[1, 2, 3, 4], + scans: 1, + }, + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn documentation_ruby_positional_exact_rows() { + positional_rows( + LANG::Ruby, + b"#!/ruby\n# frozen_string_literal: true\n# a\n#\n# b\ndef f; end", + PositionalRows { + loc: [6, 1, 1, 5, 0, 3], + docs: &[2, 3, 4], + code: &[5], + comments: &[0, 1, 2, 3, 4], + scans: 1, + }, + ); + positional_rows( + LANG::Ruby, + b"# a\n\n# b\ndef f; end", + PositionalRows { + loc: [4, 1, 1, 2, 1, 1], + docs: &[2], + code: &[3], + comments: &[0, 2], + scans: 2, + }, + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn documentation_ruby_block_legacy_rows_remain_in_physical_space() { + let source = b"foo do\n# audit\ndef f; end\nend"; + let space = analyze( + Source::new(LANG::Ruby, source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + assert_eq!( + [ + space.metrics.loc.sloc(), + space.metrics.loc.ploc(), + space.metrics.loc.lloc(), + space.metrics.loc.cloc(), + space.metrics.loc.blank(), + space.metrics.loc.dloc() + ], + [4, 3, 1, 1, 0, 1] + ); + assert_eq!(space.spaces.len(), 1); + let block = &space.spaces[0]; + assert_eq!(block.metrics.loc.dloc(), 1); + assert!(block.metrics.loc.dloc.lines.contains(1)); + assert_eq!(block.spaces.len(), 1); + assert_eq!(block.spaces[0].metrics.loc.dloc(), 0); +} + +#[cfg(feature = "lua")] +#[test] +fn documentation_lua_positional_exact_rows() { + positional_rows( + LANG::Lua, + b"module(\"m\")\n---a\n--\n-- b\nfunction f() end", + PositionalRows { + loc: [5, 2, 1, 3, 0, 3], + docs: &[1, 2, 3], + code: &[0, 4], + comments: &[1, 2, 3], + scans: 1, + }, + ); + positional_rows( + LANG::Lua, + b"module(\"m\")\n-- a\nfunction f() end", + PositionalRows { + loc: [3, 2, 1, 1, 0, 0], + docs: &[], + code: &[0, 2], + comments: &[1], + scans: 1, + }, + ); +} + #[cfg(all(feature = "java", feature = "rust"))] #[test] fn documentation_marker_stream_preserves_rows_without_source_materialization() { diff --git a/src/metrics/loc/go.rs b/src/metrics/loc/go.rs index 7dd7aba9e..4dc4a49a3 100644 --- a/src/metrics/loc/go.rs +++ b/src/metrics/loc/go.rs @@ -36,8 +36,7 @@ impl Loc for GoCode { add_multiline_string_ploc(node, ancestors, stats, start); } G::Comment => { - add_comment_lines::(node, code, ancestors, stats); - add_leading_doc_run::(node, code, ancestors, stats); + add_positional_comment::(node, code, ancestors, stats); } G::FallthroughStatement | G::BreakStatement diff --git a/src/metrics/loc/lua.rs b/src/metrics/loc/lua.rs index 4e1dce6ce..53fad3679 100644 --- a/src/metrics/loc/lua.rs +++ b/src/metrics/loc/lua.rs @@ -46,8 +46,7 @@ impl Loc for LuaCode { if ancestors.parent_has_kind(node, Lua::Comment as u16) => {} Lua::Comment => { - add_comment_lines::(node, code, ancestors, stats); - add_leading_doc_run::(node, code, ancestors, stats); + add_positional_comment::(node, code, ancestors, stats); } // Standalone assignment (`x = 1`). Skip when nested inside a local variable diff --git a/src/metrics/loc/ruby.rs b/src/metrics/loc/ruby.rs index d3a468b64..eeb329dae 100644 --- a/src/metrics/loc/ruby.rs +++ b/src/metrics/loc/ruby.rs @@ -28,8 +28,7 @@ impl Loc for RubyCode { match node.kind_id().into() { R::Program => {} R::Comment => { - add_comment_lines::(node, code, ancestors, stats); - add_leading_doc_run::(node, code, ancestors, stats); + add_positional_comment::(node, code, ancestors, stats); } // A Ruby string literal (`"…"` / `'…'` / `%q{…}`) or a heredoc // body can span several rows; credit every spanned row to PLOC to diff --git a/src/metrics/loc/shared.rs b/src/metrics/loc/shared.rs index e65d32dc1..09df0ae24 100644 --- a/src/metrics/loc/shared.rs +++ b/src/metrics/loc/shared.rs @@ -54,8 +54,9 @@ use super::continuation::BareRowIndex; use super::*; -use crate::lang_helpers::leading_doc_run; -use big_code_analysis_ast::documentation::streaming::{LegacyEvent, marker_comment}; +use big_code_analysis_ast::documentation::streaming::{ + CoverageKind, LegacyEvent, marker_comment, positional_comment, +}; #[inline] pub(crate) fn init(node: &Node, stats: &mut Stats, is_func_space: bool) -> usize { @@ -140,7 +141,7 @@ fn add_cloc_lines(stats: &mut Stats, start: usize, end: usize) { // `loc.dloc` reports, so `dloc() <= cloc()` holds by construction // (#1597). The callers are `add_comment_lines` below, Rust's // line-comment arm and Python's bare-string arms. The `dloc` set's two -// other writers, `add_leading_doc_run` and Python's documentation-string +// other writers, `add_positional_comment` and Python's documentation-string // and Sphinx-comment runs, only re-bill rows already billed here. pub(crate) fn add_comment_rows(stats: &mut Stats, start: usize, end: usize, documentation: bool) { add_cloc_lines(stats, start, end); @@ -153,18 +154,27 @@ pub(crate) fn add_comment_rows(stats: &mut Stats, start: usize, end: usize, docu // Documentation by position rather than by marker (Go, Ruby, Lua): bills // the comment run `node` ends as `dloc` when it sits directly above a // declaration the language documents, or its first member is a language's -// run opener (LDoc `---`, RDoc `##`, YARD `@!`). Called -// from the comment arm after `add_comment_lines`, so every row it credits -// is one a run member's own arm already billed to this space's cloc sets, -// and `dloc() <= cloc()` still holds (#1597). -pub(crate) fn add_leading_doc_run<'a, T: Checker>( +// run opener (LDoc `---`, RDoc `##`, YARD `@!`). The stream bills the +// current comment before emitting completed-run coverage, so every credited +// row is already in this physical space's cloc sets. +pub(crate) fn add_positional_comment<'a, T: Checker>( node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats, ) { - leading_doc_run::(node, code, ancestors, |first, last| { - stats.dloc.lines.insert_range(first, last); + positional_comment::(node, code, ancestors, |event| match event { + LegacyEvent::Comment { + node, by_placement, .. + } => add_comment_rows(stats, node.start_row(), node.end_row(), by_placement), + LegacyEvent::Coverage { + kind: CoverageKind::LeadingRun, + first, + last, + } => { + stats.dloc.lines.insert_range(first, last); + } + _ => {} }); } diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json new file mode 100644 index 000000000..2016d7e71 --- /dev/null +++ b/utils/documentation-positional-perturb.json @@ -0,0 +1,63 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], + "cases": [ + { + "name": "positional-final-member-deferral", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "if continuous && next.is_some_and(|n| run_continues_to::(comment, &n, code)) {", + "new": "if false && continuous && next.is_some_and(|n| run_continues_to::(comment, &n, code)) {", + "expect": ["documentation::streaming::positional::tests::go_completed_run_is_scanned_once", "documentation::streaming::positional::tests::ruby_completed_run_is_scanned_once", "documentation::streaming::positional::tests::lua_completed_run_is_scanned_once"] + }, + { + "name": "legacy-directive-exclusion", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "if !T::is_doc_run_directive(&member, code) {", + "new": "if true || !T::is_doc_run_directive(&member, code) {", + "expect": ["metrics::loc::documentation_tests::documentation_go_positional_exact_rows", "metrics::loc::documentation_tests::documentation_ruby_positional_exact_rows"] + }, + { + "name": "source-member-order", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "run.members.reverse();", + "new": "// mutation: leave the reverse scan reversed", + "expect": ["documentation::streaming::positional::tests::go_order_directives_and_candidate_are_independent"] + }, + { + "name": "lua-ordinary-comment-is-not-inference", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "Ok(None) if T::SOURCE_POSITIONAL_TARGETS && decision.target.is_some() => {", + "new": "Ok(None) if decision.target.is_some() => {", + "expect": ["documentation::streaming::positional::tests::lua_plain_marked_first_file_and_later_contexts"] + }, + { + "name": "source-directive-retention-is-lazy", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "if directive && !request.retain_directives {", + "new": "if false && directive && !request.retain_directives {", + "expect": ["documentation::streaming::positional::tests::go_order_directives_and_candidate_are_independent", "documentation::streaming::positional::tests::go_directive_only_evidence_is_lazy_and_not_prose"] + }, + { + "name": "ruby-source-and-legacy-scope-are-different-questions", + "file": "big-code-analysis-ast/src/lang_helpers/ruby.rs", + "old": "FoldLane::SourceDocScope", + "new": "FoldLane::DocScope", + "expect": ["documentation::streaming::positional::tests::ruby_source_and_legacy_scope_caches_disagree_in_both_orders"] + }, + { + "name": "marker-selected-composition-needs-prefix-gap", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "prefix_gap: collected.prefix_gap,", + "new": "prefix_gap: false,", + "expect": ["documentation::streaming::markers::regressions::selected_join_all_run_reports_missing_prefix_for_composition"] + }, + { + "name": "positional-selected-composition-needs-prefix-gap", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "prefix_gap: run.prefix_gap,", + "new": "prefix_gap: false,", + "expect": ["documentation::streaming::positional::tests::go_gaps_split_runs_before_selection_and_keep_composition_metadata", "documentation::streaming::positional::tests::ruby_gap_after_code_does_not_hide_incomplete_composition"] + } + ] +} From ad24b9132761c5fd68d1c94e9b34df88c925e0cf Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:01:44 -0800 Subject: [PATCH 029/221] test(ast): exercise cached positional scope discrimination --- .../src/documentation/streaming/positional/tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs index d2d84f7ed..62467bcf4 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs @@ -470,7 +470,9 @@ fn ruby_gap_after_code_does_not_hide_incomplete_composition() { #[cfg(feature = "ruby")] #[test] fn ruby_source_and_legacy_scope_caches_disagree_in_both_orders() { - let source = b"foo do\n# audit\ndef f; end\nend"; + // The conditional puts the call block above the immediate parent, so its + // different scope states occupy cached fold levels rather than fresh steps. + let source = b"foo do\nif true\n# audit\ndef f; end\nend\nend"; let parser = parse(LANG::Ruby, source); for source_first in [false, true] { let context = SourceContext::new(parser.ts_tree(), source); @@ -510,7 +512,7 @@ fn ruby_source_and_legacy_scope_caches_disagree_in_both_orders() { assert_eq!(result.len(), 1); assert_eq!(result[0].selection, RunSelection::Unattached); assert!(result[0].target.is_none()); - assert_eq!(credited, [(1, 1)]); + assert_eq!(credited, [(2, 2)]); } } From 6282d87e62001e841a4dd87ced64f7af153e93e7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:39:53 -0800 Subject: [PATCH 030/221] test(documentation): discriminate positional stream regressions --- .bca-baseline.toml | 2 +- .../streaming/positional/tests.rs | 34 +++++++++++++++++++ utils/documentation-positional-perturb.json | 28 +++++++++++++++ 3 files changed, 63 insertions(+), 1 deletion(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index fe7916aff..c786fc25d 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -281,7 +281,7 @@ value = 47971.63551728485 path = "big-code-analysis-ast/src/documentation/streaming/positional/tests.rs" qualified = "work" metric = "halstead.effort" -value = 53704.58403901065 +value = 73112.8706762203 [[entry]] path = "big-code-analysis-ast/src/getter.rs" diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs index 62467bcf4..3b0eec3cf 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs @@ -154,6 +154,12 @@ fn lua_plain_marked_first_file_and_later_contexts() { RunSelection::Opener(OpenerReason::FollowingItem), 27..43, ), + ("---\nfunction f() end", RunSelection::Unattached, 4..20), + ( + "module(\"m\")\n--- \nfunction f() end", + RunSelection::Unattached, + 17..33, + ), ] { let parser = parse(LANG::Lua, source.as_bytes()); let result = runs::(&parser, true, false); @@ -183,6 +189,19 @@ fn lua_plain_marked_first_file_and_later_contexts() { ], ); assert_eq!(result[0].end, RunEnd::EndOfScope); + let parser = parse(LANG::Lua, b"---module\n\n---later\nfunction f() end"); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 2); + assert_eq!( + result[0].selection, + RunSelection::Opener(OpenerReason::FirstFile) + ); + assert!(result[0].target.is_none()); + assert_eq!( + result[1].selection, + RunSelection::Opener(OpenerReason::FollowingItem) + ); + identity(result[1].target.unwrap(), "function_declaration", 20..36); } #[cfg(feature = "go")] @@ -385,17 +404,30 @@ fn work(prefix: &str, comment: &str, t let mut rows = Vec::new(); parser.root_node().act_on_node(&mut |node, ancestors| { if T::is_comment(node) { + let mut billed = false; super::super::positional_comment::( node, source.as_bytes(), ancestors, |event| { + if let super::super::LegacyEvent::Comment { node: current, .. } = event { + assert_eq!(current.id(), node.id()); + assert!(!billed, "each visit bills its comment once"); + billed = true; + } if let super::super::LegacyEvent::Coverage { kind, first, last } = event { + assert!(billed, "coverage follows the final comment's billing"); + assert_eq!( + node.start_row(), + width, + "only the final visit credits the run" + ); assert_eq!(kind, super::super::CoverageKind::LeadingRun); rows.push((first, last)); } }, ); + assert!(billed); } }); assert_eq!(rows, (1..=width).map(|row| (row, row)).collect::>()); @@ -591,6 +623,8 @@ fn go_missing_target_retains_uncertain_canonical_candidate() { Some(UnresolvedReason::GrammarBoundary) ); assert!(result[0].following.unwrap().node().has_error()); + assert_eq!(result[0].selection, RunSelection::FollowingTarget); + identity(result[0].target.unwrap(), "function_declaration", 19..29); assert_eq!(result[0].members.len(), 1); identity(result[0].members[0].node, "comment", 10..18); } diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json index 2016d7e71..20fb1472b 100644 --- a/utils/documentation-positional-perturb.json +++ b/utils/documentation-positional-perturb.json @@ -3,6 +3,34 @@ "runner": "cargo", "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], "cases": [ + { + "name": "legacy-comment-after-coverage", + "file": "big-code-analysis-ast/src/documentation/streaming.rs", + "old": " marker_comment::(node, code, ancestors, &mut sink);\n crate::lang_helpers::leading_doc_run::(node, code, ancestors, |first, last| {\n sink(LegacyEvent::Coverage {\n kind: CoverageKind::LeadingRun,\n first,\n last,\n });\n });", + "new": " crate::lang_helpers::leading_doc_run::(node, code, ancestors, |first, last| {\n sink(LegacyEvent::Coverage {\n kind: CoverageKind::LeadingRun,\n first,\n last,\n });\n });\n marker_comment::(node, code, ancestors, &mut sink);", + "expect": ["documentation::streaming::positional::tests::go_completed_run_is_scanned_once", "documentation::streaming::positional::tests::ruby_completed_run_is_scanned_once", "documentation::streaming::positional::tests::lua_completed_run_is_scanned_once"] + }, + { + "name": "source-drop-recovered-candidate", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": ".filter(|n| T::is_source_doc_target(n, source.bytes(), ancestors));", + "new": ".filter(|n| !n.has_error() && T::is_source_doc_target(n, source.bytes(), ancestors));", + "expect": ["documentation::streaming::positional::tests::go_missing_target_retains_uncertain_canonical_candidate"] + }, + { + "name": "source-lua-empty-opener-selects", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": "if !text.text {", + "new": "if false && !text.text {", + "expect": ["documentation::streaming::positional::tests::lua_plain_marked_first_file_and_later_contexts"] + }, + { + "name": "source-lua-forgets-earlier-file-block", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": "if opens_run\n", + "new": "if source.is_none() && opens_run\n", + "expect": ["documentation::streaming::positional::tests::lua_plain_marked_first_file_and_later_contexts"] + }, { "name": "positional-final-member-deferral", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", From 39c7d1a273700014abf4bbcf9deef128abccaee9 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:54:12 -0800 Subject: [PATCH 031/221] test(documentation): cover positional source context exclusions --- .../streaming/positional/tests.rs | 19 +++++++++++++++++ utils/documentation-positional-perturb.json | 21 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs index 3b0eec3cf..3fc8a26b9 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs @@ -155,6 +155,11 @@ fn lua_plain_marked_first_file_and_later_contexts() { 27..43, ), ("---\nfunction f() end", RunSelection::Unattached, 4..20), + ( + "---\n-- audit\nfunction f() end", + RunSelection::Opener(OpenerReason::FirstFile), + 13..29, + ), ( "module(\"m\")\n--- \nfunction f() end", RunSelection::Unattached, @@ -271,6 +276,8 @@ fn ruby_yard_scope_uses_actual_wrapper_context() { RunSelection::FollowingTarget, ), ("foo do\n# audit\ndef f; end\nend", RunSelection::Unattached), + ("foo do\n##\n# audit\nputs 1\nend", RunSelection::Unattached), + ("foo do\n# @!method ghost\nend", RunSelection::Unattached), ("def outer\n# audit\nX = 1\nend", RunSelection::Unattached), ( "if true\n# audit\ndef f; end\nend", @@ -383,6 +390,18 @@ fn lua_gap_never_fabricates_first_file_context() { assert!(result[0].prefix_gap); assert!(result[0].code_before.is_none()); assert_eq!(result[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); + let source = b"-- header\nXXXX\nmodule(\"m\")\n---audit\nfunction f() end"; + let parser = restricted(LANG::Lua, source, &[0..10, 15..source.len()]); + assert!(runs::(&parser, false, false).is_empty()); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 2); + let later = &result[1]; + assert!(!later.prefix_gap); + identity(later.code_before.unwrap(), "function_call", 15..26); + identity(later.target.unwrap(), "function_declaration", 36..52); + assert_eq!(later.selection, RunSelection::Unattached); + assert_eq!(later.uncertainty, Some(UnresolvedReason::ExcludedGap)); + members(later, &[(27..35, b"---audit", false)]); } #[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json index 20fb1472b..b3e6832fb 100644 --- a/utils/documentation-positional-perturb.json +++ b/utils/documentation-positional-perturb.json @@ -3,6 +3,27 @@ "runner": "cargo", "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], "cases": [ + { + "name": "ruby-source-opener-leaks-call-block-scope", + "file": "big-code-analysis-ast/src/checker/ruby.rs", + "old": "&& ruby_source_yard_reads(YardScope::Namespace, first, ancestors)", + "new": "&& ruby_yard_reads(YardScope::Namespace, first, ancestors)", + "expect": ["documentation::streaming::positional::tests::ruby_yard_scope_uses_actual_wrapper_context"] + }, + { + "name": "lua-first-file-scan-crosses-excluded-siblings", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": " if source.is_some_and(|source| !source.covers(sibling.start_byte()..earliest.end_byte())) {\n return Err(crate::documentation::UnresolvedReason::ExcludedGap);\n }\n if source.is_some_and(|source| {\n before\n .peek()\n .is_some_and(|above| !source.covers(above.start_byte()..sibling.end_byte()))\n }) {\n return Err(crate::documentation::UnresolvedReason::ExcludedGap);\n }\n", + "new": "", + "expect": ["documentation::streaming::positional::tests::lua_gap_never_fabricates_first_file_context"] + }, + { + "name": "lua-prose-only-in-opener-member", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": "if !text.text {", + "new": "if !{ let mut first_text = LdocText::default(); first_text.read(first, run.code); first_text.text } {", + "expect": ["documentation::streaming::positional::tests::lua_plain_marked_first_file_and_later_contexts"] + }, { "name": "legacy-comment-after-coverage", "file": "big-code-analysis-ast/src/documentation/streaming.rs", From 100b3070908bd5529e8ce58620fa48d5e83eff77 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:41:32 -0800 Subject: [PATCH 032/221] fix(documentation): preserve positional boundaries and source uncertainty --- .bca-baseline.toml | 36 ++- CHANGELOG.md | 3 +- big-code-analysis-ast/src/checker/ruby.rs | 5 +- .../src/documentation/streaming/markers.rs | 30 +- .../streaming/markers/regressions.rs | 2 + .../streaming/markers/regressions/suffix.rs | 123 +++++++ .../src/documentation/streaming/positional.rs | 104 ++++-- .../streaming/positional/tests.rs | 2 + .../streaming/positional/tests/remediation.rs | 299 ++++++++++++++++++ .../src/lang_helpers/doc_comment.rs | 100 +++++- .../src/lang_helpers/ruby.rs | 32 ++ src/metrics/loc/documentation_tests.rs | 4 +- utils/documentation-markers-perturb.json | 27 +- utils/documentation-positional-perturb.json | 60 +++- 14 files changed, 755 insertions(+), 72 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/streaming/markers/regressions/suffix.rs create mode 100644 big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs diff --git a/.bca-baseline.toml b/.bca-baseline.toml index c786fc25d..db23aeb33 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -257,7 +257,7 @@ value = 6.0 path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" qualified = "RunSelection<'t>::select" metric = "halstead.effort" -value = 55859.38834242588 +value = 59655.33539489184 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" @@ -265,17 +265,29 @@ qualified = "RunSelection<'t>::select" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "line_spelling_end" +metric = "halstead.effort" +value = 48591.21083121782 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers/regressions/suffix.rs" +qualified = "check_suffix" +metric = "halstead.effort" +value = 57170.887340554174 + [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" qualified = "SourceDecision<'t>::new" metric = "halstead.effort" -value = 48196.811018362634 +value = 53278.06215664464 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" qualified = "source_comment" metric = "halstead.effort" -value = 47971.63551728485 +value = 53469.151178029744 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/positional/tests.rs" @@ -323,7 +335,7 @@ value = 101217.532578918 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "" metric = "loc.ploc" -value = 626.0 +value = 690.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -361,6 +373,12 @@ qualified = "collect_stretch" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "exhausted_stretch" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "joined_run" @@ -371,7 +389,7 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "positional_run" metric = "halstead.effort" -value = 49504.66878343322 +value = 58580.287928857055 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -383,7 +401,7 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "stretch_end" metric = "halstead.effort" -value = 63070.7256524501 +value = 73719.8111279588 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -391,6 +409,12 @@ qualified = "stretch_end" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "suffix_gap" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/elixir_decisions.rs" qualified = "elixir_pair_section" diff --git a/CHANGELOG.md b/CHANGELOG.md index ef6ed321f..777d06b4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,8 @@ for historical reference. - Added unstable AST positional-run evidence for Go, Ruby and Lua, including ordered comments, directive members, candidate targets and opener reasons. - Marker and positional runs retain excluded-prefix composition metadata. (#1659) + Marker and positional runs retain excluded-prefix and suffix composition + metadata. Legacy positional coverage streams without buffering members. (#1659) - Added unstable AST-crate source-marker `Checker` hooks and streaming requests that retain selection, source pieces and attachment uncertainty. The separate diff --git a/big-code-analysis-ast/src/checker/ruby.rs b/big-code-analysis-ast/src/checker/ruby.rs index 8505f9950..07ed118d1 100644 --- a/big-code-analysis-ast/src/checker/ruby.rs +++ b/big-code-analysis-ast/src/checker/ruby.rs @@ -106,7 +106,10 @@ impl Checker for RubyCode { .members .first() .filter(|first| { - crate::roles::ruby::doc_run_opener::owns(first, run.code, ancestors) + (crate::roles::ruby::doc_run_opener::owns(first, run.code, ancestors) + || run.members.iter().skip(1).any(|member| { + crate::lang_helpers::ruby::source_yard_directive(member, run.code) + })) && ruby_source_yard_reads(YardScope::Namespace, first, ancestors) }) .map(|_| crate::documentation::streaming::positional::OpenerReason::Explicit)) diff --git a/big-code-analysis-ast/src/documentation/streaming/markers.rs b/big-code-analysis-ast/src/documentation/streaming/markers.rs index a1a9ee27c..8c05ce810 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers.rs @@ -95,6 +95,9 @@ pub struct MarkerRun<'s> { /// Excluded source precedes this stretch. Composition may be incomplete even /// when only selected members were requested and their attachment is known. pub prefix_gap: bool, + /// Excluded source remains after the last examined sibling. Local or + /// gathered selection can be known while composition remains incomplete. + pub suffix_gap: bool, } /// One physical source marker or uncertain comment and its selection result. @@ -131,6 +134,7 @@ struct RunSelection<'t> { gatherer: Option>, bound: Option>, gap: bool, + suffix_gap: bool, prefix_gap_row: Option, } @@ -177,6 +181,7 @@ impl<'t> RunSelection<'t> { gatherer: None, bound: Some(bound), gap: false, + suffix_gap: false, prefix_gap_row, }; } @@ -193,6 +198,7 @@ impl<'t> RunSelection<'t> { gatherer, bound: None, gap: matches!(end, StretchEnd::ExcludedGap), + suffix_gap: matches!(end, StretchEnd::SuffixGap), prefix_gap_row: None, } } @@ -270,7 +276,10 @@ impl<'t> RunSelection<'t> { }; let mut member = member(request.context, node, selection, placement)?; member.uncertainty = T::source_doc_uncertainty(node, code, ancestors); - if forward && ((self.gap && !kept) || self.prefix_gap_row == Some(node.start_row())) { + if self.suffix_gap + || (forward + && ((self.gap && !kept) || self.prefix_gap_row == Some(node.start_row()))) + { member.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); } members.push(member); @@ -318,8 +327,10 @@ pub fn source_comment<'s, T: Checker>( if matches!(end, StretchEnd::Undecided) { return Ok(()); } - if matches!(end, StretchEnd::Elsewhere | StretchEnd::ExcludedGap) - && !request.retain_unbound + if matches!( + end, + StretchEnd::Elsewhere | StretchEnd::ExcludedGap | StretchEnd::SuffixGap + ) && !request.retain_unbound && !T::SOURCE_LOCAL_DOCS && binding.gathers.is_none() { @@ -341,6 +352,7 @@ pub fn source_comment<'s, T: Checker>( containing: ancestors.parent(comment).map(canonical).transpose()?, code_before: code_before.map(canonical).transpose()?, prefix_gap: collected.prefix_gap, + suffix_gap: selection.suffix_gap, }); } Ok(()) @@ -372,21 +384,21 @@ fn member<'s>( pub(super) fn line_spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { let code = context.bytes(); let end = node.end_byte(); - let lf = if code.get(end - 1) == Some(&b'\n') { + let lf = if context.covers(end - 1..end) && code.get(end - 1) == Some(&b'\n') { end - 1 } else { end }; - if code.get(lf) == Some(&b'\n') && context.covers(lf..lf + 1) { - if code.get(lf - 1) == Some(&b'\r') && context.covers(lf - 1..lf + 1) { + if context.covers(lf..lf + 1) && code.get(lf) == Some(&b'\n') { + if context.covers(lf - 1..lf + 1) && code.get(lf - 1) == Some(&b'\r') { return lf - 1; } return lf; } // Some grammars exclude CR from the node even when no included LF follows it. - if code.get(end) == Some(&b'\r') - && context.covers(end..end + 1) - && !(code.get(end + 1) == Some(&b'\n') && context.covers(end + 1..end + 2)) + if context.covers(end..end + 1) + && code.get(end) == Some(&b'\r') + && !(context.covers(end + 1..end + 2) && code.get(end + 1) == Some(&b'\n')) { return end + 1; } diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs index 3949ceaa2..3d59729a5 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs @@ -5,6 +5,8 @@ use crate::documentation::SourcePiece; use crate::{AnyParser, LANG, Search, documentation::UnresolvedReason}; use std::ops::Range; +mod suffix; + #[cfg(any( feature = "java", feature = "rust", diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions/suffix.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions/suffix.rs new file mode 100644 index 000000000..683539e25 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions/suffix.rs @@ -0,0 +1,123 @@ +use super::*; + +#[cfg(any(feature = "rust", feature = "java", feature = "c"))] +fn check_suffix( + source: &[u8], + end: usize, + selection: MarkerSelection, +) { + for included_end in [end - 1, end] { + let parser = restricted(T::lang(), source, &[0..included_end]); + let truncated = + AnyParser::parse(T::lang(), source[..included_end].to_vec(), None, None).unwrap(); + for retain in [false, true] { + let result = runs::(&parser, retain); + let control = runs::(&truncated, retain); + let count = usize::from(retain || selection == MarkerSelection::Selected); + assert_eq!(result.len(), count); + assert_eq!(control.len(), count); + if count == 0 { + continue; + } + let run = &result[0]; + assert!(run.suffix_gap); + assert!(!control[0].suffix_gap); + assert!(run.target.is_none()); + assert_eq!(run.members.len(), 1); + assert_eq!(run.members[0].selection, selection); + assert_eq!( + run.members[0].uncertainty, + Some(UnresolvedReason::ExcludedGap) + ); + assert_eq!(control[0].members[0].uncertainty, None); + assert_eq!( + run.members[0].source.pieces()[0].bytes(), + control[0].members[0].source.pieces()[0].bytes() + ); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn rust_local_selection_keeps_suffix_composition_gap() { + check_suffix::(b"//! audit\nfn f() {}", 10, MarkerSelection::Selected); +} +#[cfg(feature = "java")] +#[test] +fn java_unattached_exhaustion_keeps_unknown_suffix() { + check_suffix::(b"/// audit\nclass C {}", 10, MarkerSelection::Unattached); +} +#[cfg(feature = "c")] +#[test] +fn c_gatherer_keeps_selected_suffix_evidence() { + check_suffix::(b"/** @file */\nint x;", 13, MarkerSelection::Selected); +} + +#[cfg(feature = "c")] +#[test] +fn gathered_markers_remain_selected_with_incomplete_suffix() { + let source = b"/** prose */\n/** @file */\nint x;"; + let parser = restricted(LANG::C, source, &[0..25]); + for retain in [false, true] { + let result = runs::(&parser, retain); + assert_eq!(result.len(), 1); + let run = &result[0]; + assert!(run.suffix_gap); + assert!(run.target.is_none()); + assert_eq!(run.members.len(), 2); + assert!(matches!( + run.members[0].placement, + MarkerPlacement::Gathered(_) + )); + assert!(matches!( + run.members[1].placement, + MarkerPlacement::Gatherer + )); + for (member, span) in run.members.iter().zip([0..12, 13..25]) { + assert_eq!(member.node.node().byte_range(), span); + assert_eq!(member.source.pieces()[0].range(), span); + assert_eq!(member.selection, MarkerSelection::Selected); + assert_eq!(member.uncertainty, Some(UnresolvedReason::ExcludedGap)); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn marker_exhaustion_checks_after_final_skipped_trivia() { + let source = b"//! audit\n#[allow(dead_code)]\nfn f() {}"; + let end = 29; + let parser = restricted(LANG::Rust, source, &[0..end]); + for retain in [false, true] { + let result = runs::(&parser, retain); + assert_eq!(result.len(), 1); + assert!(result[0].suffix_gap); + assert!(result[0].target.is_none()); + assert_eq!(result[0].members.len(), 1); + assert_eq!(result[0].members[0].selection, MarkerSelection::Selected); + assert_eq!( + result[0].members[0].uncertainty, + Some(UnresolvedReason::ExcludedGap) + ); + } + // The excluded attribute gap is not the exhaustion tail: the last examined + // sibling is the attribute, whose included end reaches actual EOF here. + let truncated = AnyParser::parse(LANG::Rust, source[..end].to_vec(), None, None).unwrap(); + let result = runs::(&truncated, false); + assert_eq!(result.len(), 1); + assert!(!result[0].suffix_gap); + assert_eq!(result[0].members[0].uncertainty, None); +} + +#[cfg(feature = "rust")] +#[test] +fn nested_marker_exhaustion_uses_lexical_scope_not_file_tail() { + let source = b"mod m { //! audit\n}\nXXXX"; + let parser = restricted(LANG::Rust, source, &[0..20]); + let result = runs::(&parser, false); + assert_eq!(result.len(), 1); + assert!(!result[0].suffix_gap); + assert_eq!(result[0].members[0].selection, MarkerSelection::Selected); + assert_eq!(result[0].members[0].uncertainty, None); +} diff --git a/big-code-analysis-ast/src/documentation/streaming/positional.rs b/big-code-analysis-ast/src/documentation/streaming/positional.rs index bce41e895..46f1bff52 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional.rs @@ -6,7 +6,7 @@ use crate::{Ancestors, Checker, Node}; use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces, UnresolvedReason}; use super::markers::CandidateView; -pub use doc_comment::{positional_predecessors, positional_runs_collected}; +pub use doc_comment::{members_materialized, positional_predecessors, positional_runs_collected}; crate::observation::counter!(evidence_built, cfg(any(test, feature = "test-support"))); /// Why the final comment cannot defer to another member. @@ -18,7 +18,8 @@ pub enum RunEnd { BlankLine, /// The language's long-comment terminator ends the run. Terminator, - /// No further sibling exists in this containing scope. + /// No further parsed sibling exists. `SourceRun::suffix_gap` distinguishes + /// unknown excluded source from a complete scope ending. EndOfScope, /// Excluded bytes interrupt the run or the following token. ExcludedGap, @@ -92,6 +93,9 @@ pub struct SourceRun<'s> { pub code_before: Option>, /// Excluded source before this run may make composition incomplete. pub prefix_gap: bool, + /// Excluded source remains after parsed sibling exhaustion. Independently + /// known selection survives, but composition or attachment is incomplete. + pub suffix_gap: bool, /// Why the run ended. pub end: RunEnd, /// An excluded gap or recovery boundary prevented a certain decision. @@ -137,11 +141,12 @@ pub fn source_comment<'s, T: Checker>( ) else { return Ok(()); }; - let decision = SourceDecision::new::(&run, ancestors, request.context); + let collected = SourceMembers::collect(&run, ancestors, request.context); + let decision = SourceDecision::new::(&run, &collected, ancestors, request.context); if decision.selection == RunSelection::Unattached && !request.retain_unbound { return Ok(()); } - let members = source_members::(&run, decision.selection, request)?; + let members = source_members::(&collected, decision.selection, request)?; if !members.is_empty() { let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); (request.sink)(SourceRun { @@ -152,6 +157,7 @@ pub fn source_comment<'s, T: Checker>( containing: ancestors.parent(comment).map(canonical).transpose()?, code_before: run.code_before.map(canonical).transpose()?, prefix_gap: run.prefix_gap, + suffix_gap: run.suffix_gap, end: run.end, uncertainty: decision.uncertainty, }); @@ -165,29 +171,78 @@ struct SourceDecision<'t> { uncertainty: Option, } +struct SourceMembers<'t> { + nodes: Vec>, + eligible_start: usize, + prefix_placement_gap: bool, +} + +impl<'t> SourceMembers<'t> { + fn collect( + run: &PositionalRun<'t>, + ancestors: Ancestors<'t, '_>, + source: &SourceContext<'t>, + ) -> Self { + let nodes = run.materialize(ancestors); + let mut eligible_start = run.first_eligible.map_or(nodes.len(), |first| { + nodes.partition_point(|node| node.start_byte() < first.start_byte()) + }); + let prefix_placement_gap = run.prefix_gap + && nodes + .get(eligible_start) + .is_some_and(|first| !complete_row_prefix(first, source)); + if prefix_placement_gap { + let row = nodes[eligible_start].start_row(); + eligible_start += nodes[eligible_start..] + .iter() + .take_while(|node| node.start_row() == row) + .count(); + } + Self { + nodes, + eligible_start, + prefix_placement_gap, + } + } +} + +fn complete_row_prefix(first: &Node<'_>, source: &SourceContext<'_>) -> bool { + let start = first + .start_byte() + .saturating_sub(first.as_tree_sitter().start_position().column); + source.covers(start..first.start_byte()) + && source.bytes()[start..first.start_byte()] + .iter() + .all(u8::is_ascii_whitespace) +} + impl<'t> SourceDecision<'t> { fn new( run: &PositionalRun<'t>, + collected: &SourceMembers<'t>, ancestors: Ancestors<'t, '_>, source: &SourceContext<'t>, ) -> Self { let mut decision = Self { selection: RunSelection::Unattached, target: None, - uncertainty: None, + uncertainty: (run.suffix_gap || collected.prefix_placement_gap) + .then_some(UnresolvedReason::ExcludedGap), }; - if !continuous_placement(run, source) { + if run.end == RunEnd::ExcludedGap + || !source.covers(run.first.start_byte()..run.last.end_byte()) + { decision.uncertainty = Some(UnresolvedReason::ExcludedGap); return decision; } + if collected.eligible_start == collected.nodes.len() { + return decision; + } decision.target = run .below .filter(|n| T::is_source_doc_target(n, source.bytes(), ancestors)); - if run.trailing_members == run.members.len() { - return decision; - } let context = RunContext { - members: &run.members[run.trailing_members..], + members: &collected.nodes[collected.eligible_start..], below: run.below, code: source.bytes(), source: Some(source), @@ -210,34 +265,15 @@ impl<'t> SourceDecision<'t> { } } -fn continuous_placement(run: &PositionalRun<'_>, source: &SourceContext<'_>) -> bool { - let Some(first) = run.members.first() else { - return false; - }; - if run.end == RunEnd::ExcludedGap || !source.covers(first.start_byte()..first.end_byte()) { - return false; - } - if !run.prefix_gap { - return true; - } - let start = first - .start_byte() - .saturating_sub(first.as_tree_sitter().start_position().column); - source.covers(start..first.start_byte()) - && source.bytes()[start..first.start_byte()] - .iter() - .all(u8::is_ascii_whitespace) -} - fn source_members<'s, T: Checker>( - run: &PositionalRun<'s>, + collected: &SourceMembers<'s>, selection: RunSelection, request: &SourceRequest<'_, 's>, ) -> Result>, SourceError> { let mut members = Vec::new(); - for (index, node) in run.members.iter().enumerate() { - let trailing = index < run.trailing_members; - if trailing && !request.retain_unbound { + for (index, node) in collected.nodes.iter().enumerate() { + let ineligible = index < collected.eligible_start; + if ineligible && !request.retain_unbound { continue; } let directive = request.context.covers(node.start_byte()..node.end_byte()) @@ -252,7 +288,7 @@ fn source_members<'s, T: Checker>( .context .pieces(node.start_byte()..spelling_end(request.context, node))?, directive, - selected: !trailing && !directive && selection != RunSelection::Unattached, + selected: !ineligible && !directive && selection != RunSelection::Unattached, }); } Ok(members) diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs index 3fc8a26b9..d5596e896 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs @@ -4,6 +4,8 @@ use super::*; use crate::{AnyParser, LANG, Search}; use std::ops::Range; +mod remediation; + #[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] fn runs(parser: &AnyParser, retain: bool, directives: bool) -> Vec> { let context = SourceContext::new(parser.ts_tree(), parser.code()); diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs new file mode 100644 index 000000000..1f8f12557 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs @@ -0,0 +1,299 @@ +use super::*; + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn allocation_free( + prefix: &str, + comment: &str, + target: &str, +) { + for source in [ + format!("{prefix}{comment}{target}"), + format!("{prefix}{comment}"), + format!("{prefix}{target} {comment}"), + format!("{prefix}{}{target}", format!("{comment}\n").repeat(64)), + format!("{prefix}{}{target}", comment.repeat(256)), + ] { + let parser = parse(T::lang(), source.as_bytes()); + let before = members_materialized::observed(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + super::super::super::positional_comment::( + node, + source.as_bytes(), + ancestors, + |_| {}, + ); + } + }); + assert_eq!(members_materialized::observed() - before, 0, "{source}"); + let expected = parser.root_node().preorder().filter(T::is_comment).count(); + assert!(expected > 0); + let source_runs = runs::(&parser, true, true); + assert!(!source_runs.is_empty()); + // Every actual source node-buffer push is counted once, including rejected runs. + assert_eq!( + members_materialized::observed() - before, + expected, + "{source}" + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_legacy_materializes_no_members() { + allocation_free::("package p\n", "// a\n", "func f() {}"); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_legacy_materializes_no_members() { + allocation_free::("X = 1\n", "# a\n", "def f; end"); +} +#[cfg(feature = "lua")] +#[test] +fn lua_legacy_materializes_no_members() { + allocation_free::("module(\"m\")\n", "---a\n", "function f() end"); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn suffix( + source: &[u8], + end: usize, + selected: RunSelection, +) { + for retained_end in [end - 1, end] { + let restricted = restricted(T::lang(), source, &[0..retained_end]); + let truncated = parse(T::lang(), &source[..retained_end]); + for retain in [false, true] { + let restricted_runs = runs::(&restricted, retain, true); + let truncated_runs = runs::(&truncated, retain, true); + let count = usize::from(retain || selected != RunSelection::Unattached); + assert_eq!(restricted_runs.len(), count); + assert_eq!(truncated_runs.len(), count); + if count == 0 { + continue; + } + let unknown = &restricted_runs[0]; + let known = &truncated_runs[0]; + assert!(unknown.suffix_gap); + assert!(!known.suffix_gap); + assert_eq!(unknown.selection, selected); + assert_eq!(known.selection, selected); + assert_eq!(unknown.uncertainty, Some(UnresolvedReason::ExcludedGap)); + assert_eq!(known.uncertainty, None); + assert_eq!(unknown.end, RunEnd::EndOfScope); + assert!(unknown.following.is_none()); + assert!(unknown.target.is_none()); + assert_eq!(unknown.members.len(), 1); + let start = source[..end - 1] + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(0, |at| at + 1); + identity(unknown.members[0].node, "comment", start..end - 1); + assert_eq!( + unknown.members[0].source.pieces()[0].range(), + start..end - 1 + ); + assert_eq!( + unknown.members[0].source.pieces()[0].bytes(), + known.members[0].source.pieces()[0].bytes() + ); + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_exhaustion_reports_unknown_suffix() { + suffix::( + b"package p\n// audit\nfunc f() {}", + 19, + RunSelection::Unattached, + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_exhaustion_preserves_explicit_selection() { + suffix::(b"# audit\ndef f; end", 8, RunSelection::Unattached); + suffix::( + b"# @!method ghost\ndef f; end", + 17, + RunSelection::Opener(OpenerReason::Explicit), + ); +} +#[cfg(feature = "lua")] +#[test] +fn lua_exhaustion_preserves_known_file_and_tagged_selection() { + suffix::( + b"--- audit\nfunction f() end", + 10, + RunSelection::Opener(OpenerReason::FirstFile), + ); + suffix::( + b"module(\"m\")\n---@function ghost\nfunction f() end", + 31, + RunSelection::Opener(OpenerReason::Tagged), + ); +} + +#[cfg(any(feature = "go", feature = "ruby"))] +fn partial_prefix( + source: &[u8], + expected_members: &[Range], + target: &(&str, Range), +) { + let parser = restricted(T::lang(), source, &[2..source.len()]); + assert!(!parser.ts_tree().root_node().has_error()); + for retain in [false, true] { + let result = runs::(&parser, retain, true); + assert_eq!(result.len(), 1); + let run = &result[0]; + assert_eq!(run.selection, RunSelection::FollowingTarget); + assert!(run.prefix_gap); + assert!(run.code_before.is_none()); + assert_eq!(run.uncertainty, Some(UnresolvedReason::ExcludedGap)); + identity(run.target.unwrap(), target.0, target.1.clone()); + let expected = if retain { + expected_members + } else { + &expected_members[expected_members.len() - 1..] + }; + assert_eq!(run.members.len(), expected.len()); + for (index, (member, range)) in run.members.iter().zip(expected).enumerate() { + identity(member.node, "comment", range.clone()); + assert_eq!(member.selected, index == expected.len() - 1); + assert_eq!(member.source.pieces()[0].bytes(), &source[range.clone()]); + } + } + let twin = parse(T::lang(), &source[2..]); + let result = runs::(&twin, false, true); + assert_eq!(result.len(), 1); + assert_eq!(result[0].members.len(), expected_members.len()); + assert!(result[0].members.iter().all(|member| member.selected)); + assert_eq!(result[0].uncertainty, None); +} + +#[cfg(feature = "go")] +#[test] +fn go_unknown_first_row_keeps_clean_suffix() { + partial_prefix::( + b"XX// a\n// b\npackage p", + &[2..6, 7..11], + &("package_clause", 12..21), + ); + partial_prefix::( + b"XX/*a*/ /*b*/\n// c\npackage p", + &[2..7, 8..13, 14..18], + &("package_clause", 19..28), + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_unknown_first_row_keeps_clean_suffix() { + partial_prefix::( + b"XX# a\n# b\ndef f; end", + &[2..5, 6..9], + &("method", 10..20), + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn yard_later_directives_follow_trivia_or_prose() { + for (prefix, directive) in [ + ("#!/ruby\n", true), + ("# prose\n", false), + ("# frozen_string_literal: true\n", true), + ] { + let source = format!("{prefix}# @!method ghost\n# audit\n"); + let parser = parse(LANG::Ruby, source.as_bytes()); + for retain in [false, true] { + let result = runs::(&parser, retain, true); + assert_eq!(result.len(), 1); + let run = &result[0]; + assert_eq!(run.selection, RunSelection::Opener(OpenerReason::Explicit)); + assert!(run.target.is_none()); + assert_eq!(run.uncertainty, None); + assert_eq!(run.members.len(), 3); + assert_eq!(run.members[0].directive, directive); + assert_eq!(run.members[0].selected, !directive); + identity( + run.members[1].node, + "comment", + prefix.len()..prefix.len() + 16, + ); + assert_eq!( + run.members[1].source.pieces()[0].bytes(), + b"# @!method ghost" + ); + } + let mut rows = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if crate::RubyCode::is_comment(node) { + super::super::super::positional_comment::( + node, + source.as_bytes(), + ancestors, + |event| { + if let super::super::super::LegacyEvent::Coverage { first, last, .. } = + event + { + rows.push((first, last)); + } + }, + ); + } + }); + assert!(rows.is_empty(), "legacy remains first-member only"); + } +} + +#[cfg(feature = "ruby")] +#[test] +fn yard_later_directive_cleanup_is_bounded() { + for (line, selected) in [ + ("# @!method ghost", true), + ("##\t@!method ghost", true), + ("# @!a.b_2. ghost", true), + ("# @!", false), + ("# @!method-bad", false), + ("# @!a..b", false), + ("# @!method ghost", false), + ("#\t\t@!method ghost", false), + ("# prose @!method ghost", false), + ("##", false), + ] { + let source = format!("# prose\n{line}\n"); + let parser = parse(LANG::Ruby, source.as_bytes()); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), usize::from(selected), "{line}"); + } + for source in [ + b"X = 1 # @!method ghost\n# prose".as_slice(), + b"foo do\n# prose\n# @!method ghost\nend", + ] { + let parser = parse(LANG::Ruby, source); + assert!(runs::(&parser, false, false).is_empty()); + } + let source = b"XX# @!method ghost\n# prose"; + let parser = restricted(LANG::Ruby, source, &[2..source.len()]); + assert!(runs::(&parser, false, false).is_empty()); + let result = runs::(&parser, true, false); + assert_eq!(result.len(), 1); + assert!(result[0].members.iter().all(|member| !member.selected)); +} + +#[cfg(feature = "ruby")] +#[test] +fn nested_positional_exhaustion_does_not_read_the_file_tail() { + let source = b"class C\n# @!method ghost\nend\nXXXX"; + let parser = restricted(LANG::Ruby, source, &[0..28]); + let result = runs::(&parser, false, false); + assert_eq!(result.len(), 1); + assert!(!result[0].suffix_gap); + assert_eq!( + result[0].selection, + RunSelection::Opener(OpenerReason::Explicit) + ); + assert_eq!(result[0].uncertainty, None); +} diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 7cec10437..2806d147c 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -430,6 +430,8 @@ pub(crate) enum StretchEnd<'a> { Elsewhere, /// Excluded bytes interrupt the source stretch or target spelling. ExcludedGap, + /// Parsed siblings are exhausted but excluded source remains in this scope. + SuffixGap, } /// Where the stretch `comment` belongs to ends. The scan stops at the @@ -448,7 +450,7 @@ pub(crate) fn stretch_end<'a, T: Checker>( let mut after = ancestors.siblings_after(comment).peekable(); let Some(&next) = after.peek() else { return if view.covers(comment.start_byte()..comment.end_byte()) { - StretchEnd::Elsewhere + exhausted_stretch(comment, comment.end_byte(), code, ancestors, view) } else { StretchEnd::ExcludedGap }; @@ -472,10 +474,45 @@ pub(crate) fn stretch_end<'a, T: Checker>( { StretchEnd::AtTarget { next, target } } + None => exhausted_stretch(comment, boundary, code, ancestors, view), _ => StretchEnd::Elsewhere, } } +fn exhausted_stretch<'a>( + comment: &Node<'a>, + last_examined_end: usize, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, +) -> StretchEnd<'a> { + if suffix_gap(comment, last_examined_end, code, ancestors, view) { + StretchEnd::SuffixGap + } else { + StretchEnd::Elsewhere + } +} + +fn suffix_gap<'a>( + comment: &Node<'a>, + last_examined_end: usize, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, +) -> bool { + if matches!(view, CandidateView::Legacy) { + return false; + } + let scope_end = if ancestors.depth().is_some_and(|depth| depth <= 1) { + code.len() + } else { + ancestors + .parent(comment) + .map_or(code.len(), |scope| scope.end_byte()) + }; + !view.covers(last_examined_end..scope_end) +} + /// The stretch `comment` ends, in source order, and the sibling before it: /// `comment` and the siblings before it that are comments or skipped, /// read past the parse errors [`stretch_end`] reads past with the same @@ -752,17 +789,17 @@ pub fn leading_doc_run<'a, T: Checker>( let Some(run) = positional_run::(comment, code, ancestors, CandidateView::Legacy) else { return; }; - let Some(first) = run.members.get(run.trailing_members) else { + let Some(first) = run.first_eligible else { return; }; let documents = run .below .is_some_and(|n| T::is_doc_target(&n, code, ancestors)) - || T::is_doc_run_opener(first, run.below.as_ref(), code, ancestors); + || T::is_doc_run_opener(&first, run.below.as_ref(), code, ancestors); if !documents { return; } - for member in run.members.into_iter().skip(run.trailing_members) { + for member in run.members_from(first, ancestors) { if !T::is_doc_run_directive(&member, code) { credit(member.start_row(), member.end_row()); } @@ -783,18 +820,42 @@ pub(crate) fn run_continues_to(comment: &Node, next: &Node, code: &[ && !T::ends_doc_run(comment, code))) } -/// Ordered members and boundaries from the completed positional run. Trailing -/// rows are rejected for billing but retained when source evidence is requested. +/// Constant-sized boundaries from the completed positional run. Members stream +/// forward only after legacy acceptance, or into source-only storage. pub(crate) struct PositionalRun<'a> { - pub(crate) members: Vec>, + pub(crate) first: Node<'a>, + pub(crate) last: Node<'a>, + pub(crate) first_eligible: Option>, pub(crate) next: Option>, pub(crate) below: Option>, pub(crate) code_before: Option>, pub(crate) prefix_gap: bool, - pub(crate) trailing_members: usize, + pub(crate) suffix_gap: bool, pub(crate) end: crate::documentation::streaming::positional::RunEnd, } +impl<'a> PositionalRun<'a> { + pub(crate) fn materialize(&self, ancestors: Ancestors<'a, '_>) -> Vec> { + let mut members = Vec::new(); + for member in self.members_from(self.first, ancestors) { + members_materialized::record(); + members.push(member); + } + members + } + + pub(crate) fn members_from<'c>( + &self, + first: Node<'a>, + ancestors: Ancestors<'a, 'c>, + ) -> impl Iterator> + use<'a, 'c> { + let last_start = self.last.start_byte(); + std::iter::once(first) + .chain(ancestors.siblings_after(&first)) + .take_while(move |member| member.start_byte() <= last_start) + } +} + crate::observation::counter!( positional_runs_collected, cfg(any(test, feature = "test-support")) @@ -803,6 +864,11 @@ crate::observation::counter!( positional_predecessors, cfg(any(test, feature = "test-support")) ); +// Counts actual node-buffer pushes; legacy boundary and coverage paths never call it. +crate::observation::counter!( + members_materialized, + cfg(any(test, feature = "test-support")) +); pub(crate) fn positional_run<'a, T: Checker>( comment: &Node<'a>, @@ -832,6 +898,8 @@ pub(crate) fn positional_run<'a, T: Checker>( let mut run = collect_positional_prefix::(comment, code, ancestors, view); run.next = next; run.below = below.filter(|_| continuous); + run.suffix_gap = + next.is_none() && suffix_gap(comment, comment.end_byte(), code, ancestors, view); run.end = end; Some(run) } @@ -845,15 +913,17 @@ fn collect_positional_prefix<'a, T: Checker>( // bca: suppress(cognitive, halstead) -- one reverse state machine preserves clean rows, same-row comments, trailing rows and excluded boundaries. positional_runs_collected::record(); let mut run = PositionalRun { - members: vec![*comment], + first: *comment, + last: *comment, + first_eligible: Some(*comment), next: None, below: None, code_before: None, prefix_gap: false, - trailing_members: 0, + suffix_gap: false, end: crate::documentation::streaming::positional::RunEnd::EndOfScope, }; - let mut clean_members = 0; + let mut clean_first = None; let mut row_first = *comment; let mut stopped = false; for prev in ancestors.siblings_before(comment) { @@ -866,7 +936,7 @@ fn collect_positional_prefix<'a, T: Checker>( if !T::is_comment(&prev) { run.code_before = Some(prev); if prev.end_row() >= row_first.start_row() { - run.trailing_members = run.members.len() - clean_members; + run.first_eligible = clean_first; } stopped = true; break; @@ -877,10 +947,10 @@ fn collect_positional_prefix<'a, T: Checker>( break; } if prev.end_row() < row_first.start_row() { - clean_members = run.members.len(); + clean_first = Some(row_first); } - run.members.push(prev); row_first = prev; + run.first_eligible = Some(row_first); } if !stopped && matches!(view, CandidateView::Source(_)) { let start = if ancestors.depth() == Some(1) { @@ -892,7 +962,7 @@ fn collect_positional_prefix<'a, T: Checker>( }; run.prefix_gap = !view.covers(start..row_first.start_byte()); } - run.members.reverse(); + run.first = row_first; run } diff --git a/big-code-analysis-ast/src/lang_helpers/ruby.rs b/big-code-analysis-ast/src/lang_helpers/ruby.rs index ee7849a1a..a8856911a 100644 --- a/big-code-analysis-ast/src/lang_helpers/ruby.rs +++ b/big-code-analysis-ast/src/lang_helpers/ruby.rs @@ -13,6 +13,38 @@ use crate::Ruby; use crate::lang_helpers::doc_comment::node_bytes; use crate::node::{Ancestors, FoldLane, Node}; +/// YARD 0.9.45 `META_MATCH` after `on_comment` hash-line cleanup: remove +/// the hash run and at most one whitespace byte, then require `@!((\w\.?)+)` +/// followed by whitespace or end of line. Indented examples remain prose. +pub(crate) fn source_yard_directive(node: &Node<'_>, code: &[u8]) -> bool { + let bytes = node_bytes(node, code); + let hashes = bytes.iter().take_while(|&&byte| byte == b'#').count(); + if hashes == 0 { + return false; + } + let body = &bytes[hashes..]; + let body = if body.first().is_some_and(u8::is_ascii_whitespace) { + &body[1..] + } else { + body + }; + let Some(mut identifier) = body.strip_prefix(b"@!") else { + return false; + }; + let mut found = false; + while let Some(byte) = identifier.first() { + if !byte.is_ascii_alphanumeric() && *byte != b'_' { + break; + } + found = true; + identifier = &identifier[1..]; + if identifier.first() == Some(&b'.') { + identifier = &identifier[1..]; + } + } + found && identifier.first().is_none_or(u8::is_ascii_whitespace) +} + /// Whether `node` — a `Block` / `DoBlock` — is the body of a stabby /// lambda (`->(z) { … }` / `->(z) do … end`), which parses as a `Lambda` /// node that CONTAINS the block. The `Lambda` wrapper already counts as diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index ef6113af0..f269fade0 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -19,9 +19,10 @@ struct PositionalRows<'a> { #[allow(clippy::arithmetic_side_effects)] fn positional_rows(lang: LANG, source: &[u8], expected: PositionalRows<'_>) { use big_code_analysis_ast::documentation::streaming::positional::{ - evidence_built, positional_runs_collected, + evidence_built, members_materialized, positional_runs_collected, }; let before = evidence_built::observed(); + let materialized = members_materialized::observed(); let scans = positional_runs_collected::observed(); let intersections = big_code_analysis_ast::documentation::included_range_visits::observed(); let space = analyze( @@ -53,6 +54,7 @@ fn positional_rows(lang: LANG, source: &[u8], expected: PositionalRows<'_>) { &json!({"ploc_rows": expected.code, "cloc_rows": expected.comments}), ); assert_eq!(evidence_built::observed() - before, 0); + assert_eq!(members_materialized::observed() - materialized, 0); assert_eq!( big_code_analysis_ast::documentation::included_range_visits::observed() - intersections, 0 diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index 2dafdded7..c83ca75e8 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -111,14 +111,14 @@ { "name": "lone-cr-is-source-content", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "let lf = if code.get(end - 1) == Some(&b'\\n') {", - "new": "let lf = if code.get(end - 1) == Some(&b'\\r') { return end - 1; } else if code.get(end - 1) == Some(&b'\\n') {", + "old": "let lf = if context.covers(end - 1..end) && code.get(end - 1) == Some(&b'\\n') {", + "new": "let lf = if code.get(end - 1) == Some(&b'\\r') { return end - 1; } else if context.covers(end - 1..end) && code.get(end - 1) == Some(&b'\\n') {", "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] }, { "name": "excluded-lf-does-not-strip-included-cr", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "if code.get(lf) == Some(&b'\\n') && context.covers(lf..lf + 1) {\n if code.get(lf - 1) == Some(&b'\\r') && context.covers(lf - 1..lf + 1) {", + "old": "if context.covers(lf..lf + 1) && code.get(lf) == Some(&b'\\n') {\n if context.covers(lf - 1..lf + 1) && code.get(lf - 1) == Some(&b'\\r') {", "new": "if code.get(lf) == Some(&b'\\n') {\n if code.get(lf - 1) == Some(&b'\\r') {", "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] }, @@ -184,6 +184,27 @@ "old": "if !view.covers(0..boundary) {", "new": "if false && !view.covers(0..boundary) {", "expect": ["documentation::streaming::markers::regressions::php_source_prefix_gap_keeps_unknown_direction_out_of_selection"] + }, + { + "name": "marker-exhaustion-retains-suffix-composition", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": "suffix_gap: selection.suffix_gap,", + "new": "suffix_gap: false,", + "expect": ["documentation::streaming::markers::regressions::suffix::rust_local_selection_keeps_suffix_composition_gap", "documentation::streaming::markers::regressions::suffix::java_unattached_exhaustion_keeps_unknown_suffix", "documentation::streaming::markers::regressions::suffix::c_gatherer_keeps_selected_suffix_evidence"] + }, + { + "name": "marker-exhaustion-after-skipped-trivia-is-not-eof", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "None => exhausted_stretch(comment, boundary, code, ancestors, view),", + "new": "None => StretchEnd::Elsewhere,", + "expect": ["documentation::streaming::markers::regressions::suffix::marker_exhaustion_checks_after_final_skipped_trivia"] + }, + { + "name": "nested-suffix-uses-lexical-boundary", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": ".map_or(code.len(), |scope| scope.end_byte())", + "new": ".map_or(code.len(), |_scope| code.len())", + "expect": ["documentation::streaming::markers::regressions::suffix::nested_marker_exhaustion_uses_lexical_scope_not_file_tail"] } ] } diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json index b3e6832fb..fa59f3179 100644 --- a/utils/documentation-positional-perturb.json +++ b/utils/documentation-positional-perturb.json @@ -69,8 +69,8 @@ { "name": "source-member-order", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "run.members.reverse();", - "new": "// mutation: leave the reverse scan reversed", + "old": "members.push(member);", + "new": "members.insert(0, member);", "expect": ["documentation::streaming::positional::tests::go_order_directives_and_candidate_are_independent"] }, { @@ -107,6 +107,62 @@ "old": "prefix_gap: run.prefix_gap,", "new": "prefix_gap: false,", "expect": ["documentation::streaming::positional::tests::go_gaps_split_runs_before_selection_and_keep_composition_metadata", "documentation::streaming::positional::tests::ruby_gap_after_code_does_not_hide_incomplete_composition"] + }, + { + "name": "legacy-must-not-materialize-before-acceptance", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "let Some(first) = run.first_eligible else {", + "new": "let _members = run.materialize(ancestors);\n let Some(first) = run.first_eligible else {", + "expect": ["documentation::streaming::positional::tests::remediation::go_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::ruby_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::lua_legacy_materializes_no_members", "metrics::loc::documentation_tests::documentation_go_positional_exact_rows"] + }, + { + "name": "source-buffer-counter-counts-actual-pushes", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "members_materialized::record();", + "new": "// mutation: omit actual buffer observation", + "expect": ["documentation::streaming::positional::tests::remediation::go_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::ruby_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::lua_legacy_materializes_no_members"] + }, + { + "name": "exhausted-positional-suffix-is-not-eof", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "!view.covers(last_examined_end..scope_end)", + "new": "false && !view.covers(last_examined_end..scope_end)", + "expect": ["documentation::streaming::positional::tests::remediation::go_exhaustion_reports_unknown_suffix", "documentation::streaming::positional::tests::remediation::ruby_exhaustion_preserves_explicit_selection", "documentation::streaming::positional::tests::remediation::lua_exhaustion_preserves_known_file_and_tagged_selection"] + }, + { + "name": "unknown-prefix-row-must-not-discard-clean-suffix", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": ".take_while(|node| node.start_row() == row)", + "new": ".take_while(|node| true || node.start_row() == row)", + "expect": ["documentation::streaming::positional::tests::remediation::go_unknown_first_row_keeps_clean_suffix", "documentation::streaming::positional::tests::remediation::ruby_unknown_first_row_keeps_clean_suffix"] + }, + { + "name": "yard-later-member-is-not-first-only", + "file": "big-code-analysis-ast/src/checker/ruby.rs", + "old": "|| run.members.iter().skip(1).any(|member| {", + "new": "|| run.members.iter().skip(1).take(0).any(|member| {", + "expect": ["documentation::streaming::positional::tests::remediation::yard_later_directives_follow_trivia_or_prose"] + }, + { + "name": "yard-cleanup-removes-at-most-one-whitespace", + "file": "big-code-analysis-ast/src/lang_helpers/ruby.rs", + "old": "let Some(mut identifier) = body.strip_prefix(b\"@!\") else {", + "new": "let Some(mut identifier) = body.trim_ascii_start().strip_prefix(b\"@!\") else {", + "expect": ["documentation::streaming::positional::tests::remediation::yard_later_directive_cleanup_is_bounded"] + }, + { + "name": "unknown-prefix-row-is-not-selected-prose", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "if prefix_placement_gap {", + "new": "if false && prefix_placement_gap {", + "expect": ["documentation::streaming::positional::tests::remediation::go_unknown_first_row_keeps_clean_suffix", "documentation::streaming::positional::tests::remediation::ruby_unknown_first_row_keeps_clean_suffix"] + }, + { + "name": "suffix-gap-does-not-erase-known-selection", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "if run.end == RunEnd::ExcludedGap", + "new": "if run.suffix_gap || run.end == RunEnd::ExcludedGap", + "expect": ["documentation::streaming::positional::tests::remediation::ruby_exhaustion_preserves_explicit_selection", "documentation::streaming::positional::tests::remediation::lua_exhaustion_preserves_known_file_and_tagged_selection"] } ] } From 076db5dbc8dd4395b14dd65f94aa453cfe5536fb Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:14:36 -0800 Subject: [PATCH 033/221] test(documentation): exercise exhausted lexical scope boundary --- .../src/lang_helpers/doc_comment.rs | 48 +++++++++++++++++++ utils/documentation-markers-perturb.json | 2 +- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 2806d147c..8adf423a9 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -988,6 +988,54 @@ pub(crate) fn lua_group_head_above<'a, T: Checker>( mod tests { use super::*; + #[cfg(feature = "rust")] + #[test] + fn documentation_exhausted_tail_uses_the_current_lexical_scope() { + use crate::documentation::SourceContext; + use crate::{AnyParser, LANG, RustCode, Search}; + let source = b"mod m { //! audit\n}\nXXXX"; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser + .set_included_ranges(&[tree_sitter::Range { + start_byte: 0, + end_byte: 20, + start_point: tree_sitter::Point::new(0, 0), + end_point: tree_sitter::Point::new(2, 0), + }]) + .unwrap(); + let tree = parser.parse(source, None).unwrap(); + let parser = AnyParser::from_tree(LANG::Rust, tree, source.to_vec()).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut checked = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if RustCode::is_comment(node) { + assert_eq!(ancestors.parent(node).unwrap().kind(), "declaration_list"); + assert_eq!(ancestors.parent(node).unwrap().end_byte(), 19); + // Exercise the exhaustion helper directly: the parsed closing + // brace normally stops marker scanning before this tail check. + assert!(!suffix_gap( + node, + node.end_byte(), + source, + ancestors, + CandidateView::Source(&context) + )); + assert!(suffix_gap( + node, + node.end_byte(), + source, + Ancestors::known(&[parser.root_node()]), + CandidateView::Source(&context) + )); + checked += 1; + } + }); + assert_eq!(checked, 1); + } + #[cfg(feature = "c")] fn read_past_error<'a, T: Checker>( node: &Node<'a>, diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index c83ca75e8..e1713b32d 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -204,7 +204,7 @@ "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", "old": ".map_or(code.len(), |scope| scope.end_byte())", "new": ".map_or(code.len(), |_scope| code.len())", - "expect": ["documentation::streaming::markers::regressions::suffix::nested_marker_exhaustion_uses_lexical_scope_not_file_tail"] + "expect": ["lang_helpers::doc_comment::tests::documentation_exhausted_tail_uses_the_current_lexical_scope"] } ] } From 4f0dc6fa8a4316a6f2f361bdcdd41dd16dd3d3b6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:53:38 -0800 Subject: [PATCH 034/221] fix(documentation): retain scope and candidate evidence at source boundaries --- .bca-baseline.toml | 4 +- .../streaming/markers/regressions.rs | 1 + .../streaming/markers/regressions/cycle2.rs | 114 +++++++ .../src/documentation/streaming/positional.rs | 34 ++- .../streaming/positional/tests.rs | 1 + .../streaming/positional/tests/cycle2.rs | 278 ++++++++++++++++++ .../streaming/positional/tests/remediation.rs | 6 + .../src/lang_helpers/doc_comment.rs | 87 ++++-- utils/documentation-markers-perturb.json | 11 +- utils/documentation-positional-perturb.json | 53 +++- 10 files changed, 544 insertions(+), 45 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/streaming/markers/regressions/cycle2.rs create mode 100644 big-code-analysis-ast/src/documentation/streaming/positional/tests/cycle2.rs diff --git a/.bca-baseline.toml b/.bca-baseline.toml index db23aeb33..ec07015fe 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -335,7 +335,7 @@ value = 101217.532578918 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "" metric = "loc.ploc" -value = 690.0 +value = 686.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -365,7 +365,7 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "collect_stretch" metric = "halstead.effort" -value = 56431.32292303746 +value = 48097.31864419657 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs index 3d59729a5..836abac07 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions.rs @@ -5,6 +5,7 @@ use crate::documentation::SourcePiece; use crate::{AnyParser, LANG, Search, documentation::UnresolvedReason}; use std::ops::Range; +mod cycle2; mod suffix; #[cfg(any( diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/regressions/cycle2.rs b/big-code-analysis-ast/src/documentation/streaming/markers/regressions/cycle2.rs new file mode 100644 index 000000000..15565978f --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/markers/regressions/cycle2.rs @@ -0,0 +1,114 @@ +use super::*; + +#[cfg(any(feature = "rust", feature = "java"))] +fn chainless_runs(parser: &AnyParser, retain: bool) -> Vec> { + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut result = Vec::new(); + parser.root_node().act_on_node(&mut |node, _| { + if T::is_comment(node) { + source_comment::( + node, + Ancestors::unknown(), + &mut SourceRequest { + context: &context, + retain_unbound: retain, + sink: &mut |run| result.push(run), + }, + ) + .unwrap(); + } + }); + result +} + +#[cfg(any(feature = "rust", feature = "java"))] +fn prefix( + source: &[u8], + kind: &str, + span: Range, + target: &(&str, Range), +) { + let parser = restricted(T::lang(), source, &[2..source.len()]); + for retain in [false, true] { + for result in [ + runs::(&parser, retain), + chainless_runs::(&parser, retain), + ] { + assert_eq!(result.len(), 1); + let run = &result[0]; + assert!(run.prefix_gap); + assert!(!run.suffix_gap); + assert!(run.code_before.is_none()); + assert_eq!(run.members.len(), 1); + assert_eq!(run.members[0].selection, MarkerSelection::Selected); + assert_eq!(run.members[0].node.node().kind(), kind); + assert_eq!(run.members[0].source.pieces()[0].range(), span); + let candidate = run.target.unwrap().node(); + assert_eq!(candidate.kind(), target.0); + assert_eq!(candidate.byte_range(), target.1); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn rust_chainless_marker_prefix_uses_full_buffer() { + prefix::( + b"XX//! audit\nfn f() {}", + "line_comment", + 2..11, + &("function_item", 12..21), + ); +} +#[cfg(feature = "java")] +#[test] +fn java_chainless_marker_prefix_uses_full_buffer() { + prefix::( + b"XX/// audit\nclass C {}", + "line_comment", + 2..11, + &("class_declaration", 12..22), + ); +} + +#[cfg(any(feature = "rust", feature = "java"))] +fn suffix( + source: &[u8], + end: usize, + selection: MarkerSelection, +) { + let parser = restricted(T::lang(), source, &[0..end]); + for retain in [false, true] { + for result in [ + runs::(&parser, retain), + chainless_runs::(&parser, retain), + ] { + assert_eq!( + result.len(), + usize::from(retain || selection == MarkerSelection::Selected) + ); + if result.is_empty() { + continue; + } + assert!(result[0].suffix_gap); + assert_eq!(result[0].members.len(), 1); + assert_eq!(result[0].members[0].selection, selection); + assert_eq!( + result[0].members[0].uncertainty, + Some(UnresolvedReason::ExcludedGap) + ); + assert!(result[0].target.is_none()); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn rust_chainless_marker_suffix_uses_full_buffer() { + suffix::(b"//! audit\nfn f() {}", 10, MarkerSelection::Selected); +} +#[cfg(feature = "java")] +#[test] +fn java_chainless_marker_suffix_uses_full_buffer() { + suffix::(b"/// audit\nclass C {}", 10, MarkerSelection::Unattached); +} diff --git a/big-code-analysis-ast/src/documentation/streaming/positional.rs b/big-code-analysis-ast/src/documentation/streaming/positional.rs index 46f1bff52..d40aa056a 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional.rs @@ -6,7 +6,9 @@ use crate::{Ancestors, Checker, Node}; use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces, UnresolvedReason}; use super::markers::CandidateView; -pub use doc_comment::{members_materialized, positional_predecessors, positional_runs_collected}; +pub use doc_comment::{ + members_materialized, positional_predecessors, positional_runs_collected, source_scope_reads, +}; crate::observation::counter!(evidence_built, cfg(any(test, feature = "test-support"))); /// Why the final comment cannot defer to another member. @@ -192,11 +194,13 @@ impl<'t> SourceMembers<'t> { .get(eligible_start) .is_some_and(|first| !complete_row_prefix(first, source)); if prefix_placement_gap { - let row = nodes[eligible_start].start_row(); - eligible_start += nodes[eligible_start..] - .iter() - .take_while(|node| node.start_row() == row) - .count(); + let mut connected_end_row = nodes[eligible_start].end_row(); + while let Some(node) = nodes.get(eligible_start) + && node.start_row() <= connected_end_row + { + connected_end_row = connected_end_row.max(node.end_row()); + eligible_start += 1; + } } Self { nodes, @@ -235,12 +239,18 @@ impl<'t> SourceDecision<'t> { decision.uncertainty = Some(UnresolvedReason::ExcludedGap); return decision; } - if collected.eligible_start == collected.nodes.len() { - return decision; - } decision.target = run .below .filter(|n| T::is_source_doc_target(n, source.bytes(), ancestors)); + if decision.uncertainty.is_none() { + decision.uncertainty = run + .next + .filter(|n| n.has_error() || n.is_missing()) + .map(|_| UnresolvedReason::GrammarBoundary); + } + if collected.eligible_start == collected.nodes.len() { + return decision; + } let context = RunContext { members: &collected.nodes[collected.eligible_start..], below: run.below, @@ -255,12 +265,6 @@ impl<'t> SourceDecision<'t> { Ok(None) => {} Err(reason) => decision.uncertainty = Some(reason), } - if decision.uncertainty.is_none() { - decision.uncertainty = run - .next - .filter(|n| n.has_error() || n.is_missing()) - .map(|_| UnresolvedReason::GrammarBoundary); - } decision } } diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs index d5596e896..a90e8b465 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests.rs @@ -4,6 +4,7 @@ use super::*; use crate::{AnyParser, LANG, Search}; use std::ops::Range; +mod cycle2; mod remediation; #[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests/cycle2.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests/cycle2.rs new file mode 100644 index 000000000..a443156e8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests/cycle2.rs @@ -0,0 +1,278 @@ +use super::*; + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn collect(parser: &AnyParser, retain: bool, chainless: bool) -> Vec> { + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut result = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + source_comment::( + node, + if chainless { + Ancestors::unknown() + } else { + ancestors + }, + &mut SourceRequest { + context: &context, + retain_unbound: retain, + retain_directives: true, + sink: &mut |run| result.push(run), + }, + ) + .unwrap(); + } + }); + result +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn suffix( + source: &[u8], + end: usize, + selection: RunSelection, +) { + let parser = restricted(T::lang(), source, &[0..end]); + assert!(!parser.ts_tree().root_node().has_error()); + for chainless in [false, true] { + for retain in [false, true] { + let result = collect::(&parser, retain, chainless); + assert_eq!( + result.len(), + usize::from(retain || selection != RunSelection::Unattached) + ); + if result.is_empty() { + continue; + } + let run = &result[0]; + assert!(run.suffix_gap); + assert!(!run.prefix_gap); + assert_eq!(run.selection, selection); + assert_eq!(run.uncertainty, Some(UnresolvedReason::ExcludedGap)); + assert!(run.target.is_none()); + assert!(run.following.is_none()); + assert_eq!(run.members.len(), 1); + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_chainless_exhaustion_keeps_full_buffer_suffix() { + suffix::( + b"package p\n// audit\nfunc f() {}", + 19, + RunSelection::Unattached, + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_chainless_exhaustion_keeps_full_buffer_suffix() { + suffix::(b"# audit\ndef f; end", 8, RunSelection::Unattached); +} +#[cfg(feature = "lua")] +#[test] +fn lua_chainless_exhaustion_keeps_full_buffer_suffix() { + suffix::( + b"--- audit\nfunction f() end", + 10, + RunSelection::Opener(OpenerReason::FirstFile), + ); +} + +#[cfg(any(feature = "go", feature = "ruby"))] +fn prefix( + source: &[u8], + spans: &[Range], + target: &(&str, Range), +) { + let parser = restricted(T::lang(), source, &[2..source.len()]); + assert!(!parser.ts_tree().root_node().has_error()); + for chainless in [false, true] { + for retain in [false, true] { + let result = collect::(&parser, retain, chainless); + assert_eq!(result.len(), 1); + let run = &result[0]; + assert!(run.prefix_gap); + assert!(!run.suffix_gap); + assert!(run.code_before.is_none()); + assert_eq!(run.uncertainty, Some(UnresolvedReason::ExcludedGap)); + assert_eq!(run.selection, RunSelection::FollowingTarget); + identity(run.target.unwrap(), target.0, target.1.clone()); + let expected = if retain { spans } else { &spans[1..] }; + assert_eq!(run.members.len(), expected.len()); + for (member, span) in run.members.iter().zip(expected) { + identity(member.node, "comment", span.clone()); + assert_eq!(member.selected, span != &spans[0]); + assert_eq!(member.source.pieces()[0].range(), *span); + } + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_chainless_prefix_keeps_unknown_first_row() { + prefix::( + b"XX// a\n// b\npackage p", + &[2..6, 7..11], + &("package_clause", 12..21), + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_chainless_prefix_keeps_unknown_first_row() { + prefix::( + b"XX# a\n# b\ndef f; end", + &[2..5, 6..9], + &("method", 10..20), + ); +} + +#[cfg(feature = "go")] +#[test] +fn uncertain_multiline_prefix_excludes_all_row_connected_members() { + for (source, spans, target) in [ + ( + b"XX/*a\nb*/ /*c*/\n// d\npackage p".as_slice(), + vec![2..9, 10..15, 16..20], + 21..30, + ), + ( + b"XX/*a\nb*/ /*c\nd*/ /*e*/\n// f\npackage p".as_slice(), + vec![2..9, 10..17, 18..23, 24..28], + 29..38, + ), + ] { + let parser = restricted(LANG::Go, source, &[2..source.len()]); + assert!(!parser.ts_tree().root_node().has_error()); + for chainless in [false, true] { + for retain in [false, true] { + let result = collect::(&parser, retain, chainless); + assert_eq!(result.len(), 1); + let run = &result[0]; + assert_eq!(run.selection, RunSelection::FollowingTarget); + assert_eq!(run.uncertainty, Some(UnresolvedReason::ExcludedGap)); + assert!(run.prefix_gap); + identity(run.target.unwrap(), "package_clause", target.clone()); + let expected = if retain { + &spans[..] + } else { + &spans[spans.len() - 1..] + }; + assert_eq!(run.members.len(), expected.len()); + for (member, span) in run.members.iter().zip(expected) { + identity(member.node, "comment", span.clone()); + assert_eq!(member.selected, span == spans.last().unwrap()); + assert_eq!(member.source.pieces()[0].bytes(), &source[span.clone()]); + } + } + } + let twin = parse(LANG::Go, &source[2..]); + let result = collect::(&twin, false, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].members.len(), spans.len()); + assert!(result[0].members.iter().all(|member| member.selected)); + assert_eq!(result[0].uncertainty, None); + } + let source = b"XX/*a\nb*/ /*c*/\npackage p"; + let parser = restricted(LANG::Go, source, &[2..source.len()]); + for chainless in [false, true] { + assert!(collect::(&parser, false, chainless).is_empty()); + let result = collect::(&parser, true, chainless); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert!(result[0].members.iter().all(|member| !member.selected)); + identity(result[0].target.unwrap(), "package_clause", 16..25); + assert_eq!(result[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); + } + let parser = parse( + LANG::Go, + b"package p\nvar x = 0 /*a\nb*/ /*c*/\n// d\nvar y = 1", + ); + let result = collect::(&parser, true, false); + assert_eq!(result.len(), 1); + assert_eq!( + result[0] + .members + .iter() + .map(|member| member.selected) + .collect::>(), + [false, false, true] + ); + assert_eq!(result[0].uncertainty, None); +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] +fn trailing( + source: &[u8], + span: Range, + target: &(&str, Range), +) { + let parser = parse(T::lang(), source); + for chainless in [false, true] { + assert!(collect::(&parser, false, chainless).is_empty()); + let result = collect::(&parser, true, chainless); + assert_eq!(result.len(), 1); + let run = &result[0]; + assert_eq!(run.selection, RunSelection::Unattached); + assert_eq!(run.uncertainty, None); + assert_eq!(run.members.len(), 1); + assert!(!run.members[0].selected); + identity(run.members[0].node, "comment", span.clone()); + identity(run.target.unwrap(), target.0, target.1.clone()); + identity(run.following.unwrap(), target.0, target.1.clone()); + } + let parser = restricted( + T::lang(), + source, + &[0..target.1.start + 1, target.1.start + 2..source.len()], + ); + let result = collect::(&parser, true, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert!(result[0].target.is_none()); + assert_eq!(result[0].uncertainty, Some(UnresolvedReason::ExcludedGap)); +} + +#[cfg(feature = "go")] +#[test] +fn go_trailing_only_keeps_candidate_without_selection() { + trailing::( + b"package p\nvar x = 1 // note\nfunc F() {}", + 20..27, + &("function_declaration", 28..39), + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_trailing_only_keeps_candidate_without_selection() { + trailing::(b"X = 1 # note\ndef f; end", 6..12, &("method", 13..23)); +} +#[cfg(feature = "lua")] +#[test] +fn lua_trailing_only_keeps_candidate_without_selection() { + trailing::( + b"x = 1 -- note\nfunction f() end", + 6..13, + &("function_declaration", 14..30), + ); +} + +#[cfg(feature = "go")] +#[test] +fn recovered_trailing_candidate_keeps_grammar_uncertainty() { + let source = b"package p\nvar x = 1 // note\nfunc F( {}"; + let parser = AnyParser::parse(LANG::Go, source.to_vec(), None, None).unwrap(); + assert!(parser.root_node().preorder().any(|node| node.is_missing())); + let result = collect::(&parser, true, false); + assert_eq!(result.len(), 1); + assert_eq!(result[0].selection, RunSelection::Unattached); + assert_eq!( + result[0].uncertainty, + Some(UnresolvedReason::GrammarBoundary) + ); + identity(result[0].target.unwrap(), "function_declaration", 28..38); + assert_eq!(result[0].members.len(), 1); + assert!(!result[0].members[0].selected); +} diff --git a/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs b/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs index 1f8f12557..b6a3e5a32 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional/tests/remediation.rs @@ -15,6 +15,7 @@ fn allocation_free( ] { let parser = parse(T::lang(), source.as_bytes()); let before = members_materialized::observed(); + let scope_reads = source_scope_reads::observed(); parser.root_node().act_on_node(&mut |node, ancestors| { if T::is_comment(node) { super::super::super::positional_comment::( @@ -26,6 +27,11 @@ fn allocation_free( } }); assert_eq!(members_materialized::observed() - before, 0, "{source}"); + assert_eq!( + source_scope_reads::observed() - scope_reads, + 0, + "legacy does not ask source scope bounds" + ); let expected = parser.root_node().preorder().filter(T::is_comment).count(); assert!(expected > 0); let source_runs = runs::(&parser, true, true); diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 8adf423a9..66a6afe48 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -503,16 +503,29 @@ fn suffix_gap<'a>( if matches!(view, CandidateView::Legacy) { return false; } - let scope_end = if ancestors.depth().is_some_and(|depth| depth <= 1) { - code.len() - } else { - ancestors - .parent(comment) - .map_or(code.len(), |scope| scope.end_byte()) - }; + let scope_end = source_scope_bounds(comment, code, ancestors).end; !view.covers(last_examined_end..scope_end) } +// The caller's chain is authoritative, including an explicitly empty one. +// Only the unknown fallback resolves physical parents; a restricted root's span +// cannot substitute for the full source interval. +fn source_scope_bounds<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, +) -> std::ops::Range { + source_scope_reads::record(); + let scope = match ancestors.depth() { + Some(0 | 1) => None, + Some(_) => ancestors.parent(node), + None => node.parent().filter(|parent| parent.parent().is_some()), + }; + scope.map_or(0..code.len(), |scope| scope.start_byte()..scope.end_byte()) +} + +crate::observation::counter!(source_scope_reads, cfg(any(test, feature = "test-support"))); + /// The stretch `comment` ends, in source order, and the sibling before it: /// `comment` and the siblings before it that are comments or skipped, /// read past the parse errors [`stretch_end`] reads past with the same @@ -561,13 +574,7 @@ pub(crate) fn collect_stretch<'a, T: Checker>( } } if matches!(view, CandidateView::Source(_)) && before.is_none() && !prefix_gap { - let start = if ancestors.depth() == Some(1) { - 0 - } else { - ancestors - .parent(comment) - .map_or(0, |parent| parent.start_byte()) - }; + let start = source_scope_bounds(comment, code, ancestors).start; prefix_gap = !view.covers(start..boundary); } stretch.reverse(); @@ -953,13 +960,7 @@ fn collect_positional_prefix<'a, T: Checker>( run.first_eligible = Some(row_first); } if !stopped && matches!(view, CandidateView::Source(_)) { - let start = if ancestors.depth() == Some(1) { - 0 - } else { - ancestors - .parent(comment) - .map_or(0, |parent| parent.start_byte()) - }; + let start = source_scope_bounds(comment, code, ancestors).start; run.prefix_gap = !view.covers(start..row_first.start_byte()); } run.first = row_first; @@ -988,6 +989,44 @@ pub(crate) fn lua_group_head_above<'a, T: Checker>( mod tests { use super::*; + #[cfg(feature = "rust")] + #[test] + fn documentation_scope_bounds_respect_known_and_unknown_context() { + use crate::node::node_resolved_parent_lookups; + use crate::{AnyParser, LANG, Search}; + let code = b"\nmod m { //! audit\n}\n"; + let parser = AnyParser::parse(LANG::Rust, code.to_vec(), None, None).unwrap(); + let root = parser.root_node(); + let before = node_resolved_parent_lookups::observed(); + assert_eq!( + source_scope_bounds(&root, code, Ancestors::unknown()), + 0..21 + ); + assert_eq!(node_resolved_parent_lookups::observed() - before, 1); + let mut checked = 0; + root.act_on_node(&mut |node, ancestors| { + let expected = match node.kind() { + "mod_item" => 0..21, + "line_comment" => 7..20, + _ => return, + }; + let before = node_resolved_parent_lookups::observed(); + assert_eq!(source_scope_bounds(node, code, ancestors), expected); + assert_eq!( + source_scope_bounds(node, code, Ancestors::known(&[])), + 0..21 + ); + assert_eq!(node_resolved_parent_lookups::observed() - before, 0); + assert_eq!( + source_scope_bounds(node, code, Ancestors::unknown()), + expected + ); + assert_eq!(node_resolved_parent_lookups::observed() - before, 2); + checked += 1; + }); + assert_eq!(checked, 2); + } + #[cfg(feature = "rust")] #[test] fn documentation_exhausted_tail_uses_the_current_lexical_scope() { @@ -1024,10 +1063,10 @@ mod tests { CandidateView::Source(&context) )); assert!(suffix_gap( - node, - node.end_byte(), + &parser.root_node(), + 20, source, - Ancestors::known(&[parser.root_node()]), + Ancestors::known(&[]), CandidateView::Source(&context) )); checked += 1; diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index e1713b32d..f722d2cf1 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -202,9 +202,16 @@ { "name": "nested-suffix-uses-lexical-boundary", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": ".map_or(code.len(), |scope| scope.end_byte())", - "new": ".map_or(code.len(), |_scope| code.len())", + "old": "scope.start_byte()..scope.end_byte()", + "new": "scope.start_byte()..code.len()", "expect": ["lang_helpers::doc_comment::tests::documentation_exhausted_tail_uses_the_current_lexical_scope"] + }, + { + "name": "chainless-marker-scope-must-recognize-root-parent", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "None => node.parent().filter(|parent| parent.parent().is_some()),", + "new": "None => node.parent(),", + "expect": ["documentation::streaming::markers::regressions::cycle2::rust_chainless_marker_prefix_uses_full_buffer", "documentation::streaming::markers::regressions::cycle2::java_chainless_marker_prefix_uses_full_buffer", "documentation::streaming::markers::regressions::cycle2::rust_chainless_marker_suffix_uses_full_buffer", "documentation::streaming::markers::regressions::cycle2::java_chainless_marker_suffix_uses_full_buffer"] } ] } diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json index fa59f3179..837e1d2e8 100644 --- a/utils/documentation-positional-perturb.json +++ b/utils/documentation-positional-perturb.json @@ -132,8 +132,8 @@ { "name": "unknown-prefix-row-must-not-discard-clean-suffix", "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", - "old": ".take_while(|node| node.start_row() == row)", - "new": ".take_while(|node| true || node.start_row() == row)", + "old": "&& node.start_row() <= connected_end_row", + "new": "&& (true || node.start_row() <= connected_end_row)", "expect": ["documentation::streaming::positional::tests::remediation::go_unknown_first_row_keeps_clean_suffix", "documentation::streaming::positional::tests::remediation::ruby_unknown_first_row_keeps_clean_suffix"] }, { @@ -163,6 +163,55 @@ "old": "if run.end == RunEnd::ExcludedGap", "new": "if run.suffix_gap || run.end == RunEnd::ExcludedGap", "expect": ["documentation::streaming::positional::tests::remediation::ruby_exhaustion_preserves_explicit_selection", "documentation::streaming::positional::tests::remediation::lua_exhaustion_preserves_known_file_and_tagged_selection"] + }, + { + "name": "chainless-positional-scope-must-recognize-root-parent", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "None => node.parent().filter(|parent| parent.parent().is_some()),", + "new": "None => node.parent(),", + "expect": ["documentation::streaming::positional::tests::cycle2::go_chainless_exhaustion_keeps_full_buffer_suffix", "documentation::streaming::positional::tests::cycle2::ruby_chainless_exhaustion_keeps_full_buffer_suffix", "documentation::streaming::positional::tests::cycle2::go_chainless_prefix_keeps_unknown_first_row", "documentation::streaming::positional::tests::cycle2::ruby_chainless_prefix_keeps_unknown_first_row"] + }, + { + "name": "known-source-context-must-not-resolve-physical-parents", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "Some(0 | 1) => None,", + "new": "Some(0 | 1) => node.parent().filter(|parent| parent.parent().is_some()),", + "expect": ["lang_helpers::doc_comment::tests::documentation_scope_bounds_respect_known_and_unknown_context"] + }, + { + "name": "uncertain-prefix-must-cover-the-first-multiline-ending-row", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "let mut connected_end_row = nodes[eligible_start].end_row();\n while let Some(node) = nodes.get(eligible_start)\n && node.start_row() <= connected_end_row\n {\n connected_end_row = connected_end_row.max(node.end_row());\n eligible_start += 1;\n }", + "new": "let row = nodes[eligible_start].start_row();\n eligible_start += nodes[eligible_start..].iter().take_while(|node| node.start_row() == row).count();", + "expect": ["documentation::streaming::positional::tests::cycle2::uncertain_multiline_prefix_excludes_all_row_connected_members"] + }, + { + "name": "uncertain-row-connection-extends-through-later-multiline-members", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "connected_end_row = connected_end_row.max(node.end_row());", + "new": "// mutation: do not extend the connected row", + "expect": ["documentation::streaming::positional::tests::cycle2::uncertain_multiline_prefix_excludes_all_row_connected_members"] + }, + { + "name": "trailing-only-keeps-its-known-candidate", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "if collected.eligible_start == collected.nodes.len() {\n return decision;", + "new": "if collected.eligible_start == collected.nodes.len() {\n decision.target = None;\n return decision;", + "expect": ["documentation::streaming::positional::tests::cycle2::go_trailing_only_keeps_candidate_without_selection", "documentation::streaming::positional::tests::cycle2::ruby_trailing_only_keeps_candidate_without_selection", "documentation::streaming::positional::tests::cycle2::lua_trailing_only_keeps_candidate_without_selection"] + }, + { + "name": "recovered-trailing-candidate-keeps-uncertainty", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": "if decision.uncertainty.is_none() {", + "new": "if decision.uncertainty.is_none() && collected.eligible_start < collected.nodes.len() {", + "expect": ["documentation::streaming::positional::tests::cycle2::recovered_trailing_candidate_keeps_grammar_uncertainty"] + }, + { + "name": "legacy-exhaustion-must-bypass-source-scope-bounds", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": "if matches!(view, CandidateView::Legacy) {\n return false;", + "new": "if false && matches!(view, CandidateView::Legacy) {\n return false;", + "expect": ["documentation::streaming::positional::tests::remediation::go_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::ruby_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::lua_legacy_materializes_no_members"] } ] } From 3b7adf45bf08ab8e5b1c77245bef3b7deeb4a108 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 20:37:40 -0800 Subject: [PATCH 035/221] feat(documentation): checkpoint borrowed collector and local text pipeline --- .bca-baseline.toml | 434 ++++++- CHANGELOG.md | 6 + big-code-analysis-ast/src/cancel.rs | 11 + big-code-analysis-ast/src/documentation.rs | 79 +- .../src/documentation/budget.rs | 165 +++ .../src/documentation/canonical.rs | 107 ++ .../src/documentation/collector.rs | 1148 +++++++++++++++++ .../src/documentation/collector/tests.rs | 1041 +++++++++++++++ .../src/documentation/content.rs | 114 +- .../src/documentation/index.rs | 323 +++++ .../src/documentation/names.rs | 88 ++ .../src/documentation/options.rs | 186 +++ .../src/documentation/ordering.rs | 174 +++ .../src/documentation/source.rs | 74 +- .../documentation/streaming/markers/tests.rs | 33 + .../src/documentation/text.rs | 122 ++ .../src/documentation/text/comments.rs | 464 +++++++ .../src/documentation/text/tests.rs | 177 +++ .../src/lang_helpers/doc_text.rs | 8 + .../src/lang_helpers/doxygen.rs | 22 +- big-code-analysis-ast/src/macros/mod.rs | 31 + big-code-analysis-ast/src/node.rs | 3 + .../src/node/ancestors/siblings.rs | 31 +- big-code-analysis-ast/src/parser.rs | 17 + utils/documentation-collector-perturb.json | 56 + 25 files changed, 4893 insertions(+), 21 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/budget.rs create mode 100644 big-code-analysis-ast/src/documentation/canonical.rs create mode 100644 big-code-analysis-ast/src/documentation/collector.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/tests.rs create mode 100644 big-code-analysis-ast/src/documentation/index.rs create mode 100644 big-code-analysis-ast/src/documentation/names.rs create mode 100644 big-code-analysis-ast/src/documentation/options.rs create mode 100644 big-code-analysis-ast/src/documentation/ordering.rs create mode 100644 big-code-analysis-ast/src/documentation/text.rs create mode 100644 big-code-analysis-ast/src/documentation/text/comments.rs create mode 100644 big-code-analysis-ast/src/documentation/text/tests.rs create mode 100644 utils/documentation-collector-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index ec07015fe..6a4d51ad0 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -253,6 +253,294 @@ qualified = "php_file_docblock" metric = "nexits" value = 6.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation.rs" +qualified = "collect" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "" +metric = "loc.ploc" +value = 1112.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>" +metric = "nom" +value = 29.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>" +metric = "wmc" +value = 183.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::c_slots" +metric = "abc" +value = 54.415071441651165 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::c_slots" +metric = "cognitive" +value = 31.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::c_slots" +metric = "halstead.effort" +value = 169049.87968189508 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::c_slots" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::combine_pending" +metric = "halstead.effort" +value = 48339.317828216816 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::document" +metric = "abc" +value = 47.16990566028302 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::document" +metric = "cognitive" +value = 31.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::document" +metric = "cyclomatic" +value = 20.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::document" +metric = "halstead.effort" +value = 147420.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::document" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::finalize_projection" +metric = "cognitive" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::finalize_projection" +metric = "cyclomatic" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::finalize_projection" +metric = "halstead.effort" +value = 97707.37584823032 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::finalize_projection" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::local_target" +metric = "abc" +value = 40.01249804748511 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::local_target" +metric = "cognitive" +value = 29.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::local_target" +metric = "cyclomatic" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::local_target" +metric = "halstead.effort" +value = 119082.74234645894 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "abc" +value = 49.889878733065686 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "cognitive" +value = 40.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "cyclomatic" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "halstead.effort" +value = 192225.81875457868 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::order_results" +metric = "abc" +value = 53.600373133029585 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::order_results" +metric = "halstead.effort" +value = 121251.12650557018 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::order_results" +metric = "nexits" +value = 13.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::recognize" +metric = "halstead.effort" +value = 72071.50108974567 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::recognize" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::render_draft" +metric = "halstead.effort" +value = 55060.1234372333 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::render_draft" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::rust_attribute" +metric = "abc" +value = 48.35286961494633 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::rust_attribute" +metric = "cognitive" +value = 22.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::rust_attribute" +metric = "halstead.effort" +value = 189226.37033980602 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "abc" +value = 84.22588675698226 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "cognitive" +value = 35.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "halstead.effort" +value = 236917.17587667526 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "nexits" +value = 12.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "collect_typed" +metric = "abc" +value = 52.316345438113316 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "collect_typed" +metric = "halstead.effort" +value = 85297.33044874134 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "collect_typed" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "collect_typed" +metric = "nexits" +value = 13.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/tests.rs" +qualified = "assert_positive" +metric = "halstead.effort" +value = 107481.6422467993 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/tests.rs" +qualified = "assert_positive" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve" +metric = "cognitive" +value = 20.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" qualified = "RunSelection<'t>::select" @@ -295,6 +583,144 @@ qualified = "work" metric = "halstead.effort" value = 73112.8706762203 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "append_range" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "abc" +value = 64.41273166075166 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "cognitive" +value = 36.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "cyclomatic" +value = 26.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "halstead.effort" +value = 379601.4471603583 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "nexits" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "abc" +value = 69.01449123191448 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "cognitive" +value = 48.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "cyclomatic" +value = 27.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "halstead.effort" +value = 292724.2899242993 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "nexits" +value = 11.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "lines" +metric = "cognitive" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "lines" +metric = "halstead.effort" +value = 62992.207215869705 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "abc" +value = 49.23413450036468 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "cognitive" +value = 39.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "cyclomatic" +value = 27.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "halstead.effort" +value = 168855.57230832687 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "nexits" +value = 9.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render" +metric = "abc" +value = 65.92419889539804 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render" +metric = "cognitive" +value = 52.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render" +metric = "cyclomatic" +value = 23.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render" +metric = "halstead.effort" +value = 231327.72273130648 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render" +metric = "nexits" +value = 15.0 + [[entry]] path = "big-code-analysis-ast/src/getter.rs" qualified = "Getter::is_braced_literal_slot" @@ -431,7 +857,13 @@ value = 5.0 path = "big-code-analysis-ast/src/node.rs" qualified = "Node<'a>" metric = "nom" -value = 44.0 +value = 45.0 + +[[entry]] +path = "big-code-analysis-ast/src/node.rs" +qualified = "Node<'a>" +metric = "wmc" +value = 58.0 [[entry]] path = "big-code-analysis-ast/src/node/ancestors/folds.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index 777d06b4c..e7f11f40a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,12 @@ for historical reference. ### Added +- Added an unstable borrowed AST documentation collector with prepared canonical + owner queries, explicit pending-adapter assessments, and retained local text and + forward-origin views. Basic comment paths cover the 17 streamed language + variants; deferred source adapters return an explicit availability error. + (#1660, #1661) + - Added unstable AST positional-run evidence for Go, Ruby and Lua, including ordered comments, directive members, candidate targets and opener reasons. Marker and positional runs retain excluded-prefix and suffix composition diff --git a/big-code-analysis-ast/src/cancel.rs b/big-code-analysis-ast/src/cancel.rs index 82090243b..01cc23bd6 100644 --- a/big-code-analysis-ast/src/cancel.rs +++ b/big-code-analysis-ast/src/cancel.rs @@ -88,6 +88,17 @@ pub(crate) fn requested() -> bool { .unwrap_or(false) } +#[cfg(test)] +pub(crate) fn cancel_installed_for_test() { + INSTALLED.with(|slot| { + let flag = slot.take(); + if let Some(flag) = &flag { + flag.cancel(); + } + slot.set(flag); + }); +} + #[cfg(test)] mod tests { use super::*; diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index 27faac38e..46fc21445 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -3,19 +3,96 @@ //! Role/context predicates recognize candidates; they do not supply semantic //! owners. Fragments add included source spelling, documents add composition //! and content state, and associations add profile-qualified attachment. -//! This module supplies storage and identity primitives, not a collector. +//! Collection retains immutable source facts, local text and prepared owner queries. //! All items are unstable direct-AST plumbing; no root facade is introduced. +pub(crate) mod budget; +mod canonical; +pub(crate) mod collector; mod content; +mod index; +mod names; +mod options; +mod ordering; mod owners; mod source; #[doc(hidden)] pub mod streaming; +mod text; pub use content::*; +pub use index::*; +pub use options::*; pub use owners::*; pub use source::*; +/// Current-thread production work counters for source-path qualification. +#[cfg(any(test, feature = "test-support"))] +#[derive(Clone, Copy, Debug)] +pub struct Observations { + /// Actual collector cancellation checkpoints. + pub polls: usize, + /// Canonical lookup candidates validated. + pub identity_probes: usize, + /// Primary structural visits. + pub visits: usize, + /// Primary source-owner classification requests. + pub target_classifications: usize, + /// Materialized owner projections. + pub owner_projections: usize, + /// Enumerated child batches. + pub child_batches: usize, + /// Required cursor-field requests. + pub field_requests: usize, + /// Completed text renders. + pub renders: usize, + /// Bounded source-to-text copy chunks. + pub copy_chunks: usize, +} + +/// Read qualification counters without resetting other consumers' observations. +#[cfg(any(test, feature = "test-support"))] +#[must_use] +pub fn observations() -> Observations { + Observations { + polls: budget::polls::observed(), + identity_probes: canonical::identity_probes::observed(), + visits: collector::visits::observed(), + target_classifications: collector::target_classifications::observed(), + owner_projections: collector::owner_projections::observed(), + child_batches: collector::child_batches::observed(), + field_requests: collector::field_requests::observed(), + renders: text::renders::observed(), + copy_chunks: text::copy_chunks::observed(), + } +} + +/// Collect source-attached documentation from a borrowed parse. +/// +/// The tree must be a complete parse of these exact bytes with the selected +/// grammar. Grammar and buffer bounds are checked, but same-length substituted +/// source, shared-grammar dialect identity, inaccurate source points and historical +/// parse cancellation cannot be reconstructed from a raw tree. Prefer a typed +/// parser's documentation method when retained completion provenance is available. +/// Tree-sitter's included-range bulk copy, individual FFI calls and allocation +/// calls cannot be interrupted internally. +/// +/// # Errors +/// Returns cancellation, disabled-language, profile/adapter availability, grammar +/// mismatch and detectable source-context failures before publishing an index. +pub fn collect<'s>( + language: crate::LANG, + tree: &'s tree_sitter::Tree, + source: &'s [u8], + context: &DocumentationContext, + options: &DocumentationOptions, +) -> Result, CollectionError> { + if crate::cancel::requested() { + return Err(CollectionError::Cancelled); + } + crate::langs::collect_documentation(language, tree, source, context, options) +} + /// One physical occurrence, whose spelling may be narrower than its syntax node. #[derive(Debug)] #[non_exhaustive] diff --git a/big-code-analysis-ast/src/documentation/budget.rs b/big-code-analysis-ast/src/documentation/budget.rs new file mode 100644 index 000000000..a0b86656c --- /dev/null +++ b/big-code-analysis-ast/src/documentation/budget.rs @@ -0,0 +1,165 @@ +//! Fallible work accounting shared by source kernels and their infallible callers. + +use std::cell::Cell; +use std::convert::Infallible; + +use super::SourceError; + +pub(crate) const STEP_INTERVAL: usize = 1_024; +pub(crate) const BYTE_INTERVAL: usize = 16 * 1_024; + +pub(crate) trait WorkBudget { + type Error: Into; + + fn checkpoint(&self) -> Result<(), Self::Error>; + fn step(&self) -> Result<(), Self::Error>; + fn bytes(&self, count: usize) -> Result<(), Self::Error>; +} + +pub(crate) struct NoBudget; + +impl WorkBudget for NoBudget { + type Error = Infallible; + + #[inline] + fn checkpoint(&self) -> Result<(), Infallible> { + Ok(()) + } + + #[inline] + fn step(&self) -> Result<(), Infallible> { + Ok(()) + } + + #[inline] + fn bytes(&self, _: usize) -> Result<(), Infallible> { + Ok(()) + } +} + +#[derive(Default)] +pub(crate) struct CollectionBudget { + steps: Cell, + bytes: Cell, +} + +// These count actual checkpoints, not calls to a generic NoBudget wrapper. +crate::observation::counter!(polls, cfg(any(test, feature = "test-support"))); + +impl CollectionBudget { + fn charge( + &self, + counter: &Cell, + count: usize, + interval: usize, + ) -> Result<(), SourceError> { + let mut remaining = count; + while remaining >= interval - counter.get() { + remaining -= interval - counter.get(); + counter.set(0); + self.checkpoint()?; + } + counter.set(counter.get() + remaining); + Ok(()) + } +} + +impl WorkBudget for CollectionBudget { + type Error = SourceError; + + fn checkpoint(&self) -> Result<(), SourceError> { + polls::record(); + #[cfg(test)] + cancel_at_checkpoint(); + self.steps.set(0); + self.bytes.set(0); + if crate::cancel::requested() { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + + fn step(&self) -> Result<(), SourceError> { + self.charge(&self.steps, 1, STEP_INTERVAL) + } + + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.charge(&self.bytes, count, BYTE_INTERVAL) + } +} + +#[cfg(test)] +thread_local! { + static CANCEL_AT: Cell> = const { Cell::new(None) }; +} + +#[cfg(test)] +fn cancel_at_checkpoint() { + CANCEL_AT.with(|at| { + if at.get() == Some(polls::observed()) { + crate::cancel::cancel_installed_for_test(); + } + }); +} + +#[cfg(test)] +pub(super) fn cancel_after(checkpoints: usize, action: impl FnOnce() -> T) -> T { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + CANCEL_AT.with(|at| at.set(self.0)); + } + } + let previous = CANCEL_AT.with(|at| at.replace(Some(polls::observed() + checkpoints))); + let _restore = Restore(previous); + crate::cancel::ParseCancel::new().run(action) +} + +pub(crate) fn infallible(result: Result) -> T { + match result { + Ok(value) => value, + Err(never) => match never {}, + } +} + +impl From for SourceError { + fn from(never: Infallible) -> Self { + match never {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mixed_work_and_explicit_checkpoints_have_bounded_intervals() { + let budget = CollectionBudget::default(); + let before = polls::observed(); + for _ in 0..STEP_INTERVAL - 1 { + budget.step().unwrap(); + } + budget.bytes(BYTE_INTERVAL - 1).unwrap(); + assert_eq!(polls::observed() - before, 0); + budget.step().unwrap(); + assert_eq!(polls::observed() - before, 1); + budget.bytes(BYTE_INTERVAL).unwrap(); + assert_eq!(polls::observed() - before, 2); + budget.checkpoint().unwrap(); + assert_eq!(polls::observed() - before, 3); + } + + #[test] + fn no_budget_never_polls_even_under_active_cancellation() { + let flag = crate::cancel::ParseCancel::new(); + flag.cancel(); + let before = polls::observed(); + flag.run(|| { + infallible(NoBudget.checkpoint()); + infallible(NoBudget.step()); + infallible(NoBudget.bytes(usize::MAX)); + }); + assert_eq!(polls::observed() - before, 0); + } +} diff --git a/big-code-analysis-ast/src/documentation/canonical.rs b/big-code-analysis-ast/src/documentation/canonical.rs new file mode 100644 index 000000000..6bf849c02 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -0,0 +1,107 @@ +//! Canonical identities and flat child batches; no parent recovery on lookup. + +use std::collections::HashMap; +use std::ops::Range; + +use super::budget::WorkBudget; +use super::{NodeEvidence, OwnerId, SourceContext, SourceError}; +use crate::Node; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) struct NodeId(pub(super) usize); + +#[derive(Debug)] +pub(super) enum Projection { + Unsupported, + Pending, + Ready(Vec), +} + +#[derive(Debug)] +pub(super) struct CanonicalNode<'s> { + pub(super) evidence: NodeEvidence<'s>, + pub(super) parent: Option, + pub(super) ordinal: usize, + pub(super) field: Option<&'static str>, + pub(super) children: Range, + pub(super) projection: Projection, + pub(super) pending: Vec, + pub(super) pending_parent: Option, + pub(super) following: Option, +} + +#[derive(Debug)] +pub(super) struct CanonicalNodes<'s> { + root: NodeEvidence<'s>, + by_id: HashMap>, + pub(super) nodes: Vec>, + pub(super) children: Vec, +} + +// Counts candidate validations, including hash collisions and zero-width nodes. +crate::observation::counter!(identity_probes, cfg(any(test, feature = "test-support"))); + +impl<'s> CanonicalNodes<'s> { + pub(super) fn new(root: NodeEvidence<'s>) -> Self { + Self { + root, + by_id: HashMap::new(), + nodes: Vec::new(), + children: Vec::new(), + } + } + + pub(super) fn insert( + &mut self, + evidence: NodeEvidence<'s>, + parent: Option, + ordinal: usize, + ) -> NodeId { + let id = NodeId(self.nodes.len()); + self.by_id.entry(evidence.node().id()).or_default().push(id); + self.nodes.push(CanonicalNode { + evidence, + parent, + ordinal, + field: None, + children: 0..0, + projection: Projection::Unsupported, + pending: Vec::new(), + pending_parent: None, + following: None, + }); + id + } + + pub(super) fn lookup(&self, node: tree_sitter::Node<'_>) -> Result { + if node.into_raw().tree != self.root.node().into_raw().tree { + return Err(SourceError::ForeignTree); + } + if let Some(candidates) = self.by_id.get(&node.id()) { + for &id in candidates { + identity_probes::record(); + if self.nodes[id.0].evidence.validate(node).is_ok() { + return Ok(id); + } + } + } + Err(SourceError::NoncanonicalNode) + } + + pub(super) fn batch( + &mut self, + id: NodeId, + children: &[Node<'s>], + context: &SourceContext<'s>, + budget: &B, + ) -> Result<(), SourceError> { + let start = self.children.len(); + for (ordinal, child) in children.iter().enumerate() { + budget.step().map_err(Into::into)?; + let child_id = self.insert(context.node(child.as_tree_sitter())?, Some(id), ordinal); + self.children.push(child_id); + } + self.nodes[id.0].children = start..self.children.len(); + Ok(()) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs new file mode 100644 index 000000000..359e53ef8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -0,0 +1,1148 @@ +//! Coordinated source-order traversal and immutable-index construction. + +use super::budget::{CollectionBudget, WorkBudget}; +use super::canonical::{CanonicalNodes, NodeId, Projection}; +use super::streaming::{markers, positional}; +use super::*; +use crate::{Ancestors, Checker, FoldCache, Node, SiblingCache}; + +enum Visit { + Enter(NodeId, usize), + Exit(NodeId, usize), +} + +#[allow(clippy::trivially_copy_pass_by_ref)] +pub(crate) fn collect_typed<'s, T: Checker + crate::traits::LanguageInfo>( + language: crate::LANG, + tree: &'s tree_sitter::Tree, + source: &'s [u8], + context: &DocumentationContext, + options: &DocumentationOptions, +) -> Result, CollectionError> { + let budget = CollectionBudget::default(); + budget.checkpoint()?; + let grammar = language + .tree_sitter_language() + .map_err(|_| CollectionError::LanguageDisabled(language))?; + let profile = options.profile.resolve(language)?; + if *tree.language() != grammar { + return Err(CollectionError::GrammarMismatch); + } + let root = tree.root_node(); + bounds(root, source.len())?; + let source = SourceContext::with_budget(tree, source, &budget)?; + let canonical = CanonicalNodes::new(source.node(root)?); + let logical_filename = if let Some(filename) = &context.logical_filename { + let mut copied = String::new(); + for character in filename.chars() { + budget.bytes(character.len_utf8())?; + copied.push(character); + } + Some(copied) + } else { + None + }; + let mut builder = Builder { + index: DocumentationIndex { + source, + facts: Facts::default(), + canonical, + context: DocumentationContext { logical_filename }, + options: *options, + profile, + capability: if profile == Profile::Helper { + Capability::NoDeclarationModel + } else { + Capability::Partial + }, + assessments: Vec::new(), + evidence: Vec::new(), + associations_by_owner: Vec::new(), + assessments_by_owner: Vec::new(), + owner_nodes: Vec::new(), + documents_ordered: Vec::new(), + associations_ordered: Vec::new(), + }, + drafts: Vec::new(), + pending_attributes: Vec::new(), + names: super::names::Names::default(), + }; + let root_id = builder + .index + .canonical + .insert(builder.index.source.node(root)?, None, 0); + if profile != Profile::Helper { + builder.add_owner(root_id, Owner::File(builder.index.source.node(root)?)); + builder.walk::(&budget)?; + builder.finish(&budget)?; + } + budget.checkpoint()?; + Ok(builder.index) +} + +fn bounds(node: tree_sitter::Node<'_>, length: usize) -> Result<(), CollectionError> { + if node.start_byte() > node.end_byte() || node.end_byte() > length { + Err(CollectionError::SourceBounds) + } else { + Ok(()) + } +} + +struct Draft<'s> { + fragments: Vec, + target: Option, + scope: NodeId, + binding: Option>, + role: DocumentRole, + unresolved: Option, + pending: bool, + gap: bool, +} + +struct Builder<'s> { + index: DocumentationIndex<'s>, + drafts: Vec>, + pending_attributes: Vec<(NodeId, FragmentId, Option)>, + names: super::names::Names, +} + +trait OwnerCandidates: Checker { + fn owner_candidate<'s>(node: &Node<'s>, code: &[u8], ancestors: Ancestors<'s, '_>) -> bool; +} + +impl OwnerCandidates for T { + fn owner_candidate<'s>(node: &Node<'s>, code: &[u8], ancestors: Ancestors<'s, '_>) -> bool { + match T::lang() { + crate::LANG::Typescript => { + crate::roles::typescript::doc_target::owns(node, code, ancestors) + } + crate::LANG::Tsx => crate::roles::tsx::doc_target::owns(node, code, ancestors), + _ => T::is_source_doc_target(node, code, ancestors), + } + } +} + +// Counts the actual primary visits and owner classification requests. +crate::observation::counter!(visits, cfg(any(test, feature = "test-support"))); +crate::observation::counter!( + target_classifications, + cfg(any(test, feature = "test-support")) +); +crate::observation::counter!(owner_projections, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(child_batches, cfg(any(test, feature = "test-support"))); + +impl<'s> Builder<'s> { + fn add_owner(&mut self, id: NodeId, owner: Owner<'s>) { + owner_projections::record(); + let owner_id = OwnerId(self.index.facts.owners.len()); + self.index.facts.owners.push(owner); + self.index.associations_by_owner.push(Vec::new()); + self.index.assessments_by_owner.push(Vec::new()); + self.index.owner_nodes.push(id); + self.index.canonical.nodes[id.0].projection = Projection::Ready(vec![owner_id]); + } + + fn walk( + &mut self, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let mut stack = vec![Visit::Enter(NodeId(0), 0)]; + let mut chain = Vec::new(); + let folds = FoldCache::default(); + let mut siblings = SiblingCache::default(); + let root = Node::from_tree_sitter(self.index.canonical.nodes[0].evidence.node()); + let mut cursor = root.as_tree_sitter().walk(); + let mut children = Vec::new(); + let mut fields = Vec::new(); + while let Some(visit) = stack.pop() { + budget.step()?; + match visit { + Visit::Exit(id, depth) => { + chain.truncate(depth); + self.finalize_projection(id, budget)?; + } + Visit::Enter(id, depth) => { + visits::record(); + chain.truncate(depth); + let node = + Node::from_tree_sitter(self.index.canonical.nodes[id.0].evidence.node()); + bounds(node.as_tree_sitter(), self.index.source.bytes().len())?; + let ancestors = Ancestors::for_walk(&chain, &node, &folds, &siblings); + self.register::(id, &node, ancestors, budget)?; + self.recognize::(id, &node, ancestors, budget)?; + children.clear(); + fields.clear(); + cursor.reset(node.as_tree_sitter()); + if cursor.goto_first_child() { + loop { + budget.step()?; + let child = cursor.node(); + bounds(child, self.index.source.bytes().len())?; + children.push(Node::from_tree_sitter(child)); + fields.push(if fields_needed(self.index.profile, node.kind()) { + field_requests::record(); + cursor.field_name() + } else { + None + }); + if !cursor.goto_next_sibling() { + break; + } + } + } + child_batches::record(); + self.index + .canonical + .batch(id, &children, &self.index.source, budget)?; + let mut following = None; + for &child in self.index.canonical.children + [self.index.canonical.nodes[id.0].children.clone()] + .iter() + .rev() + { + budget.step()?; + let record = &mut self.index.canonical.nodes[child.0]; + record.following = following; + let child_node = Node::from_tree_sitter(record.evidence.node()); + if !T::is_comment(&child_node) && child_node.kind() != "attribute_item" { + following = Some(child); + } + } + for (&child, field) in self.index.canonical.children + [self.index.canonical.nodes[id.0].children.clone()] + .iter() + .zip(&fields) + { + budget.step()?; + self.index.canonical.nodes[child.0].field = *field; + } + siblings.record_with_budget(&node, depth, children.iter().copied(), budget)?; + stack.push(Visit::Exit(id, depth)); + for &child in self.index.canonical.children + [self.index.canonical.nodes[id.0].children.clone()] + .iter() + .rev() + { + budget.step()?; + stack.push(Visit::Enter(child, depth + 1)); + } + chain.push(node); + } + } + } + debug_assert!(chain.is_empty()); + Ok(()) + } + + fn register( + &mut self, + id: NodeId, + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + if id.0 == 0 { + return Ok(()); + } + budget.step()?; + target_classifications::record(); + let wrapper_child = matches!( + self.index.profile, + Profile::Jsdoc | Profile::BcaTypescriptSource + ) && ancestors + .parent(node) + .is_some_and(|parent| is_wrapper(self.index.profile, parent.kind())); + let qualifies = if wrapper_child { + T::owner_candidate(node, self.index.source.bytes(), ancestors) + } else { + T::is_source_doc_target(node, self.index.source.bytes(), ancestors) + }; + if qualifies { + if is_wrapper(self.index.profile, node.kind()) + || needs_slot(self.index.profile, node.kind()) + || (self.index.profile == Profile::Doxygen + && matches!( + node.kind(), + "preproc_if" + | "preproc_ifdef" + | "preproc_else" + | "preproc_elif" + | "preproc_elifdef" + | "linkage_specification" + | "template_declaration" + | "expression_statement" + )) + || node.is_error() + || node.is_missing() + { + self.index.canonical.nodes[id.0].projection = Projection::Pending; + } else { + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + } + } + Ok(()) + } + + fn recognize( + &mut self, + id: NodeId, + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + budget.step()?; + if self.index.profile == Profile::Rust + && matches!(node.kind(), "attribute_item" | "inner_attribute_item") + { + self.rust_attribute(id, node, budget)?; + } + if !T::is_comment(node) { + return Ok(()); + } + let mut marker_runs = Vec::new(); + markers::source_comment::( + node, + ancestors, + &mut markers::SourceRequest { + context: &self.index.source, + retain_unbound: self.index.options.retain_unbound, + sink: &mut |run| marker_runs.push(run), + }, + )?; + for run in marker_runs { + self.marker_run(run, budget)?; + } + let mut positional_runs = Vec::new(); + positional::source_comment::( + node, + ancestors, + &mut positional::SourceRequest { + context: &self.index.source, + retain_unbound: self.index.options.retain_unbound, + retain_directives: self.index.options.retain_directives, + sink: &mut |run| positional_runs.push(run), + }, + )?; + for run in positional_runs { + self.positional_run(run, budget)?; + } + if self.index.profile == Profile::Ldoc + && ancestors.parent(node).is_some_and(|parent| { + matches!(parent.kind(), "parameters" | "field" | "table_constructor") + }) + { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Selection, + reason: "Native LDoc parameter/table comment awaits adapter context", + node: Some(self.index.canonical.nodes[id.0].evidence), + document: None, + }); + let scope = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); + self.index.canonical.nodes[scope.0].pending.push(assessment); + } + Ok(()) + } + + fn evidence_id( + &self, + node: Option>, + ) -> Result, CollectionError> { + node.map(|node| self.index.canonical.lookup(node.node()).map_err(Into::into)) + .transpose() + } + + fn fragment( + &mut self, + source: SourcePieces<'s>, + node: NodeEvidence<'s>, + form: FragmentForm, + ) -> FragmentId { + let id = FragmentId(self.index.facts.fragments.len()); + self.index.facts.fragments.push(Fragment { + source, + node: Some(node), + form, + }); + id + } + + fn marker_run( + &mut self, + run: markers::MarkerRun<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let target = self.evidence_id(run.target)?; + let scope = self.evidence_id(run.containing)?.unwrap_or(NodeId(0)); + let code_before = self.evidence_id(run.code_before)?; + let mut local: std::collections::HashMap = std::collections::HashMap::new(); + let mut gathered: std::collections::HashMap = + std::collections::HashMap::new(); + let mut forward = Draft { + fragments: Vec::new(), + target, + scope, + binding: run.target, + role: DocumentRole::Primary, + unresolved: run.target_uncertainty, + pending: false, + gap: run.prefix_gap || run.suffix_gap, + }; + for member in run.members { + budget.step()?; + if member.selection != markers::MarkerSelection::Selected { + let fragment = self.fragment(member.source, member.node, FragmentForm::Comment); + self.index.evidence.push(CandidateEvidence { + fragment, + disposition: if member.selection == markers::MarkerSelection::Superseded { + CandidateDisposition::Superseded + } else { + CandidateDisposition::Unattached + }, + }); + continue; + } + let id = self.fragment(member.source, member.node, FragmentForm::Comment); + if matches!(member.placement, markers::MarkerPlacement::Forward) { + forward.fragments.push(id); + forward.unresolved = forward.unresolved.or(member.uncertainty); + } else { + let mut draft = Draft { + fragments: vec![id], + target: None, + scope, + binding: run.target, + role: DocumentRole::Primary, + unresolved: member.uncertainty, + pending: false, + gap: run.prefix_gap || run.suffix_gap, + }; + let local_node = + if let markers::MarkerPlacement::Gathered(gatherer) = member.placement { + gatherer + } else { + member.node + }; + self.local_target(&mut draft, local_node, member.placement, budget)?; + if self.index.profile == Profile::Doxygen { + let raw = &self.index.source.bytes()[member.node.node().byte_range()]; + if matches!(raw.get(..4), Some(b"///<" | b"//!<" | b"/**<" | b"/*!<")) { + draft.target = code_before; + draft.pending = code_before.is_none(); + } + } + if matches!( + member.placement, + markers::MarkerPlacement::Gatherer | markers::MarkerPlacement::Gathered(_) + ) { + if let Some(&index) = gathered.get(&local_node.node().id()) { + self.drafts[index].fragments.push(id); + } else { + gathered.insert(local_node.node().id(), self.drafts.len()); + self.drafts.push(draft); + } + } else if self.index.profile == Profile::Rust + && let Some(target) = draft.target + { + if let Some(&index) = local.get(&target) { + self.drafts[index].fragments.push(id); + } else { + local.insert(target, self.drafts.len()); + self.drafts.push(draft); + } + } else { + self.drafts.push(draft); + } + } + } + if !forward.fragments.is_empty() { + self.drafts.push(forward); + } + Ok(()) + } + + fn positional_run( + &mut self, + run: positional::SourceRun<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let target = self.evidence_id(run.target)?; + let scope = self.evidence_id(run.containing)?.unwrap_or(NodeId(0)); + let mut draft = Draft { + fragments: Vec::new(), + target, + scope, + binding: run.target, + role: DocumentRole::Primary, + unresolved: run.uncertainty, + pending: false, + gap: run.prefix_gap || run.suffix_gap, + }; + for member in run.members { + budget.step()?; + let fragment = self.fragment(member.source, member.node, FragmentForm::Comment); + if member.selected { + draft.fragments.push(fragment); + } else { + self.index.evidence.push(CandidateEvidence { + fragment, + disposition: if member.directive { + CandidateDisposition::Directive + } else { + CandidateDisposition::Unattached + }, + }); + } + } + if draft.fragments.is_empty() { + return Ok(()); + } + match run.selection { + positional::RunSelection::Opener(positional::OpenerReason::FirstFile) => { + draft.target = Some(NodeId(0)); + draft.role = DocumentRole::FilePackage; + } + positional::RunSelection::Opener( + positional::OpenerReason::Explicit | positional::OpenerReason::Tagged, + ) => { + draft.target = None; + draft.pending = true; + } + _ => {} + } + self.drafts.push(draft); + Ok(()) + } + + fn local_target( + &self, + draft: &mut Draft<'s>, + node: NodeEvidence<'s>, + placement: markers::MarkerPlacement<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + budget.step()?; + if draft.unresolved == Some(UnresolvedReason::Expansion) { + return Ok(()); + } + if self.index.profile == Profile::Doxygen { + let raw = &self.index.source.bytes()[node.node().byte_range()]; + if let Some((command, _)) = crate::lang_helpers::doxygen::structural_command(raw) { + if command == b"file" { + draft.target = Some(NodeId(0)); + draft.role = DocumentRole::FilePackage; + } else { + draft.target = None; + draft.pending = true; + } + return Ok(()); + } + } + if self.index.profile == Profile::Doxygen + && !matches!( + placement, + markers::MarkerPlacement::Gatherer | markers::MarkerPlacement::Gathered(_) + ) + { + draft.pending = true; + } + match self.index.profile { + Profile::Rust => { + if draft.scope.0 == 0 { + draft.target = Some(NodeId(0)); + draft.role = DocumentRole::FilePackage; + } else if let Some(parent) = self.index.canonical.nodes[draft.scope.0].parent { + let evidence = self.index.canonical.nodes[parent.0].evidence; + if matches!(evidence.node().kind(), "mod_item" | "function_item") { + draft.target = Some(parent); + if evidence.node().kind() == "mod_item" { + draft.role = DocumentRole::FilePackage; + } + } else { + draft.pending = true; + } + } else { + draft.pending = true; + } + } + Profile::BcaPhpSource if draft.scope.0 == 0 => { + draft.target = Some(NodeId(0)); + draft.role = DocumentRole::FilePackage; + } + Profile::Jsdoc | Profile::BcaTypescriptSource => { + let raw = &self.index.source.bytes()[node.node().byte_range()]; + let file = if self.index.profile == Profile::BcaTypescriptSource { + crate::lang_helpers::doc_text::tsdoc_module(raw) + } else { + crate::lang_helpers::doc_text::jsdoc_file(raw) + }; + if file { + draft.target = Some(NodeId(0)); + draft.role = DocumentRole::FilePackage; + } else { + draft.pending = true; + } + } + _ => draft.pending = true, + } + Ok(()) + } + + fn rust_attribute( + &mut self, + id: NodeId, + node: &Node<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let mut is_doc = false; + for child in node.children() { + budget.step()?; + if child.kind() != "attribute" { + continue; + } + let mut cursor = child.cursor(); + for path in child.children_with(&mut cursor) { + budget.step()?; + if !path.is_named() { + continue; + } + if path.kind() == "identifier" + && self.index.source.covers(path.start_byte()..path.end_byte()) + { + let bytes = &self.index.source.bytes()[path.start_byte()..path.end_byte()]; + is_doc = matches!(bytes, b"doc" | b"cfg_attr"); + } + break; + } + } + if !is_doc { + return Ok(()); + } + let mut target = if node.kind() == "attribute_item" { + self.index.canonical.nodes[id.0].following + } else { + let parent = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); + if parent.0 == 0 { + Some(parent) + } else { + self.index.canonical.nodes[parent.0] + .parent + .filter(|&outer| { + matches!( + self.index.canonical.nodes[outer.0].evidence.node().kind(), + "mod_item" | "function_item" + ) + }) + } + }; + if let Some(candidate) = target { + let target_node = self.index.canonical.nodes[candidate.0].evidence.node(); + if node.kind() == "attribute_item" + && !self + .index + .source + .covers(node.end_byte()..target_node.start_byte()) + { + target = None; + } + } + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Occurrence, + reason: "Structured Rust doc/cfg_attr carrier awaits interpretation", + node: Some(self.index.canonical.nodes[id.0].evidence), + document: None, + }); + let pending_scope = target + .or(self.index.canonical.nodes[id.0].parent) + .unwrap_or(NodeId(0)); + self.index.canonical.nodes[pending_scope.0] + .pending + .push(assessment); + let publication = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Publication, + reason: "Rust documentation/publication metadata awaits interpretation", + node: Some(self.index.canonical.nodes[id.0].evidence), + document: None, + }); + self.index.canonical.nodes[pending_scope.0] + .pending + .push(publication); + let source = self + .index + .source + .pieces_with_budget(node.start_byte()..node.end_byte(), budget)?; + let fragment = self.fragment( + source, + self.index.canonical.nodes[id.0].evidence, + FragmentForm::Attribute, + ); + self.pending_attributes.push((id, fragment, target)); + Ok(()) + } + + fn finalize_projection( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + budget.step()?; + let node = self.index.canonical.nodes[id.0].evidence.node(); + if self.index.profile == Profile::Doxygen + && matches!(node.kind(), "declaration" | "field_declaration") + && matches!( + self.index.canonical.nodes[id.0].projection, + Projection::Pending + ) + { + return self.c_slots(id, budget); + } + if !is_wrapper(self.index.profile, node.kind()) + || !matches!( + self.index.canonical.nodes[id.0].projection, + Projection::Pending + ) + { + return Ok(()); + } + let range = self.index.canonical.nodes[id.0].children.clone(); + let mut owners = Vec::new(); + for &child in &self.index.canonical.children[range] { + budget.step()?; + let record = &self.index.canonical.nodes[child.0]; + if matches!( + self.index.profile, + Profile::Jsdoc | Profile::BcaTypescriptSource + ) && node.kind() == "export_statement" + && !matches!(record.field, Some("declaration" | "value")) + { + continue; + } + if self.index.profile == Profile::Yard + && matches!(node.kind(), "if_modifier" | "unless_modifier") + && record.field != Some("body") + { + continue; + } + if let Projection::Ready(ids) = &self.index.canonical.nodes[child.0].projection { + for &owner in ids { + budget.step()?; + owners.push(owner); + } + break; + } + } + if !owners.is_empty() { + self.index.canonical.nodes[id.0].projection = Projection::Ready(owners); + self.index.canonical.nodes[id.0].pending.clear(); + } + Ok(()) + } + + fn c_slots(&mut self, id: NodeId, budget: &CollectionBudget) -> Result<(), CollectionError> { + let enclosing = OwnerId(self.index.facts.owners.len()); + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + let mut slots = Vec::new(); + let mut work = Vec::new(); + for &child in + &self.index.canonical.children[self.index.canonical.nodes[id.0].children.clone()] + { + budget.step()?; + if self.index.canonical.nodes[child.0].field == Some("declarator") { + work.push(child); + } + } + let mut ordinal = 0; + for mut child in work { + let mut function = false; + loop { + budget.step()?; + let record = &self.index.canonical.nodes[child.0]; + let node = record.evidence.node(); + if matches!(node.kind(), "identifier" | "field_identifier") { + if function { + slots.push(enclosing); + let declaration = self.index.canonical.nodes[id.0].evidence.node(); + let mut end = declaration.end_byte(); + if self.index.source.bytes().get(end.saturating_sub(1)) == Some(&b';') { + end -= 1; + } + self.names.insert( + &self.index.source.bytes()[node.byte_range()], + &self.index.source.bytes()[declaration.start_byte()..end], + enclosing, + budget, + )?; + } else { + let source = self + .index + .source + .pieces_with_budget(node.byte_range(), budget)?; + let slot = OwnerId(self.index.facts.owners.len()); + self.index.facts.owners.push(Owner::Slot(Slot { + enclosing, + role: SlotRole::Field, + ordinal, + source, + })); + self.index.associations_by_owner.push(Vec::new()); + self.index.assessments_by_owner.push(Vec::new()); + self.index.owner_nodes.push(id); + slots.push(slot); + ordinal += 1; + } + break; + } + function |= node.kind() == "function_declarator"; + let mut inner = None; + for &candidate in &self.index.canonical.children[record.children.clone()] { + budget.step()?; + if self.index.canonical.nodes[candidate.0].field == Some("declarator") { + inner = Some(candidate); + break; + } + } + let Some(next) = inner else { + break; + }; + child = next; + } + } + self.index.canonical.nodes[id.0].projection = if slots.is_empty() { + Projection::Pending + } else { + self.index.canonical.nodes[id.0].pending.clear(); + Projection::Ready(slots) + }; + Ok(()) + } + + fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + self.combine_pending(budget)?; + for draft in std::mem::take(&mut self.drafts) { + budget.step()?; + self.document(draft, budget)?; + } + self.pending_scopes(budget)?; + self.order_results(budget) + } + + fn pending_scopes(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + for id in 0..self.index.canonical.nodes.len() { + budget.step()?; + if matches!( + self.index.canonical.nodes[id].projection, + Projection::Pending + ) { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(self.index.canonical.nodes[id].evidence), + document: None, + }); + self.index.canonical.nodes[id].pending.push(assessment); + } + if let Some(parent) = self.index.canonical.nodes[id].parent { + let parent_node = &self.index.canonical.nodes[parent.0]; + let inherited = if parent_node.pending.is_empty() { + parent_node.pending_parent + } else { + Some(parent) + }; + self.index.canonical.nodes[id].pending_parent = inherited; + } + } + Ok(()) + } + + fn order_results(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + let mut keys = Vec::new(); + for (ordinal, document) in self.index.facts.documents.iter().enumerate() { + budget.step()?; + let fragment = &self.index.facts.fragments[document.fragments[0].0]; + let first = fragment + .source + .pieces() + .first() + .ok_or(SourceError::Excluded)? + .range(); + let last = fragment + .source + .pieces() + .last() + .ok_or(SourceError::Excluded)? + .range(); + keys.push((first.start, last.end, document.role.source_rank(), ordinal)); + } + for key in super::ordering::ordered(keys, budget)? { + budget.step()?; + self.index.documents_ordered.push(key.3); + } + let mut ranks = Vec::new(); + for _ in 0..self.index.facts.documents.len() { + budget.step()?; + ranks.push(0); + } + for (rank, &id) in self.index.documents_ordered.iter().enumerate() { + budget.step()?; + ranks[id] = rank; + } + let mut associations = Vec::new(); + for (ordinal, association) in self.index.facts.associations.iter().enumerate() { + budget.step()?; + let (anchor, slot) = association.owners.first().map_or((0, 0), |id| { + let node = &self.index.canonical.nodes[self.index.owner_nodes[id.0].0]; + match &self.index.facts.owners[id.0] { + Owner::Slot(slot) => (slot.source.pieces()[0].range().start, slot.ordinal), + _ => (node.evidence.node().start_byte(), node.ordinal), + } + }); + associations.push((ranks[association.document.0], anchor, slot, ordinal)); + } + for (_, _, _, ordinal) in super::ordering::ordered(associations, budget)? { + budget.step()?; + self.index.associations_ordered.push(ordinal); + } + for owners in &mut self.index.associations_by_owner { + budget.step()?; + owners.clear(); + } + for &ordinal in &self.index.associations_ordered { + budget.step()?; + for &owner in &self.index.facts.associations[ordinal].owners { + budget.step()?; + self.index.associations_by_owner[owner.0].push(ordinal); + } + } + Ok(()) + } + + fn combine_pending(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + let mut by_target = std::collections::HashMap::new(); + for (index, draft) in self.drafts.iter().enumerate() { + budget.step()?; + if let Some(target) = draft.target { + by_target.insert(target, index); + } + } + for (node, fragment, target) in std::mem::take(&mut self.pending_attributes) { + budget.step()?; + if let Some(&index) = target.as_ref().and_then(|target| by_target.get(target)) { + self.drafts[index].fragments.push(fragment); + self.drafts[index].pending = true; + } else { + let scope = self.index.canonical.nodes[node.0] + .parent + .unwrap_or(NodeId(0)); + if let Some(target) = target { + by_target.insert(target, self.drafts.len()); + } + self.drafts.push(Draft { + fragments: vec![fragment], + target, + scope, + binding: target.map(|id| self.index.canonical.nodes[id.0].evidence), + role: if target.is_some_and(|id| { + id.0 == 0 + || self.index.canonical.nodes[id.0].evidence.node().kind() == "mod_item" + }) { + DocumentRole::FilePackage + } else { + DocumentRole::Primary + }, + unresolved: None, + pending: true, + gap: false, + }); + } + } + Ok(()) + } + + fn document( + &mut self, + mut draft: Draft<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let (content, attribute) = self.render_draft(&mut draft, budget)?; + let composition = if attribute { + Composition::AttributeSequence + } else if draft.fragments.len() == 1 { + Composition::Single + } else { + Composition::CommentRun + }; + let document = DocumentId(self.index.facts.documents.len()); + self.index.facts.documents.push(Document { + fragments: draft.fragments, + composition, + role: draft.role, + content, + }); + let mut owners = Vec::new(); + let mut pending = draft.pending; + let mut named_resolution = None; + if self.index.profile == Profile::Doxygen && draft.target.is_none() { + let fragment = + &self.index.facts.fragments[self.index.facts.documents[document.0].fragments[0].0]; + if let Some(node) = fragment.node { + let raw = &self.index.source.bytes()[node.node().byte_range()]; + if let Some((b"fn", name)) = crate::lang_helpers::doxygen::structural_command(raw) { + let (found, reason) = self.names.resolve(name, budget)?; + owners = found; + named_resolution = + Some(reason.map_or(Resolution::Resolved, Resolution::Unresolved)); + pending = false; + } + } + } + if let Some(target) = draft.target { + match &self.index.canonical.nodes[target.0].projection { + Projection::Ready(ids) => { + for &id in ids { + budget.step()?; + owners.push(id); + } + } + Projection::Pending | Projection::Unsupported => pending = true, + } + } + if pending { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: if attribute { + AssessmentAxis::Composition + } else { + AssessmentAxis::Owner + }, + reason: if attribute { + "Rust doc/cfg_attr carrier awaits adapter composition" + } else { + "Selected local or wrapper form awaits owner projection" + }, + node: draft.binding, + document: Some(document), + }); + for owner in &owners { + budget.step()?; + self.index.assessments_by_owner[owner.0].push(assessment); + } + if owners.is_empty() { + self.index.canonical.nodes[draft.target.unwrap_or(draft.scope).0] + .pending + .push(assessment); + } + } + if !owners.is_empty() || draft.unresolved.is_some() || named_resolution.is_some() { + let association = self.index.facts.associations.len(); + for owner in &owners { + budget.step()?; + self.index.associations_by_owner[owner.0].push(association); + } + self.index.facts.associations.push(Association { + document, + owners, + resolution: named_resolution.unwrap_or_else(|| { + draft + .unresolved + .map_or(Resolution::Resolved, Resolution::Unresolved) + }), + convention: Convention(self.index.profile.name()), + binding: draft.binding, + lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence, + publication: Publication::Unknown, + }); + } + Ok(()) + } + + fn render_draft( + &self, + draft: &mut Draft<'s>, + budget: &CollectionBudget, + ) -> Result<(Content<'s>, bool), CollectionError> { + let mut keys = Vec::new(); + for id in &draft.fragments { + budget.step()?; + let start = self.index.facts.fragments[id.0].source.pieces()[0] + .range() + .start; + keys.push((start, id.0)); + } + draft.fragments.clear(); + for (_, id) in super::ordering::ordered(keys, budget)? { + budget.step()?; + draft.fragments.push(FragmentId(id)); + } + let mut fragments = Vec::new(); + let mut attribute = false; + for id in &draft.fragments { + budget.step()?; + let fragment = &self.index.facts.fragments[id.0]; + attribute |= fragment.form == FragmentForm::Attribute; + fragments.push(fragment); + } + let content = if attribute { + Content::PendingAdapter + } else if draft.gap { + Content::Unavailable(UnavailableReason::ExcludedGap) + } else { + match super::text::comments::render( + self.index.profile, + &self.index.source, + &fragments, + budget, + ) { + Ok(content) => content, + Err(super::text::TextError::Source(error)) => return Err(error.into()), + Err(super::text::TextError::Unavailable(reason)) => Content::Unavailable(reason), + } + }; + Ok((content, attribute)) + } +} + +fn is_wrapper(profile: Profile, kind: &str) -> bool { + match profile { + Profile::Jsdoc | Profile::BcaTypescriptSource => { + matches!(kind, "export_statement" | "ambient_declaration") + } + Profile::Yard => matches!( + kind, + "if_modifier" | "unless_modifier" | "body_statement" | "block_body" | "then" + ), + Profile::Ldoc => kind == "block", + _ => false, + } +} + +fn needs_slot(profile: Profile, kind: &str) -> bool { + match profile { + Profile::Doxygen => matches!(kind, "declaration" | "field_declaration"), + Profile::GoDoc => matches!(kind, "field_declaration" | "method_elem" | "type_elem"), + Profile::Jsdoc | Profile::BcaTypescriptSource => matches!( + kind, + "lexical_declaration" + | "variable_declaration" + | "expression_statement" + | "required_parameter" + | "optional_parameter" + ), + _ => false, + } +} + +fn fields_needed(profile: Profile, kind: &str) -> bool { + (profile == Profile::Doxygen + && (matches!(kind, "declaration" | "field_declaration") || kind.ends_with("declarator"))) + || (matches!(profile, Profile::Jsdoc | Profile::BcaTypescriptSource) + && kind == "export_statement") + || (profile == Profile::Yard && matches!(kind, "if_modifier" | "unless_modifier")) +} + +crate::observation::counter!(field_requests, cfg(any(test, feature = "test-support"))); + +#[cfg(test)] +mod tests; diff --git a/big-code-analysis-ast/src/documentation/collector/tests.rs b/big-code-analysis-ast/src/documentation/collector/tests.rs new file mode 100644 index 000000000..66c31dcf7 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/tests.rs @@ -0,0 +1,1041 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(any( + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "go", + feature = "groovy", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "php", + feature = "ruby", + feature = "rust", + feature = "typescript" +))] +fn assert_positive( + language: LANG, + source: &[u8], + fragment: std::ops::Range, + owner: std::ops::Range, + text: &str, +) { + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!( + !parser.root_node().has_error(), + "{language:?}: {:?}", + parser.root_node() + ); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + language, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + let documents: Vec<_> = index.documents().collect(); + assert_eq!(documents.len(), 1, "{language:?}"); + let document = documents[0]; + assert_eq!(document.get().fragment_count(), 1); + let raw = index.facts().document_fragment(document, 0).unwrap(); + assert_eq!(raw.get().source().pieces().len(), 1); + assert_eq!(raw.get().source().pieces()[0].range(), fragment); + let complete = index.complete_text(document).unwrap().unwrap(); + assert_eq!(complete.text(), text, "{language:?}"); + let associations: Vec<_> = index.associations().collect(); + assert_eq!(associations.len(), 1, "{language:?}"); + assert_eq!(associations[0].get().resolution, Resolution::Resolved); + assert_eq!(associations[0].get().publication, Publication::Unknown); + let target = index.facts().associated_owner(associations[0], 0).unwrap(); + let Owner::Node(node) = target.get() else { + panic!("expected node owner") + }; + assert_eq!(node.node().byte_range(), owner, "{language:?}"); + let query = index.node_associations(node.node()).unwrap(); + assert_eq!(query.associations().count(), 1); + let origins: Vec<_> = complete.origins(0..text.len()).unwrap().collect(); + assert_eq!(origins.len(), 1); + let OriginView::Copied(piece) = &origins[0].origin else { + panic!("copied origin") + }; + assert_eq!(piece.bytes(), text.as_bytes()); + let offset = match language { + LANG::Php => 4, + LANG::Ruby => 2, + _ => 3, + }; + assert_eq!( + piece.range(), + fragment.start + offset..fragment.start + offset + text.len() + ); + } +} + +#[cfg(feature = "rust")] +#[test] +fn rust_production_positive() { + assert_positive(LANG::Rust, b"///audit\nfn f() {}", 0..8, 9..18, "audit"); +} +#[cfg(feature = "java")] +#[test] +fn java_production_positive() { + assert_positive(LANG::Java, b"///audit\nclass C {}", 0..8, 9..19, "audit"); +} +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_production_positive() { + assert_positive( + LANG::Kotlin, + b"/**audit*/\nfun f() {}", + 0..10, + 11..21, + "audit", + ); +} +#[cfg(feature = "groovy")] +#[test] +fn groovy_production_positive() { + assert_positive( + LANG::Groovy, + b"/**audit*/\nclass C {}", + 0..10, + 11..21, + "audit", + ); +} +#[cfg(feature = "csharp")] +#[test] +fn csharp_production_positive() { + assert_positive( + LANG::Csharp, + b"///audit\nclass C {}", + 0..27, + 28..38, + "audit", + ); +} +#[cfg(feature = "php")] +#[test] +fn php_production_positive() { + assert_positive( + LANG::Php, + b"; }", + 0..10, + 11..42, + "audit", + ); +} +#[cfg(feature = "c")] +#[test] +fn c_production_positive() { + assert_positive( + LANG::C, + b"/**audit*/\nvoid f(void) {}", + 0..10, + 11..26, + "audit", + ); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_production_positive() { + assert_positive( + LANG::Cpp, + b"/**audit*/\nvoid f() {}", + 0..10, + 11..22, + "audit", + ); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_production_positive() { + assert_positive( + LANG::Mozcpp, + b"/**audit*/\nvoid f() {}", + 0..10, + 11..22, + "audit", + ); +} +#[cfg(feature = "objc")] +#[test] +fn objc_production_positive() { + assert_positive( + LANG::Objc, + b"/**audit*/\nvoid f(void) {}", + 0..10, + 11..26, + "audit", + ); +} +#[cfg(feature = "go")] +#[test] +fn go_production_positive() { + assert_positive( + LANG::Go, + b"package p\n// audit\nfunc F() {}", + 10..18, + 19..30, + "audit", + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_production_positive() { + assert_positive(LANG::Ruby, b"# audit\ndef f\nend", 0..7, 8..17, "audit"); +} +#[cfg(feature = "lua")] +#[test] +fn lua_production_positive() { + assert_positive( + LANG::Lua, + b"module(\"m\")\n---audit\nfunction f() end", + 12..20, + 21..37, + "audit", + ); +} + +#[cfg(feature = "rust")] +#[test] +fn rust_joint_smoke_pins_exact_composition_and_maps() { + let parser = + AnyParser::parse(LANG::Rust, b"///a\n///b\nfn f() {}".to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let document = index.documents().next().unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(document.get().fragment_count(), 2); + assert_eq!( + index + .facts() + .document_fragment(document, 0) + .unwrap() + .get() + .source() + .pieces()[0] + .range(), + 0..4 + ); + assert_eq!( + index + .facts() + .document_fragment(document, 1) + .unwrap() + .get() + .source() + .pieces()[0] + .range(), + 5..9 + ); + let text = index.complete_text(document).unwrap().unwrap(); + assert_eq!(text.text(), "a\nb"); + let portions: Vec<_> = text.origins(0..3).unwrap().collect(); + assert_eq!(portions.len(), 3); + let OriginView::Copied(a) = &portions[0].origin else { + panic!("copied a") + }; + assert_eq!(a.range(), 3..4); + assert_eq!(portions[1].origin, OriginView::Synthetic); + assert_eq!(portions[1].output, 1..2); + let OriginView::Copied(b) = &portions[2].origin else { + panic!("copied b") + }; + assert_eq!(b.range(), 8..9); +} + +#[cfg(feature = "rust")] +#[test] +fn rust_pending_attributes_never_report_complete_partial_text() { + for (source, forms) in [ + ( + "#[doc = \"audit\"]\nfn f() {}", + vec![FragmentForm::Attribute], + ), + ( + "/// first\n#[doc = \"second\"]\nfn f() {}", + vec![FragmentForm::Comment, FragmentForm::Attribute], + ), + ( + "#[doc = \"first\"]\n/// second\nfn f() {}", + vec![FragmentForm::Attribute, FragmentForm::Comment], + ), + ("#[doc(hidden)]\nfn f() {}", vec![FragmentForm::Attribute]), + ( + "#[cfg_attr(feature = \"x\", doc = \"audit\")]\nfn f() {}", + vec![FragmentForm::Attribute], + ), + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1, "{source}"); + let document = index.documents().next().unwrap(); + assert!(matches!(document.get().content(), Content::PendingAdapter)); + assert!(index.complete_text(document).unwrap().is_none()); + assert_eq!(document.get().role(), DocumentRole::Primary); + assert_eq!(document.get().fragment_count(), forms.len()); + for (position, form) in forms.into_iter().enumerate() { + assert_eq!( + index + .facts() + .document_fragment(document, position) + .unwrap() + .get() + .form(), + form + ); + } + let owner = parser + .root_node() + .children() + .find(|node| node.kind() == "function_item") + .unwrap(); + let query = index.node_associations(owner.as_tree_sitter()).unwrap(); + assert_eq!(query.associations().count(), 1); + assert!( + query + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Composition) + ); + } + for source in [ + "#[document]\nfn f() {}", + "#[test]\nfn f() {}", + "#[rustfmt::skip]\nfn f() {}", + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 0, "{source}"); + } +} + +#[cfg(feature = "rust")] +#[test] +fn canonical_queries_reject_foreign_nodes_handles_and_edited_values() { + fn send_sync() {} + send_sync::>(); + let source = b"fn f() {}"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let foreign = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let index = parser.documentation(&context, &options).unwrap(); + let second = parser.documentation(&context, &options).unwrap(); + let node = parser + .root_node() + .children() + .next() + .unwrap() + .as_tree_sitter(); + assert_eq!( + index.node_associations(node).unwrap().associations().len(), + 0 + ); + assert!(matches!( + index.node_associations( + foreign + .root_node() + .children() + .next() + .unwrap() + .as_tree_sitter() + ), + Err(OwnerError::Source(SourceError::ForeignTree)) + )); + let mut edited = node; + edited.edit(&tree_sitter::InputEdit { + start_byte: 0, + old_end_byte: 0, + new_end_byte: 1, + start_position: tree_sitter::Point::new(0, 0), + old_end_position: tree_sitter::Point::new(0, 0), + new_end_position: tree_sitter::Point::new(0, 1), + }); + assert!(matches!( + index.node_associations(edited), + Err(OwnerError::Source(SourceError::NoncanonicalNode)) + )); + assert!(matches!( + index.owner_associations(second.facts().owners().next().unwrap()), + Err(OwnerError::Fact(FactError::ForeignIndex)) + )); + assert!(matches!( + index.node_associations(node.child(0).unwrap()), + Err(OwnerError::UnsupportedOwner) + )); +} + +#[cfg(feature = "rust")] +#[test] +fn collector_structural_counters_and_retained_reads_price_real_work() { + use super::{child_batches, owner_projections, target_classifications, visits}; + let parser = AnyParser::parse( + LANG::Rust, + b"///audit\nfn f() {}\nfn g() {}".to_vec(), + None, + None, + ) + .unwrap(); + let count = parser.root_node().preorder().count(); + let before = ( + visits::observed(), + child_batches::observed(), + target_classifications::observed(), + owner_projections::observed(), + crate::documentation::text::renders::observed(), + ); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(visits::observed() - before.0, count); + assert_eq!(child_batches::observed() - before.1, count); + assert_eq!(target_classifications::observed() - before.2, count - 1); + assert_eq!(owner_projections::observed() - before.3, 3); + assert_eq!( + crate::documentation::text::renders::observed() - before.4, + 1 + ); + let document = index.documents().next().unwrap(); + let owner = parser.root_node().children().last().unwrap(); + let before = ( + crate::documentation::canonical::identity_probes::observed(), + crate::documentation::text::renders::observed(), + crate::documentation::text::copy_chunks::observed(), + ); + for _ in 0..128 { + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + "audit" + ); + assert_eq!( + index + .node_associations(owner.as_tree_sitter()) + .unwrap() + .associations() + .len(), + 0 + ); + } + assert_eq!( + crate::documentation::canonical::identity_probes::observed() - before.0, + 128 + ); + assert_eq!( + crate::documentation::text::renders::observed() - before.1, + 0 + ); + assert_eq!( + crate::documentation::text::copy_chunks::observed() - before.2, + 0 + ); +} + +#[cfg(feature = "c")] +#[test] +fn c_declaration_fanout_and_trailing_projection_share_retained_text() { + for (source, names) in [ + ("/**audit*/\nint a, b;", vec!["a", "b"]), + ("struct S { int x; /// 10); + for stop in [1, 2, 3, checkpoints / 2, checkpoints - 1, checkpoints] { + assert!( + matches!( + crate::documentation::budget::cancel_after(stop, || parser + .documentation(&context, &options)), + Err(CollectionError::Cancelled) + ), + "checkpoint {stop}" + ); + assert_eq!( + parser + .documentation(&context, &options) + .unwrap() + .documents() + .len(), + 1 + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_group_and_spec_have_separate_documents_and_owners() { + let source = b"package p\n// group\nvar (\n// member\nX int\n)"; + let parser = AnyParser::parse(LANG::Go, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let documents: Vec<_> = index.documents().collect(); + assert_eq!(documents.len(), 2); + assert_eq!( + index.complete_text(documents[0]).unwrap().unwrap().text(), + "group" + ); + assert_eq!( + index.complete_text(documents[1]).unwrap().unwrap().text(), + "member" + ); + let associations: Vec<_> = index.associations().collect(); + assert_eq!(associations.len(), 2); + for (association, kind) in associations + .into_iter() + .zip(["var_declaration", "var_spec"]) + { + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("group or spec") + }; + assert_eq!(node.node().kind(), kind); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .len(), + 1 + ); + } +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_modifier_and_body_wrappers_project_the_semantic_method() { + for source in [ + "# audit\ndef f; end if true", + "class C\n# audit\ndef f\nend\nend", + ] { + let parser = AnyParser::parse(LANG::Ruby, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1, "{source}"); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("method") + }; + assert_eq!(node.node().kind(), "method"); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .len(), + 1 + ); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_selected_empty_document_keeps_superseded_raw_evidence_only_on_request() { + let parser = AnyParser::parse( + LANG::Java, + b"/** old */\n/**/\nclass C {}".to_vec(), + None, + None, + ) + .unwrap(); + for retain_unbound in [false, true] { + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + let index = parser + .documentation(&DocumentationContext::default(), &options) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(index.complete_text(document).unwrap().unwrap().text(), ""); + assert_eq!(index.evidence().len(), usize::from(retain_unbound)); + if retain_unbound { + let evidence = index.evidence().next().unwrap(); + assert_eq!(evidence.get().disposition, CandidateDisposition::Superseded); + assert_eq!( + index + .evidence_fragment(evidence) + .unwrap() + .get() + .source() + .pieces()[0] + .bytes(), + b"/** old */" + ); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn document_handles_are_index_qualified_even_for_one_shared_parse() { + let parser = AnyParser::parse(LANG::Rust, b"///audit\nfn f() {}".to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let first = parser.documentation(&context, &options).unwrap(); + let second = parser.documentation(&context, &options).unwrap(); + let document = first.documents().next().unwrap(); + assert!(matches!( + second.complete_text(document), + Err(FactError::ForeignIndex) + )); + assert_eq!( + first.complete_text(document).unwrap().unwrap().text(), + "audit" + ); +} diff --git a/big-code-analysis-ast/src/documentation/content.rs b/big-code-analysis-ast/src/documentation/content.rs index 3d0667613..c32e4be9f 100644 --- a/big-code-analysis-ast/src/documentation/content.rs +++ b/big-code-analysis-ast/src/documentation/content.rs @@ -1,6 +1,6 @@ //! Local content states and forward-map coordinates, without a renderer. -use super::SourcePieces; +use super::{SourcePiece, SourcePieces}; use std::ops::Range; /// Document-local UTF-8 byte coordinates, distinct from source coordinates. @@ -8,6 +8,9 @@ use std::ops::Range; pub struct TextRange(Range); impl TextRange { + pub(super) fn validated(range: Range) -> Self { + Self(range) + } /// Validate a range against its output string. Empty ranges, including EOF, /// are valid; endpoints inside a scalar are not. /// @@ -87,8 +90,117 @@ pub enum Content<'s> { MetadataOnly, /// A complete value cannot be provided; raw fragments are retained. Unavailable(UnavailableReason), + /// An adapter has not assessed every contributing occurrence or composition + /// rule. Consult the index's assessment records for the pending form. + PendingAdapter, +} + +/// Borrowed, builder-validated local text and forward mappings from one index. +#[derive(Clone, Copy, Debug)] +pub struct CompleteText<'i, 's> { + pub(super) text: &'i str, + pub(super) mappings: &'i [Mapping<'s>], +} + +impl<'i, 's> CompleteText<'i, 's> { + /// Retained UTF-8 local markup, without reconstruction. + #[must_use] + pub fn text(self) -> &'i str { + self.text + } + + /// All retained mapping runs, without validation or reconstruction. + #[must_use] + pub fn mappings(self) -> &'i [Mapping<'s>] { + self.mappings + } + + /// Query exact output coordinates in `O(log(S + 1) + K)` work without + /// allocating, where S is the run count and K the returned origins. + /// Valid empty queries, including EOF, take constant time. + /// + /// # Errors + /// Rejects reversed/out-of-bounds coordinates and split UTF-8 scalars. + pub fn origins(self, range: Range) -> Result, TextRangeError> { + let range = TextRange::new(self.text, range)?.range(); + let first = if range.is_empty() { + self.mappings.len() + } else { + self.mappings.partition_point(|mapping| { + map_searches::record(); + mapping.output.0.end <= range.start + }) + }; + Ok(MappingPortions { + remaining: self.mappings[first..].iter(), + range, + }) + } +} + +// Late tiny queries must not walk every preceding run or clone token pieces. +crate::observation::counter!(map_searches, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(map_runs_visited, cfg(any(test, feature = "test-support"))); + +/// An allocation-free forward-origin view. Copied origins are clipped exactly; +/// transformed origins borrow all responsible token pieces. +#[derive(Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum OriginView<'i, 's> { + /// A contiguous source slice clipped to the output portion. + Copied(SourcePiece<'s>), + /// All included pieces of a decoded token. + Decoded(&'i [SourcePiece<'s>]), + /// All included pieces of an expanded token. + Expanded(&'i [SourcePiece<'s>]), + /// Inserted output without source bytes. + Synthetic, } +/// One intersecting output portion and its exact origin. +#[derive(Debug, PartialEq, Eq)] +pub struct MappingPortion<'i, 's> { + /// Half-open UTF-8 byte coordinates in the complete text. + pub output: Range, + /// The responsible source bytes or synthetic origin. + pub origin: OriginView<'i, 's>, +} + +/// Lazy, allocation-free portions of a validated mapping query. +#[derive(Debug)] +pub struct MappingPortions<'i, 's> { + remaining: std::slice::Iter<'i, Mapping<'s>>, + range: Range, +} + +impl<'i, 's> Iterator for MappingPortions<'i, 's> { + type Item = MappingPortion<'i, 's>; + + fn next(&mut self) -> Option { + let mapping = self.remaining.next()?; + if mapping.output.0.start >= self.range.end { + self.remaining = [].iter(); + return None; + } + map_runs_visited::record(); + let output = + self.range.start.max(mapping.output.0.start)..self.range.end.min(mapping.output.0.end); + let origin = match &mapping.origin { + Origin::Copied(pieces) => { + let piece = &pieces.pieces()[0]; + let start = piece.range().start + output.start - mapping.output.0.start; + OriginView::Copied(piece.slice(start..start + output.len())) + } + Origin::Decoded(pieces) => OriginView::Decoded(pieces.pieces()), + Origin::Expanded(pieces) => OriginView::Expanded(pieces.pieces()), + Origin::Synthetic => OriginView::Synthetic, + }; + Some(MappingPortion { output, origin }) + } +} + +impl std::iter::FusedIterator for MappingPortions<'_, '_> {} + /// Why complete local text cannot be represented. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/big-code-analysis-ast/src/documentation/index.rs b/big-code-analysis-ast/src/documentation/index.rs new file mode 100644 index 000000000..4886cc068 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/index.rs @@ -0,0 +1,323 @@ +//! Immutable source-bound facts and prepared owner queries. + +use super::canonical::{CanonicalNodes, Projection}; +use super::*; + +/// Whether the selected grammar has a source declaration model. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Capability { + /// Implemented source paths coexist with default-visible pending forms. + Partial, + /// A helper grammar has no declaration model. + NoDeclarationModel, +} + +/// Independent assessment dimensions; pending work is never semantic absence. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum AssessmentAxis { + /// Recognition of a potential documentation carrier. + Occurrence, + /// Selection among recognized forms. + Selection, + /// Projection onto a semantic declaration or slot. + Owner, + /// Composition and local text of selected occurrences. + Composition, + /// Publication eligibility under the named profile. + Publication, +} + +/// A default-visible pending implementation assessment. +#[derive(Debug)] +pub struct Assessment<'s> { + /// The unfinished decision, independent of other dimensions. + pub axis: AssessmentAxis, + /// Source form or implementation limitation. + pub reason: &'static str, + /// Canonical evidence when a specific occurrence is known. + pub node: Option>, + pub(super) document: Option, +} + +/// Retained nonselected source evidence, independently of pending assessments. +#[derive(Debug)] +pub struct CandidateEvidence { + pub(super) fragment: FragmentId, + /// Why this occurrence does not contribute to selected prose. + pub disposition: CandidateDisposition, +} + +/// Source-selection evidence, not an owner or publication conclusion. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CandidateDisposition { + /// A later candidate replaced this occurrence. + Superseded, + /// The current profile established no attachment. + Unattached, + /// A recognized non-prose directive. + Directive, +} + +/// A caller-owned immutable index borrowing exactly one parse and source buffer. +#[derive(Debug)] +pub struct DocumentationIndex<'s> { + pub(super) source: SourceContext<'s>, + pub(super) facts: Facts<'s>, + pub(super) canonical: CanonicalNodes<'s>, + pub(super) context: DocumentationContext, + pub(super) options: DocumentationOptions, + pub(super) profile: Profile, + pub(super) capability: Capability, + pub(super) assessments: Vec>, + pub(super) evidence: Vec, + pub(super) associations_by_owner: Vec>, + pub(super) assessments_by_owner: Vec>, + pub(super) owner_nodes: Vec, + pub(super) documents_ordered: Vec, + pub(super) associations_ordered: Vec, +} + +/// Prepared results for one semantic owner, including known associations and +/// pending assessments in separate borrowed sequences. +pub struct OwnerAssociations<'i, 's> { + index: &'i DocumentationIndex<'s>, + associations: &'i [usize], + assessments: &'i [usize], + scope: Option, +} + +impl<'i, 's> OwnerAssociations<'i, 's> { + /// Known association records, without scanning other owners. + pub fn associations(&self) -> impl ExactSizeIterator>> + '_ { + self.associations.iter().map(|&ordinal| FactRef { + scope: &self.index.facts.scope, + ordinal, + fact: &self.index.facts.associations[ordinal], + }) + } + + /// Pending assessments affecting this owner, visible under default options. + pub fn assessments(&self) -> impl Iterator>> + '_ { + let mut scope = self.scope; + let mut at = 0; + self.assessments + .iter() + .copied() + .chain(std::iter::from_fn(move || { + loop { + let node = &self.index.canonical.nodes[scope?.0]; + if let Some(&assessment) = node.pending.get(at) { + at += 1; + return Some(assessment); + } + scope = node.pending_parent; + at = 0; + } + })) + .map(|ordinal| FactRef { + scope: &self.index.facts.scope, + ordinal, + fact: &self.index.assessments[ordinal], + }) + } +} + +/// Owner lookup outcomes distinct from a supported, assessed empty result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum OwnerError { + /// A node is outside this profile's declaration model. + UnsupportedOwner, + /// A recognized owner form awaits semantic projection. + PendingOwner, + /// This wrapper projects to more than one owner; enumerate those owners. + MultipleOwners, + /// Canonical node validation failed. + Source(SourceError), + /// A borrowed handle belongs to another index. + Fact(FactError), +} + +impl<'s> DocumentationIndex<'s> { + /// Immutable physical records and association-navigation operations. + #[must_use] + pub fn facts(&self) -> &Facts<'s> { + &self.facts + } + + /// The exact parsed source bytes. + #[must_use] + pub fn source(&self) -> &'s [u8] { + self.source.bytes() + } + + /// Copied caller metadata, with no inferred filesystem provenance. + #[must_use] + pub fn context(&self) -> &DocumentationContext { + &self.context + } + + /// The selected collection options. + #[must_use] + pub fn options(&self) -> DocumentationOptions { + self.options + } + + /// The resolved named profile, never `Default`. + #[must_use] + pub fn profile(&self) -> Profile { + self.profile + } + + /// Partial source support or an explicit helper capability. + #[must_use] + pub fn capability(&self) -> Capability { + self.capability + } + + /// All pending assessments, including occurrence/owner/composition uncertainty. + pub fn assessments(&self) -> impl ExactSizeIterator>> { + self.facts.references(&self.assessments) + } + + /// Opt-in rejected, superseded and directive evidence in collection order. + pub fn evidence(&self) -> impl ExactSizeIterator> { + self.facts.references(&self.evidence) + } + + /// The physical spelling retained for a nonselected candidate. + /// + /// # Errors + /// Rejects references from another index. + pub fn evidence_fragment( + &self, + evidence: FactRef<'_, CandidateEvidence>, + ) -> Result>, FactError> { + self.facts.check_scope(evidence)?; + self.facts + .reference(&self.facts.fragments, evidence.fact.fragment.0) + .ok_or(FactError::MissingRecord) + } + + /// The document affected by a retained assessment, if one has been composed. + /// + /// # Errors + /// Rejects an assessment borrowed from another index. + pub fn assessed_document( + &self, + assessment: FactRef<'_, Assessment<'s>>, + ) -> Result>>, FactError> { + self.facts.check_scope(assessment)?; + Ok(assessment + .fact + .document + .and_then(|id| self.facts.reference(&self.facts.documents, id.0))) + } + + /// Documents in deterministic anchor, role and creation order. + pub fn documents(&self) -> impl ExactSizeIterator>> { + self.documents_ordered.iter().map(|&ordinal| FactRef { + scope: &self.facts.scope, + ordinal, + fact: &self.facts.documents[ordinal], + }) + } + + /// Associations in document order, then owner anchor and slot order. + pub fn associations(&self) -> impl ExactSizeIterator>> { + self.associations_ordered.iter().map(|&ordinal| FactRef { + scope: &self.facts.scope, + ordinal, + fact: &self.facts.associations[ordinal], + }) + } + + /// Constant-time access to validated complete text. Other content states + /// return `None` and remain inspectable on the retained document. + /// + /// # Errors + /// Rejects a document reference obtained from another index. + pub fn complete_text( + &self, + document: FactRef<'_, Document<'s>>, + ) -> Result>, FactError> { + self.facts.check_scope(document)?; + Ok(match &self.facts.documents[document.ordinal].content { + Content::Complete { text, mappings } => Some(CompleteText { text, mappings }), + _ => None, + }) + } + + /// Prepared query using an index-qualified semantic owner handle. + /// + /// # Errors + /// Rejects a handle from another index. + pub fn owner_associations( + &self, + owner: FactRef<'_, Owner<'s>>, + ) -> Result, OwnerError> { + self.facts.check_scope(owner).map_err(OwnerError::Fact)?; + Ok(self.prepared_owner(owner.ordinal)) + } + + /// Canonical-node convenience for a single-owner projection. + /// + /// # Errors + /// Distinguishes identity failures, unsupported and pending forms, and + /// wrappers projecting to several owners. + pub fn node_associations( + &self, + node: tree_sitter::Node<'_>, + ) -> Result, OwnerError> { + let id = self.canonical.lookup(node).map_err(OwnerError::Source)?; + match &self.canonical.nodes[id.0].projection { + Projection::Ready(owners) if owners.is_empty() => Err(OwnerError::UnsupportedOwner), + Projection::Pending => Err(OwnerError::PendingOwner), + Projection::Ready(owners) if owners.len() == 1 => { + let ordinal = owners[0].0; + Ok(self.prepared_owner(ordinal)) + } + Projection::Ready(_) => Err(OwnerError::MultipleOwners), + Projection::Unsupported => Err(OwnerError::UnsupportedOwner), + } + } + + /// Semantic owners projected from a canonical node, including multi-slot + /// declarations. The projection is stored once during collection. + /// + /// # Errors + /// Rejects noncanonical/foreign nodes and unsupported or pending forms. + pub fn node_owners( + &self, + node: tree_sitter::Node<'_>, + ) -> Result>>, OwnerError> { + let id = self.canonical.lookup(node).map_err(OwnerError::Source)?; + let owners = match &self.canonical.nodes[id.0].projection { + Projection::Ready(owners) => owners.as_slice(), + Projection::Pending => return Err(OwnerError::PendingOwner), + Projection::Unsupported => return Err(OwnerError::UnsupportedOwner), + }; + Ok(owners.iter().map(|id| FactRef { + scope: &self.facts.scope, + ordinal: id.0, + fact: &self.facts.owners[id.0], + })) + } + + fn prepared_owner(&self, ordinal: usize) -> OwnerAssociations<'_, 's> { + let id = self.owner_nodes[ordinal]; + let node = &self.canonical.nodes[id.0]; + let scope = if node.pending.is_empty() { + node.pending_parent + } else { + Some(id) + }; + OwnerAssociations { + index: self, + associations: &self.associations_by_owner[ordinal], + assessments: &self.assessments_by_owner[ordinal], + scope, + } + } +} diff --git a/big-code-analysis-ast/src/documentation/names.rs b/big-code-analysis-ast/src/documentation/names.rs new file mode 100644 index 000000000..0c2774926 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/names.rs @@ -0,0 +1,88 @@ +//! Bounded same-file exact structural names and signatures. + +use std::collections::HashMap; + +use super::budget::WorkBudget; +use super::{OwnerId, SourceError, UnresolvedReason}; + +#[derive(Default)] +pub(super) struct Names { + names: HashMap, OwnerId)>>, + signatures: HashMap, OwnerId)>>, +} + +fn key(bytes: &[u8], budget: &B) -> Result<(u64, Vec), SourceError> { + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + let mut key = Vec::new(); + for &byte in bytes { + budget.bytes(1).map_err(Into::into)?; + if !byte.is_ascii_whitespace() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3); + key.push(byte); + } + } + Ok((hash, key)) +} + +impl Names { + pub(super) fn insert( + &mut self, + name: &[u8], + signature: &[u8], + owner: OwnerId, + budget: &B, + ) -> Result<(), SourceError> { + let (hash, name) = key(name, budget)?; + self.names.entry(hash).or_default().push((name, owner)); + let (hash, signature) = key(signature, budget)?; + self.signatures + .entry(hash) + .or_default() + .push((signature, owner)); + Ok(()) + } + + pub(super) fn resolve( + &self, + reference: &[u8], + budget: &B, + ) -> Result<(Vec, Option), SourceError> { + let (hash, key) = key(reference, budget)?; + let mut signatures = false; + for byte in &key { + budget.bytes(1).map_err(Into::into)?; + signatures |= *byte == b'('; + } + let index = if signatures { + &self.signatures + } else { + &self.names + }; + let mut owners = Vec::new(); + if let Some(candidates) = index.get(&hash) { + for (candidate, owner) in candidates { + budget.step().map_err(Into::into)?; + if candidate.len() != key.len() { + continue; + } + let mut matches = true; + for (left, right) in candidate.iter().zip(&key) { + budget.bytes(1).map_err(Into::into)?; + if left != right { + matches = false; + break; + } + } + if matches { + owners.push(*owner); + } + } + } + let reason = match owners.len() { + 0 => Some(UnresolvedReason::MissingName), + 1 => None, + _ => Some(UnresolvedReason::Ambiguous), + }; + Ok((owners, reason)) + } +} diff --git a/big-code-analysis-ast/src/documentation/options.rs b/big-code-analysis-ast/src/documentation/options.rs new file mode 100644 index 000000000..81854813b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/options.rs @@ -0,0 +1,186 @@ +//! Explicit attachment profiles and collection outcomes. + +use super::SourceError; +use crate::LANG; + +/// Caller metadata used by documentation rules, never a filesystem credential. +#[derive(Clone, Debug, Default)] +pub struct DocumentationContext { + /// Explicit logical filename. Display labels are not substituted for it. + pub logical_filename: Option, +} + +/// One named source attachment convention. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum Profile { + /// The language's documented default convention. + #[default] + Default, + /// Compiler documentation attributes and comments. + Rust, + /// PEP 257/258 and Sphinx source documentation. + Python, + /// JDK 25 source attachment with BCA local cleanup. + Javadoc, + /// Kotlin documentation comments. + Kdoc, + /// Groovy documentation comments. + Groovydoc, + /// C# XML source documentation. + CsharpXml, + /// Declaration-before-file PHP source selection. + BcaPhpSource, + /// File-before-declaration phpDocumentor selection. + PhpDocumentor, + /// JavaScript source documentation. + Jsdoc, + /// TypeScript attachment with TypeDoc structural-file precedence. + BcaTypescriptSource, + /// Doxygen source documentation. + Doxygen, + /// go/doc source groups. + GoDoc, + /// Ruby YARD documentation. + Yard, + /// Ruby RDoc documentation. + Rdoc, + /// Lua LDoc documentation. + Ldoc, + /// Perl POD file documentation. + Pod, + /// Compiler source documentation attributes. + Elixir, + /// Bash shdoc comments. + Shdoc, + /// Static Ruff! 3.0.4 documentation. + Ruff, + /// BCA leading/body iRules convention. + Irules, + /// A helper grammar with no declaration model. + Helper, +} + +impl Profile { + /// Stable convention identifier used in associations and errors. + #[must_use] + pub const fn name(self) -> &'static str { + // bca: suppress(cyclomatic) -- exhaustive profile identifier table. + match self { + Self::Default => "Default", + Self::Rust => "Rust", + Self::Python => "Python", + Self::Javadoc => "Javadoc", + Self::Kdoc => "KDoc", + Self::Groovydoc => "Groovydoc", + Self::CsharpXml => "CsharpXml", + Self::BcaPhpSource => "BcaPhpSource", + Self::PhpDocumentor => "PhpDocumentor", + Self::Jsdoc => "JSDoc", + Self::BcaTypescriptSource => "BcaTypescriptSource", + Self::Doxygen => "Doxygen", + Self::GoDoc => "GoDoc", + Self::Yard => "YARD", + Self::Rdoc => "RDoc", + Self::Ldoc => "LDoc", + Self::Pod => "POD", + Self::Elixir => "Elixir", + Self::Shdoc => "shdoc", + Self::Ruff => "Ruff", + Self::Irules => "Irules", + Self::Helper => "Helper", + } + } + + pub(super) fn resolve(self, language: LANG) -> Result { + // bca: suppress(cyclomatic, halstead) -- exhaustive language/profile compatibility and deferred-adapter table. + let default = match language { + LANG::Rust => Self::Rust, + LANG::Python => Self::Python, + LANG::Java => Self::Javadoc, + LANG::Kotlin => Self::Kdoc, + LANG::Groovy => Self::Groovydoc, + LANG::Csharp => Self::CsharpXml, + LANG::Php => Self::BcaPhpSource, + LANG::Javascript | LANG::Mozjs => Self::Jsdoc, + LANG::Typescript | LANG::Tsx => Self::BcaTypescriptSource, + LANG::C | LANG::Cpp | LANG::Mozcpp | LANG::Objc => Self::Doxygen, + LANG::Go => Self::GoDoc, + LANG::Ruby => Self::Yard, + LANG::Lua => Self::Ldoc, + LANG::Perl => Self::Pod, + LANG::Elixir => Self::Elixir, + LANG::Bash => Self::Shdoc, + LANG::Tcl => Self::Ruff, + LANG::Irules => Self::Irules, + LANG::Ccomment | LANG::Preproc => Self::Helper, + }; + let profile = if self == Self::Default { default } else { self }; + let alternate = matches!( + (language, profile), + (LANG::Php, Self::PhpDocumentor) | (LANG::Ruby, Self::Rdoc) + ); + if profile != default && !alternate { + return Err(CollectionError::UnsupportedProfile { language, profile }); + } + if alternate + || matches!( + profile, + Self::Python | Self::Pod | Self::Elixir | Self::Shdoc | Self::Ruff | Self::Irules + ) + { + return Err(CollectionError::AdapterUnavailable { language, profile }); + } + Ok(profile) + } +} + +/// Immutable collection choices; pending assessments are always retained. +#[derive(Clone, Copy, Debug, Default)] +pub struct DocumentationOptions { + /// One named attachment convention. + pub profile: Profile, + /// Preserve superseded and unattached candidate details. + pub retain_unbound: bool, + /// Preserve recognized non-prose directive occurrences. + pub retain_directives: bool, +} + +/// Failure before a complete immutable index can be returned. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum CollectionError { + /// Active collection cancellation or retained typed parse abort. + Cancelled, + /// The grammar feature is disabled. + LanguageDisabled(LANG), + /// The named profile does not apply to this language. + UnsupportedProfile { + /// Requested source language. + language: LANG, + /// Requested profile. + profile: Profile, + }, + /// The recognized adapter/profile has not been implemented. + AdapterUnavailable { + /// Requested source language. + language: LANG, + /// Recognized profile. + profile: Profile, + }, + /// The supplied tree uses a different pinned grammar. + GrammarMismatch, + /// A root or visited node has invalid source-buffer bounds. + SourceBounds, + /// A source operation failed; cancellation has its own top-level variant. + Source(SourceError), +} + +impl From for CollectionError { + fn from(error: SourceError) -> Self { + match error { + SourceError::Cancelled => Self::Cancelled, + error => Self::Source(error), + } + } +} diff --git a/big-code-analysis-ast/src/documentation/ordering.rs b/big-code-analysis-ast/src/documentation/ordering.rs new file mode 100644 index 000000000..8cd9973c1 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/ordering.rs @@ -0,0 +1,174 @@ +//! Bounded chunk sorts followed by an interruptible numeric-key merge. + +use std::cell::RefCell; +use std::cmp::Reverse; +use std::collections::BinaryHeap; + +use super::budget::{STEP_INTERVAL, WorkBudget}; + +struct Comparisons<'b, B: WorkBudget> { + budget: &'b B, + error: RefCell>, +} + +impl Comparisons<'_, B> { + fn compare(&self, left: &K, right: &K) -> std::cmp::Ordering { + if self.error.borrow().is_none() { + *self.error.borrow_mut() = self.budget.step().err(); + } + left.cmp(right) + } + + fn check(&self) -> Result<(), B::Error> { + match self.error.take() { + Some(error) => Err(error), + None => Ok(()), + } + } +} + +struct Entry<'b, K: Ord, B: WorkBudget> { + key: (K, usize), + comparisons: &'b Comparisons<'b, B>, +} + +impl PartialEq for Entry<'_, K, B> { + fn eq(&self, other: &Self) -> bool { + self.key == other.key + } +} + +impl Eq for Entry<'_, K, B> {} + +impl PartialOrd for Entry<'_, K, B> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for Entry<'_, K, B> { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.comparisons.compare(&self.key, &other.key) + } +} + +pub(super) fn ordered( + mut keys: Vec, + budget: &B, +) -> Result, B::Error> { + // bca: suppress(nexits, halstead) -- each bounded sort and heap operation must propagate its latched cancellation before publishing output. + let comparisons = Comparisons { + budget, + error: RefCell::new(None), + }; + for chunk in keys.chunks_mut(STEP_INTERVAL) { + budget.checkpoint()?; + chunk.sort_unstable_by(|left, right| comparisons.compare(left, right)); + comparisons.check()?; + } + let mut heap = BinaryHeap::new(); + for (chunk, values) in keys.chunks(STEP_INTERVAL).enumerate() { + budget.step()?; + heap.push(Reverse(Entry { + key: (values[0], chunk * STEP_INTERVAL), + comparisons: &comparisons, + })); + comparisons.check()?; + } + let mut output = Vec::with_capacity(keys.len()); + while let Some(Reverse(entry)) = heap.pop() { + comparisons.check()?; + budget.step()?; + let (key, at) = entry.key; + output.push(key); + let next = at + 1; + if next < keys.len() && next % STEP_INTERVAL != 0 { + heap.push(Reverse(Entry { + key: (keys[next], next), + comparisons: &comparisons, + })); + comparisons.check()?; + } + } + budget.checkpoint()?; + Ok(output) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::documentation::budget::NoBudget; + use std::cell::Cell; + + struct StopAt { + work: Cell, + stop: usize, + } + + impl WorkBudget for StopAt { + type Error = crate::documentation::SourceError; + fn checkpoint(&self) -> Result<(), Self::Error> { + Ok(()) + } + fn bytes(&self, _: usize) -> Result<(), Self::Error> { + self.step() + } + fn step(&self) -> Result<(), Self::Error> { + let next = self.work.get() + 1; + self.work.set(next); + if next == self.stop { + Err(Self::Error::Cancelled) + } else { + Ok(()) + } + } + } + + #[test] + fn chunk_sort_cancellation_latches_without_corrupting_comparator_order() { + let budget = StopAt { + work: Cell::new(0), + stop: 3, + }; + let input: Vec<_> = (0..3000).rev().collect(); + assert_eq!( + ordered(input.clone(), &budget), + Err(crate::documentation::SourceError::Cancelled) + ); + assert_eq!(budget.work.get(), 3); + assert_eq!( + ordered(input, &NoBudget).unwrap(), + (0..3000).collect::>() + ); + } + + #[test] + fn merge_comparisons_are_budgeted_and_duplicates_preserve_numeric_order() { + let input: Vec<_> = (0..3000).map(|i| (i * 53 % 137, i)).collect(); + let budget = StopAt { + work: Cell::new(0), + stop: usize::MAX, + }; + let comparisons = Comparisons { + budget: &budget, + error: RefCell::new(None), + }; + for chunk in input.chunks(STEP_INTERVAL) { + let mut chunk = chunk.to_vec(); + chunk.sort_unstable_by(|a, b| comparisons.compare(a, b)); + } + let sort_steps = budget.work.get(); + let budget = StopAt { + work: Cell::new(0), + stop: sort_steps + 20, + }; + assert_eq!( + ordered(input.clone(), &budget), + Err(crate::documentation::SourceError::Cancelled) + ); + assert_eq!(budget.work.get(), sort_steps + 20); + let mut expected = input.clone(); + expected.sort_unstable(); + assert_eq!(ordered(input, &NoBudget).unwrap(), expected); + } +} diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index e68955aee..ae655b82e 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -2,6 +2,8 @@ use std::ops::Range; +use super::budget::{NoBudget, WorkBudget, infallible}; + // Output alone cannot reveal scanning empty ranges or seeking from the start. crate::observation::counter!( included_range_visits, @@ -16,6 +18,12 @@ pub struct SourcePiece<'s> { } impl<'s> SourcePiece<'s> { + pub(super) fn slice(&self, range: Range) -> Self { + Self { + bytes: &self.bytes[range.start - self.range.start..range.end - self.range.start], + range, + } + } /// Half-open byte coordinates in the actual parsed buffer. #[must_use] pub fn range(&self) -> Range { @@ -37,6 +45,12 @@ pub struct SourcePieces<'s> { } impl<'s> SourcePieces<'s> { + pub(super) fn single(piece: SourcePiece<'s>) -> Self { + Self { + pieces: vec![piece], + has_excluded_gap: false, + } + } /// The individual pieces; intervening excluded bytes are never returned. #[must_use] pub fn pieces(&self) -> &[SourcePiece<'s>] { @@ -71,24 +85,43 @@ impl<'s> SourceContext<'s> { /// infer completion; adopted/raw inputs retain the caller's precondition. #[must_use] pub fn new(tree: &'s tree_sitter::Tree, bytes: &'s [u8]) -> Self { - let mut included = tree.included_ranges(); - included.retain(|range| range.start_byte < range.end_byte); + infallible(Self::with_budget(tree, bytes, &NoBudget)) + } + + pub(crate) fn with_budget( + tree: &'s tree_sitter::Tree, + bytes: &'s [u8], + budget: &B, + ) -> Result { + budget.checkpoint()?; + // The safe dependency copies the range array atomically. Only our + // subsequent normalization loop can be interrupted internally. + let raw = tree.included_ranges(); + budget.checkpoint()?; + let mut included = Vec::new(); let mut continuous: Vec> = Vec::new(); - for range in &included { + for range in raw { + budget.step()?; + let start = range.start_byte.min(bytes.len()); + let end = range.end_byte.min(bytes.len()); + if start == end { + continue; + } + included.push(range); if let Some(last) = continuous.last_mut() - && last.end == range.start_byte + && last.end == start { - last.end = range.end_byte; + last.end = end; } else { - continuous.push(range.start_byte..range.end_byte); + continuous.push(start..end); } } - Self { + Ok(Self { tree, bytes, included, continuous, - } + }) } /// Intersect a nonempty spelling in `O(log R + I)` work for R included @@ -97,16 +130,33 @@ impl<'s> SourceContext<'s> { /// # Errors /// Rejects empty, reversed, out-of-buffer and wholly excluded spellings. pub fn pieces(&self, spelling: Range) -> Result, SourceError> { + self.pieces_with_budget(spelling, &NoBudget) + } + + pub(crate) fn pieces_with_budget( + &self, + spelling: Range, + budget: &B, + ) -> Result, SourceError> { // bca: suppress(halstead) -- one interval-intersection loop retains raw slices and excluded-gap evidence together. if spelling.start >= spelling.end || spelling.end > self.bytes.len() { return Err(SourceError::InvalidRange); } - let first = self - .included - .partition_point(|range| range.end_byte <= spelling.start); + let mut first = 0; + let mut end = self.included.len(); + while first < end { + budget.step().map_err(Into::into)?; + let middle = first + (end - first) / 2; + if self.included[middle].end_byte <= spelling.start { + first = middle + 1; + } else { + end = middle; + } + } let mut pieces = Vec::new(); let mut included_bytes = 0; for range in &self.included[first..] { + budget.step().map_err(Into::into)?; included_range_visits::record(); if range.start_byte >= spelling.end { break; @@ -233,6 +283,8 @@ impl<'s> NodeEvidence<'s> { #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub enum SourceError { + /// Active collection cancellation; no successful partial result is returned. + Cancelled, /// Empty, reversed or out-of-buffer spelling. InvalidRange, /// No requested bytes were included in the parse. diff --git a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs index 758741bfe..6d7660a00 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers/tests.rs @@ -300,6 +300,39 @@ fn kotlin_last_reads_across_plain_comments() { ); } +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_source_signature_comment_emits_local_placement() { + use crate::KotlinCode; + let source = b"fun f() /**audit*/ {}"; + let parser = AnyParser::parse(LANG::Kotlin, source.to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let mut runs = Vec::new(); + parser.root_node().act_on_node(&mut |node, ancestors| { + if KotlinCode::is_comment(node) { + source_comment::( + node, + ancestors, + &mut SourceRequest { + context: &context, + retain_unbound: false, + sink: &mut |run| runs.push(run), + }, + ) + .unwrap(); + } + }); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].members.len(), 1); + assert_eq!(runs[0].members[0].source.pieces()[0].range(), 8..18); + assert_eq!(runs[0].members[0].selection, MarkerSelection::Selected); + assert!(matches!( + runs[0].members[0].placement, + MarkerPlacement::Local + )); +} + #[cfg(feature = "groovy")] #[test] fn groovy_nearest_plain_comment_detaches() { diff --git a/big-code-analysis-ast/src/documentation/text.rs b/big-code-analysis-ast/src/documentation/text.rs new file mode 100644 index 000000000..6984a960f --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text.rs @@ -0,0 +1,122 @@ +//! Append-only local text with exact origins and bounded UTF-8 validation. + +use std::ops::Range; + +use super::budget::{BYTE_INTERVAL, WorkBudget}; +use super::{ + Content, Mapping, Origin, SourceContext, SourceError, SourcePieces, TextRange, + UnavailableReason, +}; + +pub(super) mod comments; + +#[derive(Debug)] +pub(super) enum TextError { + Source(SourceError), + Unavailable(UnavailableReason), +} + +impl From for TextError { + fn from(error: SourceError) -> Self { + Self::Source(error) + } +} + +#[derive(Default)] +pub(super) struct TextBuilder<'s> { + text: String, + mappings: Vec>, +} + +// The same document must not be rendered once per association or retained read. +crate::observation::counter!(renders, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(copy_chunks, cfg(any(test, feature = "test-support"))); + +impl<'s> TextBuilder<'s> { + pub(super) fn copied( + &mut self, + pieces: &SourcePieces<'s>, + budget: &B, + ) -> Result<(), TextError> { + if pieces.has_excluded_gap() { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + } + for piece in pieces.pieces() { + budget.step().map_err(Into::into)?; + let start = self.text.len(); + self.append_utf8(piece.bytes(), budget)?; + self.push_mapping(start, Origin::Copied(SourcePieces::single(piece.clone()))); + } + Ok(()) + } + + pub(super) fn transformed( + &mut self, + text: &str, + origin: Origin<'s>, + budget: &B, + ) -> Result<(), TextError> { + let start = self.text.len(); + self.append_utf8(text.as_bytes(), budget)?; + self.push_mapping(start, origin); + Ok(()) + } + + pub(super) fn source( + &mut self, + context: &SourceContext<'s>, + range: Range, + budget: &B, + ) -> Result<(), TextError> { + if !range.is_empty() { + self.copied(&context.pieces_with_budget(range, budget)?, budget)?; + } + Ok(()) + } + + fn append_utf8(&mut self, bytes: &[u8], budget: &B) -> Result<(), TextError> { + // bca: suppress(nexits, halstead) -- validation, scalar carry and copying each require a separate fallible checkpoint. + let mut at = 0; + while at < bytes.len() { + let end = (at + BYTE_INTERVAL).min(bytes.len()); + budget.checkpoint().map_err(Into::into)?; + budget.bytes(end - at).map_err(Into::into)?; + let valid = match std::str::from_utf8(&bytes[at..end]) { + Ok(text) => text, + Err(error) if error.error_len().is_none() && end < bytes.len() => { + budget.checkpoint().map_err(Into::into)?; + budget.bytes(error.valid_up_to()).map_err(Into::into)?; + std::str::from_utf8(&bytes[at..at + error.valid_up_to()]) + .map_err(|_| TextError::Unavailable(UnavailableReason::InvalidEncoding))? + } + Err(_) => return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)), + }; + budget.checkpoint().map_err(Into::into)?; + budget.bytes(valid.len()).map_err(Into::into)?; + self.text.push_str(valid); + copy_chunks::record(); + at += valid.len(); + } + Ok(()) + } + + fn push_mapping(&mut self, start: usize, origin: Origin<'s>) { + if start != self.text.len() { + self.mappings.push(Mapping { + output: TextRange::validated(start..self.text.len()), + origin, + }); + } + } + + pub(super) fn finish(self) -> Content<'s> { + renders::record(); + Content::Complete { + text: self.text, + mappings: self.mappings, + } + } +} + +#[cfg(test)] +mod tests; diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs new file mode 100644 index 000000000..e4be501a7 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -0,0 +1,464 @@ +//! Comment-local cleanup over source coordinates, before any output copying. + +use super::{TextBuilder, TextError}; +use crate::documentation::budget::WorkBudget; +use crate::documentation::{Content, Fragment, Origin, Profile, SourceContext, UnavailableReason}; +use std::ops::Range; + +struct Line { + content: Range, + ending: Range, +} + +struct Block { + lines: Vec, + rust_decoration: bool, + markdown: bool, +} + +fn charge(budget: &B) -> Result<(), TextError> { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into())) +} + +fn margin(bytes: &[u8], budget: &B) -> Result { + let mut count = 0; + for byte in bytes { + charge(budget)?; + if !matches!(byte, b' ' | b'\t') { + break; + } + count += 1; + } + Ok(count) +} + +fn splice(bytes: &[u8], at: usize) -> usize { + if bytes[at..].starts_with(b"\\\r\n") { + 3 + } else if bytes[at..].starts_with(b"\\\n") { + 2 + } else { + 0 + } +} + +fn lines( + bytes: &[u8], + range: Range, + splices: bool, + budget: &B, +) -> Result, TextError> { + let mut lines = Vec::new(); + let mut start = range.start; + let mut at = start; + while at < range.end { + charge(budget)?; + let removed = if splices { + splice(&bytes[..range.end], at) + } else { + 0 + }; + if removed != 0 { + for _ in 1..removed { + charge(budget)?; + } + at += removed; + continue; + } + if bytes[at] == b'\n' { + let end = if at > start && bytes[at - 1] == b'\r' { + at - 1 + } else { + at + }; + lines.push(Line { + content: start..end, + ending: end..at + 1, + }); + start = at + 1; + } + at += 1; + } + lines.push(Line { + content: start..range.end, + ending: range.end..range.end, + }); + Ok(lines) +} + +fn delimiters( + profile: Profile, + bytes: &[u8], + range: Range, + budget: &B, +) -> Result<(Range, bool, bool), TextError> { + let raw = &bytes[range.clone()]; + let (prefix, suffix, block) = if raw.starts_with(b"/*") { + let prefix = if profile == Profile::GoDoc { 2 } else { 3 }; + if !raw.ends_with(b"*/") { + return Err(TextError::Unavailable(UnavailableReason::GrammarBoundary)); + } + (prefix.min(raw.len() - 2), 2, true) + } else if raw.starts_with(b"//") { + (if profile == Profile::GoDoc { 2 } else { 3 }, 0, false) + } else if raw.starts_with(b"--[") { + let mut equals = 3; + while raw.get(equals) == Some(&b'=') { + charge(budget)?; + equals += 1; + } + if raw.get(equals) == Some(&b'[') { + let close = equals - 1; + if raw.len() < equals + 1 + close + || raw[raw.len() - close] != b']' + || raw.last() != Some(&b']') + { + return Err(TextError::Unavailable(UnavailableReason::GrammarBoundary)); + } + for byte in &raw[raw.len() - close + 1..raw.len() - 1] { + charge(budget)?; + if *byte != b'=' { + return Err(TextError::Unavailable(UnavailableReason::GrammarBoundary)); + } + } + let mut prefix = equals + 1; + while raw.get(prefix) == Some(&b'-') { + charge(budget)?; + prefix += 1; + } + (prefix, close, true) + } else { + (2, 0, false) + } + } else if raw.starts_with(b"--") { + let mut prefix = 2; + while raw.get(prefix) == Some(&b'-') { + charge(budget)?; + prefix += 1; + } + (prefix, 0, false) + } else if raw.starts_with(b"#") { + ( + if raw.starts_with(b"##") && raw.get(2) != Some(&b'#') { + 2 + } else { + 1 + }, + 0, + false, + ) + } else if raw.starts_with(b"=begin") { + let mut first = 0; + while first < raw.len() && raw[first] != b'\n' { + charge(budget)?; + first += 1; + } + let mut last = raw.len(); + while last > first && raw[last - 1] != b'\n' { + charge(budget)?; + last -= 1; + } + return Ok(( + range.start + (first + 1).min(raw.len())..range.start + last, + true, + false, + )); + } else { + return Err(TextError::Unavailable(UnavailableReason::GrammarBoundary)); + }; + let mut start = range.start + prefix; + let end = range.end - suffix; + if profile == Profile::Doxygen && bytes.get(start) == Some(&b'<') { + start += 1; + } + Ok((start.min(end)..end, block, raw.starts_with(b"/*"))) +} + +fn prepare( + profile: Profile, + context: &SourceContext<'_>, + fragment: &Fragment<'_>, + budget: &B, +) -> Result { + if fragment.source.has_excluded_gap() { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + } + let pieces = fragment.source.pieces(); + let Some(first) = pieces.first() else { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + }; + let Some(last) = pieces.last() else { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + }; + let raw = first.range().start..last.range().end; + let bytes = context.bytes(); + if profile == Profile::Javadoc { + for pair in bytes[raw.clone()].windows(2) { + charge(budget)?; + if pair == b"\\u" { + return Err(TextError::Unavailable( + UnavailableReason::UnsupportedDecoding, + )); + } + } + } + let (body, block, c_block) = delimiters(profile, bytes, raw, budget)?; + let mut lines = lines(bytes, body, profile == Profile::Doxygen, budget)?; + if profile != Profile::Rust && (profile != Profile::Javadoc || block) { + if (c_block || !block) + && lines + .first() + .is_some_and(|line| bytes.get(line.content.start) == Some(&b' ')) + { + lines[0].content.start += 1; + } + if c_block + && let Some(last) = lines.last_mut() + && !last.content.is_empty() + && bytes[last.content.end - 1] == b' ' + { + last.content.end -= 1; + } + if c_block && profile != Profile::GoDoc { + for line in lines.iter_mut().skip(1) { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let indent = margin(&bytes[line.content.clone()], budget)?; + let star = line.content.start + indent; + if bytes.get(star) == Some(&b'*') && star < line.content.end { + line.content.start = star + 1; + if line.content.start < line.content.end && bytes[line.content.start] == b' ' { + line.content.start += 1; + } + } else if star == line.content.end { + line.content.start = star; + } + } + } + } + Ok(Block { + lines, + rust_decoration: profile == Profile::Rust && block, + markdown: profile == Profile::Javadoc && !block, + }) +} + +fn append_range<'s, B: WorkBudget>( + builder: &mut TextBuilder<'s>, + context: &SourceContext<'s>, + range: Range, + splices: bool, + budget: &B, +) -> Result<(), TextError> { + if !splices { + return builder.source(context, range, budget); + } + let mut start = range.start; + let mut at = start; + while at < range.end { + charge(budget)?; + let removed = splice(&context.bytes()[..range.end], at); + if removed == 0 { + at += 1; + continue; + } + for _ in 1..removed { + charge(budget)?; + } + builder.source(context, start..at, budget)?; + at += removed; + start = at; + } + builder.source(context, start..range.end, budget) +} + +pub(in crate::documentation) fn render<'s, B: WorkBudget>( + profile: Profile, + context: &SourceContext<'s>, + fragments: &[&Fragment<'s>], + budget: &B, +) -> Result, TextError> { + let mut blocks = Vec::new(); + for fragment in fragments { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + blocks.push(prepare(profile, context, fragment, budget)?); + } + if profile == Profile::Rust { + for block in &mut blocks { + beautify(block, context.bytes(), budget)?; + } + } + if profile == Profile::Rust || blocks.first().is_some_and(|block| block.markdown) { + let mut minimum = usize::MAX; + for block in &blocks { + for line in &block.lines { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let indent = margin(&context.bytes()[line.content.clone()], budget)?; + if indent < line.content.len() { + minimum = minimum.min(indent); + } + } + } + if minimum != usize::MAX { + for block in &mut blocks { + for line in &mut block.lines { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let indent = margin(&context.bytes()[line.content.clone()], budget)?; + if indent < line.content.len() { + line.content.start += minimum; + } + } + } + } + } + let mut builder = TextBuilder::default(); + for (position, block) in blocks.iter().enumerate() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + if position != 0 { + builder.transformed("\n", Origin::Synthetic, budget)?; + } + let mut first = 0; + let mut end = block.lines.len(); + if profile != Profile::Rust { + while first < end && block.lines[first].content.is_empty() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + first += 1; + } + while end > first && block.lines[end - 1].content.is_empty() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + end -= 1; + } + } + for (index, line) in block.lines[first..end].iter().enumerate() { + append_range( + &mut builder, + context, + line.content.clone(), + profile == Profile::Doxygen, + budget, + )?; + if index + first + 1 < end { + if line.ending.len() == 2 { + builder.transformed( + "\n", + Origin::Decoded(context.pieces_with_budget(line.ending.clone(), budget)?), + budget, + )?; + } else { + builder.source(context, line.ending.clone(), budget)?; + } + } + } + } + Ok(builder.finish()) +} + +fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Result<(), TextError> { + if block.lines.len() < 2 { + return Ok(()); + } + let all_stars = |range: Range| -> Result { + for byte in &bytes[range] { + charge(budget)?; + if *byte != b'*' { + return Ok(false); + } + } + Ok(true) + }; + let first = usize::from(all_stars(block.lines[0].content.clone())?); + let mut end = block.lines.len(); + if end > first + && !block.lines[end - 1].content.is_empty() + && all_stars(block.lines[end - 1].content.clone())? + { + end -= 1; + } + let mut selected = Vec::new(); + for line in block.lines.drain(..).skip(first).take(end - first) { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + selected.push(line); + } + block.lines = selected; + let mut start = 0; + let mut end = block.lines.len(); + if block.rust_decoration { + if let Some(line) = block.lines.first() { + let indent = margin(&bytes[line.content.clone()], budget)?; + if bytes.get(line.content.start + indent) != Some(&b'*') { + start = 1; + } + } + while start < end + && margin(&bytes[block.lines[start].content.clone()], budget)? + == block.lines[start].content.len() + { + start += 1; + } + while end > start + && margin(&bytes[block.lines[end - 1].content.clone()], budget)? + == block.lines[end - 1].content.len() + { + end -= 1; + } + } + let mut star_column = None; + for line in &block.lines[start..end] { + let indent = margin(&bytes[line.content.clone()], budget)?; + if line.content.start + indent >= line.content.end + || bytes[line.content.start + indent] != b'*' + { + return Ok(()); + } + if star_column.is_some_and(|column| column != indent) { + return Ok(()); + } + star_column = Some(indent); + } + let Some(column) = star_column else { + return Ok(()); + }; + let prefix = + &bytes[block.lines[start].content.start..block.lines[start].content.start + column]; + for line in &mut block.lines { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let content = &bytes[line.content.clone()]; + let mut matching = content.len() >= prefix.len(); + for (actual, expected) in content.iter().zip(prefix) { + charge(budget)?; + if actual != expected { + matching = false; + break; + } + } + if matching { + line.content.start += column; + let content = &bytes[line.content.clone()]; + if block.rust_decoration + && (content == b"*" || content.starts_with(b"* ") || content.starts_with(b"**")) + { + line.content.start += 1; + } + } + } + Ok(()) +} diff --git a/big-code-analysis-ast/src/documentation/text/tests.rs b/big-code-analysis-ast/src/documentation/text/tests.rs new file mode 100644 index 000000000..9bd750e53 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/tests.rs @@ -0,0 +1,177 @@ +#![allow(clippy::similar_names)] + +use super::*; +use crate::documentation::budget::{CollectionBudget, NoBudget}; +use crate::documentation::{CompleteText, OriginView, TextRangeError}; +use crate::{AnyParser, LANG}; + +fn complete<'i, 's>(content: &'i Content<'s>) -> CompleteText<'i, 's> { + match content { + Content::Complete { text, mappings } => CompleteText { text, mappings }, + other => panic!("expected complete local text, got {other:?}"), + } +} + +#[cfg(feature = "rust")] +#[test] +fn copied_decoded_expanded_and_synthetic_origins_keep_exact_responsibility() { + let source = b"abcX\\x40Y\t"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut builder = TextBuilder::default(); + builder.source(&context, 0..3, &NoBudget).unwrap(); + builder + .transformed( + "@", + Origin::Decoded(context.pieces(4..8).unwrap()), + &NoBudget, + ) + .unwrap(); + builder + .transformed( + " ", + Origin::Expanded(context.pieces(9..10).unwrap()), + &NoBudget, + ) + .unwrap(); + builder + .transformed("\n", Origin::Synthetic, &NoBudget) + .unwrap(); + let content = builder.finish(); + let view = complete(&content); + assert_eq!(view.text(), "abc@ \n"); + let portions: Vec<_> = view.origins(1..8).unwrap().collect(); + assert_eq!(portions.len(), 4); + assert_eq!(portions[0].output, 1..3); + let OriginView::Copied(piece) = &portions[0].origin else { + panic!("copied origin") + }; + assert_eq!(piece.range(), 1..3); + assert_eq!(piece.bytes(), b"bc"); + let OriginView::Decoded(pieces) = &portions[1].origin else { + panic!("decoded origin") + }; + assert_eq!(pieces[0].range(), 4..8); + assert_eq!(pieces[0].bytes(), b"\\x40"); + let OriginView::Expanded(pieces) = &view.origins(5..6).unwrap().next().unwrap().origin else { + panic!("expanded origin") + }; + assert_eq!(pieces[0].range(), 9..10); + assert_eq!(pieces[0].bytes(), b"\t"); + assert_eq!(portions[3].origin, OriginView::Synthetic); + assert_eq!(portions[3].output, 7..8); +} + +#[cfg(feature = "rust")] +#[test] +fn utf8_carry_and_invalid_source_are_not_lossily_decoded() { + let source = format!("{}é🦀", "a".repeat(BYTE_INTERVAL - 1)); + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut builder = TextBuilder::default(); + builder + .source(&context, 0..source.len(), &NoBudget) + .unwrap(); + let content = builder.finish(); + let view = complete(&content); + assert_eq!(view.text(), source); + assert_eq!(view.mappings().len(), 1); + assert_eq!( + view.origins(BYTE_INTERVAL..BYTE_INTERVAL + 1).unwrap_err(), + TextRangeError::ScalarBoundary + ); + let mut builder = TextBuilder::default(); + assert!(matches!( + builder.append_utf8(b"a\xffb", &NoBudget), + Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)) + )); +} + +#[test] +fn late_and_empty_queries_do_not_scan_or_copy_preceding_runs() { + let mut builder = TextBuilder::default(); + for _ in 0..4096 { + builder + .transformed("a", Origin::Synthetic, &NoBudget) + .unwrap(); + } + let content = builder.finish(); + let view = complete(&content); + let before = crate::documentation::content::map_searches::observed(); + let portions: Vec<_> = view.origins(4095..4096).unwrap().collect(); + assert_eq!(portions.len(), 1); + assert_eq!(portions[0].output, 4095..4096); + // expected: Rust slice::partition_point performs log2(4096) + 1 comparisons. + assert_eq!( + crate::documentation::content::map_searches::observed() - before, + 13 + ); + let before = crate::documentation::content::map_searches::observed(); + assert_eq!(view.origins(4096..4096).unwrap().count(), 0); + assert_eq!( + crate::documentation::content::map_searches::observed() - before, + 0 + ); + assert_eq!( + view.origins(4097..4097).unwrap_err(), + TextRangeError::Bounds + ); +} + +#[test] +fn active_text_cancellation_is_an_error_and_the_next_operation_succeeds() { + let cancel = crate::cancel::ParseCancel::new(); + cancel.cancel(); + let mut builder = TextBuilder::default(); + let result = cancel.run(|| builder.append_utf8(b"audit", &CollectionBudget::default())); + assert!(matches!( + result, + Err(TextError::Source(SourceError::Cancelled)) + )); + builder + .append_utf8(b"audit", &CollectionBudget::default()) + .unwrap(); + assert_eq!(builder.text, "audit"); +} + +#[cfg(feature = "rust")] +#[test] +fn comment_cleanup_preserves_markup_hard_breaks_and_phase_two_splices() { + use crate::documentation::{FragmentForm, Profile}; + for (profile, source, expected) in [ + (Profile::Jsdoc, "/**\n * a \n * b\n */", "a \n b"), + (Profile::Javadoc, "/**/", ""), + (Profile::Javadoc, "////", "/"), + (Profile::Rust, "/*!*/", ""), + (Profile::Rust, "/**\n * a \n * b\n */", "a \n b\n"), + (Profile::GoDoc, "/* a\n * b */", "a\n * b"), + (Profile::Doxygen, "///a\\\nb", "ab"), + (Profile::Doxygen, "/**a\\\r\nb*/", "ab"), + (Profile::Doxygen, "///a\\\\\nb", "a\\b"), + (Profile::CsharpXml, "///a\\\nb", "a\\\nb"), + (Profile::Ldoc, "--[==[-audit]==]", "audit"), + (Profile::Yard, "=begin\naudit\n=end", "audit"), + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let fragment = crate::documentation::Fragment { + source: context.pieces(0..source.len()).unwrap(), + node: None, + form: FragmentForm::Comment, + }; + let content = comments::render(profile, &context, &[&fragment], &NoBudget).unwrap(); + let view = complete(&content); + assert_eq!(view.text(), expected, "{profile:?}: {source:?}"); + let portions: Vec<_> = view.origins(0..view.text().len()).unwrap().collect(); + let mut offset = 0; + for portion in portions { + assert_eq!(portion.output.start, offset); + offset = portion.output.end; + if let OriginView::Copied(piece) = portion.origin { + assert_eq!(piece.bytes(), &view.text().as_bytes()[portion.output]); + assert_eq!(piece.bytes(), &source.as_bytes()[piece.range()]); + } + } + assert_eq!(offset, expected.len()); + } +} diff --git a/big-code-analysis-ast/src/lang_helpers/doc_text.rs b/big-code-analysis-ast/src/lang_helpers/doc_text.rs index 7ff5c3afc..543885227 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_text.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_text.rs @@ -204,6 +204,14 @@ pub(crate) fn jsdoc_virtual(s: &[u8]) -> bool { false } +pub(crate) fn jsdoc_file(s: &[u8]) -> bool { + jsdoc_lines(s).filter_map(jsdoc_tag_open).any(|(title, _)| { + [b"file".as_slice(), b"fileoverview", b"overview", b"module"] + .iter() + .any(|name| title.eq_ignore_ascii_case(name)) + }) +} + /// A TypeDoc module comment: one carrying `@module` or /// `@packageDocumentation`, which `getCommentImpl` withholds from any /// declaration and reads as the file's documentation (#1613). diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index 1fdf332de..209391505 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -40,6 +40,24 @@ pub(crate) fn doxygen_member_after(s: &[u8]) -> bool { /// does. #[must_use] pub(crate) fn doxygen_standalone(s: &[u8]) -> bool { + structural_command_at(s).is_some() +} + +pub(crate) fn structural_command(s: &[u8]) -> Option<(&[u8], &[u8])> { + let (word, at) = structural_command_at(s)?; + let end = s[at..] + .iter() + .position(|byte| *byte == b'\n') + .map_or(s.len(), |end| at + end); + let argument = s[at..end].trim_ascii(); + let argument = argument + .strip_suffix(b"*/") + .unwrap_or(argument) + .trim_ascii_end(); + Some((word, argument)) +} + +fn structural_command_at(s: &[u8]) -> Option<(&[u8], usize)> { const ALWAYS: &[&[u8]] = &[ b"file", b"mainpage", @@ -82,10 +100,10 @@ pub(crate) fn doxygen_standalone(s: &[u8]) -> bool { }; at += 1 + word.len(); if ALWAYS.contains(&word) || (NAMED.contains(&word) && names_something(&s[at..])) { - return true; + return Some((word, at)); } } - false + None } /// Where the text Doxygen does not read for commands ends, when such text diff --git a/big-code-analysis-ast/src/macros/mod.rs b/big-code-analysis-ast/src/macros/mod.rs index dcbd3dadd..7365a976b 100644 --- a/big-code-analysis-ast/src/macros/mod.rs +++ b/big-code-analysis-ast/src/macros/mod.rs @@ -395,6 +395,21 @@ macro_rules! mk_action { $crate::with_any_parser!(self, |p| p.parse_completion()) } + /// Collect source documentation while checking retained parse completion. + /// + /// # Errors + /// Rejects cancelled parses and raw collection/profile failures. + pub fn documentation( + &self, + context: &$crate::documentation::DocumentationContext, + options: &$crate::documentation::DocumentationOptions, + ) -> Result<$crate::documentation::DocumentationIndex<'_>, $crate::documentation::CollectionError> { + if self.parse_completion() == $crate::parser::ParseCompletion::Cancelled { + return Err($crate::documentation::CollectionError::Cancelled); + } + $crate::documentation::collect(self.language(), self.ts_tree(), self.code(), context, options) + } + /// The root [`Node`] of the held tree. #[must_use] pub fn root_node(&self) -> Node<'_> { @@ -722,6 +737,22 @@ macro_rules! mk_langs { mk_extensions!($( ($camel, [ $( $ext ),* ]) ),*); mk_emacs_mode!($( ($camel, [ $( $emacs_mode ),* ]) ),*); mk_code!($( ($camel, $code, $parser, $name, stringify!($camel)) ),*); + pub(crate) fn collect_documentation<'s>( + language: LANG, + tree: &'s tree_sitter::Tree, + source: &'s [u8], + context: &crate::documentation::DocumentationContext, + options: &crate::documentation::DocumentationOptions, + ) -> Result, crate::documentation::CollectionError> { + $( + #[cfg(feature = $feature)] + if language == LANG::$camel { + return crate::documentation::collector::collect_typed::<$code>(language, tree, source, context, options); + } + )* + let _ = (tree, source, context, options); + Err(crate::documentation::CollectionError::LanguageDisabled(language)) + } }; } diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index faf6ac8bb..88439ed1a 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -146,6 +146,9 @@ impl Tree { pub struct Node<'a>(OtherNode<'a>); impl<'a> Node<'a> { + pub(crate) fn from_tree_sitter(node: OtherNode<'a>) -> Self { + Self(node) + } /// Returns the underlying [`tree_sitter::Node`] for callers that /// want to drive their own traversal alongside the metric walker. /// diff --git a/big-code-analysis-ast/src/node/ancestors/siblings.rs b/big-code-analysis-ast/src/node/ancestors/siblings.rs index ed6fff982..45a7f50a7 100644 --- a/big-code-analysis-ast/src/node/ancestors/siblings.rs +++ b/big-code-analysis-ast/src/node/ancestors/siblings.rs @@ -227,24 +227,45 @@ impl<'tree> SiblingCache<'tree> { depth: usize, children: impl IntoIterator>, ) { + crate::documentation::budget::infallible(self.record_with_budget( + node, + depth, + children, + &crate::documentation::budget::NoBudget, + )); + } + + pub(crate) fn record_with_budget( + &mut self, + node: &Node<'tree>, + depth: usize, + children: impl IntoIterator>, + budget: &B, + ) -> Result<(), B::Error> { if node.child_count() <= WIDE_PARENT { - return; + return Ok(()); } - if self.0.len() <= depth { - self.0.resize_with(depth + 1, Default::default); + while self.0.len() <= depth { + budget.step()?; + self.0.push(Default::default()); } // An unused slot's id is 0, which no node has: tree-sitter's id // is the address of the node's subtree. let (id, recorded) = &mut self.0[depth]; - *id = node.id(); + *id = 0; recorded.clear(); - recorded.extend(children); + for child in children { + budget.step()?; + recorded.push(child); + } debug_assert_eq!( recorded.len(), node.child_count(), "a walk must record every child of a wide {}, in one batch (#1871)", node.kind() ); + *id = node.id(); + Ok(()) } /// Whether no node is recorded. Test-only: the record is otherwise diff --git a/big-code-analysis-ast/src/parser.rs b/big-code-analysis-ast/src/parser.rs index b8a265c24..68d286133 100644 --- a/big-code-analysis-ast/src/parser.rs +++ b/big-code-analysis-ast/src/parser.rs @@ -275,6 +275,23 @@ impl Parser { pub fn parse_completion(&self) -> ParseCompletion { self.tree.completion() } + + /// Collect a borrowed immutable documentation index from this parse. + /// Adopted trees retain the matching-source and complete-parse preconditions. + /// + /// # Errors + /// Rejects retained parse cancellation and every raw collection failure. + pub fn documentation( + &self, + context: &crate::documentation::DocumentationContext, + options: &crate::documentation::DocumentationOptions, + ) -> Result, crate::documentation::CollectionError> + { + if self.parse_completion() == ParseCompletion::Cancelled { + return Err(crate::documentation::CollectionError::Cancelled); + } + crate::documentation::collect(T::lang(), self.ts_tree(), &self.code, context, options) + } } #[cfg(test)] diff --git a/utils/documentation-collector-perturb.json b/utils/documentation-collector-perturb.json new file mode 100644 index 000000000..ff42c271e --- /dev/null +++ b/utils/documentation-collector-perturb.json @@ -0,0 +1,56 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "raw-grammar-validation-disabled", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "if *tree.language() != grammar {", + "new": "if false && *tree.language() != grammar {", + "expect": ["documentation::collector::tests::mismatched_raw_grammar_is_rejected_before_predicates"] + }, + { + "name": "pending-composition-becomes-empty-complete", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "let content = if attribute {\n Content::PendingAdapter", + "new": "let content = if attribute {\n Content::Complete { text: String::new(), mappings: Vec::new() }", + "expect": ["documentation::collector::tests::rust_pending_attributes_never_report_complete_partial_text"] + }, + { + "name": "foreign-document-handles-accepted", + "file": "big-code-analysis-ast/src/documentation/index.rs", + "old": " self.facts.check_scope(document)?;", + "new": " let _ = document;", + "expect": ["documentation::collector::tests::document_handles_are_index_qualified_even_for_one_shared_parse"] + }, + { + "name": "copied-origins-not-clipped", + "file": "big-code-analysis-ast/src/documentation/content.rs", + "old": "let start = piece.range().start + output.start - mapping.output.0.start;", + "new": "let start = piece.range().start;", + "expect": ["documentation::text::tests::copied_decoded_expanded_and_synthetic_origins_keep_exact_responsibility"] + }, + { + "name": "single-chunk-sort-cancellation-ignored", + "file": "big-code-analysis-ast/src/documentation/ordering.rs", + "old": " *self.error.borrow_mut() = self.budget.step().err();", + "new": " let _ = self.budget.step();", + "expect": ["documentation::ordering::tests::chunk_sort_cancellation_latches_without_corrupting_comparator_order"] + }, + { + "name": "explicit-name-collision-selects-first", + "file": "big-code-analysis-ast/src/documentation/names.rs", + "old": " _ => Some(UnresolvedReason::Ambiguous),", + "new": " _ => None,", + "expect": ["documentation::collector::tests::doxygen_static_names_resolve_unique_missing_and_ambiguous_targets"] + }, + { + "name": "crlf-splice-retained", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "if bytes[at..].starts_with(b\"\\\\\\r\\n\") {\n 3", + "new": "if bytes[at..].starts_with(b\"\\\\\\r\\n\") {\n 0", + "expect": ["documentation::text::tests::comment_cleanup_preserves_markup_hard_breaks_and_phase_two_splices"] + } + ] +} From 1129c080b83671586ea18edd92957124b0650323 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:44:08 -0800 Subject: [PATCH 036/221] feat(documentation): propagate fallible source work through shared kernels --- .bca-baseline.toml | 848 +++++++++++++++--- CHANGELOG.md | 3 + big-code-analysis-ast/src/checker.rs | 6 +- big-code-analysis-ast/src/checker/lua.rs | 260 ++++-- big-code-analysis-ast/src/checker/php.rs | 75 +- big-code-analysis-ast/src/checker/ruby.rs | 203 ++++- big-code-analysis-ast/src/documentation.rs | 18 + .../src/documentation/budget.rs | 101 ++- .../src/documentation/byte_scan.rs | 105 +++ .../src/documentation/canonical.rs | 2 + .../src/documentation/collector.rs | 572 ++++-------- .../src/documentation/collector/assembly.rs | 248 +++++ .../collector/assessment_tests.rs | 353 ++++++++ .../collector/cancellation_tests.rs | 222 +++++ .../src/documentation/collector/cost_tests.rs | 86 ++ .../collector/projection_tests.rs | 181 ++++ .../documentation/collector/projections.rs | 209 +++++ .../src/documentation/collector/tests.rs | 40 +- .../src/documentation/forms.rs | 123 +++ .../src/documentation/index.rs | 33 +- .../src/documentation/names.rs | 171 +++- .../src/documentation/ordering.rs | 9 + .../src/documentation/recognition.rs | 333 +++++++ .../src/documentation/source.rs | 48 +- .../src/documentation/streaming/markers.rs | 216 +++-- .../src/documentation/streaming/positional.rs | 129 ++- .../src/documentation/text.rs | 49 + .../src/documentation/text/comments.rs | 90 +- .../src/documentation/text/literals.rs | 308 +++++++ .../src/documentation/text/tests.rs | 74 +- .../src/lang_helpers/doc_comment.rs | 539 ++++++++--- .../src/lang_helpers/doc_text.rs | 305 ++++--- .../src/lang_helpers/doxygen.rs | 381 +++++--- .../src/lang_helpers/ruby.rs | 145 +-- .../src/node/ancestors/folds.rs | 136 ++- .../src/node/ancestors/siblings.rs | 90 +- big-code-analysis-ast/src/roles/go.rs | 58 +- big-code-analysis-ast/src/roles/js_family.rs | 133 ++- big-code-analysis-ast/src/roles/lua.rs | 191 +++- big-code-analysis-ast/src/roles/php.rs | 63 +- big-code-analysis-ast/src/roles/rust.rs | 18 +- big-code-analysis-bench/Cargo.toml | 6 +- .../benches/documentation.rs | 222 +++++ utils/documentation-collector-perturb.json | 48 +- utils/documentation-form-matrix.json | 93 ++ utils/documentation-markers-perturb.json | 34 +- utils/documentation-positional-perturb.json | 34 +- 47 files changed, 6165 insertions(+), 1446 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/byte_scan.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/assembly.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/assessment_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/cost_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/projection_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/projections.rs create mode 100644 big-code-analysis-ast/src/documentation/forms.rs create mode 100644 big-code-analysis-ast/src/documentation/recognition.rs create mode 100644 big-code-analysis-ast/src/documentation/text/literals.rs create mode 100644 big-code-analysis-bench/benches/documentation.rs create mode 100644 utils/documentation-form-matrix.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 6a4d51ad0..880a8b69e 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -231,141 +231,147 @@ value = 32.0 [[entry]] path = "big-code-analysis-ast/src/checker/lua.rs" -qualified = "lua_first_block_in" +qualified = "lua_block_text_with_budget" metric = "nexits" value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/checker/php.rs" -qualified = "php_file_docblock" -metric = "cognitive" -value = 15.0 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "abc" +value = 45.48626166217664 [[entry]] -path = "big-code-analysis-ast/src/checker/php.rs" -qualified = "php_file_docblock" -metric = "halstead.effort" -value = 85764.10672424761 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "cognitive" +value = 17.0 [[entry]] -path = "big-code-analysis-ast/src/checker/php.rs" -qualified = "php_file_docblock" -metric = "nexits" -value = 6.0 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "cyclomatic" +value = 16.0 [[entry]] -path = "big-code-analysis-ast/src/documentation.rs" -qualified = "collect" +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_with_budget" metric = "nargs" value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "" -metric = "loc.ploc" -value = 1112.0 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "nexits" +value = 13.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>" -metric = "nom" -value = 29.0 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "abc" +value = 43.05810028322197 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>" -metric = "wmc" -value = 183.0 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "cyclomatic" +value = 15.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::c_slots" -metric = "abc" -value = 54.415071441651165 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "halstead.effort" +value = 74556.63603392318 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::c_slots" -metric = "cognitive" -value = 31.0 +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "nexits" +value = 15.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::c_slots" -metric = "halstead.effort" -value = 169049.87968189508 +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "abc" +value = 41.30375285612676 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::c_slots" -metric = "nexits" -value = 5.0 +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "cognitive" +value = 15.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::combine_pending" +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock_with_budget" metric = "halstead.effort" -value = 48339.317828216816 +value = 111370.05894260037 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::document" -metric = "abc" -value = 47.16990566028302 +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "nargs" +value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::document" -metric = "cognitive" -value = 31.0 +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "nexits" +value = 14.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::document" -metric = "cyclomatic" -value = 20.0 +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "ruby_core_answer" +metric = "halstead.effort" +value = 99252.01656831444 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::document" -metric = "halstead.effort" -value = 147420.0 +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "ruby_core_answer" +metric = "nargs" +value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::document" +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "ruby_core_answer" metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "ruby_doc_target_with_budget" +metric = "nargs" value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::finalize_projection" -metric = "cognitive" -value = 17.0 +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "source_opener_with_budget" +metric = "nexits" +value = 6.0 [[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::finalize_projection" -metric = "cyclomatic" -value = 16.0 +path = "big-code-analysis-ast/src/documentation.rs" +qualified = "collect" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::finalize_projection" -metric = "halstead.effort" -value = 97707.37584823032 +qualified = "" +metric = "loc.ploc" +value = 882.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::finalize_projection" -metric = "nexits" -value = 5.0 +qualified = "Builder<'s>" +metric = "wmc" +value = 123.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::local_target" metric = "abc" -value = 40.01249804748511 +value = 42.02380277890139 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -383,31 +389,37 @@ value = 17.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::local_target" metric = "halstead.effort" -value = 119082.74234645894 +value = 123236.88212462913 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::local_target" +metric = "nexits" +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "abc" -value = 49.889878733065686 +value = 55.97320787662612 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "cognitive" -value = 40.0 +value = 48.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "cyclomatic" -value = 16.0 +value = 20.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "halstead.effort" -value = 192225.81875457868 +value = 232144.35747298473 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -437,31 +449,49 @@ value = 13.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::recognize" metric = "halstead.effort" -value = 72071.50108974567 +value = 86240.41224844726 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::recognize" metric = "nexits" -value = 7.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::render_draft" +qualified = "Builder<'s>::record_children" metric = "halstead.effort" -value = 55060.1234372333 +value = 67267.11040846657 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::render_draft" -metric = "nexits" +qualified = "Builder<'s>::record_children" +metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "cyclomatic" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "halstead.effort" +value = 70341.82893047434 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "nexits" +value = 6.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::rust_attribute" metric = "abc" -value = 48.35286961494633 +value = 50.21951811795888 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -473,43 +503,43 @@ value = 22.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::rust_attribute" metric = "halstead.effort" -value = 189226.37033980602 +value = 192758.27410592738 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::walk" -metric = "abc" -value = 84.22588675698226 +qualified = "Builder<'s>::rust_attribute" +metric = "nexits" +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" -metric = "cognitive" -value = 35.0 +metric = "abc" +value = 47.56048780237646 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "halstead.effort" -value = 236917.17587667526 +value = 110827.26177270018 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "nexits" -value = 12.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "abc" -value = 52.316345438113316 +value = 53.291650377896914 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "halstead.effort" -value = 85297.33044874134 +value = 87295.73158561725 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -523,6 +553,120 @@ qualified = "collect_typed" metric = "nexits" value = 13.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::combine_pending" +metric = "cognitive" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::combine_pending" +metric = "halstead.effort" +value = 58161.637831875196 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "abc" +value = 47.01063709417264 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "cognitive" +value = 25.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "cyclomatic" +value = 19.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "halstead.effort" +value = 135337.94741648942 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::pending_document" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::render_draft" +metric = "halstead.effort" +value = 56025.386626091306 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::render_draft" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "abc" +value = 51.24451190127583 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "cognitive" +value = 20.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "halstead.effort" +value = 139186.7870688173 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "cognitive" +value = 19.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "cyclomatic" +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "halstead.effort" +value = 101368.16786835015 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::index_function_definition" +metric = "nexits" +value = 8.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/collector/tests.rs" qualified = "assert_positive" @@ -535,29 +679,101 @@ qualified = "assert_positive" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/forms.rs" +qualified = "assess" +metric = "cyclomatic" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/forms.rs" +qualified = "assess" +metric = "halstead.effort" +value = 48579.95593242823 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/forms.rs" +qualified = "assess" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::resolve" -metric = "cognitive" -value = 20.0 +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/recognition.rs" +qualified = "NativeRules::forward" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/recognition.rs" +qualified = "NativeRules::target" +metric = "halstead.effort" +value = 62580.37535783485 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/recognition.rs" +qualified = "NativeRules::target::" +metric = "cyclomatic" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/recognition.rs" +qualified = "source_target" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::members" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::members" +metric = "nexits" +value = 9.0 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" qualified = "RunSelection<'t>::select" metric = "halstead.effort" -value = 59655.33539489184 +value = 78266.7217720615 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" qualified = "RunSelection<'t>::select" metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::select" +metric = "nexits" value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" qualified = "line_spelling_end" metric = "halstead.effort" -value = 48591.21083121782 +value = 61202.196886790516 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "line_spelling_end" +metric = "nexits" +value = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "member" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/markers/regressions/suffix.rs" @@ -569,13 +785,31 @@ value = 57170.887340554174 path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" qualified = "SourceDecision<'t>::new" metric = "halstead.effort" -value = 53278.06215664464 +value = 64712.3508182161 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" -qualified = "source_comment" +qualified = "SourceDecision<'t>::new" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceDecision<'t>::new" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "source_comment_with_budget" metric = "halstead.effort" -value = 53469.151178029744 +value = 62284.85470995608 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "source_members" +metric = "nexits" +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/streaming/positional/tests.rs" @@ -583,6 +817,24 @@ qualified = "work" metric = "halstead.effort" value = 73112.8706762203 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text.rs" +qualified = "TextBuilder<'s>::copied_pieces" +metric = "abc" +value = 44.56455991031439 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text.rs" +qualified = "TextBuilder<'s>::copied_pieces" +metric = "halstead.effort" +value = 53116.211721440406 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text.rs" +qualified = "TextBuilder<'s>::copied_pieces" +metric = "nexits" +value = 8.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "append_range" @@ -593,7 +845,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "abc" -value = 64.41273166075166 +value = 62.68173577685928 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -611,7 +863,7 @@ value = 26.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "halstead.effort" -value = 379601.4471603583 +value = 350711.9003697722 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -619,6 +871,12 @@ qualified = "beautify" metric = "nexits" value = 15.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "blank" +metric = "nexits" +value = 7.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "delimiters" @@ -665,25 +923,31 @@ value = 62992.207215869705 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "prepare" metric = "abc" -value = 49.23413450036468 +value = 49.80963762164909 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "prepare" metric = "cognitive" -value = 39.0 +value = 40.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "prepare" metric = "cyclomatic" -value = 27.0 +value = 28.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "prepare" metric = "halstead.effort" -value = 168855.57230832687 +value = 176271.65882530835 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -693,33 +957,87 @@ value = 9.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render" +qualified = "render_local" metric = "abc" -value = 65.92419889539804 +value = 72.53275122315436 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render" +qualified = "render_local" metric = "cognitive" -value = 52.0 +value = 56.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render" +qualified = "render_local" metric = "cyclomatic" -value = 23.0 +value = 25.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render" +qualified = "render_local" metric = "halstead.effort" -value = 231327.72273130648 +value = 270557.5417208994 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render_local" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render" +qualified = "render_local" metric = "nexits" -value = 15.0 +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "abc" +value = 87.55569655939013 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "cognitive" +value = 42.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "cyclomatic" +value = 38.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "halstead.effort" +value = 430739.9986277097 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "nexits" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "expand_tabs" +metric = "halstead.effort" +value = 53178.14428542049 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "expand_tabs" +metric = "nexits" +value = 7.0 [[entry]] path = "big-code-analysis-ast/src/getter.rs" @@ -761,7 +1079,7 @@ value = 101217.532578918 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "" metric = "loc.ploc" -value = 686.0 +value = 909.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -769,9 +1087,63 @@ qualified = "bind_gathered" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_gathered_with_budget" +metric = "halstead.effort" +value = 91678.87676432476 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_gathered_with_budget" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_gathered_with_budget" +metric = "nexits" +value = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_last" +metric = "halstead.effort" +value = 52878.01706536632 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_last" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_last" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_leading" +metric = "halstead.effort" +value = 61219.96388225051 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_leading" +metric = "nargs" +value = 6.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "bind_leading" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_nearest" metric = "nargs" value = 5.0 @@ -787,15 +1159,45 @@ qualified = "bound_doc_run" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_positional_prefix" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_positional_prefix" +metric = "nexits" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "collect_stretch" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_stretch_with_budget" metric = "halstead.effort" -value = 48097.31864419657 +value = 66915.85266413665 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "collect_stretch" +qualified = "collect_stretch_with_budget" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_stretch_with_budget" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "error_holds_target_with_budget" metric = "nargs" value = 5.0 @@ -803,19 +1205,43 @@ value = 5.0 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "exhausted_stretch" metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "held_in_body_with_budget" +metric = "nargs" value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "joined_run" metric = "nargs" -value = 5.0 +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "positional_run" +qualified = "positional_run_with_budget" metric = "halstead.effort" -value = 58580.287928857055 +value = 77303.1230783747 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "positional_run_with_budget" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "positional_run_with_budget" +metric = "nexits" +value = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "read_past_error_with_budget" +metric = "nargs" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -825,9 +1251,21 @@ value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "stretch_end" +qualified = "select_bound_with_budget" metric = "halstead.effort" -value = 73719.8111279588 +value = 74299.0960371325 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "select_bound_with_budget" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "select_bound_with_budget" +metric = "nexits" +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -837,10 +1275,112 @@ value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "suffix_gap" +qualified = "stretch_end_with_budget" +metric = "cyclomatic" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end_with_budget" +metric = "halstead.effort" +value = 113377.45845370996 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end_with_budget" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end_with_budget" +metric = "nexits" +value = 12.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "suffix_gap_with_budget" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_text.rs" +qualified = "jsdoc_names" +metric = "cognitive" +value = 22.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_text.rs" +qualified = "jsdoc_virtual_with_budget" +metric = "halstead.effort" +value = 58207.82461766628 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_text.rs" +qualified = "jsdoc_virtual_with_budget" +metric = "nexits" +value = 9.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_text.rs" +qualified = "ruby_magic_comment_with_budget" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_text.rs" +qualified = "ruby_magic_setting" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "children_declare" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "code_span_close" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "conditional_declares_with_budget" +metric = "halstead.effort" +value = 48258.766765046166 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "delimited_end" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "doxygen_command" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "literal_end" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "structural_command_at" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doxygen.rs" +qualified = "structural_command_with_budget" +metric = "nexits" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/elixir_decisions.rs" qualified = "elixir_pair_section" @@ -853,6 +1393,12 @@ qualified = "documentation_run" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/ruby.rs" +qualified = "yard_reads_with_budget" +metric = "nargs" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/node.rs" qualified = "Node<'a>" @@ -871,9 +1417,33 @@ qualified = "Ancestors<'tree, 'chain>::fold_down" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/node/ancestors/folds.rs" +qualified = "Ancestors<'tree, 'chain>::fold_down_with_budget" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/node/ancestors/folds.rs" +qualified = "FoldCache::fold" +metric = "halstead.effort" +value = 66325.29412020449 + +[[entry]] +path = "big-code-analysis-ast/src/node/ancestors/folds.rs" +qualified = "FoldCache::fold" +metric = "nargs" +value = 6.0 + [[entry]] path = "big-code-analysis-ast/src/node/ancestors/folds.rs" qualified = "FoldCache::fold" +metric = "nexits" +value = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/node/ancestors/folds.rs" +qualified = "fold_climbed" metric = "nargs" value = 5.0 @@ -901,6 +1471,18 @@ qualified = "record_indirect_includes" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/roles/lua.rs" +qualified = "assigns_one_name_with_budget" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/roles/lua.rs" +qualified = "opens_with_budget" +metric = "nexits" +value = 7.0 + [[entry]] path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" diff --git a/CHANGELOG.md b/CHANGELOG.md index e7f11f40a..0d2a045a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,9 @@ for historical reference. owner queries, explicit pending-adapter assessments, and retained local text and forward-origin views. Basic comment paths cover the 17 streamed language variants; deferred source adapters return an explicit availability error. + Source recognition uses fallible work-budget kernels shared with legacy + wrappers. Kotlin local KDoc retains complete text with pending owner evidence; + Java prelexing limitations retain separately labeled source-cleaned spelling. (#1660, #1661) - Added unstable AST positional-run evidence for Go, Ruby and Lua, including diff --git a/big-code-analysis-ast/src/checker.rs b/big-code-analysis-ast/src/checker.rs index c9c172a18..e83746e3d 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -987,15 +987,15 @@ mod irules; mod java; mod javascript; mod kotlin; -mod lua; +pub(crate) mod lua; mod mozcpp; mod mozjs; mod objc; mod perl; -mod php; +pub(crate) mod php; mod preproc; mod python; -mod ruby; +pub(crate) mod ruby; mod rust; mod tcl; mod tsx; diff --git a/big-code-analysis-ast/src/checker/lua.rs b/big-code-analysis-ast/src/checker/lua.rs index 8fc6397f7..4f30dd151 100644 --- a/big-code-analysis-ast/src/checker/lua.rs +++ b/big-code-analysis-ast/src/checker/lua.rs @@ -2,9 +2,9 @@ #![allow(clippy::wildcard_imports, clippy::enum_glob_use)] use super::*; -use crate::lang_helpers::doc_comment::{ - ldoc_opener, lua_long_comment, node_bytes, run_continues_to, -}; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::documentation::byte_scan as scan; +use crate::lang_helpers::doc_comment::{lua_long_comment, node_bytes}; /// What the text of the block `first` opens holds, read over the run /// `first` starts, as `leading_doc_run` delimits it. @@ -20,37 +20,64 @@ struct LdocText { } impl LdocText { - fn read(&mut self, member: &Node<'_>, code: &[u8]) { - for line in node_bytes(member, code).split(|&byte| byte == b'\n') { - let body = ldoc_line_body(line); - self.text |= body.iter().any(|&byte| { - !matches!(byte, b'-' | b'[' | b']' | b'=') && !byte.is_ascii_whitespace() - }); - self.tag |= - matches!(body.trim_ascii_start(), [b'@', tag, ..] if tag.is_ascii_alphanumeric()); + fn read_with_budget( + &mut self, + member: &Node<'_>, + code: &[u8], + budget: &B, + ) -> Result<(), B::Error> { + for line in scan::lines(node_bytes(member, code), budget) { + budget.step()?; + let body = ldoc_line_body(line?, budget)?; + self.text |= scan::position( + body, + |byte| !matches!(byte, b'-' | b'[' | b']' | b'=') && !byte.is_ascii_whitespace(), + budget, + )? + .is_some(); + self.tag |= matches!(scan::trim_start(body, budget)?, [b'@', tag, ..] if tag.is_ascii_alphanumeric()); } + Ok(()) } } fn lua_block_text<'a>(first: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>) -> LdocText { + infallible(lua_block_text_with_budget( + first, code, ancestors, &NoBudget, + )) +} + +fn lua_block_text_with_budget<'a, B: WorkBudget>( + first: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { let mut found = LdocText::default(); let mut member = *first; - let mut after = ancestors.siblings_after(first); + let mut after = ancestors.siblings_after_with_budget(first, budget)?; loop { - found.read(&member, code); - match after.next() { - Some(next) if run_continues_to::(&member, &next, code) => member = next, - _ => return found, + budget.step()?; + found.read_with_budget(&member, code, budget)?; + if let Some(next) = after.next() + && crate::lang_helpers::doc_comment::run_continues_with_budget::< + crate::documentation::recognition::NativeRules, + _, + >(&member, &next, code, budget)? + { + member = next; + } else { + return Ok(found); } } } /// A comment line with its leading whitespace and comment dashes /// stripped: the text LDoc reads. -fn ldoc_line_body(line: &[u8]) -> &[u8] { - let line = line.trim_ascii_start(); - let dashes = line.iter().take_while(|&&byte| byte == b'-').count(); - line.get(dashes..).unwrap_or_default() +fn ldoc_line_body<'s, B: WorkBudget>(line: &'s [u8], budget: &B) -> Result<&'s [u8], B::Error> { + let line = scan::trim_start(line, budget)?; + let dashes = scan::position(line, |byte| byte != b'-', budget)?.unwrap_or(line.len()); + Ok(&line[dashes..]) } /// Whether the block `first` opens is the file's first LDoc block, which @@ -72,6 +99,18 @@ fn lua_first_block_in<'a>( ancestors: Ancestors<'a, '_>, source: Option<&crate::documentation::SourceContext<'a>>, ) -> Result { + infallible(lua_first_block_with_budget( + first, code, ancestors, source, &NoBudget, + )) +} + +fn lua_first_block_with_budget<'a, B: WorkBudget>( + first: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: Option<&crate::documentation::SourceContext<'a>>, + budget: &B, +) -> Result, B::Error> { // bca: suppress(halstead) -- the same reverse first-block decision serves legacy and source, with source-only gap barriers. // A fast path, not a separate rule: every other container opens with a // token (`if`, `do`, `{`), and the grammar parks a comment above a @@ -83,56 +122,144 @@ fn lua_first_block_in<'a>( .parent(first) .is_none_or(|parent| parent.kind_id() != Lua::Chunk) { - return Ok(false); + return Ok(Ok(false)); } let mut earliest = *first; - let mut before = ancestors.siblings_before(first).peekable(); + let mut before = ancestors + .siblings_before_with_budget(first, budget)? + .peekable(); while let Some(sibling) = before.next() { - if source.is_some_and(|source| !source.covers(sibling.start_byte()..earliest.end_byte())) { - return Err(crate::documentation::UnresolvedReason::ExcludedGap); + budget.step()?; + if let Some(source) = source + && !source.covers_with_budget(sibling.start_byte()..earliest.end_byte(), budget)? + { + return Ok(Err(crate::documentation::UnresolvedReason::ExcludedGap)); } - if source.is_some_and(|source| { - before - .peek() - .is_some_and(|above| !source.covers(above.start_byte()..sibling.end_byte())) - }) { - return Err(crate::documentation::UnresolvedReason::ExcludedGap); + if let Some(source) = source + && let Some(above) = before.peek() + && !source.covers_with_budget(above.start_byte()..sibling.end_byte(), budget)? + { + return Ok(Err(crate::documentation::UnresolvedReason::ExcludedGap)); } // `run_continues_to` asks only whether `sibling` continues a run // from `above`, so a comment directly under code needs the // comment test too: it opens its run. - let opens_run = before.peek().is_none_or(|above| { - !(LuaCode::is_comment(above) && run_continues_to::(above, &sibling, code)) - }); + let opens_run = if let Some(above) = before.peek() { + !(LuaCode::is_comment(above) + && crate::lang_helpers::doc_comment::run_continues_with_budget::< + crate::documentation::recognition::NativeRules, + _, + >(above, &sibling, code, budget)?) + } else { + true + }; // role-bypass: allow(Comment, DocRunOpener) — the backward scan for an // earlier block: run traversal over the rows, not membership if opens_run && sibling.kind_id() == Lua::Comment - && ldoc_opener(node_bytes(&sibling, code)) - && lua_block_text(&sibling, code, ancestors).text + && crate::lang_helpers::doc_text::ldoc_opener_with_budget( + node_bytes(&sibling, code), + budget, + )? + && lua_block_text_with_budget(&sibling, code, ancestors, budget)?.text { - return Ok(false); + return Ok(Ok(false)); } earliest = sibling; } - if source.is_some_and(|source| !source.covers(0..earliest.start_byte())) { - return Err(crate::documentation::UnresolvedReason::ExcludedGap); + if let Some(source) = source + && !source.covers_with_budget(0..earliest.start_byte(), budget)? + { + return Ok(Err(crate::documentation::UnresolvedReason::ExcludedGap)); } // role-bypass: allow(Comment) — whether the file opens with a comment or // a shebang, LDoc's first-token rule; traversal, not membership - Ok(matches!( + Ok(Ok(matches!( earliest.kind_id().into(), Lua::Comment | Lua::HashBangLine - )) + ))) } /// The first statement of a `block`, which stands for it: the grammar parks /// a comment that precedes the first statement of an `if`, `do` or loop /// body outside the `block`. fn lua_block_first_statement<'a>(node: &Node<'a>) -> Option> { - (node.kind_id() == Lua::Block) - .then(|| node.children().find(Node::is_named)) - .flatten() + infallible(lua_block_first_with_budget(node, &NoBudget)) +} + +fn lua_block_first_with_budget<'a, B: WorkBudget>( + node: &Node<'a>, + budget: &B, +) -> Result>, B::Error> { + if node.kind_id() == Lua::Block { + for child in node.children() { + budget.step()?; + if child.is_named() { + return Ok(Some(child)); + } + } + } + Ok(None) +} + +pub(crate) fn target_with_budget( + node: &Node<'_>, + budget: &B, +) -> Result { + if let Some(item) = lua_block_first_with_budget(node, budget)? { + crate::roles::lua::target_with_budget(&item, budget) + } else { + crate::roles::lua::target_with_budget(node, budget) + } +} + +pub(crate) fn source_opener_with_budget<'a, B: WorkBudget>( + run: &crate::documentation::streaming::positional::RunContext<'_, 'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result< + Result< + Option, + crate::documentation::UnresolvedReason, + >, + B::Error, +> { + use crate::documentation::streaming::positional::OpenerReason; + let Some(first) = run.members.first() else { + return Ok(Ok(None)); + }; + if let Some(above) = ancestors.siblings_before_with_budget(first, budget)?.next() + && LuaCode::is_comment(&above) + && let Some(source) = run.source + && !source.covers_with_budget(above.start_byte()..first.end_byte(), budget)? + { + return Ok(Err(crate::documentation::UnresolvedReason::ExcludedGap)); + } + if !crate::roles::lua::opens_with_budget(first, run.code, ancestors, budget)? { + return Ok(Ok(None)); + } + let mut text = LdocText::default(); + for member in run.members { + budget.step()?; + text.read_with_budget(member, run.code, budget)?; + } + if !text.text { + return Ok(Ok(None)); + } + match lua_first_block_with_budget(first, run.code, ancestors, run.source, budget)? { + Ok(true) => return Ok(Ok(Some(OpenerReason::FirstFile))), + Err(reason) => return Ok(Err(reason)), + Ok(false) => {} + } + if text.tag { + return Ok(Ok(Some(OpenerReason::Tagged))); + } + if let Some(next) = run.below + && target_with_budget(&next, budget)? + { + return Ok(Ok(Some(OpenerReason::FollowingItem))); + } + Ok(Ok(None)) } impl Checker for LuaCode { @@ -143,11 +270,8 @@ impl Checker for LuaCode { code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - if let Some(item) = lua_block_first_statement(node) { - crate::roles::lua::doc_target::owns(&item, code, ancestors.of_children(node).get()) - } else { - crate::roles::lua::doc_target::owns(node, code, ancestors) - } + let _ = (code, ancestors); + infallible(target_with_budget(node, &NoBudget)) } fn source_doc_run_opener<'a>( @@ -157,45 +281,7 @@ impl Checker for LuaCode { Option, crate::documentation::UnresolvedReason, > { - // bca: suppress(nexits, halstead) -- retain unknown prefix context before selecting file, tagged or following-item documentation. - use crate::documentation::streaming::positional::OpenerReason; - if run.members.first().is_some_and(|first| { - ancestors - .siblings_before(first) - .next() - .is_some_and(|above| { - Self::is_comment(&above) - && run.source.is_some_and(|source| { - !source.covers(above.start_byte()..first.end_byte()) - }) - }) - }) { - return Err(crate::documentation::UnresolvedReason::ExcludedGap); - } - let Some(first) = run - .members - .first() - .filter(|first| crate::roles::lua::doc_run_opener::owns(first, run.code, ancestors)) - else { - return Ok(None); - }; - let mut text = LdocText::default(); - for member in run.members { - text.read(member, run.code); - } - if !text.text { - return Ok(None); - } - if lua_first_block_in(first, run.code, ancestors, run.source)? { - return Ok(Some(OpenerReason::FirstFile)); - } - if text.tag { - return Ok(Some(OpenerReason::Tagged)); - } - Ok(run - .below - .filter(|next| Self::is_source_doc_target(next, run.code, ancestors)) - .map(|_| OpenerReason::FollowingItem)) + infallible(source_opener_with_budget(run, ancestors, &NoBudget)) } // The `Comment` row of `roles/lua.rs` (#1699); no `DocComment`. impl_comment_from_rows!(lua); diff --git a/big-code-analysis-ast/src/checker/php.rs b/big-code-analysis-ast/src/checker/php.rs index 2d2dc2ca2..25be74d85 100644 --- a/big-code-analysis-ast/src/checker/php.rs +++ b/big-code-analysis-ast/src/checker/php.rs @@ -2,6 +2,7 @@ #![allow(clippy::wildcard_imports, clippy::enum_glob_use)] use super::*; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; use crate::documentation::streaming::markers::CandidateView; use crate::lang_helpers::doc_comment::never_joins; @@ -30,6 +31,18 @@ fn php_file_docblock<'a>( ancestors: Ancestors<'a, '_>, view: CandidateView, ) -> Option { + infallible(php_file_docblock_with_budget( + comment, code, ancestors, view, &NoBudget, + )) +} + +fn php_file_docblock_with_budget<'a, B: WorkBudget>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView, + budget: &B, +) -> Result, B::Error> { let marker = |n: &Node| match view { CandidateView::Legacy => PhpCode::is_doc_comment(n, code), CandidateView::Source(_) => view.marker::(n, code, ancestors), @@ -38,31 +51,33 @@ fn php_file_docblock<'a>( |n: Node| php_file_preamble(&n) || (PhpCode::is_comment(&n) && !marker(&n)); let mut boundary = comment.start_byte(); if !ancestors.parent_has_kind(comment, Php::Program as u16) { - return Some(false); + return Ok(Some(false)); } - for node in ancestors.siblings_before(comment) { - if !view.covers(node.start_byte()..boundary) { - return None; + for node in ancestors.siblings_before_with_budget(comment, budget)? { + budget.step()?; + if !view.covers_with_budget(node.start_byte()..boundary, budget)? { + return Ok(None); } boundary = node.start_byte(); if !preamble_or_plain(node) { - return Some(false); + return Ok(Some(false)); } } - if !view.covers(0..boundary) { - return None; + if !view.covers_with_budget(0..boundary, budget)? { + return Ok(None); } let mut docs = 1_usize; let mut boundary = comment.end_byte(); - for node in ancestors.siblings_after(comment) { - if !view.covers(boundary..node.end_byte()) { - return None; + for node in ancestors.siblings_after_with_budget(comment, budget)? { + budget.step()?; + if !view.covers_with_budget(boundary..node.end_byte(), budget)? { + return Ok(None); } boundary = node.end_byte(); if marker(&node) { docs += 1; } else if !PhpCode::is_comment(&node) && !php_file_preamble(&node) { - return Some( + return Ok(Some( docs == 2 // role-bypass: allow(DocTarget, FuncOpener, Container, Member) — the subset // of targets `createFileDocBlock` treats as the file's first element: a @@ -76,10 +91,31 @@ fn php_file_docblock<'a>( | Php::InterfaceDeclaration | Php::TraitDeclaration ), - ); + )); } } - view.covers(boundary..code.len()).then_some(true) + Ok(view + .covers_with_budget(boundary..code.len(), budget)? + .then_some(true)) +} + +pub(crate) fn source_forward_with_budget<'a, B: WorkBudget>( + node: &Node<'a>, + context: &crate::documentation::SourceContext<'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result, B::Error> { + if php_doc_in_signature(node, ancestors) { + return Ok(Some(false)); + } + Ok(php_file_docblock_with_budget( + node, + context.bytes(), + ancestors, + CandidateView::Source(context), + budget, + )? + .map(|file| !file)) } fn php_doc_in_signature<'a>(comment: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { @@ -115,16 +151,9 @@ impl Checker for PhpCode { context: &crate::documentation::SourceContext<'a>, ancestors: Ancestors<'a, '_>, ) -> Option { - if php_doc_in_signature(node, ancestors) { - return Some(false); - } - php_file_docblock( - node, - context.bytes(), - ancestors, - CandidateView::Source(context), - ) - .map(|file| !file) + infallible(source_forward_with_budget( + node, context, ancestors, &NoBudget, + )) } // phpDocumentor gives an element PHP-Parser's `getDocComment`: the diff --git a/big-code-analysis-ast/src/checker/ruby.rs b/big-code-analysis-ast/src/checker/ruby.rs index 07ed118d1..75cb62646 100644 --- a/big-code-analysis-ast/src/checker/ruby.rs +++ b/big-code-analysis-ast/src/checker/ruby.rs @@ -2,7 +2,8 @@ #![allow(clippy::wildcard_imports, clippy::enum_glob_use)] use super::*; -use crate::lang_helpers::ruby::{YardScope, ruby_source_yard_reads, ruby_yard_reads}; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::lang_helpers::ruby::YardScope; /// The statement a comment run directly above `node` documents: `node` /// itself, or the statement a wrapper stands for. A statement modifier @@ -25,22 +26,29 @@ use crate::lang_helpers::ruby::{YardScope, ruby_source_yard_reads, ruby_yard_rea /// was an `O(depth)` copy before #1805, which a documented statement at /// each nesting level made quadratic (`loc/ruby-nested-doc-constants`); /// it is one small allocation now. -fn ruby_documented_core<'a, 'c>( +fn ruby_documented_core<'a, 'c, B: WorkBudget>( node: &Node<'a>, ancestors: Ancestors<'a, 'c>, -) -> Option<(Node<'a>, Option>)> { + budget: &B, + mut visit: impl FnMut(Node<'a>), +) -> Result, Option>)>, B::Error> { let mut node = *node; let mut chain: Option> = None; loop { + budget.step()?; + visit(node); let inner = match node.kind_id().into() { // role-bypass: allow(Branch) — the modifier's body is the // documented item; doc attachment, not membership // The `?`s are defensive: the grammar requires a modifier's // `body`, and an empty body is no node at all rather than an // empty wrapper, so neither arm's `None` has a spelling. - Ruby::IfModifier | Ruby::UnlessModifier => node.child_by_field_name("body")?, - Ruby::BodyStatement | Ruby::BodyStatement2 | Ruby::BlockBody => node.child(0)?, - _ => return Some((node, chain)), + Ruby::IfModifier | Ruby::UnlessModifier => node.child_by_field_name("body"), + Ruby::BodyStatement | Ruby::BodyStatement2 | Ruby::BlockBody => node.child(0), + _ => return Ok(Some((node, chain))), + }; + let Some(inner) = inner else { + return Ok(None); }; match &mut chain { Some(chain) => chain.descend(&node), @@ -53,9 +61,27 @@ fn ruby_documented_core<'a, 'c>( /// The first statement of a `then` wrapper (`Then`, 243 — `Then2`, 55, is /// the keyword token, never a wrapper), or `None` for any other node. fn ruby_then_first_statement<'a>(node: &Node<'a>) -> Option> { - (node.kind_id() == Ruby::Then) - .then(|| node.children().find(Node::is_named)) - .flatten() + infallible(ruby_then_with_budget(node, &NoBudget)) +} + +pub(crate) fn start_row_with_budget( + node: &Node<'_>, + budget: &B, +) -> Result { + Ok(ruby_then_with_budget(node, budget)? + .unwrap_or(*node) + .start_row()) +} + +fn ruby_then_with_budget<'a, B: WorkBudget>( + node: &Node<'a>, + budget: &B, +) -> Result>, B::Error> { + if node.kind_id() == Ruby::Then { + crate::documentation::budget::child(node, Node::is_named, budget) + } else { + Ok(None) + } } fn ruby_doc_target<'a>( @@ -64,23 +90,137 @@ fn ruby_doc_target<'a>( ancestors: Ancestors<'a, '_>, source: bool, ) -> bool { - let (statement, chain) = match ruby_then_first_statement(node) { + infallible(ruby_doc_target_with_budget( + node, code, ancestors, source, &NoBudget, + )) +} + +#[allow(clippy::similar_names)] +pub(crate) fn ruby_doc_target_with_budget<'a, B: WorkBudget>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: bool, + budget: &B, +) -> Result { + let (target, namespace) = ruby_core_answer(node, code, ancestors, source, budget)?; + Ok(target + && crate::lang_helpers::ruby::yard_reads_with_budget( + if namespace { + YardScope::Namespace + } else { + YardScope::DefBody + }, + node, + ancestors, + source, + budget, + )?) +} + +#[allow(clippy::similar_names)] +fn ruby_core_answer<'a, B: WorkBudget>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: bool, + budget: &B, +) -> Result<(bool, bool), B::Error> { + use crate::node::MemoQuestion; + let target_memo = source + .then(|| ancestors.node_memo(MemoQuestion::DocCoreTarget)) + .flatten(); + let namespace_memo = source + .then(|| ancestors.node_memo(MemoQuestion::DocCoreNamespace)) + .flatten(); + if let Some(target) = target_memo.and_then(|memo| memo.get(node)) { + return Ok(( + target, + namespace_memo + .and_then(|memo| memo.get(node)) + .unwrap_or(false), + )); + } + let (statement, chain) = match ruby_then_with_budget(node, budget)? { Some(first) => (first, Some(ancestors.of_children(node))), None => (*node, None), }; let statement_chain = chain.as_ref().map_or(ancestors, ChildAncestors::get); - ruby_documented_core(&statement, statement_chain).is_some_and(|(core, core_chain)| { - let core_chain = core_chain - .as_ref() - .map_or(statement_chain, ChildAncestors::get); - let reads = if source { - ruby_source_yard_reads - } else { - ruby_yard_reads - }; + let mut wrappers = Vec::new(); + let Some((core, core_chain)) = + ruby_documented_core(&statement, statement_chain, budget, |node| { + if source { + wrappers.push(node); + } + })? + else { + return Ok((false, false)); + }; + let core_chain = core_chain + .as_ref() + .map_or(statement_chain, ChildAncestors::get); + let target = if crate::roles::ruby::call::lists_kind(core.kind_id()) { + crate::lang_helpers::ruby::ruby_documented_call_with_budget(&core, code, budget)? + } else { crate::roles::ruby::doc_target::owns(&core, code, core_chain) - && reads(YardScope::of(&core), node, ancestors) - }) + }; + let namespace = matches!(YardScope::of(&core), YardScope::Namespace); + if let Some(memo) = target_memo { + memo.set(node, target); + } + if let Some(memo) = namespace_memo { + memo.set(node, namespace); + } + for wrapper in wrappers { + budget.step()?; + if let Some(memo) = target_memo { + memo.set(&wrapper, target); + } + if let Some(memo) = namespace_memo { + memo.set(&wrapper, namespace); + } + } + Ok((target, namespace)) +} + +pub(crate) fn source_opener_with_budget<'a, B: WorkBudget>( + run: &crate::documentation::streaming::positional::RunContext<'_, 'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result, B::Error> { + let Some(first) = run.members.first() else { + return Ok(None); + }; + let mut opens = crate::lang_helpers::doc_text::ruby_directive_opener_with_budget( + crate::lang_helpers::doc_comment::node_bytes(first, run.code), + budget, + )? && crate::lang_helpers::ruby::yard_reads_with_budget( + YardScope::Namespace, + first, + ancestors, + false, + budget, + )?; + if !opens { + for member in run.members.iter().skip(1) { + budget.step()?; + if crate::lang_helpers::ruby::source_yard_directive_with_budget( + member, run.code, budget, + )? { + opens = true; + break; + } + } + } + Ok((opens + && crate::lang_helpers::ruby::yard_reads_with_budget( + YardScope::Namespace, + first, + ancestors, + true, + budget, + )?) + .then_some(crate::documentation::streaming::positional::OpenerReason::Explicit)) } impl Checker for RubyCode { @@ -102,17 +242,9 @@ impl Checker for RubyCode { Option, crate::documentation::UnresolvedReason, > { - Ok(run - .members - .first() - .filter(|first| { - (crate::roles::ruby::doc_run_opener::owns(first, run.code, ancestors) - || run.members.iter().skip(1).any(|member| { - crate::lang_helpers::ruby::source_yard_directive(member, run.code) - })) - && ruby_source_yard_reads(YardScope::Namespace, first, ancestors) - }) - .map(|_| crate::documentation::streaming::positional::OpenerReason::Explicit)) + Ok(infallible(source_opener_with_budget( + run, ancestors, &NoBudget, + ))) } // The `Comment` row of `roles/ruby.rs` (#1699); no `DocComment`. impl_comment_from_rows!(ruby); @@ -240,7 +372,12 @@ mod tests { None => (*node, None), }; let statement_chain = then_chain.as_ref().map_or(ancestors, ChildAncestors::get); - let Some((core, core_chain)) = ruby_documented_core(&statement, statement_chain) else { + let Some((core, core_chain)) = infallible(ruby_documented_core( + &statement, + statement_chain, + &NoBudget, + |_| {}, + )) else { return; }; let asked = core_chain diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index 46fc21445..f615d4c85 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -7,14 +7,17 @@ //! All items are unstable direct-AST plumbing; no root facade is introduced. pub(crate) mod budget; +pub(crate) mod byte_scan; mod canonical; pub(crate) mod collector; mod content; +mod forms; mod index; mod names; mod options; mod ordering; mod owners; +pub(crate) mod recognition; mod source; #[doc(hidden)] pub mod streaming; @@ -48,6 +51,16 @@ pub struct Observations { pub renders: usize, /// Bounded source-to-text copy chunks. pub copy_chunks: usize, + /// Name bytes hashed or compared during indexed finalization. + pub name_bytes: usize, + /// Distinct name candidates compared inside hash buckets. + pub name_candidates: usize, + /// Actual source-target requests, including binding callbacks. + pub target_queries: usize, + /// Source-target cache misses that execute classification. + pub target_computations: usize, + /// Byte visits in shared classifier scans. + pub classifier_bytes: usize, } /// Read qualification counters without resetting other consumers' observations. @@ -64,6 +77,11 @@ pub fn observations() -> Observations { field_requests: collector::field_requests::observed(), renders: text::renders::observed(), copy_chunks: text::copy_chunks::observed(), + name_bytes: names::name_bytes::observed(), + name_candidates: names::name_candidates::observed(), + target_queries: recognition::target_queries::observed(), + target_computations: recognition::target_computations::observed(), + classifier_bytes: byte_scan::bytes_read::observed(), } } diff --git a/big-code-analysis-ast/src/documentation/budget.rs b/big-code-analysis-ast/src/documentation/budget.rs index a0b86656c..8df873061 100644 --- a/big-code-analysis-ast/src/documentation/budget.rs +++ b/big-code-analysis-ast/src/documentation/budget.rs @@ -14,6 +14,56 @@ pub(crate) trait WorkBudget { fn checkpoint(&self) -> Result<(), Self::Error>; fn step(&self) -> Result<(), Self::Error>; fn bytes(&self, count: usize) -> Result<(), Self::Error>; + fn phase(&self) -> WorkPhase { + WorkPhase::Collection + } + fn set_phase(&self, _: WorkPhase) {} +} + +pub(crate) fn binary_search_end( + mut end: usize, + predicate: impl Fn(usize) -> bool, + budget: &B, +) -> Result { + let mut first = 0; + while first < end { + budget.step()?; + let middle = first + (end - first) / 2; + if predicate(middle) { + first = middle + 1; + } else { + end = middle; + } + } + Ok(first) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum WorkPhase { + #[default] + Collection, + Classification, + Ranges, + Batch, + Text, + Names, + Ordering, +} + +pub(crate) fn in_phase( + budget: &B, + phase: WorkPhase, + action: impl FnOnce() -> T, +) -> T { + struct Restore<'b, B: WorkBudget>(&'b B, WorkPhase); + impl Drop for Restore<'_, B> { + fn drop(&mut self) { + self.0.set_phase(self.1); + } + } + let _restore = Restore(budget, budget.phase()); + budget.set_phase(phase); + action() } pub(crate) struct NoBudget; @@ -41,6 +91,7 @@ impl WorkBudget for NoBudget { pub(crate) struct CollectionBudget { steps: Cell, bytes: Cell, + phase: Cell, } // These count actual checkpoints, not calls to a generic NoBudget wrapper. @@ -70,7 +121,7 @@ impl WorkBudget for CollectionBudget { fn checkpoint(&self) -> Result<(), SourceError> { polls::record(); #[cfg(test)] - cancel_at_checkpoint(); + cancel_at_checkpoint(self.phase.get()); self.steps.set(0); self.bytes.set(0); if crate::cancel::requested() { @@ -87,20 +138,44 @@ impl WorkBudget for CollectionBudget { fn bytes(&self, count: usize) -> Result<(), SourceError> { self.charge(&self.bytes, count, BYTE_INTERVAL) } + fn phase(&self) -> WorkPhase { + self.phase.get() + } + fn set_phase(&self, phase: WorkPhase) { + self.phase.set(phase); + } } #[cfg(test)] thread_local! { static CANCEL_AT: Cell> = const { Cell::new(None) }; + static CANCEL_PHASE: Cell> = const { Cell::new(None) }; } #[cfg(test)] -fn cancel_at_checkpoint() { +fn cancel_at_checkpoint(phase: WorkPhase) { CANCEL_AT.with(|at| { if at.get() == Some(polls::observed()) { crate::cancel::cancel_installed_for_test(); } }); + CANCEL_PHASE.with(|wanted| { + if wanted.get() == Some(phase) { + crate::cancel::cancel_installed_for_test(); + } + }); +} + +#[cfg(test)] +pub(super) fn cancel_in_phase(phase: WorkPhase, action: impl FnOnce() -> T) -> T { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + CANCEL_PHASE.with(|slot| slot.set(self.0)); + } + } + let _restore = Restore(CANCEL_PHASE.with(|slot| slot.replace(Some(phase)))); + crate::cancel::ParseCancel::new().run(action) } #[cfg(test)] @@ -123,6 +198,28 @@ pub(crate) fn infallible(result: Result) -> T { } } +pub(crate) fn reverse(items: &mut [T], budget: &B) -> Result<(), B::Error> { + for at in 0..items.len() / 2 { + budget.step()?; + items.swap(at, items.len() - at - 1); + } + Ok(()) +} + +pub(crate) fn child<'s, B: WorkBudget>( + node: &crate::Node<'s>, + predicate: impl Fn(&crate::Node<'s>) -> bool, + budget: &B, +) -> Result>, B::Error> { + for child in node.children() { + budget.step()?; + if predicate(&child) { + return Ok(Some(child)); + } + } + Ok(None) +} + impl From for SourceError { fn from(never: Infallible) -> Self { match never {} diff --git a/big-code-analysis-ast/src/documentation/byte_scan.rs b/big-code-analysis-ast/src/documentation/byte_scan.rs new file mode 100644 index 000000000..ce87fce0b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/byte_scan.rs @@ -0,0 +1,105 @@ +//! Fallible byte-slice scans used by recognition and text kernels. + +use super::budget::WorkBudget; + +crate::observation::counter!(bytes_read, cfg(any(test, feature = "test-support"))); + +pub(crate) fn position( + bytes: &[u8], + predicate: impl Fn(u8) -> bool, + budget: &B, +) -> Result, B::Error> { + for (at, &byte) in bytes.iter().enumerate() { + budget.bytes(1)?; + bytes_read::record(); + if predicate(byte) { + return Ok(Some(at)); + } + } + Ok(None) +} + +pub(crate) fn rposition( + bytes: &[u8], + predicate: impl Fn(u8) -> bool, + budget: &B, +) -> Result, B::Error> { + for (at, &byte) in bytes.iter().enumerate().rev() { + budget.bytes(1)?; + bytes_read::record(); + if predicate(byte) { + return Ok(Some(at)); + } + } + Ok(None) +} + +pub(crate) fn trim_start<'s, B: WorkBudget>( + bytes: &'s [u8], + budget: &B, +) -> Result<&'s [u8], B::Error> { + let first = position(bytes, |byte| !byte.is_ascii_whitespace(), budget)?.unwrap_or(bytes.len()); + Ok(&bytes[first..]) +} + +pub(crate) fn trim_end<'s, B: WorkBudget>( + bytes: &'s [u8], + budget: &B, +) -> Result<&'s [u8], B::Error> { + let end = rposition(bytes, |byte| !byte.is_ascii_whitespace(), budget)?.map_or(0, |at| at + 1); + Ok(&bytes[..end]) +} + +pub(crate) fn trim<'s, B: WorkBudget>(bytes: &'s [u8], budget: &B) -> Result<&'s [u8], B::Error> { + trim_end(trim_start(bytes, budget)?, budget) +} + +pub(crate) struct Lines<'s, 'b, B> { + remaining: Option<&'s [u8]>, + budget: &'b B, +} + +impl Clone for Lines<'_, '_, B> { + fn clone(&self) -> Self { + Self { + remaining: self.remaining, + budget: self.budget, + } + } +} + +pub(crate) fn lines<'s, 'b, B: WorkBudget>(bytes: &'s [u8], budget: &'b B) -> Lines<'s, 'b, B> { + Lines { + remaining: Some(bytes), + budget, + } +} + +impl<'s, B: WorkBudget> Iterator for Lines<'s, '_, B> { + type Item = Result<&'s [u8], B::Error>; + fn next(&mut self) -> Option { + let bytes = self.remaining.take()?; + Some(match position(bytes, |byte| byte == b'\n', self.budget) { + Ok(Some(at)) => { + self.remaining = Some(&bytes[at + 1..]); + Ok(&bytes[..at]) + } + Ok(None) => Ok(bytes), + Err(error) => Err(error), + }) + } +} + +pub(crate) fn contains_ci( + bytes: &[u8], + needle: &[u8], + budget: &B, +) -> Result { + for window in bytes.windows(needle.len()) { + budget.bytes(needle.len())?; + if window.eq_ignore_ascii_case(needle) { + return Ok(true); + } + } + Ok(false) +} diff --git a/big-code-analysis-ast/src/documentation/canonical.rs b/big-code-analysis-ast/src/documentation/canonical.rs index 6bf849c02..75fe163c9 100644 --- a/big-code-analysis-ast/src/documentation/canonical.rs +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -28,6 +28,7 @@ pub(super) struct CanonicalNode<'s> { pub(super) pending: Vec, pub(super) pending_parent: Option, pub(super) following: Option, + pub(super) owner_context: NodeId, } #[derive(Debug)] @@ -69,6 +70,7 @@ impl<'s> CanonicalNodes<'s> { pending: Vec::new(), pending_parent: None, following: None, + owner_context: id, }); id } diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 359e53ef8..ce2816f05 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -2,10 +2,14 @@ use super::budget::{CollectionBudget, WorkBudget}; use super::canonical::{CanonicalNodes, NodeId, Projection}; +use super::recognition::{NativeRules, SourceRules}; use super::streaming::{markers, positional}; use super::*; use crate::{Ancestors, Checker, FoldCache, Node, SiblingCache}; +mod assembly; +mod projections; + enum Visit { Enter(NodeId, usize), Exit(NodeId, usize), @@ -62,6 +66,7 @@ pub(crate) fn collect_typed<'s, T: Checker + crate::traits::LanguageInfo>( owner_nodes: Vec::new(), documents_ordered: Vec::new(), associations_ordered: Vec::new(), + source_cleaned: Vec::new(), }, drafts: Vec::new(), pending_attributes: Vec::new(), @@ -107,17 +112,29 @@ struct Builder<'s> { } trait OwnerCandidates: Checker { - fn owner_candidate<'s>(node: &Node<'s>, code: &[u8], ancestors: Ancestors<'s, '_>) -> bool; + fn owner_candidate<'s>( + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + budget: &CollectionBudget, + ) -> Result; } impl OwnerCandidates for T { - fn owner_candidate<'s>(node: &Node<'s>, code: &[u8], ancestors: Ancestors<'s, '_>) -> bool { + fn owner_candidate<'s>( + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + budget: &CollectionBudget, + ) -> Result { match T::lang() { crate::LANG::Typescript => { - crate::roles::typescript::doc_target::owns(node, code, ancestors) + crate::roles::typescript::doc_target_with_budget(node, code, ancestors, budget) } - crate::LANG::Tsx => crate::roles::tsx::doc_target::owns(node, code, ancestors), - _ => T::is_source_doc_target(node, code, ancestors), + crate::LANG::Tsx => { + crate::roles::tsx::doc_target_with_budget(node, code, ancestors, budget) + } + _ => NativeRules::::target(node, code, ancestors, budget), } } } @@ -167,55 +184,22 @@ impl<'s> Builder<'s> { let node = Node::from_tree_sitter(self.index.canonical.nodes[id.0].evidence.node()); bounds(node.as_tree_sitter(), self.index.source.bytes().len())?; - let ancestors = Ancestors::for_walk(&chain, &node, &folds, &siblings); - self.register::(id, &node, ancestors, budget)?; - self.recognize::(id, &node, ancestors, budget)?; - children.clear(); - fields.clear(); - cursor.reset(node.as_tree_sitter()); - if cursor.goto_first_child() { - loop { - budget.step()?; - let child = cursor.node(); - bounds(child, self.index.source.bytes().len())?; - children.push(Node::from_tree_sitter(child)); - fields.push(if fields_needed(self.index.profile, node.kind()) { - field_requests::record(); - cursor.field_name() - } else { - None - }); - if !cursor.goto_next_sibling() { - break; - } - } - } - child_batches::record(); - self.index - .canonical - .batch(id, &children, &self.index.source, budget)?; - let mut following = None; - for &child in self.index.canonical.children - [self.index.canonical.nodes[id.0].children.clone()] - .iter() - .rev() - { - budget.step()?; - let record = &mut self.index.canonical.nodes[child.0]; - record.following = following; - let child_node = Node::from_tree_sitter(record.evidence.node()); - if !T::is_comment(&child_node) && child_node.kind() != "attribute_item" { - following = Some(child); - } - } - for (&child, field) in self.index.canonical.children - [self.index.canonical.nodes[id.0].children.clone()] - .iter() - .zip(&fields) + if transparent_doc_context(node.kind()) + && let Some(parent) = self.index.canonical.nodes[id.0].parent { - budget.step()?; - self.index.canonical.nodes[child.0].field = *field; + self.index.canonical.nodes[id.0].owner_context = + self.index.canonical.nodes[parent.0].owner_context; } + let ancestors = Ancestors::for_walk(&chain, &node, &folds, &siblings); + super::budget::in_phase( + budget, + super::budget::WorkPhase::Classification, + || { + self.register::(id, &node, ancestors, budget)?; + self.recognize::(id, &node, ancestors, budget) + }, + )?; + self.record_children::(id, &mut cursor, &mut children, &mut fields, budget)?; siblings.record_with_budget(&node, depth, children.iter().copied(), budget)?; stack.push(Visit::Exit(id, depth)); for &child in self.index.canonical.children @@ -234,6 +218,58 @@ impl<'s> Builder<'s> { Ok(()) } + fn record_children( + &mut self, + id: NodeId, + cursor: &mut tree_sitter::TreeCursor<'s>, + children: &mut Vec>, + fields: &mut Vec>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let node = self.index.canonical.nodes[id.0].evidence.node(); + children.clear(); + fields.clear(); + cursor.reset(node); + if cursor.goto_first_child() { + loop { + budget.step()?; + let child = cursor.node(); + bounds(child, self.index.source.bytes().len())?; + children.push(Node::from_tree_sitter(child)); + fields.push(if fields_needed(self.index.profile, node.kind()) { + field_requests::record(); + cursor.field_name() + } else { + None + }); + if !cursor.goto_next_sibling() { + break; + } + } + } + child_batches::record(); + self.index + .canonical + .batch(id, children, &self.index.source, budget)?; + let mut following = None; + for (&child, field) in self.index.canonical.children + [self.index.canonical.nodes[id.0].children.clone()] + .iter() + .zip(fields) + .rev() + { + budget.step()?; + let record = &mut self.index.canonical.nodes[child.0]; + record.field = *field; + record.following = following; + let child_node = Node::from_tree_sitter(record.evidence.node()); + if !T::is_comment(&child_node) && child_node.kind() != "attribute_item" { + following = Some(child); + } + } + Ok(()) + } + fn register( &mut self, id: NodeId, @@ -246,6 +282,16 @@ impl<'s> Builder<'s> { } budget.step()?; target_classifications::record(); + if !self + .index + .source + .covers_with_budget(node.start_byte()..node.end_byte(), budget)? + { + if node.is_named() && !T::is_comment(node) { + self.index.canonical.nodes[id.0].projection = Projection::Pending; + } + return Ok(()); + } let wrapper_child = matches!( self.index.profile, Profile::Jsdoc | Profile::BcaTypescriptSource @@ -253,13 +299,14 @@ impl<'s> Builder<'s> { .parent(node) .is_some_and(|parent| is_wrapper(self.index.profile, parent.kind())); let qualifies = if wrapper_child { - T::owner_candidate(node, self.index.source.bytes(), ancestors) + T::owner_candidate(node, self.index.source.bytes(), ancestors, budget)? } else { - T::is_source_doc_target(node, self.index.source.bytes(), ancestors) + NativeRules::::target(node, self.index.source.bytes(), ancestors, budget)? }; if qualifies { if is_wrapper(self.index.profile, node.kind()) || needs_slot(self.index.profile, node.kind()) + || super::forms::owner_pending(self.index.profile, node, ancestors) || (self.index.profile == Profile::Doxygen && matches!( node.kind(), @@ -283,7 +330,7 @@ impl<'s> Builder<'s> { Ok(()) } - fn recognize( + fn recognize( &mut self, id: NodeId, node: &Node<'s>, @@ -299,8 +346,26 @@ impl<'s> Builder<'s> { if !T::is_comment(node) { return Ok(()); } + if let super::forms::CommentAssessment::Pending(reason) = super::forms::assess( + self.index.profile, + node, + ancestors, + &self.index.source, + budget, + )? { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Selection, + reason, + node: Some(self.index.canonical.nodes[id.0].evidence), + document: None, + }); + let parent = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); + let scope = self.index.canonical.nodes[parent.0].owner_context; + self.index.canonical.nodes[scope.0].pending.push(assessment); + } let mut marker_runs = Vec::new(); - markers::source_comment::( + markers::source_comment_with_budget::, _>( node, ancestors, &mut markers::SourceRequest { @@ -308,12 +373,13 @@ impl<'s> Builder<'s> { retain_unbound: self.index.options.retain_unbound, sink: &mut |run| marker_runs.push(run), }, + budget, )?; for run in marker_runs { self.marker_run(run, budget)?; } let mut positional_runs = Vec::new(); - positional::source_comment::( + positional::source_comment_with_budget::, _>( node, ancestors, &mut positional::SourceRequest { @@ -322,25 +388,11 @@ impl<'s> Builder<'s> { retain_directives: self.index.options.retain_directives, sink: &mut |run| positional_runs.push(run), }, + budget, )?; for run in positional_runs { self.positional_run(run, budget)?; } - if self.index.profile == Profile::Ldoc - && ancestors.parent(node).is_some_and(|parent| { - matches!(parent.kind(), "parameters" | "field" | "table_constructor") - }) - { - let assessment = self.index.assessments.len(); - self.index.assessments.push(Assessment { - axis: AssessmentAxis::Selection, - reason: "Native LDoc parameter/table comment awaits adapter context", - node: Some(self.index.canonical.nodes[id.0].evidence), - document: None, - }); - let scope = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); - self.index.canonical.nodes[scope.0].pending.push(assessment); - } Ok(()) } @@ -424,6 +476,17 @@ impl<'s> Builder<'s> { member.node }; self.local_target(&mut draft, local_node, member.placement, budget)?; + if self.index.profile == Profile::BcaPhpSource + && draft.role == DocumentRole::FilePackage + && let Some(target) = target + { + let kind = self.index.canonical.nodes[target.0].evidence.node().kind(); + if matches!(kind, "enum_declaration" | "expression_statement") { + draft.target = Some(target); + draft.role = DocumentRole::Primary; + draft.pending = kind == "expression_statement"; + } + } if self.index.profile == Profile::Doxygen { let raw = &self.index.source.bytes()[member.node.node().byte_range()]; if matches!(raw.get(..4), Some(b"///<" | b"//!<" | b"/**<" | b"/*!<")) { @@ -527,7 +590,9 @@ impl<'s> Builder<'s> { } if self.index.profile == Profile::Doxygen { let raw = &self.index.source.bytes()[node.node().byte_range()]; - if let Some((command, _)) = crate::lang_helpers::doxygen::structural_command(raw) { + if let Some((command, _)) = + crate::lang_helpers::doxygen::structural_command_with_budget(raw, budget)? + { if command == b"file" { draft.target = Some(NodeId(0)); draft.role = DocumentRole::FilePackage; @@ -572,9 +637,9 @@ impl<'s> Builder<'s> { Profile::Jsdoc | Profile::BcaTypescriptSource => { let raw = &self.index.source.bytes()[node.node().byte_range()]; let file = if self.index.profile == Profile::BcaTypescriptSource { - crate::lang_helpers::doc_text::tsdoc_module(raw) + crate::lang_helpers::doc_text::tsdoc_module_with_budget(raw, budget)? } else { - crate::lang_helpers::doc_text::jsdoc_file(raw) + crate::lang_helpers::doc_text::jsdoc_file_with_budget(raw, budget)? }; if file { draft.target = Some(NodeId(0)); @@ -607,7 +672,10 @@ impl<'s> Builder<'s> { continue; } if path.kind() == "identifier" - && self.index.source.covers(path.start_byte()..path.end_byte()) + && self + .index + .source + .covers_with_budget(path.start_byte()..path.end_byte(), budget)? { let bytes = &self.index.source.bytes()[path.start_byte()..path.end_byte()]; is_doc = matches!(bytes, b"doc" | b"cfg_attr"); @@ -641,7 +709,7 @@ impl<'s> Builder<'s> { && !self .index .source - .covers(node.end_byte()..target_node.start_byte()) + .covers_with_budget(node.end_byte()..target_node.start_byte(), budget)? { target = None; } @@ -682,142 +750,6 @@ impl<'s> Builder<'s> { Ok(()) } - fn finalize_projection( - &mut self, - id: NodeId, - budget: &CollectionBudget, - ) -> Result<(), CollectionError> { - budget.step()?; - let node = self.index.canonical.nodes[id.0].evidence.node(); - if self.index.profile == Profile::Doxygen - && matches!(node.kind(), "declaration" | "field_declaration") - && matches!( - self.index.canonical.nodes[id.0].projection, - Projection::Pending - ) - { - return self.c_slots(id, budget); - } - if !is_wrapper(self.index.profile, node.kind()) - || !matches!( - self.index.canonical.nodes[id.0].projection, - Projection::Pending - ) - { - return Ok(()); - } - let range = self.index.canonical.nodes[id.0].children.clone(); - let mut owners = Vec::new(); - for &child in &self.index.canonical.children[range] { - budget.step()?; - let record = &self.index.canonical.nodes[child.0]; - if matches!( - self.index.profile, - Profile::Jsdoc | Profile::BcaTypescriptSource - ) && node.kind() == "export_statement" - && !matches!(record.field, Some("declaration" | "value")) - { - continue; - } - if self.index.profile == Profile::Yard - && matches!(node.kind(), "if_modifier" | "unless_modifier") - && record.field != Some("body") - { - continue; - } - if let Projection::Ready(ids) = &self.index.canonical.nodes[child.0].projection { - for &owner in ids { - budget.step()?; - owners.push(owner); - } - break; - } - } - if !owners.is_empty() { - self.index.canonical.nodes[id.0].projection = Projection::Ready(owners); - self.index.canonical.nodes[id.0].pending.clear(); - } - Ok(()) - } - - fn c_slots(&mut self, id: NodeId, budget: &CollectionBudget) -> Result<(), CollectionError> { - let enclosing = OwnerId(self.index.facts.owners.len()); - self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); - let mut slots = Vec::new(); - let mut work = Vec::new(); - for &child in - &self.index.canonical.children[self.index.canonical.nodes[id.0].children.clone()] - { - budget.step()?; - if self.index.canonical.nodes[child.0].field == Some("declarator") { - work.push(child); - } - } - let mut ordinal = 0; - for mut child in work { - let mut function = false; - loop { - budget.step()?; - let record = &self.index.canonical.nodes[child.0]; - let node = record.evidence.node(); - if matches!(node.kind(), "identifier" | "field_identifier") { - if function { - slots.push(enclosing); - let declaration = self.index.canonical.nodes[id.0].evidence.node(); - let mut end = declaration.end_byte(); - if self.index.source.bytes().get(end.saturating_sub(1)) == Some(&b';') { - end -= 1; - } - self.names.insert( - &self.index.source.bytes()[node.byte_range()], - &self.index.source.bytes()[declaration.start_byte()..end], - enclosing, - budget, - )?; - } else { - let source = self - .index - .source - .pieces_with_budget(node.byte_range(), budget)?; - let slot = OwnerId(self.index.facts.owners.len()); - self.index.facts.owners.push(Owner::Slot(Slot { - enclosing, - role: SlotRole::Field, - ordinal, - source, - })); - self.index.associations_by_owner.push(Vec::new()); - self.index.assessments_by_owner.push(Vec::new()); - self.index.owner_nodes.push(id); - slots.push(slot); - ordinal += 1; - } - break; - } - function |= node.kind() == "function_declarator"; - let mut inner = None; - for &candidate in &self.index.canonical.children[record.children.clone()] { - budget.step()?; - if self.index.canonical.nodes[candidate.0].field == Some("declarator") { - inner = Some(candidate); - break; - } - } - let Some(next) = inner else { - break; - }; - child = next; - } - } - self.index.canonical.nodes[id.0].projection = if slots.is_empty() { - Projection::Pending - } else { - self.index.canonical.nodes[id.0].pending.clear(); - Projection::Ready(slots) - }; - Ok(()) - } - fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { self.combine_pending(budget)?; for draft in std::mem::take(&mut self.drafts) { @@ -918,190 +850,6 @@ impl<'s> Builder<'s> { } Ok(()) } - - fn combine_pending(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { - let mut by_target = std::collections::HashMap::new(); - for (index, draft) in self.drafts.iter().enumerate() { - budget.step()?; - if let Some(target) = draft.target { - by_target.insert(target, index); - } - } - for (node, fragment, target) in std::mem::take(&mut self.pending_attributes) { - budget.step()?; - if let Some(&index) = target.as_ref().and_then(|target| by_target.get(target)) { - self.drafts[index].fragments.push(fragment); - self.drafts[index].pending = true; - } else { - let scope = self.index.canonical.nodes[node.0] - .parent - .unwrap_or(NodeId(0)); - if let Some(target) = target { - by_target.insert(target, self.drafts.len()); - } - self.drafts.push(Draft { - fragments: vec![fragment], - target, - scope, - binding: target.map(|id| self.index.canonical.nodes[id.0].evidence), - role: if target.is_some_and(|id| { - id.0 == 0 - || self.index.canonical.nodes[id.0].evidence.node().kind() == "mod_item" - }) { - DocumentRole::FilePackage - } else { - DocumentRole::Primary - }, - unresolved: None, - pending: true, - gap: false, - }); - } - } - Ok(()) - } - - fn document( - &mut self, - mut draft: Draft<'s>, - budget: &CollectionBudget, - ) -> Result<(), CollectionError> { - let (content, attribute) = self.render_draft(&mut draft, budget)?; - let composition = if attribute { - Composition::AttributeSequence - } else if draft.fragments.len() == 1 { - Composition::Single - } else { - Composition::CommentRun - }; - let document = DocumentId(self.index.facts.documents.len()); - self.index.facts.documents.push(Document { - fragments: draft.fragments, - composition, - role: draft.role, - content, - }); - let mut owners = Vec::new(); - let mut pending = draft.pending; - let mut named_resolution = None; - if self.index.profile == Profile::Doxygen && draft.target.is_none() { - let fragment = - &self.index.facts.fragments[self.index.facts.documents[document.0].fragments[0].0]; - if let Some(node) = fragment.node { - let raw = &self.index.source.bytes()[node.node().byte_range()]; - if let Some((b"fn", name)) = crate::lang_helpers::doxygen::structural_command(raw) { - let (found, reason) = self.names.resolve(name, budget)?; - owners = found; - named_resolution = - Some(reason.map_or(Resolution::Resolved, Resolution::Unresolved)); - pending = false; - } - } - } - if let Some(target) = draft.target { - match &self.index.canonical.nodes[target.0].projection { - Projection::Ready(ids) => { - for &id in ids { - budget.step()?; - owners.push(id); - } - } - Projection::Pending | Projection::Unsupported => pending = true, - } - } - if pending { - let assessment = self.index.assessments.len(); - self.index.assessments.push(Assessment { - axis: if attribute { - AssessmentAxis::Composition - } else { - AssessmentAxis::Owner - }, - reason: if attribute { - "Rust doc/cfg_attr carrier awaits adapter composition" - } else { - "Selected local or wrapper form awaits owner projection" - }, - node: draft.binding, - document: Some(document), - }); - for owner in &owners { - budget.step()?; - self.index.assessments_by_owner[owner.0].push(assessment); - } - if owners.is_empty() { - self.index.canonical.nodes[draft.target.unwrap_or(draft.scope).0] - .pending - .push(assessment); - } - } - if !owners.is_empty() || draft.unresolved.is_some() || named_resolution.is_some() { - let association = self.index.facts.associations.len(); - for owner in &owners { - budget.step()?; - self.index.associations_by_owner[owner.0].push(association); - } - self.index.facts.associations.push(Association { - document, - owners, - resolution: named_resolution.unwrap_or_else(|| { - draft - .unresolved - .map_or(Resolution::Resolved, Resolution::Unresolved) - }), - convention: Convention(self.index.profile.name()), - binding: draft.binding, - lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence, - publication: Publication::Unknown, - }); - } - Ok(()) - } - - fn render_draft( - &self, - draft: &mut Draft<'s>, - budget: &CollectionBudget, - ) -> Result<(Content<'s>, bool), CollectionError> { - let mut keys = Vec::new(); - for id in &draft.fragments { - budget.step()?; - let start = self.index.facts.fragments[id.0].source.pieces()[0] - .range() - .start; - keys.push((start, id.0)); - } - draft.fragments.clear(); - for (_, id) in super::ordering::ordered(keys, budget)? { - budget.step()?; - draft.fragments.push(FragmentId(id)); - } - let mut fragments = Vec::new(); - let mut attribute = false; - for id in &draft.fragments { - budget.step()?; - let fragment = &self.index.facts.fragments[id.0]; - attribute |= fragment.form == FragmentForm::Attribute; - fragments.push(fragment); - } - let content = if attribute { - Content::PendingAdapter - } else if draft.gap { - Content::Unavailable(UnavailableReason::ExcludedGap) - } else { - match super::text::comments::render( - self.index.profile, - &self.index.source, - &fragments, - budget, - ) { - Ok(content) => content, - Err(super::text::TextError::Source(error)) => return Err(error.into()), - Err(super::text::TextError::Unavailable(reason)) => Content::Unavailable(reason), - } - }; - Ok((content, attribute)) - } } fn is_wrapper(profile: Profile, kind: &str) -> bool { @@ -1136,13 +884,41 @@ fn needs_slot(profile: Profile, kind: &str) -> bool { fn fields_needed(profile: Profile, kind: &str) -> bool { (profile == Profile::Doxygen - && (matches!(kind, "declaration" | "field_declaration") || kind.ends_with("declarator"))) + && (matches!( + kind, + "declaration" | "field_declaration" | "function_definition" + ) || kind.ends_with("declarator"))) || (matches!(profile, Profile::Jsdoc | Profile::BcaTypescriptSource) && kind == "export_statement") || (profile == Profile::Yard && matches!(kind, "if_modifier" | "unless_modifier")) } +fn transparent_doc_context(kind: &str) -> bool { + matches!( + kind, + "parameters" + | "formal_parameters" + | "function_value_parameters" + | "class_parameters" + | "class_parameter" + | "parameter" + | "required_parameter" + | "optional_parameter" + | "simple_parameter" + | "property_promotion_parameter" + | "modifiers" + ) +} + crate::observation::counter!(field_requests, cfg(any(test, feature = "test-support"))); +#[cfg(test)] +mod assessment_tests; +#[cfg(test)] +mod cancellation_tests; +#[cfg(test)] +mod cost_tests; +#[cfg(test)] +mod projection_tests; #[cfg(test)] mod tests; diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs new file mode 100644 index 000000000..1ac7450d1 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -0,0 +1,248 @@ +//! Draft composition and once-per-document text materialization. + +use super::*; + +impl<'s> Builder<'s> { + pub(super) fn combine_pending( + &mut self, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let mut by_target = std::collections::HashMap::new(); + for (index, draft) in self.drafts.iter().enumerate() { + budget.step()?; + if let Some(target) = draft.target && matches!(draft.role, DocumentRole::Primary | DocumentRole::FilePackage) { + by_target.insert(target, index); + } + } + for (node, fragment, target) in std::mem::take(&mut self.pending_attributes) { + budget.step()?; + if let Some(&index) = target.as_ref().and_then(|target| by_target.get(target)) { + self.drafts[index].fragments.push(fragment); + self.drafts[index].pending = true; + } else { + let scope = self.index.canonical.nodes[node.0] + .parent + .unwrap_or(NodeId(0)); + if let Some(target) = target { + by_target.insert(target, self.drafts.len()); + } + self.drafts.push(Draft { + fragments: vec![fragment], + target, + scope, + binding: target.map(|id| self.index.canonical.nodes[id.0].evidence), + role: if target.is_some_and(|id| { + id.0 == 0 + || self.index.canonical.nodes[id.0].evidence.node().kind() == "mod_item" + }) { + DocumentRole::FilePackage + } else { + DocumentRole::Primary + }, + unresolved: None, + pending: true, + gap: false, + }); + } + } + Ok(()) + } + + pub(super) fn document( + &mut self, + mut draft: Draft<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let (content, attribute) = self.render_draft(&mut draft, budget)?; + let prelex = self.index.profile == Profile::Javadoc + && matches!( + content, + Content::Unavailable(UnavailableReason::UnsupportedDecoding) + ); + let spelling = if prelex { + self.render_spelling(&draft, budget)? + } else { + None + }; + self.index.source_cleaned.push(spelling); + if prelex { + draft.unresolved = Some(UnresolvedReason::GrammarBoundary); + } + let composition = if attribute { + Composition::AttributeSequence + } else if draft.fragments.len() == 1 { + Composition::Single + } else { + Composition::CommentRun + }; + let document = DocumentId(self.index.facts.documents.len()); + self.index.facts.documents.push(Document { + fragments: std::mem::take(&mut draft.fragments), + composition, + role: draft.role, + content, + }); + let mut owners = Vec::new(); + let mut pending = draft.pending; + let mut named_resolution = None; + if self.index.profile == Profile::Doxygen && draft.target.is_none() { + let fragment = + &self.index.facts.fragments[self.index.facts.documents[document.0].fragments[0].0]; + if let Some(node) = fragment.node { + let raw = &self.index.source.bytes()[node.node().byte_range()]; + if let Some((b"fn", name)) = + crate::lang_helpers::doxygen::structural_command_with_budget(raw, budget)? + { + let (found, reason) = self.names.resolve(name, budget)?; + owners = found; + named_resolution = + Some(reason.map_or(Resolution::Resolved, Resolution::Unresolved)); + pending = false; + } + } + } + if let Some(target) = draft.target { + match &self.index.canonical.nodes[target.0].projection { + Projection::Ready(ids) => { + for &id in ids { + budget.step()?; + owners.push(id); + } + } + Projection::Pending | Projection::Unsupported => pending = true, + } + } + if pending { + self.pending_document(&draft, document, &owners, attribute, budget)?; + } + if !owners.is_empty() || draft.unresolved.is_some() || named_resolution.is_some() { + let association = self.index.facts.associations.len(); + for owner in &owners { + budget.step()?; + self.index.associations_by_owner[owner.0].push(association); + } + self.index.facts.associations.push(Association { + document, + owners, + resolution: named_resolution.unwrap_or_else(|| { + draft + .unresolved + .map_or(Resolution::Resolved, Resolution::Unresolved) + }), + convention: Convention(self.index.profile.name()), + binding: draft.binding, + lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence, + publication: Publication::Unknown, + }); + } + Ok(()) + } + + fn pending_document( + &mut self, + draft: &Draft<'s>, + document: DocumentId, + owners: &[OwnerId], + attribute: bool, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: if attribute { + AssessmentAxis::Composition + } else { + AssessmentAxis::Owner + }, + reason: if attribute { + "Rust doc/cfg_attr carrier awaits adapter composition" + } else { + "Selected local or wrapper form awaits owner projection" + }, + node: draft.binding, + document: Some(document), + }); + for owner in owners { + budget.step()?; + self.index.assessments_by_owner[owner.0].push(assessment); + } + if owners.is_empty() { + self.index.canonical.nodes[draft.target.unwrap_or(draft.scope).0] + .pending + .push(assessment); + } + Ok(()) + } + + fn render_draft( + &self, + draft: &mut Draft<'s>, + budget: &CollectionBudget, + ) -> Result<(Content<'s>, bool), CollectionError> { + let mut keys = Vec::new(); + for id in &draft.fragments { + budget.step()?; + keys.push(( + self.index.facts.fragments[id.0].source.pieces()[0] + .range() + .start, + id.0, + )); + } + draft.fragments.clear(); + for (_, id) in crate::documentation::ordering::ordered(keys, budget)? { + budget.step()?; + draft.fragments.push(FragmentId(id)); + } + let mut fragments = Vec::new(); + let mut attribute = false; + for id in &draft.fragments { + budget.step()?; + let fragment = &self.index.facts.fragments[id.0]; + attribute |= fragment.form == FragmentForm::Attribute; + fragments.push(fragment); + } + let content = if attribute { + Content::PendingAdapter + } else if draft.gap { + Content::Unavailable(UnavailableReason::ExcludedGap) + } else { + match crate::documentation::text::comments::render( + self.index.profile, + &self.index.source, + &fragments, + budget, + ) { + Ok(content) => content, + Err(crate::documentation::text::TextError::Source(error)) => { + return Err(error.into()); + } + Err(crate::documentation::text::TextError::Unavailable(reason)) => { + Content::Unavailable(reason) + } + } + }; + Ok((content, attribute)) + } + + fn render_spelling( + &self, + draft: &Draft<'s>, + budget: &CollectionBudget, + ) -> Result>, CollectionError> { + let mut fragments = Vec::new(); + for id in &draft.fragments { + budget.step()?; + fragments.push(&self.index.facts.fragments[id.0]); + } + match crate::documentation::text::comments::render_source_cleaned( + self.index.profile, + &self.index.source, + &fragments, + budget, + ) { + Ok(content) => Ok(Some(content)), + Err(crate::documentation::text::TextError::Source(error)) => Err(error.into()), + Err(crate::documentation::text::TextError::Unavailable(_)) => Ok(None), + } + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs new file mode 100644 index 000000000..4d5304ec3 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs @@ -0,0 +1,353 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_local_pending_owner_keeps_complete_text_and_known_leading_association() { + for (source, expected_docs, local_start) in [ + ("fun f() /**audit*/ {}", 1, 8), + ("/**first*/\nfun f() /**audit*/ {}", 2, 19), + ("class C { fun f() /**audit*/ {} }", 1, 18), + ] { + let parser = + AnyParser::parse(LANG::Kotlin, source.as_bytes().to_vec(), None, None).unwrap(); + for retain_unbound in [false, true] { + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Kotlin, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + assert_eq!(index.documents().len(), expected_docs); + let local = index.documents().last().unwrap(); + let fragment = index.facts().document_fragment(local, 0).unwrap(); + assert_eq!( + fragment.get().source().pieces()[0].range(), + local_start..local_start + 10 + ); + let text = index.complete_text(local).unwrap().unwrap(); + assert_eq!(text.text(), "audit"); + let origin = text.origins(0..5).unwrap().next().unwrap(); + let OriginView::Copied(piece) = origin.origin else { + panic!("copied KDoc") + }; + assert_eq!(piece.range(), local_start + 3..local_start + 8); + assert_eq!(index.associations().len(), expected_docs - 1); + let function = parser + .root_node() + .preorder() + .find(|node| node.kind() == "function_declaration") + .unwrap(); + let query = index.node_associations(function.as_tree_sitter()).unwrap(); + assert_eq!(query.associations().len(), expected_docs - 1); + assert!( + query + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Owner + && index.assessed_document(assessment).unwrap() == Some(local)) + ); + } + } + } +} + +#[cfg(feature = "go")] +#[test] +fn pending_go_field_query_exposes_assessment_instead_of_unusable_error() { + let parser = AnyParser::parse( + LANG::Go, + b"package p\ntype S struct {\n// both\nX, Y int\n}".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let field = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap(); + let query = index.node_associations(field.as_tree_sitter()).unwrap(); + assert!(query.projection_pending()); + assert_eq!(query.associations().len(), 0); + assert!( + query + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Owner) + ); + assert_eq!( + index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap() + .text(), + "both" + ); +} + +#[cfg(feature = "php")] +#[test] +fn php_default_precedence_preserves_original_candidate_sequence() { + for (source, texts, files) in [ + ("(source: &[u8]) { + use crate::Search; + let parser = AnyParser::parse(T::lang(), source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut selected = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if T::is_comment(node) { + streaming::markers::source_comment::( + node, + ancestors, + &mut streaming::markers::SourceRequest { + context: &context, + retain_unbound: true, + sink: &mut |run| { + for member in run.members { + assert!(!matches!( + member.placement, + streaming::markers::MarkerPlacement::Local + )); + selected += usize::from( + member.selection == streaming::markers::MarkerSelection::Selected, + ); + } + }, + }, + ) + .unwrap(); + } + }); + assert_eq!(selected, 1); +} + +#[cfg(feature = "java")] +#[test] +fn java_current_hooks_never_emit_local_placement() { + no_local::(b"/**audit*/\nclass C { void f() { /** note */ } }"); +} +#[cfg(feature = "groovy")] +#[test] +fn groovy_current_hooks_never_emit_local_placement() { + no_local::(b"/**audit*/\nclass C { void f() { /** note */ } }"); +} +#[cfg(feature = "csharp")] +#[test] +fn csharp_current_hooks_never_emit_local_placement() { + no_local::(b"///audit\nclass C { void F() { /** note */ } }"); +} + +#[cfg(feature = "rust")] +#[test] +fn retained_parse_abort_is_rejected_after_flag_scope_and_next_parse_succeeds() { + let flag = crate::cancel::ParseCancel::new(); + flag.cancel(); + let source = "fn f() {}\n".repeat(10_000).into_bytes(); + let parser = flag.run(|| AnyParser::parse(LANG::Rust, source, None, None).unwrap()); + assert_eq!( + parser.parse_completion(), + crate::parser::ParseCompletion::Cancelled + ); + assert!(matches!( + parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ), + Err(CollectionError::Cancelled) + )); + let next = AnyParser::parse(LANG::Rust, b"///audit\nfn f() {}".to_vec(), None, None).unwrap(); + assert_eq!( + next.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + .documents() + .len(), + 1 + ); +} + +#[cfg(feature = "rust")] +#[test] +fn nested_collection_cancellation_restores_outer_flag_after_unwind() { + let parser = AnyParser::parse(LANG::Rust, b"///audit\nfn f() {}".to_vec(), None, None).unwrap(); + let outer = crate::cancel::ParseCancel::new(); + let inner = crate::cancel::ParseCancel::new(); + inner.cancel(); + outer.run(|| { + inner.run(|| { + assert!(matches!( + parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ), + Err(CollectionError::Cancelled) + )); + }); + assert_eq!( + parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + .documents() + .len(), + 1 + ); + let stopped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + inner.run(|| panic!("unwind cancellation scope")) + })); + assert!(stopped.is_err()); + assert_eq!( + parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + .documents() + .len(), + 1 + ); + }); +} diff --git a/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs b/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs new file mode 100644 index 000000000..e7cc817f2 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs @@ -0,0 +1,222 @@ +use crate::documentation::budget::{WorkPhase, cancel_in_phase}; +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(any( + feature = "lua", + feature = "javascript", + feature = "ruby", + feature = "cpp" +))] +fn classification_abort(language: LANG, source: Vec) { + let parser = AnyParser::parse(language, source, None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations().renders; + let result = cancel_in_phase(WorkPhase::Classification, || { + parser.documentation(&context, &options) + }); + assert!(matches!(result, Err(CollectionError::Cancelled))); + assert_eq!( + observations().renders - before, + 0, + "abort must happen inside recognition before rendering" + ); + let next = parser.documentation(&context, &options).unwrap(); + assert_eq!(next.documents().len(), 1); + assert!( + next.complete_text(next.documents().next().unwrap()) + .unwrap() + .unwrap() + .text() + .len() + > 20_000 + ); +} + +#[cfg(feature = "lua")] +#[test] +fn lua_single_line_cancels_inside_content_classifier() { + classification_abort( + LANG::Lua, + format!("module(\"m\")\n---{}\nfunction f() end", "a".repeat(40_000)).into_bytes(), + ); +} + +#[cfg(feature = "javascript")] +#[test] +fn jsdoc_single_line_cancels_inside_virtual_classifier() { + classification_abort( + LANG::Javascript, + format!("/**{}*/\nfunction f() {{}}", "a".repeat(40_000)).into_bytes(), + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_single_line_cancels_inside_magic_classifier() { + classification_abort( + LANG::Ruby, + format!("# {}\ndef f\nend", "a".repeat(40_000)).into_bytes(), + ); +} + +#[cfg(feature = "cpp")] +#[test] +fn doxygen_single_line_cancels_inside_structural_classifier() { + classification_abort( + LANG::Cpp, + format!("/**{}*/\nvoid f() {{}}", "a".repeat(40_000)).into_bytes(), + ); +} + +#[cfg(feature = "rust")] +#[test] +fn legacy_recognition_never_polls_collector_budget() { + use crate::{Checker, Search}; + let source = format!("///{}\nfn f() {{}}", "a".repeat(40_000)); + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let mut markers = 0; + parser.root_node().act_on_node(&mut |node, ancestors| { + if crate::RustCode::is_comment(node) { + streaming::marker_comment::(node, parser.code(), ancestors, |_| { + markers += 1; + }); + } + }); + assert_eq!(markers, 2); + let after = observations(); + assert_eq!(after.polls - before.polls, 0); + assert_eq!(after.renders - before.renders, 0); + assert_eq!(after.visits - before.visits, 0); +} + +#[cfg(feature = "rust")] +#[test] +fn cancellation_reaches_wide_batch_copy_text_and_ordering() { + let source = format!( + "///{}\nfn f() {{}}\n{}", + "a".repeat(40_000), + "fn g() {}\n".repeat(1500) + ); + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + for phase in [WorkPhase::Batch, WorkPhase::Text, WorkPhase::Ordering] { + let result = cancel_in_phase(phase, || { + parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + }); + assert!( + matches!(result, Err(CollectionError::Cancelled)), + "{phase:?}" + ); + } + assert_eq!( + parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + .documents() + .len(), + 1 + ); +} + +#[cfg(feature = "cpp")] +#[test] +fn giant_static_name_cancels_during_index_key_processing() { + let source = format!("/** @fn missing */\nvoid {}();", "a".repeat(40_000)); + let parser = AnyParser::parse(LANG::Cpp, source.into_bytes(), None, None).unwrap(); + let result = cancel_in_phase(WorkPhase::Names, || { + parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + }); + assert!(matches!(result, Err(CollectionError::Cancelled))); + assert_eq!( + parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + .documents() + .len(), + 1 + ); +} + +#[cfg(feature = "rust")] +#[test] +fn many_included_ranges_cancel_inside_normalization() { + let bytes = b" ".repeat(5000); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + let ranges: Vec<_> = (0..2500) + .map(|at| tree_sitter::Range { + start_byte: at * 2, + end_byte: at * 2 + 1, + start_point: tree_sitter::Point::new(0, at * 2), + end_point: tree_sitter::Point::new(0, at * 2 + 1), + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(&bytes, None).unwrap(); + let result = cancel_in_phase(WorkPhase::Ranges, || { + collect( + LANG::Rust, + &tree, + &bytes, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + }); + assert!(matches!(result, Err(CollectionError::Cancelled))); + assert_eq!( + collect( + LANG::Rust, + &tree, + &bytes, + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + .documents() + .len(), + 0 + ); +} + +#[cfg(feature = "rust")] +#[test] +fn range_intersection_cancels_after_prepared_context_exists() { + use crate::documentation::budget::CollectionBudget; + let bytes = b" ".repeat(5000); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + let ranges: Vec<_> = (0..2500) + .map(|at| tree_sitter::Range { + start_byte: at * 2, + end_byte: at * 2 + 1, + start_point: tree_sitter::Point::new(0, at * 2), + end_point: tree_sitter::Point::new(0, at * 2 + 1), + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(&bytes, None).unwrap(); + let context = SourceContext::new(&tree, &bytes); + let result = cancel_in_phase(WorkPhase::Ranges, || { + context.pieces_with_budget(0..bytes.len(), &CollectionBudget::default()) + }); + assert!(matches!(result, Err(SourceError::Cancelled))); + assert_eq!(context.pieces(0..bytes.len()).unwrap().pieces().len(), 2500); +} diff --git a/big-code-analysis-ast/src/documentation/collector/cost_tests.rs b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs new file mode 100644 index 000000000..0b33b183b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs @@ -0,0 +1,86 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(feature = "rust")] +#[test] +fn deep_and_wide_source_walks_visit_every_node_once() { + for size in [40, 80, 160] { + for source in [ + format!( + "{}///audit\nfn f() {{}}{}", + "mod m {".repeat(size), + "}".repeat(size) + ), + "///audit\nfn f() {}\n".repeat(size), + ] { + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + let nodes = parser.root_node().preorder().count(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + assert_eq!(after.visits - before.visits, nodes); + assert_eq!(after.child_batches - before.child_batches, nodes); + assert_eq!( + after.target_classifications - before.target_classifications, + nodes - 1 + ); + assert_eq!( + after.target_computations - before.target_computations, + nodes - 1 + ); + assert_eq!(after.renders - before.renders, index.documents().len()); + } + } +} + +#[cfg(feature = "c")] +#[test] +fn owner_fanout_does_not_multiply_rendered_text_or_mapping_storage() { + for width in [2, 40, 80] { + let names = (0..width) + .map(|at| format!("v{at}")) + .collect::>() + .join(","); + let source = format!("/**{}*/\nint {names};", "audit".repeat(400)); + let parser = AnyParser::parse(LANG::C, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + let text = index.complete_text(document).unwrap().unwrap(); + assert_eq!(text.text().len(), 2000); + assert_eq!(text.mappings().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().owner_count(), width); + assert_eq!(observations().renders - before.renders, 1); + assert_eq!(observations().copy_chunks - before.copy_chunks, 1); + } +} + +#[cfg(feature = "rust")] +#[test] +fn pending_scope_relations_are_shared_instead_of_copied_per_owner() { + let source = format!("#![doc(hidden)]\n{}", "fn f() {}\n".repeat(300)); + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.assessments().len(), 3); + let node = parser.root_node().children().last().unwrap(); + let query = index.node_associations(node.as_tree_sitter()).unwrap(); + assert_eq!(query.associations().count(), 0); + assert_eq!(query.assessments().count(), 2); +} diff --git a/big-code-analysis-ast/src/documentation/collector/projection_tests.rs b/big-code-analysis-ast/src/documentation/collector/projection_tests.rs new file mode 100644 index 000000000..d7704a084 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/projection_tests.rs @@ -0,0 +1,181 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn splices(language: LANG) { + for (source, expected, copied) in [ + ("/**a\\\nb*/\nvoid f() {}", "ab", vec![3..4, 6..7]), + ("/**a\\\r\nb*/\nvoid f() {}", "ab", vec![3..4, 7..8]), + ("///a\\\nb\nvoid f() {}", "ab", vec![3..4, 6..7]), + ("///a\\\\\nb\nvoid f() {}", "a\\b", vec![3..5, 7..8]), + ("///a\\\n///b\nvoid f() {}", "a///b", vec![3..4, 6..10]), + ] { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1, "{language:?}: {source}"); + let text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + assert_eq!(text.text(), expected, "{language:?}: {source}"); + let origins: Vec<_> = text + .origins(0..text.text().len()) + .unwrap() + .map(|portion| { + let OriginView::Copied(piece) = portion.origin else { + panic!("copied splice piece") + }; + piece.range() + }) + .collect(); + assert_eq!(origins, copied); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_phase_two_line_and_block_maps() { + splices(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_phase_two_line_and_block_maps() { + splices(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_phase_two_line_and_block_maps() { + splices(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_phase_two_line_and_block_maps() { + splices(LANG::Objc); +} + +#[cfg(any(feature = "javascript", feature = "mozjs", feature = "typescript"))] +fn structural_file(language: LANG, source: &str, expected: &str) { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().role(), DocumentRole::FilePackage); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + expected + ); + let association = index.associations().next().unwrap(); + assert!(matches!( + index + .facts() + .associated_owner(association, 0) + .unwrap() + .get(), + Owner::File(_) + )); +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_file_tags_override_following_declaration() { + structural_file( + LANG::Javascript, + "/**@file audit*/\nfunction f() {}", + "@file audit", + ); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_file_tags_override_following_declaration() { + structural_file( + LANG::Mozjs, + "/**@file audit*/\nfunction f() {}", + "@file audit", + ); +} +#[cfg(feature = "typescript")] +#[test] +fn typescript_file_tags_override_following_declaration() { + structural_file( + LANG::Typescript, + "/** @packageDocumentation */\nexport const x = 1;", + "@packageDocumentation", + ); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_file_tags_override_following_declaration() { + structural_file( + LANG::Tsx, + "/** @packageDocumentation */\nexport const x = 1;", + "@packageDocumentation", + ); +} + +#[cfg(feature = "lua")] +#[test] +fn lua_block_wrapper_projects_following_function() { + let parser = AnyParser::parse( + LANG::Lua, + b"module(\"m\")\ndo\n---audit\nfunction f() end\nend".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("function owner") + }; + assert_eq!(node.node().kind(), "function_declaration"); +} + +#[cfg(feature = "cpp")] +#[test] +fn doxygen_file_gathering_is_one_document_and_page_remains_pending() { + for (source, file) in [ + ("/**license*/\n/**@file*/", true), + ("/**@page p Audit*/\nvoid f();", false), + ] { + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), usize::from(file)); + if file { + let doc = index.documents().next().unwrap(); + assert_eq!(doc.get().fragment_count(), 2); + assert_eq!( + index.complete_text(doc).unwrap().unwrap().text(), + "license\n@file" + ); + } else { + assert!( + index + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Owner) + ); + } + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/projections.rs b/big-code-analysis-ast/src/documentation/collector/projections.rs new file mode 100644 index 000000000..0f5f9c919 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/projections.rs @@ -0,0 +1,209 @@ +//! Semantic wrapper and declarator projections, finalized once on exit. + +use super::*; + +impl Builder<'_> { + pub(super) fn finalize_projection( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + budget.step()?; + let node = self.index.canonical.nodes[id.0].evidence.node(); + if self.index.profile == Profile::Doxygen && node.kind() == "function_definition" { + self.index_function_definition(id, budget)?; + } + if self.index.profile == Profile::Doxygen + && matches!(node.kind(), "declaration" | "field_declaration") + && matches!( + self.index.canonical.nodes[id.0].projection, + Projection::Pending + ) + { + return self.c_slots(id, budget); + } + if !is_wrapper(self.index.profile, node.kind()) + || !matches!( + self.index.canonical.nodes[id.0].projection, + Projection::Pending + ) + { + return Ok(()); + } + let range = self.index.canonical.nodes[id.0].children.clone(); + let mut owners = Vec::new(); + for &child in &self.index.canonical.children[range] { + budget.step()?; + let record = &self.index.canonical.nodes[child.0]; + if matches!( + self.index.profile, + Profile::Jsdoc | Profile::BcaTypescriptSource + ) && node.kind() == "export_statement" + && !matches!(record.field, Some("declaration" | "value")) + { + continue; + } + if self.index.profile == Profile::Yard + && matches!(node.kind(), "if_modifier" | "unless_modifier") + && record.field != Some("body") + { + continue; + } + if let Projection::Ready(ids) = &record.projection { + for &owner in ids { + budget.step()?; + owners.push(owner); + } + break; + } + } + if !owners.is_empty() { + self.index.canonical.nodes[id.0].projection = Projection::Ready(owners); + } + Ok(()) + } + + fn declarator_child( + &self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + for &child in + &self.index.canonical.children[self.index.canonical.nodes[id.0].children.clone()] + { + budget.step()?; + if self.index.canonical.nodes[child.0].field == Some("declarator") { + return Ok(Some(child)); + } + } + Ok(None) + } + + fn declared_name( + &self, + mut current: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let mut function = false; + loop { + budget.step()?; + let node = self.index.canonical.nodes[current.0].evidence.node(); + if matches!(node.kind(), "identifier" | "field_identifier") { + return Ok(Some((current, function))); + } + function |= node.kind() == "function_declarator"; + let Some(child) = self.declarator_child(current, budget)? else { + return Ok(None); + }; + current = child; + } + } + + fn c_slots(&mut self, id: NodeId, budget: &CollectionBudget) -> Result<(), CollectionError> { + let enclosing = OwnerId(self.index.facts.owners.len()); + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + let mut slots = Vec::new(); + let mut work = Vec::new(); + for &child in + &self.index.canonical.children[self.index.canonical.nodes[id.0].children.clone()] + { + budget.step()?; + if self.index.canonical.nodes[child.0].field == Some("declarator") { + work.push(child); + } + } + if work.len() > 1 { + for &child in &work { + if self + .declared_name(child, budget)? + .is_some_and(|(_, function)| function) + { + self.index.canonical.nodes[id.0].projection = Projection::Pending; + return Ok(()); + } + } + } + for child in work { + let Some((name, function)) = self.declared_name(child, budget)? else { + continue; + }; + let node = self.index.canonical.nodes[name.0].evidence.node(); + if function { + slots.push(enclosing); + let declaration = self.index.canonical.nodes[id.0].evidence.node(); + let mut end = declaration.end_byte(); + if self.index.source.bytes().get(end.saturating_sub(1)) == Some(&b';') { + end -= 1; + } + self.names.insert( + &self.index.source.bytes()[node.byte_range()], + &self.index.source.bytes()[declaration.start_byte()..end], + enclosing, + budget, + )?; + } else { + let source = self + .index + .source + .pieces_with_budget(node.byte_range(), budget)?; + let slot = OwnerId(self.index.facts.owners.len()); + self.index.facts.owners.push(Owner::Slot(Slot { + enclosing, + role: SlotRole::Field, + ordinal: slots.len(), + source, + })); + self.index.associations_by_owner.push(Vec::new()); + self.index.assessments_by_owner.push(Vec::new()); + self.index.owner_nodes.push(id); + slots.push(slot); + } + } + self.index.canonical.nodes[id.0].projection = if slots.is_empty() { + Projection::Pending + } else { + Projection::Ready(slots) + }; + Ok(()) + } + + fn index_function_definition( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let Projection::Ready(owners) = &self.index.canonical.nodes[id.0].projection else { + return Ok(()); + }; + let Some(&owner) = owners.first() else { + return Ok(()); + }; + let node = self.index.canonical.nodes[id.0].evidence.node(); + let Some(declarator) = self.declarator_child(id, budget)? else { + return Ok(()); + }; + let Some((name, _)) = self.declared_name(declarator, budget)? else { + return Ok(()); + }; + let end = self.index.canonical.nodes[declarator.0] + .evidence + .node() + .end_byte(); + if self + .index + .source + .covers_with_budget(node.start_byte()..end, budget)? + { + self.names.insert( + &self.index.source.bytes()[self.index.canonical.nodes[name.0] + .evidence + .node() + .byte_range()], + &self.index.source.bytes()[node.start_byte()..end], + owner, + budget, + )?; + } + Ok(()) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/tests.rs b/big-code-analysis-ast/src/documentation/collector/tests.rs index 66c31dcf7..c0eb40f5b 100644 --- a/big-code-analysis-ast/src/documentation/collector/tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/tests.rs @@ -725,6 +725,16 @@ fn doxygen_static_names_resolve_unique_missing_and_ambiguous_targets() { Resolution::Resolved, 1, ), + ( + "/**@fn void f()\n * audit*/\nvoid f() {}", + Resolution::Resolved, + 1, + ), + ( + "void f() {}\n/**@fn void f()\n * audit*/", + Resolution::Resolved, + 1, + ), ( "/**@fn void missing()\n * audit*/\nvoid f();", Resolution::Unresolved(UnresolvedReason::MissingName), @@ -780,22 +790,28 @@ fn deep_missing_collection_and_teardown_fit_a_small_stack() { index.node_associations(missing.as_tree_sitter()), Err(OwnerError::UnsupportedOwner) )); - assert_eq!( - crate::node::node_resolved_parent_lookups::observed() - before, - 0 - ); + if cfg!(chain_audit) { + assert!(crate::node::node_resolved_parent_lookups::observed() > before); + } else { + assert_eq!( + crate::node::node_resolved_parent_lookups::observed() - before, + 0 + ); + } drop(index); std::thread::Builder::new() .stack_size(128 * 1024) .spawn(move || { - let index = parser - .documentation( - &DocumentationContext::default(), - &DocumentationOptions::default(), - ) - .unwrap(); - assert_eq!(index.documents().len(), 0); - drop(index); + if !cfg!(chain_audit) { + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 0); + drop(index); + } drop(parser); }) .unwrap() diff --git a/big-code-analysis-ast/src/documentation/forms.rs b/big-code-analysis-ast/src/documentation/forms.rs new file mode 100644 index 000000000..c8aaade67 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/forms.rs @@ -0,0 +1,123 @@ +//! Explicit implementation assessment for native source forms. + +use super::{Profile, SourceContext}; +use crate::{Ancestors, Node}; + +#[derive(Clone, Copy)] +pub(super) enum CommentAssessment { + Implemented, + Ineligible, + Pending(&'static str), +} + +pub(super) fn assess<'s, B: super::budget::WorkBudget>( + profile: Profile, + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + source: &SourceContext<'s>, + budget: &B, +) -> Result { + let parent = ancestors.parent(node).map(|node| node.kind()); + if !source.covers_with_budget(node.start_byte()..node.end_byte(), budget)? { + return Ok(CommentAssessment::Pending( + "Excluded bytes prevent complete native-carrier assessment", + )); + } + let bytes = &source.bytes()[node.start_byte()..node.end_byte()]; + Ok(match profile { + Profile::Rust if matches!(parent, Some("ordered_field_declaration_list")) => { + CommentAssessment::Pending( + "Rust tuple-field slot projection awaits the language adapter", + ) + } + Profile::Kdoc + if bytes.starts_with(b"/**") + && matches!( + parent, + Some( + "class_parameters" + | "class_parameter" + | "function_value_parameters" + | "parameter" + | "primary_constructor" + | "modifiers" + ) + ) => + { + CommentAssessment::Pending("KDoc signature or parameter form awaits owner projection") + } + Profile::BcaPhpSource + if bytes.starts_with(b"/**") + && matches!( + parent, + Some( + "formal_parameters" + | "property_promotion_parameter" + | "simple_parameter" + | "variadic_parameter" + ) + ) => + { + CommentAssessment::Pending("PHP signature/promoted slot awaits owner projection") + } + Profile::BcaTypescriptSource + if bytes.starts_with(b"/**") + && matches!( + parent, + Some("formal_parameters" | "required_parameter" | "optional_parameter") + ) => + { + CommentAssessment::Pending("TypeScript parameter documentation awaits slot projection") + } + Profile::Ldoc if matches!(parent, Some("parameters" | "field" | "table_constructor")) => { + CommentAssessment::Pending("Native LDoc parameter/table comment awaits adapter context") + } + Profile::Javadoc | Profile::Groovydoc | Profile::CsharpXml + if matches!( + parent, + Some( + "formal_parameters" + | "parameter_list" + | "accessor_list" + | "accessor_declaration" + ) + ) => + { + CommentAssessment::Ineligible + } + _ => CommentAssessment::Implemented, + }) +} + +pub(super) fn owner_pending( + profile: Profile, + node: &Node<'_>, + ancestors: Ancestors<'_, '_>, +) -> bool { + let parent = ancestors.parent(node).map(|node| node.kind()); + match profile { + Profile::Rust => { + matches!(parent, Some("ordered_field_declaration_list")) + || matches!( + node.kind(), + "field_declaration" | "enum_variant" | "associated_type" + ) + } + Profile::Kdoc => matches!( + node.kind(), + "class_parameter" | "parameter" | "primary_constructor" + ), + Profile::BcaPhpSource => matches!( + node.kind(), + "property_promotion_parameter" + | "simple_parameter" + | "variadic_parameter" + | "expression_statement" + ), + Profile::GoDoc => matches!( + node.kind(), + "field_declaration" | "method_elem" | "type_elem" + ), + _ => false, + } +} diff --git a/big-code-analysis-ast/src/documentation/index.rs b/big-code-analysis-ast/src/documentation/index.rs index 4886cc068..1e8a0a047 100644 --- a/big-code-analysis-ast/src/documentation/index.rs +++ b/big-code-analysis-ast/src/documentation/index.rs @@ -76,6 +76,7 @@ pub struct DocumentationIndex<'s> { pub(super) owner_nodes: Vec, pub(super) documents_ordered: Vec, pub(super) associations_ordered: Vec, + pub(super) source_cleaned: Vec>>, } /// Prepared results for one semantic owner, including known associations and @@ -85,9 +86,16 @@ pub struct OwnerAssociations<'i, 's> { associations: &'i [usize], assessments: &'i [usize], scope: Option, + projection_pending: bool, } impl<'i, 's> OwnerAssociations<'i, 's> { + /// Whether the queried syntax still requires a semantic owner projection. + /// Known associations and pending assessment records remain accessible. + #[must_use] + pub fn projection_pending(&self) -> bool { + self.projection_pending + } /// Known association records, without scanning other owners. pub fn associations(&self) -> impl ExactSizeIterator>> + '_ { self.associations.iter().map(|&ordinal| FactRef { @@ -249,6 +257,22 @@ impl<'s> DocumentationIndex<'s> { }) } + /// Source-cleaned spelling retained where semantic prelexing is unsupported. + /// This is explicitly not a complete decoded documentation value. + /// + /// # Errors + /// Rejects a foreign document handle. + pub fn source_cleaned_text( + &self, + document: FactRef<'_, Document<'s>>, + ) -> Result>, FactError> { + self.facts.check_scope(document)?; + Ok(match &self.source_cleaned[document.ordinal] { + Some(Content::Complete { text, mappings }) => Some(CompleteText { text, mappings }), + _ => None, + }) + } + /// Prepared query using an index-qualified semantic owner handle. /// /// # Errors @@ -273,7 +297,13 @@ impl<'s> DocumentationIndex<'s> { let id = self.canonical.lookup(node).map_err(OwnerError::Source)?; match &self.canonical.nodes[id.0].projection { Projection::Ready(owners) if owners.is_empty() => Err(OwnerError::UnsupportedOwner), - Projection::Pending => Err(OwnerError::PendingOwner), + Projection::Pending => Ok(OwnerAssociations { + index: self, + associations: &[], + assessments: &[], + scope: Some(id), + projection_pending: true, + }), Projection::Ready(owners) if owners.len() == 1 => { let ordinal = owners[0].0; Ok(self.prepared_owner(ordinal)) @@ -318,6 +348,7 @@ impl<'s> DocumentationIndex<'s> { associations: &self.associations_by_owner[ordinal], assessments: &self.assessments_by_owner[ordinal], scope, + projection_pending: false, } } } diff --git a/big-code-analysis-ast/src/documentation/names.rs b/big-code-analysis-ast/src/documentation/names.rs index 0c2774926..9d0e76a8b 100644 --- a/big-code-analysis-ast/src/documentation/names.rs +++ b/big-code-analysis-ast/src/documentation/names.rs @@ -1,27 +1,92 @@ //! Bounded same-file exact structural names and signatures. use std::collections::HashMap; +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hasher}; use super::budget::WorkBudget; use super::{OwnerId, SourceError, UnresolvedReason}; #[derive(Default)] pub(super) struct Names { - names: HashMap, OwnerId)>>, - signatures: HashMap, OwnerId)>>, + identifiers: HashMap>, + signatures: HashMap>, + hasher: RandomState, } -fn key(bytes: &[u8], budget: &B) -> Result<(u64, Vec), SourceError> { - let mut hash = 0xcbf2_9ce4_8422_2325_u64; +struct NameEntry { + spelling: Vec, + owners: Vec, +} + +crate::observation::counter!(name_bytes, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(name_candidates, cfg(any(test, feature = "test-support"))); + +fn key( + bytes: &[u8], + hasher: &RandomState, + budget: &B, +) -> Result<(u64, Vec), SourceError> { + super::budget::in_phase(budget, super::budget::WorkPhase::Names, || { + normalized_key(bytes, hasher, budget) + }) +} + +fn normalized_key( + bytes: &[u8], + hasher: &RandomState, + budget: &B, +) -> Result<(u64, Vec), SourceError> { + let mut hash = hasher.build_hasher(); let mut key = Vec::new(); for &byte in bytes { budget.bytes(1).map_err(Into::into)?; + name_bytes::record(); if !byte.is_ascii_whitespace() { - hash = (hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3); + hash.write_u8(byte); key.push(byte); } } - Ok((hash, key)) + Ok((hash.finish(), key)) +} + +fn same_spelling( + left: &[u8], + right: &[u8], + budget: &B, +) -> Result { + name_candidates::record(); + if left.len() != right.len() { + return Ok(false); + } + for (left, right) in left.iter().zip(right) { + budget.bytes(1).map_err(Into::into)?; + name_bytes::record(); + if left != right { + return Ok(false); + } + } + Ok(true) +} + +fn insert_entry( + bucket: &mut Vec, + spelling: Vec, + owner: OwnerId, + budget: &B, +) -> Result<(), SourceError> { + for entry in bucket.iter_mut() { + budget.step().map_err(Into::into)?; + if same_spelling(&entry.spelling, &spelling, budget)? { + entry.owners.push(owner); + return Ok(()); + } + } + bucket.push(NameEntry { + spelling, + owners: vec![owner], + }); + Ok(()) } impl Names { @@ -32,13 +97,20 @@ impl Names { owner: OwnerId, budget: &B, ) -> Result<(), SourceError> { - let (hash, name) = key(name, budget)?; - self.names.entry(hash).or_default().push((name, owner)); - let (hash, signature) = key(signature, budget)?; - self.signatures - .entry(hash) - .or_default() - .push((signature, owner)); + let (hash, name) = key(name, &self.hasher, budget)?; + insert_entry( + self.identifiers.entry(hash).or_default(), + name, + owner, + budget, + )?; + let (hash, signature) = key(signature, &self.hasher, budget)?; + insert_entry( + self.signatures.entry(hash).or_default(), + signature, + owner, + budget, + )?; Ok(()) } @@ -47,7 +119,7 @@ impl Names { reference: &[u8], budget: &B, ) -> Result<(Vec, Option), SourceError> { - let (hash, key) = key(reference, budget)?; + let (hash, key) = key(reference, &self.hasher, budget)?; let mut signatures = false; for byte in &key { budget.bytes(1).map_err(Into::into)?; @@ -56,25 +128,18 @@ impl Names { let index = if signatures { &self.signatures } else { - &self.names + &self.identifiers }; let mut owners = Vec::new(); if let Some(candidates) = index.get(&hash) { - for (candidate, owner) in candidates { + for entry in candidates { budget.step().map_err(Into::into)?; - if candidate.len() != key.len() { - continue; - } - let mut matches = true; - for (left, right) in candidate.iter().zip(&key) { - budget.bytes(1).map_err(Into::into)?; - if left != right { - matches = false; - break; + if same_spelling(&entry.spelling, &key, budget)? { + for &owner in &entry.owners { + budget.step().map_err(Into::into)?; + owners.push(owner); } - } - if matches { - owners.push(*owner); + break; } } } @@ -86,3 +151,53 @@ impl Names { Ok((owners, reason)) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::documentation::budget::NoBudget; + + #[test] + fn duplicate_names_share_spelling_and_query_compares_once() { + let mut names = Names::default(); + let name = b"a".repeat(4096); + for ordinal in 0..128 { + names + .insert(&name, &name, OwnerId(ordinal), &NoBudget) + .unwrap(); + } + assert_eq!(names.identifiers.values().map(Vec::len).sum::(), 1); + let entry = &names.identifiers.values().next().unwrap()[0]; + assert_eq!(entry.spelling.len(), 4096); + assert_eq!(entry.owners.len(), 128); + let before = name_candidates::observed(); + let (owners, reason) = names.resolve(&name, &NoBudget).unwrap(); + assert_eq!(reason, Some(UnresolvedReason::Ambiguous)); + assert_eq!(owners.len(), 128); + assert_eq!(name_candidates::observed() - before, 1); + } + + #[test] + fn hash_collision_does_not_substitute_another_name() { + let mut names = Names::default(); + let (hash, _) = key(b"f", &names.hasher, &NoBudget).unwrap(); + names.identifiers.insert( + hash, + vec![ + NameEntry { + spelling: b"g".to_vec(), + owners: vec![OwnerId(0)], + }, + NameEntry { + spelling: b"f".to_vec(), + owners: vec![OwnerId(1)], + }, + ], + ); + let before = name_candidates::observed(); + let (owners, reason) = names.resolve(b"f", &NoBudget).unwrap(); + assert_eq!(reason, None); + assert_eq!(owners.iter().map(|owner| owner.0).collect::>(), [1]); + assert_eq!(name_candidates::observed() - before, 2); + } +} diff --git a/big-code-analysis-ast/src/documentation/ordering.rs b/big-code-analysis-ast/src/documentation/ordering.rs index 8cd9973c1..78cc3921a 100644 --- a/big-code-analysis-ast/src/documentation/ordering.rs +++ b/big-code-analysis-ast/src/documentation/ordering.rs @@ -53,6 +53,15 @@ impl Ord for Entry<'_, K, B> { } pub(super) fn ordered( + keys: Vec, + budget: &B, +) -> Result, B::Error> { + super::budget::in_phase(budget, super::budget::WorkPhase::Ordering, || { + sort_and_merge(keys, budget) + }) +} + +fn sort_and_merge( mut keys: Vec, budget: &B, ) -> Result, B::Error> { diff --git a/big-code-analysis-ast/src/documentation/recognition.rs b/big-code-analysis-ast/src/documentation/recognition.rs new file mode 100644 index 000000000..b08a0740b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/recognition.rs @@ -0,0 +1,333 @@ +//! Private fallible counterparts for public infallible source-recognition hooks. + +use std::marker::PhantomData; + +use super::budget::WorkBudget; +use super::streaming::{ + markers::CandidateView, + positional::{OpenerReason, RunContext}, +}; +use super::{SourceContext, UnresolvedReason}; +use crate::{Ancestors, Checker, Node}; + +crate::observation::counter!(target_queries, cfg(any(test, feature = "test-support"))); +crate::observation::counter!( + target_computations, + cfg(any(test, feature = "test-support")) +); + +pub(crate) trait SourceRules { + type Checker: Checker; + fn start_row(node: &Node<'_>, budget: &B) -> Result; + fn marker(node: &Node<'_>, code: &[u8], budget: &B) -> Result; + + fn target<'s, B: WorkBudget>( + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result; + fn forward<'s, B: WorkBudget>( + node: &Node<'s>, + context: &SourceContext<'s>, + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result, B::Error>; + fn skips<'s, B: WorkBudget>( + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result; + fn gathers(node: &Node<'_>, code: &[u8], budget: &B) -> Result; + fn opener<'s, B: WorkBudget>( + run: &RunContext<'_, 's>, + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result, UnresolvedReason>, B::Error>; + fn directive(node: &Node<'_>, code: &[u8], budget: &B) + -> Result; + fn ends(node: &Node<'_>, code: &[u8], budget: &B) -> Result; +} + +pub(crate) struct PublicRules(PhantomData); +pub(crate) struct NativeRules(PhantomData); + +impl SourceRules for NativeRules { + type Checker = T; + fn start_row(node: &Node<'_>, budget: &B) -> Result { + if T::lang() == crate::LANG::Ruby { + crate::checker::ruby::start_row_with_budget(node, budget) + } else { + Ok(T::doc_target_start_row(node)) + } + } + fn marker(node: &Node<'_>, code: &[u8], budget: &B) -> Result { + if T::lang() == crate::LANG::Rust && T::is_comment(node) { + crate::roles::rust::doc_marker_with_budget(node, budget) + } else { + Ok(T::is_source_doc_comment(node, code)) + } + } + + fn target<'s, B: WorkBudget>( + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result { + target_queries::record(); + ancestors.try_memoised(crate::node::MemoQuestion::SourceDocTarget, node, || { + target_computations::record(); + match T::lang() { + crate::LANG::C => crate::lang_helpers::doxygen::doxygen_target_with_budget::< + crate::CCode, + _, + >(node, code, ancestors, budget), + crate::LANG::Cpp => crate::lang_helpers::doxygen::doxygen_target_with_budget::< + crate::CppCode, + _, + >(node, code, ancestors, budget), + crate::LANG::Mozcpp => crate::lang_helpers::doxygen::doxygen_target_with_budget::< + crate::MozcppCode, + _, + >(node, code, ancestors, budget), + crate::LANG::Objc => crate::lang_helpers::doxygen::doxygen_target_with_budget::< + crate::ObjcCode, + _, + >(node, code, ancestors, budget), + crate::LANG::Go => { + crate::roles::go::doc_target_with_budget(node, ancestors, budget) + } + crate::LANG::Ruby => crate::checker::ruby::ruby_doc_target_with_budget( + node, code, ancestors, true, budget, + ), + crate::LANG::Lua => crate::checker::lua::target_with_budget(node, budget), + crate::LANG::Php => { + crate::roles::php::target_with_budget(node, code, ancestors, budget) + } + crate::LANG::Javascript => { + crate::roles::javascript::doc_target_with_budget(node, code, ancestors, budget) + } + crate::LANG::Mozjs => { + crate::roles::mozjs::doc_target_with_budget(node, code, ancestors, budget) + } + crate::LANG::Typescript | crate::LANG::Tsx + if ancestors.parent(node).is_some_and(|parent| { + matches!(parent.kind(), "export_statement" | "ambient_declaration") + }) => + { + Ok(false) + } + crate::LANG::Typescript => { + crate::roles::typescript::doc_target_with_budget(node, code, ancestors, budget) + } + crate::LANG::Tsx => { + crate::roles::tsx::doc_target_with_budget(node, code, ancestors, budget) + } + _ => PublicRules::::target(node, code, ancestors, budget), + } + }) + } + fn forward<'s, B: WorkBudget>( + node: &Node<'s>, + context: &SourceContext<'s>, + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result, B::Error> { + let bytes = crate::lang_helpers::doc_comment::node_bytes(node, context.bytes()); + match T::lang() { + crate::LANG::C => Ok(Some( + crate::lang_helpers::doxygen::doxygen_forward_with_budget::( + node, + context.bytes(), + ancestors, + budget, + )?, + )), + crate::LANG::Cpp => Ok(Some( + crate::lang_helpers::doxygen::doxygen_forward_with_budget::( + node, + context.bytes(), + ancestors, + budget, + )?, + )), + crate::LANG::Mozcpp => { + Ok(Some( + crate::lang_helpers::doxygen::doxygen_forward_with_budget::< + crate::MozcppCode, + _, + >(node, context.bytes(), ancestors, budget)?, + )) + } + crate::LANG::Objc => Ok(Some( + crate::lang_helpers::doxygen::doxygen_forward_with_budget::( + node, + context.bytes(), + ancestors, + budget, + )?, + )), + crate::LANG::Php => { + crate::checker::php::source_forward_with_budget(node, context, ancestors, budget) + } + crate::LANG::Javascript | crate::LANG::Mozjs => Ok(Some( + !crate::lang_helpers::doc_text::jsdoc_virtual_with_budget(bytes, budget)?, + )), + crate::LANG::Typescript | crate::LANG::Tsx => Ok(Some( + !crate::lang_helpers::doc_text::tsdoc_module_with_budget(bytes, budget)?, + )), + _ => PublicRules::::forward(node, context, ancestors, budget), + } + } + fn skips<'s, B: WorkBudget>( + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result { + match T::lang() { + crate::LANG::C => crate::lang_helpers::doxygen::doxygen_skips_with_budget::< + crate::CCode, + _, + >(node, ancestors, budget), + crate::LANG::Cpp => crate::lang_helpers::doxygen::doxygen_skips_with_budget::< + crate::CppCode, + _, + >(node, ancestors, budget), + crate::LANG::Mozcpp => crate::lang_helpers::doxygen::doxygen_skips_with_budget::< + crate::MozcppCode, + _, + >(node, ancestors, budget), + crate::LANG::Objc => crate::lang_helpers::doxygen::doxygen_skips_with_budget::< + crate::ObjcCode, + _, + >(node, ancestors, budget), + _ => PublicRules::::skips(node, ancestors, budget), + } + } + fn gathers(node: &Node<'_>, code: &[u8], budget: &B) -> Result { + if matches!( + T::lang(), + crate::LANG::C | crate::LANG::Cpp | crate::LANG::Mozcpp | crate::LANG::Objc + ) { + crate::lang_helpers::doxygen::doxygen_standalone_with_budget( + crate::lang_helpers::doc_comment::node_bytes(node, code), + budget, + ) + } else { + PublicRules::::gathers(node, code, budget) + } + } + fn opener<'s, B: WorkBudget>( + run: &RunContext<'_, 's>, + ancestors: Ancestors<'s, '_>, + budget: &B, + ) -> Result, UnresolvedReason>, B::Error> { + match T::lang() { + crate::LANG::Ruby => Ok(Ok(crate::checker::ruby::source_opener_with_budget( + run, ancestors, budget, + )?)), + crate::LANG::Lua => { + crate::checker::lua::source_opener_with_budget(run, ancestors, budget) + } + _ => PublicRules::::opener(run, ancestors, budget), + } + } + fn directive( + node: &Node<'_>, + code: &[u8], + budget: &B, + ) -> Result { + let bytes = crate::lang_helpers::doc_comment::node_bytes(node, code); + match T::lang() { + crate::LANG::Go => { + crate::lang_helpers::doc_text::go_directive_with_budget(bytes, budget) + } + crate::LANG::Ruby => { + crate::lang_helpers::doc_text::ruby_magic_comment_with_budget(bytes, budget) + } + _ => PublicRules::::directive(node, code, budget), + } + } + fn ends(node: &Node<'_>, code: &[u8], budget: &B) -> Result { + if T::lang() == crate::LANG::Lua && T::is_comment(node) { + crate::lang_helpers::doc_text::lua_long_comment_with_budget( + crate::lang_helpers::doc_comment::node_bytes(node, code), + budget, + ) + } else { + PublicRules::::ends(node, code, budget) + } + } +} + +impl SourceRules for PublicRules { + type Checker = T; + fn start_row(node: &Node<'_>, _: &B) -> Result { + Ok(T::doc_target_start_row(node)) + } + fn marker(node: &Node<'_>, code: &[u8], _: &B) -> Result { + Ok(T::is_source_doc_comment(node, code)) + } + + fn target<'s, B: WorkBudget>( + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + _: &B, + ) -> Result { + Ok(T::is_source_doc_target(node, code, ancestors)) + } + fn forward<'s, B: WorkBudget>( + node: &Node<'s>, + context: &SourceContext<'s>, + ancestors: Ancestors<'s, '_>, + _: &B, + ) -> Result, B::Error> { + Ok(T::source_doc_binds_forward(node, context, ancestors)) + } + fn skips<'s, B: WorkBudget>( + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + _: &B, + ) -> Result { + Ok(T::source_doc_binding().is_some_and(|binding| (binding.skips)(node, ancestors))) + } + fn gathers(node: &Node<'_>, code: &[u8], _: &B) -> Result { + Ok(T::source_doc_binding() + .and_then(|binding| binding.gathers) + .is_some_and(|gathers| gathers(node, code))) + } + fn opener<'s, B: WorkBudget>( + run: &RunContext<'_, 's>, + ancestors: Ancestors<'s, '_>, + _: &B, + ) -> Result, UnresolvedReason>, B::Error> { + Ok(T::source_doc_run_opener(run, ancestors)) + } + fn directive(node: &Node<'_>, code: &[u8], _: &B) -> Result { + Ok(T::is_doc_run_directive(node, code)) + } + fn ends(node: &Node<'_>, code: &[u8], _: &B) -> Result { + Ok(T::ends_doc_run(node, code)) + } +} + +pub(crate) fn source_target<'s, R: SourceRules, B: WorkBudget>( + view: CandidateView<'_>, + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + budget: &B, +) -> Result { + budget.step()?; + match view { + CandidateView::Legacy => Ok(R::Checker::is_doc_target(node, code, ancestors)), + CandidateView::Source(_) + if view.covers_with_budget(node.start_byte()..node.end_byte(), budget)? => + { + R::target(node, code, ancestors, budget) + } + CandidateView::Source(_) => Ok(false), + } +} diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index ae655b82e..339b26006 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -2,7 +2,7 @@ use std::ops::Range; -use super::budget::{NoBudget, WorkBudget, infallible}; +use super::budget::{NoBudget, WorkBudget, WorkPhase, in_phase, infallible}; // Output alone cannot reveal scanning empty ranges or seeking from the start. crate::observation::counter!( @@ -92,6 +92,16 @@ impl<'s> SourceContext<'s> { tree: &'s tree_sitter::Tree, bytes: &'s [u8], budget: &B, + ) -> Result { + in_phase(budget, WorkPhase::Ranges, || { + Self::prepare(tree, bytes, budget) + }) + } + + fn prepare( + tree: &'s tree_sitter::Tree, + bytes: &'s [u8], + budget: &B, ) -> Result { budget.checkpoint()?; // The safe dependency copies the range array atomically. Only our @@ -137,6 +147,16 @@ impl<'s> SourceContext<'s> { &self, spelling: Range, budget: &B, + ) -> Result, SourceError> { + in_phase(budget, WorkPhase::Ranges, || { + self.intersect(spelling, budget) + }) + } + + fn intersect( + &self, + spelling: Range, + budget: &B, ) -> Result, SourceError> { // bca: suppress(halstead) -- one interval-intersection loop retains raw slices and excluded-gap evidence together. if spelling.start >= spelling.end || spelling.end > self.bytes.len() { @@ -181,20 +201,32 @@ impl<'s> SourceContext<'s> { } /// Whether the whole interval is available, without joining across a gap. + #[cfg(test)] pub(crate) fn covers(&self, span: Range) -> bool { + infallible(self.covers_with_budget(span, &NoBudget)) + } + + pub(crate) fn covers_with_budget( + &self, + span: Range, + budget: &B, + ) -> Result { if span.start > span.end || span.end > self.bytes.len() { - return false; + return Ok(false); } if span.is_empty() { - return true; + return Ok(true); } - let first = self - .continuous - .partition_point(|range| range.end <= span.start); + let first = super::budget::binary_search_end( + self.continuous.len(), + |at| self.continuous[at].end <= span.start, + budget, + )?; included_range_visits::record(); - self.continuous + Ok(self + .continuous .get(first) - .is_some_and(|range| range.start <= span.start && range.end >= span.end) + .is_some_and(|range| range.start <= span.start && range.end >= span.end)) } /// Record a node reached canonically by a collector cursor. The caller diff --git a/big-code-analysis-ast/src/documentation/streaming/markers.rs b/big-code-analysis-ast/src/documentation/streaming/markers.rs index 8c05ce810..1021de978 100644 --- a/big-code-analysis-ast/src/documentation/streaming/markers.rs +++ b/big-code-analysis-ast/src/documentation/streaming/markers.rs @@ -6,6 +6,8 @@ use crate::node::WordSlot; use crate::{Ancestors, Checker, Node}; use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces}; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::documentation::recognition::{PublicRules, SourceRules}; // Separate slots are necessary even on one visited node: Java's empty marker // answers differently before the same Last selector runs. @@ -16,44 +18,42 @@ pub(crate) enum CandidateView<'s> { } impl CandidateView<'_> { - pub(crate) fn covers(self, span: std::ops::Range) -> bool { - match self { - Self::Legacy => true, - Self::Source(context) => context.covers(span), - } - } - - pub(crate) fn marker(self, node: &Node, code: &[u8], ancestors: Ancestors) -> bool { - if !self.covers(node.start_byte()..node.end_byte()) { - return false; + pub(crate) fn marker_with_budget( + self, + node: &Node, + code: &[u8], + ancestors: Ancestors, + budget: &B, + ) -> Result { + if !self.covers_with_budget(node.start_byte()..node.end_byte(), budget)? { + return Ok(false); } let slot = match self { Self::Legacy => WordSlot::LegacyDocMarker, Self::Source(_) => WordSlot::SourceDocMarker, }; - ancestors.classified(slot, node, || { + Ok(ancestors.try_classified(slot, node, || { marker_reads::record(); - u8::from(match self { - Self::Legacy => T::is_doc_comment(node, code), - Self::Source(_) => T::is_source_doc_comment(node, code), - }) - }) != 0 + Ok(u8::from(match self { + Self::Legacy => R::Checker::is_doc_comment(node, code), + Self::Source(_) => R::marker(node, code, budget)?, + })) + })? != 0) } - - pub(crate) fn target<'t, T: Checker>( + pub(crate) fn covers_with_budget( self, - node: &Node<'t>, - code: &[u8], - ancestors: Ancestors<'t, '_>, - ) -> bool { + span: std::ops::Range, + budget: &B, + ) -> Result { match self { - Self::Legacy => T::is_doc_target(node, code, ancestors), - Self::Source(_) => { - self.covers(node.start_byte()..node.end_byte()) - && T::is_source_doc_target(node, code, ancestors) - } + Self::Legacy => Ok(true), + Self::Source(context) => context.covers_with_budget(span, budget), } } + + pub(crate) fn marker(self, node: &Node, code: &[u8], ancestors: Ancestors) -> bool { + infallible(self.marker_with_budget::, _>(node, code, ancestors, &NoBudget)) + } } pub(crate) fn legacy_marker(node: &Node, code: &[u8], ancestors: Ancestors) -> bool { @@ -139,19 +139,22 @@ struct RunSelection<'t> { } impl<'t> RunSelection<'t> { - fn select( + fn select( collected: &doc_comment::CollectedStretch<'t>, end: StretchEnd<'t>, binding: DocBinding, context: &SourceContext<'t>, ancestors: Ancestors<'t, '_>, - ) -> Self { + budget: &B, + ) -> Result { let stretch = &collected.members; let code_before = collected.code_before; let code = context.bytes(); - let marker = |n: &Node<'t>| CandidateView::Source(context).marker::(n, code, ancestors); + let marker = |n: &Node<'t>| { + CandidateView::Source(context).marker_with_budget::(n, code, ancestors, budget) + }; let forward = |n: &Node<'t>| { - marker(n) && T::source_doc_binds_forward(n, context, ancestors) == Some(true) + Ok(marker(n)? && R::forward(n, context, ancestors, budget)? == Some(true)) }; if let StretchEnd::AtTarget { next, target } = end { // Only a leading-trivia policy that rejects after-code comments @@ -164,7 +167,7 @@ impl<'t> RunSelection<'t> { } _ => None, }; - let mut bound = doc_comment::select_bound::( + let mut bound = doc_comment::select_bound_with_budget::( stretch, code, binding.kept, @@ -174,8 +177,9 @@ impl<'t> RunSelection<'t> { target, }, forward, - ); - return Self { + budget, + )?; + return Ok(Self { kept: std::mem::take(&mut bound.nodes), target: Some(target), gatherer: None, @@ -183,16 +187,25 @@ impl<'t> RunSelection<'t> { gap: false, suffix_gap: false, prefix_gap_row, - }; + }); } - let result = binding - .gathers - .map(|gathers| doc_comment::bind_gathered(stretch, code, gathers, marker, forward)); + let result = if binding.gathers.is_some() { + Some(doc_comment::bind_gathered_with_budget( + stretch, + code, + |node| R::gathers(node, code, budget), + marker, + forward, + budget, + )?) + } else { + None + }; let doc_comment::Gathered { kept, gatherer } = result.unwrap_or(doc_comment::Gathered { kept: Vec::new(), gatherer: None, }); - Self { + Ok(Self { kept, target: None, gatherer, @@ -200,42 +213,53 @@ impl<'t> RunSelection<'t> { gap: matches!(end, StretchEnd::ExcludedGap), suffix_gap: matches!(end, StretchEnd::SuffixGap), prefix_gap_row: None, - } + }) } - fn members( + fn members( &self, stretch: &[Node<'t>], binding: DocBinding, ancestors: Ancestors<'t, '_>, request: &SourceRequest<'_, 't>, + budget: &B, ) -> Result>, SourceError> { // bca: suppress(halstead, cognitive, cyclomatic, abc) -- one ordered merge preserves selection, uncertain tokens and lazy evidence without rescanning the stretch. let code = request.context.bytes(); let mut selected = self.kept.iter().peekable(); let mut members = Vec::new(); for (index, node) in stretch.iter().enumerate() { - if !request.context.covers(node.start_byte()..node.end_byte()) { - if request.retain_unbound && T::is_comment(node) { + budget.step().map_err(Into::into)?; + if !request + .context + .covers_with_budget(node.start_byte()..node.end_byte(), budget) + .map_err(Into::into)? + { + if request.retain_unbound && R::Checker::is_comment(node) { let mut evidence = member( request.context, node, MarkerSelection::Unattached, MarkerPlacement::Unknown, + budget, )?; evidence.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); members.push(evidence); } continue; } - if !CandidateView::Source(request.context).marker::(node, code, ancestors) { + if !CandidateView::Source(request.context) + .marker_with_budget::(node, code, ancestors, budget) + .map_err(Into::into)? + { continue; } let kept = selected.peek().is_some_and(|n| n.id() == node.id()); if kept { selected.next(); } - let Some(forward) = T::source_doc_binds_forward(node, request.context, ancestors) + let Some(forward) = + R::forward(node, request.context, ancestors, budget).map_err(Into::into)? else { if request.retain_unbound { let mut evidence = member( @@ -243,6 +267,7 @@ impl<'t> RunSelection<'t> { node, MarkerSelection::Unattached, MarkerPlacement::Unknown, + budget, )?; evidence.uncertainty = Some(super::super::UnresolvedReason::ExcludedGap); members.push(evidence); @@ -265,7 +290,10 @@ impl<'t> RunSelection<'t> { continue; } let placement = match (forward, kept, self.gatherer) { - (false, _, _) if binding.gathers.is_some_and(|gathers| gathers(node, code)) => { + (false, _, _) + if binding.gathers.is_some() + && R::gathers(node, code, budget).map_err(Into::into)? => + { MarkerPlacement::Gatherer } (false, _, _) => MarkerPlacement::Local, @@ -274,8 +302,8 @@ impl<'t> RunSelection<'t> { } _ => MarkerPlacement::Forward, }; - let mut member = member(request.context, node, selection, placement)?; - member.uncertainty = T::source_doc_uncertainty(node, code, ancestors); + let mut member = member(request.context, node, selection, placement, budget)?; + member.uncertainty = R::Checker::source_doc_uncertainty(node, code, ancestors); if self.suffix_gap || (forward && ((self.gap && !kept) || self.prefix_gap_row == Some(node.start_row()))) @@ -315,15 +343,32 @@ pub fn source_comment<'s, T: Checker>( comment: &Node<'s>, ancestors: Ancestors<'s, '_>, request: &mut SourceRequest<'_, 's>, +) -> Result<(), SourceError> { + source_comment_with_budget::, _>(comment, ancestors, request, &NoBudget) +} + +pub(crate) fn source_comment_with_budget<'s, R: SourceRules, B: WorkBudget>( + comment: &Node<'s>, + ancestors: Ancestors<'s, '_>, + request: &mut SourceRequest<'_, 's>, + budget: &B, ) -> Result<(), SourceError> { // bca: suppress(nexits, halstead) -- early deferral and source identity failures propagate before any sink call. - let Some(binding) = T::source_doc_binding() else { + let Some(binding) = R::Checker::source_doc_binding() else { return Ok(()); }; let code = request.context.bytes(); request.context.node(comment.as_tree_sitter())?; let view = CandidateView::Source(request.context); - let end = doc_comment::stretch_end::(comment, code, ancestors, binding.skips, view); + let end = doc_comment::stretch_end_with_budget::( + comment, + code, + ancestors, + |node, ancestors| R::skips(node, ancestors, budget), + view, + budget, + ) + .map_err(Into::into)?; if matches!(end, StretchEnd::Undecided) { return Ok(()); } @@ -331,16 +376,26 @@ pub fn source_comment<'s, T: Checker>( end, StretchEnd::Elsewhere | StretchEnd::ExcludedGap | StretchEnd::SuffixGap ) && !request.retain_unbound - && !T::SOURCE_LOCAL_DOCS + && !R::Checker::SOURCE_LOCAL_DOCS && binding.gathers.is_none() { return Ok(()); } - let collected = - doc_comment::collect_stretch::(comment, code, ancestors, binding.skips, view); + let collected = doc_comment::collect_stretch_with_budget::( + comment, + code, + ancestors, + |node, ancestors| R::skips(node, ancestors, budget), + view, + budget, + ) + .map_err(Into::into)?; let code_before = collected.code_before; - let selection = RunSelection::select::(&collected, end, binding, request.context, ancestors); - let members = selection.members::(&collected.members, binding, ancestors, request)?; + let selection = + RunSelection::select::(&collected, end, binding, request.context, ancestors, budget) + .map_err(Into::into)?; + let members = + selection.members::(&collected.members, binding, ancestors, request, budget)?; if !members.is_empty() { let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); (request.sink)(MarkerRun { @@ -348,7 +403,7 @@ pub fn source_comment<'s, T: Checker>( target: selection.target.map(canonical).transpose()?, target_uncertainty: selection .target - .and_then(|node| T::source_doc_uncertainty(&node, code, ancestors)), + .and_then(|node| R::Checker::source_doc_uncertainty(&node, code, ancestors)), containing: ancestors.parent(comment).map(canonical).transpose()?, code_before: code_before.map(canonical).transpose()?, prefix_gap: collected.prefix_gap, @@ -358,51 +413,64 @@ pub fn source_comment<'s, T: Checker>( Ok(()) } -fn member<'s>( +fn member<'s, B: WorkBudget>( context: &SourceContext<'s>, node: &Node<'s>, selection: MarkerSelection, placement: MarkerPlacement<'s>, + budget: &B, ) -> Result, SourceError> { evidence_built::record(); let bytes = doc_comment::node_bytes(node, context.bytes()); - let end = - if bytes.starts_with(b"//") && context.covers(node.start_byte()..node.start_byte() + 2) { - line_spelling_end(context, node) - } else { - node.end_byte() - }; + let end = if bytes.starts_with(b"//") + && context + .covers_with_budget(node.start_byte()..node.start_byte() + 2, budget) + .map_err(Into::into)? + { + line_spelling_end(context, node, budget).map_err(Into::into)? + } else { + node.end_byte() + }; Ok(MarkerMember { node: context.node(node.as_tree_sitter())?, - source: context.pieces(node.start_byte()..end)?, + source: context.pieces_with_budget(node.start_byte()..end, budget)?, selection, placement, uncertainty: None, }) } -pub(super) fn line_spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { +pub(super) fn line_spelling_end( + context: &SourceContext<'_>, + node: &Node<'_>, + budget: &B, +) -> Result { let code = context.bytes(); let end = node.end_byte(); - let lf = if context.covers(end - 1..end) && code.get(end - 1) == Some(&b'\n') { + let lf = if context.covers_with_budget(end.saturating_sub(1)..end, budget)? + && code.get(end.wrapping_sub(1)) == Some(&b'\n') + { end - 1 } else { end }; - if context.covers(lf..lf + 1) && code.get(lf) == Some(&b'\n') { - if context.covers(lf - 1..lf + 1) && code.get(lf - 1) == Some(&b'\r') { - return lf - 1; + if context.covers_with_budget(lf..lf + 1, budget)? && code.get(lf) == Some(&b'\n') { + if context.covers_with_budget(lf.saturating_sub(1)..lf + 1, budget)? + && code.get(lf.wrapping_sub(1)) == Some(&b'\r') + { + return Ok(lf - 1); } - return lf; + return Ok(lf); } // Some grammars exclude CR from the node even when no included LF follows it. - if context.covers(end..end + 1) + if context.covers_with_budget(end..end + 1, budget)? && code.get(end) == Some(&b'\r') - && !(context.covers(end + 1..end + 2) && code.get(end + 1) == Some(&b'\n')) + && !(context.covers_with_budget(end + 1..end + 2, budget)? + && code.get(end + 1) == Some(&b'\n')) { - return end + 1; + return Ok(end + 1); } - end + Ok(end) } #[cfg(test)] diff --git a/big-code-analysis-ast/src/documentation/streaming/positional.rs b/big-code-analysis-ast/src/documentation/streaming/positional.rs index d40aa056a..bddf9c315 100644 --- a/big-code-analysis-ast/src/documentation/streaming/positional.rs +++ b/big-code-analysis-ast/src/documentation/streaming/positional.rs @@ -5,6 +5,8 @@ use crate::{Ancestors, Checker, Node}; use super::super::{NodeEvidence, SourceContext, SourceError, SourcePieces, UnresolvedReason}; use super::markers::CandidateView; +use crate::documentation::budget::{NoBudget, WorkBudget}; +use crate::documentation::recognition::{PublicRules, SourceRules}; pub use doc_comment::{ members_materialized, positional_predecessors, positional_runs_collected, source_scope_reads, @@ -128,27 +130,41 @@ pub fn source_comment<'s, T: Checker>( comment: &Node<'s>, ancestors: Ancestors<'s, '_>, request: &mut SourceRequest<'_, 's>, +) -> Result<(), SourceError> { + source_comment_with_budget::, _>(comment, ancestors, request, &NoBudget) +} + +pub(crate) fn source_comment_with_budget<'s, R: SourceRules, B: WorkBudget>( + comment: &Node<'s>, + ancestors: Ancestors<'s, '_>, + request: &mut SourceRequest<'_, 's>, + budget: &B, ) -> Result<(), SourceError> { // bca: suppress(nexits) -- defer or reject before canonicalizing a complete run; every identity failure precedes the sink. - if !T::SOURCE_POSITIONAL_DOCS { + if !R::Checker::SOURCE_POSITIONAL_DOCS { return Ok(()); } request.context.node(comment.as_tree_sitter())?; let code = request.context.bytes(); - let Some(run) = doc_comment::positional_run::( + let Some(run) = doc_comment::positional_run_with_budget::( comment, code, ancestors, CandidateView::Source(request.context), - ) else { + budget, + ) + .map_err(Into::into)? + else { return Ok(()); }; - let collected = SourceMembers::collect(&run, ancestors, request.context); - let decision = SourceDecision::new::(&run, &collected, ancestors, request.context); + let collected = SourceMembers::collect(&run, ancestors, request.context, budget)?; + let decision = + SourceDecision::new::(&run, &collected, ancestors, request.context, budget) + .map_err(Into::into)?; if decision.selection == RunSelection::Unattached && !request.retain_unbound { return Ok(()); } - let members = source_members::(&collected, decision.selection, request)?; + let members = source_members::(&collected, decision.selection, request, budget)?; if !members.is_empty() { let canonical = |node: Node<'s>| request.context.node(node.as_tree_sitter()); (request.sink)(SourceRun { @@ -180,53 +196,70 @@ struct SourceMembers<'t> { } impl<'t> SourceMembers<'t> { - fn collect( + fn collect( run: &PositionalRun<'t>, ancestors: Ancestors<'t, '_>, source: &SourceContext<'t>, - ) -> Self { - let nodes = run.materialize(ancestors); + budget: &B, + ) -> Result { + let nodes = run + .materialize_with_budget(ancestors, budget) + .map_err(Into::into)?; let mut eligible_start = run.first_eligible.map_or(nodes.len(), |first| { nodes.partition_point(|node| node.start_byte() < first.start_byte()) }); - let prefix_placement_gap = run.prefix_gap - && nodes - .get(eligible_start) - .is_some_and(|first| !complete_row_prefix(first, source)); + let prefix_placement_gap = if run.prefix_gap + && let Some(first) = nodes.get(eligible_start) + { + !complete_row_prefix(first, source, budget).map_err(Into::into)? + } else { + false + }; if prefix_placement_gap { let mut connected_end_row = nodes[eligible_start].end_row(); while let Some(node) = nodes.get(eligible_start) && node.start_row() <= connected_end_row { + budget.step().map_err(Into::into)?; connected_end_row = connected_end_row.max(node.end_row()); eligible_start += 1; } } - Self { + Ok(Self { nodes, eligible_start, prefix_placement_gap, - } + }) } } -fn complete_row_prefix(first: &Node<'_>, source: &SourceContext<'_>) -> bool { +fn complete_row_prefix( + first: &Node<'_>, + source: &SourceContext<'_>, + budget: &B, +) -> Result { let start = first .start_byte() .saturating_sub(first.as_tree_sitter().start_position().column); - source.covers(start..first.start_byte()) - && source.bytes()[start..first.start_byte()] - .iter() - .all(u8::is_ascii_whitespace) + Ok( + source.covers_with_budget(start..first.start_byte(), budget)? + && crate::documentation::byte_scan::position( + &source.bytes()[start..first.start_byte()], + |byte| !byte.is_ascii_whitespace(), + budget, + )? + .is_none(), + ) } impl<'t> SourceDecision<'t> { - fn new( + fn new( run: &PositionalRun<'t>, collected: &SourceMembers<'t>, ancestors: Ancestors<'t, '_>, source: &SourceContext<'t>, - ) -> Self { + budget: &B, + ) -> Result { let mut decision = Self { selection: RunSelection::Unattached, target: None, @@ -234,14 +267,16 @@ impl<'t> SourceDecision<'t> { .then_some(UnresolvedReason::ExcludedGap), }; if run.end == RunEnd::ExcludedGap - || !source.covers(run.first.start_byte()..run.last.end_byte()) + || !source.covers_with_budget(run.first.start_byte()..run.last.end_byte(), budget)? { decision.uncertainty = Some(UnresolvedReason::ExcludedGap); - return decision; + return Ok(decision); + } + if let Some(node) = run.below + && R::target(&node, source.bytes(), ancestors, budget)? + { + decision.target = Some(node); } - decision.target = run - .below - .filter(|n| T::is_source_doc_target(n, source.bytes(), ancestors)); if decision.uncertainty.is_none() { decision.uncertainty = run .next @@ -249,7 +284,7 @@ impl<'t> SourceDecision<'t> { .map(|_| UnresolvedReason::GrammarBoundary); } if collected.eligible_start == collected.nodes.len() { - return decision; + return Ok(decision); } let context = RunContext { members: &collected.nodes[collected.eligible_start..], @@ -257,40 +292,47 @@ impl<'t> SourceDecision<'t> { code: source.bytes(), source: Some(source), }; - match T::source_doc_run_opener(&context, ancestors) { + match R::opener(&context, ancestors, budget)? { Ok(Some(reason)) => decision.selection = RunSelection::Opener(reason), - Ok(None) if T::SOURCE_POSITIONAL_TARGETS && decision.target.is_some() => { + Ok(None) if R::Checker::SOURCE_POSITIONAL_TARGETS && decision.target.is_some() => { decision.selection = RunSelection::FollowingTarget; } Ok(None) => {} Err(reason) => decision.uncertainty = Some(reason), } - decision + Ok(decision) } } -fn source_members<'s, T: Checker>( +fn source_members<'s, R: SourceRules, B: WorkBudget>( collected: &SourceMembers<'s>, selection: RunSelection, request: &SourceRequest<'_, 's>, + budget: &B, ) -> Result>, SourceError> { let mut members = Vec::new(); for (index, node) in collected.nodes.iter().enumerate() { + budget.step().map_err(Into::into)?; let ineligible = index < collected.eligible_start; if ineligible && !request.retain_unbound { continue; } - let directive = request.context.covers(node.start_byte()..node.end_byte()) - && T::is_doc_run_directive(node, request.context.bytes()); + let directive = request + .context + .covers_with_budget(node.start_byte()..node.end_byte(), budget) + .map_err(Into::into)? + && R::directive(node, request.context.bytes(), budget).map_err(Into::into)?; if directive && !request.retain_directives { continue; } evidence_built::record(); members.push(RunMember { node: request.context.node(node.as_tree_sitter())?, - source: request - .context - .pieces(node.start_byte()..spelling_end(request.context, node))?, + source: request.context.pieces_with_budget( + node.start_byte() + ..spelling_end(request.context, node, budget).map_err(Into::into)?, + budget, + )?, directive, selected: !ineligible && !directive && selection != RunSelection::Unattached, }); @@ -298,15 +340,20 @@ fn source_members<'s, T: Checker>( Ok(members) } -fn spelling_end(context: &SourceContext<'_>, node: &Node<'_>) -> usize { +fn spelling_end( + context: &SourceContext<'_>, + node: &Node<'_>, + budget: &B, +) -> Result { let bytes = doc_comment::node_bytes(node, context.bytes()); if bytes.starts_with(b"//") || bytes.starts_with(b"#") - || (bytes.starts_with(b"--") && !doc_comment::lua_long_comment(bytes)) + || (bytes.starts_with(b"--") + && !crate::lang_helpers::doc_text::lua_long_comment_with_budget(bytes, budget)?) { - super::markers::line_spelling_end(context, node) + super::markers::line_spelling_end(context, node, budget) } else { - node.end_byte() + Ok(node.end_byte()) } } diff --git a/big-code-analysis-ast/src/documentation/text.rs b/big-code-analysis-ast/src/documentation/text.rs index 6984a960f..c09e0d901 100644 --- a/big-code-analysis-ast/src/documentation/text.rs +++ b/big-code-analysis-ast/src/documentation/text.rs @@ -9,6 +9,8 @@ use super::{ }; pub(super) mod comments; +#[allow(dead_code)] +pub(super) mod literals; #[derive(Debug)] pub(super) enum TextError { @@ -41,6 +43,9 @@ impl<'s> TextBuilder<'s> { if pieces.has_excluded_gap() { return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); } + if pieces.pieces().len() > 1 { + return self.copied_pieces(pieces, budget); + } for piece in pieces.pieces() { budget.step().map_err(Into::into)?; let start = self.text.len(); @@ -50,6 +55,44 @@ impl<'s> TextBuilder<'s> { Ok(()) } + fn copied_pieces( + &mut self, + pieces: &SourcePieces<'s>, + budget: &B, + ) -> Result<(), TextError> { + let mut buffer = Vec::with_capacity(BYTE_INTERVAL); + let mut output = self.text.len(); + for piece in pieces.pieces() { + budget.step().map_err(Into::into)?; + for chunk in piece.bytes().chunks(BYTE_INTERVAL - 4) { + budget.checkpoint().map_err(Into::into)?; + budget.bytes(chunk.len()).map_err(Into::into)?; + buffer.extend_from_slice(chunk); + budget.checkpoint().map_err(Into::into)?; + budget.bytes(buffer.len()).map_err(Into::into)?; + let valid = match std::str::from_utf8(&buffer) { + Ok(text) => text.len(), + Err(error) if error.error_len().is_none() => error.valid_up_to(), + Err(_) => { + return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)); + } + }; + self.append_utf8(&buffer[..valid], budget)?; + buffer.drain(..valid); + } + let end = output + piece.bytes().len(); + self.mappings.push(Mapping { + output: TextRange::validated(output..end), + origin: Origin::Copied(SourcePieces::single(piece.clone())), + }); + output = end; + } + if !buffer.is_empty() { + return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)); + } + Ok(()) + } + pub(super) fn transformed( &mut self, text: &str, @@ -75,6 +118,12 @@ impl<'s> TextBuilder<'s> { } fn append_utf8(&mut self, bytes: &[u8], budget: &B) -> Result<(), TextError> { + super::budget::in_phase(budget, super::budget::WorkPhase::Text, || { + self.append_chunks(bytes, budget) + }) + } + + fn append_chunks(&mut self, bytes: &[u8], budget: &B) -> Result<(), TextError> { // bca: suppress(nexits, halstead) -- validation, scalar carry and copying each require a separate fallible checkpoint. let mut at = 0; while at < bytes.len() { diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs index e4be501a7..2da70394c 100644 --- a/big-code-analysis-ast/src/documentation/text/comments.rs +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -181,6 +181,7 @@ fn prepare( context: &SourceContext<'_>, fragment: &Fragment<'_>, budget: &B, + source_cleaned: bool, ) -> Result { if fragment.source.has_excluded_gap() { return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); @@ -194,7 +195,7 @@ fn prepare( }; let raw = first.range().start..last.range().end; let bytes = context.bytes(); - if profile == Profile::Javadoc { + if profile == Profile::Javadoc && !source_cleaned { for pair in bytes[raw.clone()].windows(2) { charge(budget)?; if pair == b"\\u" { @@ -280,17 +281,44 @@ pub(in crate::documentation) fn render<'s, B: WorkBudget>( context: &SourceContext<'s>, fragments: &[&Fragment<'s>], budget: &B, +) -> Result, TextError> { + render_local(profile, context, fragments, budget, false) +} + +pub(in crate::documentation) fn render_source_cleaned<'s, B: WorkBudget>( + profile: Profile, + context: &SourceContext<'s>, + fragments: &[&Fragment<'s>], + budget: &B, +) -> Result, TextError> { + render_local(profile, context, fragments, budget, true) +} + +fn render_local<'s, B: WorkBudget>( + profile: Profile, + context: &SourceContext<'s>, + fragments: &[&Fragment<'s>], + budget: &B, + source_cleaned: bool, ) -> Result, TextError> { let mut blocks = Vec::new(); for fragment in fragments { budget .step() .map_err(|error| TextError::Source(error.into()))?; - blocks.push(prepare(profile, context, fragment, budget)?); + blocks.push(prepare(profile, context, fragment, budget, source_cleaned)?); } if profile == Profile::Rust { for block in &mut blocks { beautify(block, context.bytes(), budget)?; + if block.lines.len() > 1 + && block + .lines + .last() + .is_some_and(|line| line.content.is_empty()) + { + block.lines.pop(); + } } } if profile == Profile::Rust || blocks.first().is_some_and(|block| block.markdown) { @@ -301,7 +329,11 @@ pub(in crate::documentation) fn render<'s, B: WorkBudget>( .step() .map_err(|error| TextError::Source(error.into()))?; let indent = margin(&context.bytes()[line.content.clone()], budget)?; - if indent < line.content.len() { + if !blank( + &context.bytes()[line.content.clone()], + profile == Profile::Rust, + budget, + )? { minimum = minimum.min(indent); } } @@ -312,8 +344,11 @@ pub(in crate::documentation) fn render<'s, B: WorkBudget>( budget .step() .map_err(|error| TextError::Source(error.into()))?; - let indent = margin(&context.bytes()[line.content.clone()], budget)?; - if indent < line.content.len() { + if !blank( + &context.bytes()[line.content.clone()], + profile == Profile::Rust, + budget, + )? { line.content.start += minimum; } } @@ -368,6 +403,41 @@ pub(in crate::documentation) fn render<'s, B: WorkBudget>( Ok(builder.finish()) } +fn blank(bytes: &[u8], unicode: bool, budget: &B) -> Result { + if !unicode { + return Ok(crate::documentation::byte_scan::position( + bytes, + |byte| !matches!(byte, b' ' | b'\t'), + budget, + ) + .map_err(|error| TextError::Source(error.into()))? + .is_none()); + } + let mut at = 0; + while at < bytes.len() { + let width = match bytes[at] { + 0..=0x7f => 1, + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)), + }; + budget + .bytes(width) + .map_err(|error| TextError::Source(error.into()))?; + let scalar = bytes + .get(at..at + width) + .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + let text = std::str::from_utf8(scalar) + .map_err(|_| TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + if text.chars().any(|character| !character.is_whitespace()) { + return Ok(false); + } + at += width; + } + Ok(true) +} + fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Result<(), TextError> { if block.lines.len() < 2 { return Ok(()); @@ -406,16 +476,10 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul start = 1; } } - while start < end - && margin(&bytes[block.lines[start].content.clone()], budget)? - == block.lines[start].content.len() - { + while start < end && blank(&bytes[block.lines[start].content.clone()], true, budget)? { start += 1; } - while end > start - && margin(&bytes[block.lines[end - 1].content.clone()], budget)? - == block.lines[end - 1].content.len() - { + while end > start && blank(&bytes[block.lines[end - 1].content.clone()], true, budget)? { end -= 1; } } diff --git a/big-code-analysis-ast/src/documentation/text/literals.rs b/big-code-analysis-ast/src/documentation/text/literals.rs new file mode 100644 index 000000000..b1282f0a1 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/literals.rs @@ -0,0 +1,308 @@ +//! Static literal projection interfaces for deferred language adapters. + +use super::{TextBuilder, TextError}; +use crate::documentation::budget::WorkBudget; +use crate::documentation::{Content, Origin, SourceContext, UnavailableReason}; +use std::ops::Range; + +#[derive(Clone, Copy)] +pub(super) enum LiteralPolicy { + PythonCooked, + Raw, + TclQuoted, + TclBraced, +} + +#[allow(clippy::too_many_lines)] +pub(super) fn decode<'s, B: WorkBudget>( + context: &SourceContext<'s>, + interior: Range, + policy: LiteralPolicy, + output: &mut TextBuilder<'s>, + budget: &B, +) -> Result<(), TextError> { + if !context + .covers_with_budget(interior.clone(), budget) + .map_err(|error| TextError::Source(error.into()))? + { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + } + let bytes = context.bytes(); + let mut at = interior.start; + let mut copied = at; + while at < interior.end { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + if matches!(policy, LiteralPolicy::TclQuoted) && matches!(bytes[at], b'$' | b'[') { + return Err(TextError::Unavailable(UnavailableReason::Dynamic)); + } + if bytes[at] != b'\\' || matches!(policy, LiteralPolicy::Raw) { + at += 1; + continue; + } + let next = bytes + .get(at + 1) + .copied() + .filter(|_| at + 1 < interior.end) + .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + if matches!(policy, LiteralPolicy::TclBraced) && !matches!(next, b'\n' | b'\r') { + at += 2; + continue; + } + output.source(context, copied..at, budget)?; + let start = at; + at += 2; + let scalar = match next { + b'\n' | b'\r' => { + if next == b'\r' && bytes.get(at) == Some(&b'\n') { + at += 1; + } + if matches!(policy, LiteralPolicy::TclQuoted | LiteralPolicy::TclBraced) { + while at < interior.end && matches!(bytes[at], b' ' | b'\t') { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + at += 1; + } + Some(' ') + } else { + None + } + } + b'n' => Some('\n'), + b'r' => Some('\r'), + b't' => Some('\t'), + b'a' => Some('\u{7}'), + b'b' => Some('\u{8}'), + b'f' => Some('\u{c}'), + b'v' => Some('\u{b}'), + b'\\' => Some('\\'), + b'\'' => Some('\''), + b'"' => Some('"'), + b'N' if matches!(policy, LiteralPolicy::PythonCooked) => { + return Err(TextError::Unavailable( + UnavailableReason::UnsupportedDecoding, + )); + } + b'x' | b'u' | b'U' => { + let width = match next { + b'x' => 2, + b'u' => 4, + _ => 8, + }; + let end = at + .checked_add(width) + .filter(|end| *end <= interior.end) + .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + let mut value = 0_u32; + for &digit in &bytes[at..end] { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + value = value + .checked_mul(16) + .and_then(|value| char::from(digit).to_digit(16).map(|digit| value + digit)) + .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + } + at = end; + Some( + char::from_u32(value) + .ok_or(TextError::Unavailable(UnavailableReason::NonScalar))?, + ) + } + b'0'..=b'7' => { + let mut value = u32::from(next - b'0'); + for _ in 0..2 { + if at >= interior.end || !matches!(bytes[at], b'0'..=b'7') { + break; + } + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + value = value * 8 + u32::from(bytes[at] - b'0'); + at += 1; + } + Some( + char::from_u32(value) + .ok_or(TextError::Unavailable(UnavailableReason::NonScalar))?, + ) + } + _ if matches!(policy, LiteralPolicy::PythonCooked) => { + output.source(context, start..at, budget)?; + None + } + _ => Some(char::from(next)), + }; + if let Some(scalar) = scalar { + let mut buffer = [0; 4]; + output.transformed( + scalar.encode_utf8(&mut buffer), + Origin::Decoded(context.pieces_with_budget(start..at, budget)?), + budget, + )?; + } + copied = at; + } + output.source(context, copied..interior.end, budget) +} + +pub(super) fn expand_tabs<'s, B: WorkBudget>( + context: &SourceContext<'s>, + interior: Range, + budget: &B, +) -> Result, TextError> { + if !context + .covers_with_budget(interior.clone(), budget) + .map_err(|error| TextError::Source(error.into()))? + { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + } + let mut output = TextBuilder::default(); + let mut start = interior.start; + let mut column = 0; + for at in interior.clone() { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + match context.bytes()[at] { + b'\t' => { + output.source(context, start..at, budget)?; + let count = 8 - column % 8; + output.transformed( + &" "[..count], + Origin::Expanded(context.pieces_with_budget(at..at + 1, budget)?), + budget, + )?; + column += count; + start = at + 1; + } + b'\n' | b'\r' => column = 0, + byte if byte & 0xc0 != 0x80 => column += 1, + _ => {} + } + } + output.source(context, start..interior.end, budget)?; + Ok(output.finish()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::similar_names)] + use super::*; + use crate::documentation::budget::NoBudget; + use crate::documentation::{CompleteText, OriginView}; + use crate::{AnyParser, LANG}; + + #[cfg(any(feature = "python", feature = "tcl"))] + fn view<'i, 's>(content: &'i Content<'s>) -> CompleteText<'i, 's> { + let Content::Complete { text, mappings } = content else { + panic!("complete text") + }; + CompleteText { text, mappings } + } + + #[cfg(feature = "python")] + #[test] + fn python_raw_concatenation_and_escape_origins_are_independent() { + let source = b"(\"@au\" # ordinary\n \"dit\\x40\")"; + let parser = AnyParser::parse(LANG::Python, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut builder = TextBuilder::default(); + decode(&context, 2..5, LiteralPolicy::Raw, &mut builder, &NoBudget).unwrap(); + decode( + &context, + 20..27, + LiteralPolicy::PythonCooked, + &mut builder, + &NoBudget, + ) + .unwrap(); + let content = builder.finish(); + let text = view(&content); + assert_eq!(text.text(), "@audit@"); + let pieces: Vec<_> = text.origins(0..7).unwrap().collect(); + assert_eq!(pieces.len(), 3); + let OriginView::Decoded(tokens) = &pieces[2].origin else { + panic!("decoded escape") + }; + assert_eq!(tokens[0].range(), 23..27); + } + + #[cfg(feature = "tcl")] + #[test] + fn tcl_quoted_and_braced_preambles_use_distinct_substitution_rules() { + for (source, policy, expected) in [ + ( + "{# Heading\\n detail}", + LiteralPolicy::TclBraced, + "# Heading\\n detail", + ), + ( + "\"# Heading\\n detail\"", + LiteralPolicy::TclQuoted, + "# Heading\n detail", + ), + ( + "{# $name [call]}", + LiteralPolicy::TclBraced, + "# $name [call]", + ), + ("{a\\\n b}", LiteralPolicy::TclBraced, "a b"), + ] { + let parser = + AnyParser::parse(LANG::Tcl, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut builder = TextBuilder::default(); + decode( + &context, + 1..source.len() - 1, + policy, + &mut builder, + &NoBudget, + ) + .unwrap(); + assert_eq!(view(&builder.finish()).text(), expected); + } + } + + #[cfg(feature = "python")] + #[test] + fn tab_expansion_maps_every_space_to_the_responsible_token() { + let source = b"\"a\tb\""; + let parser = AnyParser::parse(LANG::Python, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let content = expand_tabs(&context, 1..4, &NoBudget).unwrap(); + let text = view(&content); + assert_eq!(text.text(), "a b"); + let portion = text.origins(3..4).unwrap().next().unwrap(); + let OriginView::Expanded(pieces) = portion.origin else { + panic!("expanded tab") + }; + assert_eq!(pieces[0].range(), 2..3); + } + + #[cfg(feature = "bash")] + #[test] + fn bash_comment_projection_preserves_literal_backslash_newline() { + let source = b"# @description a\\\n# b\nf() { :; }"; + let parser = AnyParser::parse(LANG::Bash, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let mut output = TextBuilder::default(); + decode(&context, 2..18, LiteralPolicy::Raw, &mut output, &NoBudget).unwrap(); + let Content::Complete { text, .. } = output.finish() else { + panic!("raw projection") + }; + assert_eq!(text, "@description a\\\n"); + assert!(matches!( + parser.documentation( + &crate::documentation::DocumentationContext::default(), + &crate::documentation::DocumentationOptions::default() + ), + Err(crate::documentation::CollectionError::AdapterUnavailable { + language: LANG::Bash, + .. + }) + )); + } +} diff --git a/big-code-analysis-ast/src/documentation/text/tests.rs b/big-code-analysis-ast/src/documentation/text/tests.rs index 9bd750e53..fed049ab6 100644 --- a/big-code-analysis-ast/src/documentation/text/tests.rs +++ b/big-code-analysis-ast/src/documentation/text/tests.rs @@ -143,7 +143,7 @@ fn comment_cleanup_preserves_markup_hard_breaks_and_phase_two_splices() { (Profile::Javadoc, "/**/", ""), (Profile::Javadoc, "////", "/"), (Profile::Rust, "/*!*/", ""), - (Profile::Rust, "/**\n * a \n * b\n */", "a \n b\n"), + (Profile::Rust, "/**\n * a \n * b\n */", "a \n b"), (Profile::GoDoc, "/* a\n * b */", "a\n * b"), (Profile::Doxygen, "///a\\\nb", "ab"), (Profile::Doxygen, "/**a\\\r\nb*/", "ab"), @@ -175,3 +175,75 @@ fn comment_cleanup_preserves_markup_hard_breaks_and_phase_two_splices() { assert_eq!(offset, expected.len()); } } + +#[cfg(feature = "rust")] +#[test] +fn copied_utf8_scalar_can_cross_adjacent_included_pieces() { + let source = "é".as_bytes(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser + .set_included_ranges(&[ + tree_sitter::Range { + start_byte: 0, + end_byte: 1, + start_point: tree_sitter::Point::new(0, 0), + end_point: tree_sitter::Point::new(0, 1), + }, + tree_sitter::Range { + start_byte: 1, + end_byte: 2, + start_point: tree_sitter::Point::new(0, 1), + end_point: tree_sitter::Point::new(0, 2), + }, + ]) + .unwrap(); + let tree = parser.parse(source, None).unwrap(); + let context = SourceContext::new(&tree, source); + let pieces = context.pieces(0..2).unwrap(); + assert_eq!(pieces.pieces().len(), 2); + let mut builder = TextBuilder::default(); + builder.copied(&pieces, &NoBudget).unwrap(); + let content = builder.finish(); + let view = complete(&content); + assert_eq!(view.text(), "é"); + let portions: Vec<_> = view.origins(0..2).unwrap().collect(); + assert_eq!(portions.len(), 2); + for (portion, expected) in portions.iter().zip([0..1, 1..2]) { + let OriginView::Copied(piece) = &portion.origin else { + panic!("copied piece") + }; + assert_eq!(piece.range(), expected); + assert_eq!(portion.output, expected); + } + assert_eq!( + view.origins(0..1).unwrap_err(), + TextRangeError::ScalarBoundary + ); +} + +#[cfg(feature = "rust")] +#[test] +fn rust_cleanup_keeps_unicode_blank_lines_and_removes_only_assembly_newline() { + for (source, expected) in [ + ("/**\n * a \n * b\n */\nfn f() {}", "a \n b"), + ("/// a\n///\u{a0}\n/// b\nfn f() {}", "a\n\u{a0}\n b"), + ("/**a /* nested */ b*/\nfn f() {}", "a /* nested */ b"), + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &crate::documentation::DocumentationContext::default(), + &crate::documentation::DocumentationOptions::default(), + ) + .unwrap(); + let document = index.documents().next().unwrap(); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + expected, + "{source}" + ); + } +} diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 66a6afe48..24fc639b6 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -6,10 +6,12 @@ pub(crate) use super::doc_text::{ csharp_doc, doxygen, go_directive, java_doc, javadoc_block, jsdoc_virtual, kotlin_doc, - ldoc_opener, lua_long_comment, phpdoc, pod_comment_region, ruby_directive_opener, - ruby_magic_comment, tsdoc_block, tsdoc_module, + lua_long_comment, phpdoc, pod_comment_region, ruby_directive_opener, ruby_magic_comment, + tsdoc_block, tsdoc_module, }; use crate::checker::Checker; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::documentation::recognition::{PublicRules, SourceRules, source_target}; use crate::documentation::streaming::markers::CandidateView; use crate::node::{Ancestors, FoldLane, Node}; @@ -178,7 +180,20 @@ pub(crate) fn outside_function_bodies<'a, T: Checker>( code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - !held_in_body::(comment, code, 0, ancestors) + infallible(outside_function_bodies_with_budget::( + comment, code, ancestors, &NoBudget, + )) +} + +pub(crate) fn outside_function_bodies_with_budget<'a, T: Checker, B: WorkBudget>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + Ok(!held_in_body_with_budget::( + comment, code, 0, ancestors, budget, + )?) } /// Whether an ancestor of `node`, past the `skip` nearest ones, holds it @@ -192,15 +207,30 @@ fn held_in_body<'a, T: Checker>( skip: usize, ancestors: Ancestors<'a, '_>, ) -> bool { - ancestors.fold_down( + infallible(held_in_body_with_budget::( + node, code, skip, ancestors, &NoBudget, + )) +} + +fn held_in_body_with_budget<'a, T: Checker, B: WorkBudget>( + node: &Node<'a>, + code: &[u8], + skip: usize, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + Ok(ancestors.fold_down_with_budget( node, skip, FoldLane::DocInBody, 0, |held, ancestor, outer, below| { - u8::from(held != 0 || T::holds_doc_comment_in_body(ancestor, code, outer, below)) + Ok(u8::from( + held != 0 || T::holds_doc_comment_in_body(ancestor, code, outer, below), + )) }, - ) != 0 + budget, + )? != 0) } // --------------------------------------------------------------------- @@ -373,6 +403,24 @@ pub(crate) fn select_bound<'a, T: Checker>( boundaries: StretchBounds<'a>, forward: impl Fn(&Node<'a>) -> bool, ) -> BoundSelection<'a> { + infallible(select_bound_with_budget::( + stretch, + code, + kept, + boundaries, + |node| Ok(forward(node)), + &NoBudget, + )) +} + +pub(crate) fn select_bound_with_budget<'a, T: Checker, B: WorkBudget>( + stretch: &[Node<'a>], + code: &[u8], + kept: KeptDocs, + boundaries: StretchBounds<'a>, + forward: impl Fn(&Node<'a>) -> Result, + budget: &B, +) -> Result, B::Error> { let StretchBounds { code_before, next, @@ -386,15 +434,26 @@ pub(crate) fn select_bound<'a, T: Checker>( next, }; selection.nodes = match kept { - KeptDocs::All => stretch.iter().copied().filter(forward).collect(), + KeptDocs::All => { + let mut nodes = Vec::new(); + for node in stretch { + budget.step()?; + if forward(node)? { + nodes.push(*node); + } + } + nodes + } KeptDocs::Last { joins } => { - let (nodes, eligible_end) = bind_last::(stretch, code, joins, forward); + let (nodes, eligible_end) = bind_last::(stretch, code, joins, forward, budget)?; selection.eligible_end = eligible_end; nodes } - KeptDocs::Nearest { hidden } => bind_nearest::(stretch, next, hidden, forward) - .into_iter() - .collect(), + KeptDocs::Nearest { hidden } => { + bind_nearest::(stretch, next, hidden, forward, budget)? + .into_iter() + .collect() + } KeptDocs::Leading { hidden, joins, @@ -407,13 +466,14 @@ pub(crate) fn select_bound<'a, T: Checker>( .filter(|_| !after_code(&target)) .map(|before| before.end_row()); let attaches = - |n: &Node<'a>| forward(n) && Some(n.start_row()) != selection.after_code_row; - let (nodes, eligible_end) = bind_leading::(stretch, code, hidden, joins, attaches); + |n: &Node<'a>| Ok(forward(n)? && Some(n.start_row()) != selection.after_code_row); + let (nodes, eligible_end) = + bind_leading::(stretch, code, hidden, joins, attaches, budget)?; selection.eligible_end = eligible_end; nodes } }; - selection + Ok(selection) } /// Where a stretch of comments ends, asked of its last comment. @@ -447,52 +507,88 @@ pub(crate) fn stretch_end<'a, T: Checker>( skips: for<'b> fn(&Node<'a>, Ancestors<'a, 'b>) -> bool, view: CandidateView, ) -> StretchEnd<'a> { - let mut after = ancestors.siblings_after(comment).peekable(); + infallible(stretch_end_with_budget::, _>( + comment, + code, + ancestors, + |node, ancestors| Ok(skips(node, ancestors)), + view, + &NoBudget, + )) +} + +pub(crate) fn stretch_end_with_budget<'a, R: SourceRules, B: WorkBudget>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + skips: impl Fn(&Node<'a>, Ancestors<'a, '_>) -> Result, + view: CandidateView<'_>, + budget: &B, +) -> Result, B::Error> { + let mut after = ancestors + .siblings_after_with_budget(comment, budget)? + .peekable(); let Some(&next) = after.peek() else { - return if view.covers(comment.start_byte()..comment.end_byte()) { - exhausted_stretch(comment, comment.end_byte(), code, ancestors, view) - } else { - StretchEnd::ExcludedGap - }; + return Ok( + if view.covers_with_budget(comment.start_byte()..comment.end_byte(), budget)? { + exhausted_stretch(comment, comment.end_byte(), code, ancestors, view, budget)? + } else { + StretchEnd::ExcludedGap + }, + ); }; let mut boundary = comment.start_byte(); let mut continuous = true; - let target = after.find(|n| { - continuous = view.covers(boundary..n.end_byte()); + let mut target = None; + for n in after { + budget.step()?; + continuous = view.covers_with_budget(boundary..n.end_byte(), budget)?; boundary = n.end_byte(); - !continuous || (!skips(n, ancestors) && !read_past_error_in::(n, code, ancestors, view)) - }); + if !continuous + || (!skips(&n, ancestors)? + && !read_past_error_with_budget::(&n, code, ancestors, view, budget)?) + { + target = Some(n); + break; + } + } if !continuous { - return StretchEnd::ExcludedGap; + return Ok(StretchEnd::ExcludedGap); } - match target { - Some(target) if T::is_comment(&target) => StretchEnd::Undecided, + Ok(match target { + Some(target) if R::Checker::is_comment(&target) => StretchEnd::Undecided, Some(target) - if view.target::(&target, code, ancestors) + if source_target::(view, &target, code, ancestors, budget)? || (target.is_error() - && error_holds_target_in::(&target, code, ancestors, view)) => + && error_holds_target_with_budget::( + &target, code, ancestors, view, budget, + )?) => { StretchEnd::AtTarget { next, target } } - None => exhausted_stretch(comment, boundary, code, ancestors, view), + None => exhausted_stretch(comment, boundary, code, ancestors, view, budget)?, _ => StretchEnd::Elsewhere, - } + }) } -fn exhausted_stretch<'a>( +fn exhausted_stretch<'a, B: WorkBudget>( comment: &Node<'a>, last_examined_end: usize, code: &[u8], ancestors: Ancestors<'a, '_>, view: CandidateView<'_>, -) -> StretchEnd<'a> { - if suffix_gap(comment, last_examined_end, code, ancestors, view) { - StretchEnd::SuffixGap - } else { - StretchEnd::Elsewhere - } + budget: &B, +) -> Result, B::Error> { + Ok( + if suffix_gap_with_budget(comment, last_examined_end, code, ancestors, view, budget)? { + StretchEnd::SuffixGap + } else { + StretchEnd::Elsewhere + }, + ) } +#[cfg(all(test, feature = "rust"))] fn suffix_gap<'a>( comment: &Node<'a>, last_examined_end: usize, @@ -500,11 +596,29 @@ fn suffix_gap<'a>( ancestors: Ancestors<'a, '_>, view: CandidateView<'_>, ) -> bool { + infallible(suffix_gap_with_budget( + comment, + last_examined_end, + code, + ancestors, + view, + &NoBudget, + )) +} + +fn suffix_gap_with_budget<'a, B: WorkBudget>( + comment: &Node<'a>, + last_examined_end: usize, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, + budget: &B, +) -> Result { if matches!(view, CandidateView::Legacy) { - return false; + return Ok(false); } let scope_end = source_scope_bounds(comment, code, ancestors).end; - !view.covers(last_examined_end..scope_end) + Ok(!view.covers_with_budget(last_examined_end..scope_end, budget)?) } // The caller's chain is authoritative, including an explicitly empty one. @@ -547,6 +661,24 @@ pub(crate) fn collect_stretch<'a, T: Checker>( skips: for<'b> fn(&Node<'a>, Ancestors<'a, 'b>) -> bool, view: CandidateView, ) -> CollectedStretch<'a> { + infallible(collect_stretch_with_budget::, _>( + comment, + code, + ancestors, + |node, ancestors| Ok(skips(node, ancestors)), + view, + &NoBudget, + )) +} + +pub(crate) fn collect_stretch_with_budget<'a, R: SourceRules, B: WorkBudget>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + skips: impl Fn(&Node<'a>, Ancestors<'a, '_>) -> Result, + view: CandidateView<'_>, + budget: &B, +) -> Result, B::Error> { stretches_collected::record(); let mut stretch = vec![*comment]; let mut before = None; @@ -557,16 +689,17 @@ pub(crate) fn collect_stretch<'a, T: Checker>( // the last doc comment before the first token (tsc's, JSDoc's, // javac's) would read the error as that token and keep the comment // above it instead of the one the tool attaches. - for sibling in ancestors.siblings_before(comment) { - if !view.covers(sibling.start_byte()..boundary) { + for sibling in ancestors.siblings_before_with_budget(comment, budget)? { + budget.step()?; + if !view.covers_with_budget(sibling.start_byte()..boundary, budget)? { prefix_gap = true; break; } boundary = sibling.start_byte(); - if read_past_error_in::(&sibling, code, ancestors, view) { + if read_past_error_with_budget::(&sibling, code, ancestors, view, budget)? { continue; } - if T::is_comment(&sibling) || skips(&sibling, ancestors) { + if R::Checker::is_comment(&sibling) || skips(&sibling, ancestors)? { stretch.push(sibling); } else { before = Some(sibling); @@ -575,14 +708,14 @@ pub(crate) fn collect_stretch<'a, T: Checker>( } if matches!(view, CandidateView::Source(_)) && before.is_none() && !prefix_gap { let start = source_scope_bounds(comment, code, ancestors).start; - prefix_gap = !view.covers(start..boundary); + prefix_gap = !view.covers_with_budget(start..boundary, budget)?; } - stretch.reverse(); - CollectedStretch { + crate::documentation::budget::reverse(&mut stretch, budget)?; + Ok(CollectedStretch { members: stretch, code_before: before, prefix_gap, - } + }) } /// Whether a stretch reads past `node`: a parse error that is no doc @@ -591,15 +724,28 @@ pub(crate) fn collect_stretch<'a, T: Checker>( /// error between the item's doc comment and the rest of it. Given the /// benefit of the doubt, as Doxygen's binding gives one (`doxygen_skips`), /// rather than dropping the doc comment on a parse failure. +#[cfg(all(test, feature = "c"))] fn read_past_error_in<'a, T: Checker>( node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, view: CandidateView, ) -> bool { - node.is_error() - && !view.target::(node, code, ancestors) - && !error_holds_target_in::(node, code, ancestors, view) + infallible(read_past_error_with_budget::, _>( + node, code, ancestors, view, &NoBudget, + )) +} + +fn read_past_error_with_budget<'a, R: SourceRules, B: WorkBudget>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, + budget: &B, +) -> Result { + Ok(node.is_error() + && !source_target::(view, node, code, ancestors, budget)? + && !error_holds_target_with_budget::(node, code, ancestors, view, budget)?) } /// Whether a child of the parse error `error` is a doc target: a @@ -612,17 +758,34 @@ fn read_past_error_in<'a, T: Checker>( /// chain the children are judged with none, which a target test that /// climbs pays for at `O(depth)`; every production walk lends one, so /// only a test reaches that fallback. +#[cfg(all(test, feature = "java"))] fn error_holds_target_in<'a, T: Checker>( error: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, view: CandidateView, ) -> bool { + infallible(error_holds_target_with_budget::, _>( + error, code, ancestors, view, &NoBudget, + )) +} + +fn error_holds_target_with_budget<'a, R: SourceRules, B: WorkBudget>( + error: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, + budget: &B, +) -> Result { let under = ancestors.of_children(error); let inside = under.get(); - error - .children() - .any(|child| child.is_named() && view.target::(&child, code, inside)) + for child in error.children() { + budget.step()?; + if child.is_named() && source_target::(view, &child, code, inside, budget)? { + return Ok(true); + } + } + Ok(false) } // Output alone cannot reveal repeated prefix collection or rejected-path work. @@ -651,14 +814,38 @@ pub(crate) fn bind_gathered<'a>( marker: impl Fn(&Node<'a>) -> bool, forward: impl Fn(&Node<'a>) -> bool, ) -> Gathered<'a> { - let Some(gatherer) = stretch.iter().rposition(|n| { + infallible(bind_gathered_with_budget( + stretch, + code, + |node| Ok(gathers(node, code)), + |node| Ok(marker(node)), + |node| Ok(forward(node)), + &NoBudget, + )) +} + +pub(crate) fn bind_gathered_with_budget<'a, B: WorkBudget>( + stretch: &[Node<'a>], + code: &[u8], + gathers: impl Fn(&Node<'a>) -> Result, + marker: impl Fn(&Node<'a>) -> Result, + forward: impl Fn(&Node<'a>) -> Result, + budget: &B, +) -> Result, B::Error> { + let mut gatherer = None; + for (at, n) in stretch.iter().enumerate().rev() { + budget.step()?; gatherer_probes::record(); - marker(n) && gathers(n, code) - }) else { - return Gathered { + if marker(n)? && gathers(n)? { + gatherer = Some(at); + break; + } + } + let Some(gatherer) = gatherer else { + return Ok(Gathered { kept: Vec::new(), gatherer: None, - }; + }); }; let line = |n: &Node| node_bytes(n, code).starts_with(b"//"); // Only a line-comment gatherer reads the line doc comments below it @@ -668,103 +855,157 @@ pub(crate) fn bind_gathered<'a>( while let Some(below) = stretch.get(last + 1) && gathers_below && line(below) - && marker(below) + && marker(below)? && below.start_row() == stretch[last].end_row().saturating_add(1) { + budget.step()?; last += 1; } - Gathered { - kept: stretch[..=last].iter().copied().filter(forward).collect(), - gatherer: Some(stretch[gatherer]), + let mut kept = Vec::new(); + for node in &stretch[..=last] { + budget.step()?; + if forward(node)? { + kept.push(*node); + } } + Ok(Gathered { + kept, + gatherer: Some(stretch[gatherer]), + }) } /// [`KeptDocs::Last`] over a stretch in source order: the last doc /// comment before the first skipped node — the declaration's first token — /// with the doc comments it joins, or else the first doc comment after it. -fn bind_last<'a, T: Checker>( +fn bind_last<'a, T: Checker, B: WorkBudget>( stretch: &[Node<'a>], code: &[u8], joins: fn(&Node, &Node, &[u8]) -> bool, - forward: impl Fn(&Node<'a>) -> bool, -) -> (Vec>, usize) { - let split = stretch - .iter() - .position(|n| !T::is_comment(n)) - .unwrap_or(stretch.len()); + forward: impl Fn(&Node<'a>) -> Result, + budget: &B, +) -> Result<(Vec>, usize), B::Error> { + let mut split = stretch.len(); + for (at, n) in stretch.iter().enumerate() { + budget.step()?; + if !T::is_comment(n) { + split = at; + break; + } + } let (before, after) = stretch.split_at(split); - let Some(last) = before.iter().rposition(&forward) else { - return ( - after.iter().copied().find(forward).into_iter().collect(), - stretch.len(), - ); + let mut last = None; + for (at, node) in before.iter().enumerate().rev() { + budget.step()?; + if forward(node)? { + last = Some(at); + break; + } + } + let Some(last) = last else { + let mut found = Vec::new(); + for node in after { + budget.step()?; + if forward(node)? { + found.push(*node); + break; + } + } + return Ok((found, stretch.len())); }; - (joined_run(before, last, code, joins, forward), split) + Ok(( + joined_run(before, last, code, joins, forward, budget)?, + split, + )) } /// [`KeptDocs::Leading`] over a stretch in source order: the members /// before the first token, read back past the hidden ones to the nearest /// other one, kept if it is a doc comment that binds forward, with the doc /// comments directly before it that it joins. -fn bind_leading<'a, T: Checker>( +fn bind_leading<'a, T: Checker, B: WorkBudget>( stretch: &[Node<'a>], code: &[u8], hidden: fn(&Node, &[u8]) -> bool, joins: fn(&Node, &Node, &[u8]) -> bool, - forward: impl Fn(&Node<'a>) -> bool, -) -> (Vec>, usize) { - let first_token = stretch - .iter() - .position(|n| !T::is_comment(n) && !hidden(n, code)) - .unwrap_or(stretch.len()); + forward: impl Fn(&Node<'a>) -> Result, + budget: &B, +) -> Result<(Vec>, usize), B::Error> { + let mut first_token = stretch.len(); + for (at, n) in stretch.iter().enumerate() { + budget.step()?; + if !T::is_comment(n) && !hidden(n, code) { + first_token = at; + break; + } + } let before = &stretch[..first_token]; - let Some(last) = before.iter().rposition(|n| !hidden(n, code)) else { - return (Vec::new(), first_token); + let mut last = None; + for (at, n) in before.iter().enumerate().rev() { + budget.step()?; + if !hidden(n, code) { + last = Some(at); + break; + } + } + let Some(last) = last else { + return Ok((Vec::new(), first_token)); }; - if !forward(&before[last]) { - return (Vec::new(), first_token); + if !forward(&before[last])? { + return Ok((Vec::new(), first_token)); } - (joined_run(before, last, code, joins, forward), first_token) + Ok(( + joined_run(before, last, code, joins, forward, budget)?, + first_token, + )) } /// `before[last]` with the doc comments directly before it that it /// joins, in source order. `joins` is asked first: for a binding whose /// `joins` is [`never_joins`] it answers at once, where `forward` /// would scan the comment's bytes for nothing. -fn joined_run<'a>( +fn joined_run<'a, B: WorkBudget>( before: &[Node<'a>], last: usize, code: &[u8], joins: fn(&Node, &Node, &[u8]) -> bool, - forward: impl Fn(&Node<'a>) -> bool, -) -> Vec> { + forward: impl Fn(&Node<'a>) -> Result, + budget: &B, +) -> Result>, B::Error> { let mut first = last; while first > 0 && joins(&before[first - 1], &before[first], code) - && forward(&before[first - 1]) + && forward(&before[first - 1])? { + budget.step()?; first -= 1; } - before[first..=last].to_vec() + let mut nodes = Vec::new(); + for node in &before[first..=last] { + budget.step()?; + nodes.push(*node); + } + Ok(nodes) } /// [`KeptDocs::Nearest`] over a stretch in source order whose last /// member `next` follows: the comment nearest the declaration that the /// tool can see, if it is a doc comment. -fn bind_nearest<'a, T: Checker>( +fn bind_nearest<'a, T: Checker, B: WorkBudget>( stretch: &[Node<'a>], next: Node<'a>, hidden: fn(&Node, &Node) -> bool, - forward: impl Fn(&Node<'a>) -> bool, -) -> Option> { + forward: impl Fn(&Node<'a>) -> Result, + budget: &B, +) -> Result>, B::Error> { let mut later = next; for member in stretch.iter().rev() { + budget.step()?; if T::is_comment(member) && !hidden(member, &later) { - return Some(*member).filter(forward); + return Ok(forward(member)?.then_some(*member)); } later = *member; } - None + Ok(None) } /// Credits the rows of the comment run that `comment` ends, when the @@ -820,11 +1061,16 @@ pub fn leading_doc_run<'a, T: Checker>( /// one: asked about a code node, it reports that the comment on the row /// below continues the code's run, which once let a backward scan run /// to the top of the file for every LDoc block (#1597). -pub(crate) fn run_continues_to(comment: &Node, next: &Node, code: &[u8]) -> bool { - T::is_comment(next) +pub(crate) fn run_continues_with_budget( + comment: &Node, + next: &Node, + code: &[u8], + budget: &B, +) -> Result { + Ok(R::Checker::is_comment(next) && (next.start_row() <= comment.end_row() || (next.start_row() == comment.end_row().saturating_add(1) - && !T::ends_doc_run(comment, code))) + && !R::ends(comment, code, budget)?))) } /// Constant-sized boundaries from the completed positional run. Members stream @@ -842,13 +1088,22 @@ pub(crate) struct PositionalRun<'a> { } impl<'a> PositionalRun<'a> { - pub(crate) fn materialize(&self, ancestors: Ancestors<'a, '_>) -> Vec> { + pub(crate) fn materialize_with_budget( + &self, + ancestors: Ancestors<'a, '_>, + budget: &B, + ) -> Result>, B::Error> { let mut members = Vec::new(); - for member in self.members_from(self.first, ancestors) { + let after = ancestors.siblings_after_with_budget(&self.first, budget)?; + for member in std::iter::once(self.first) + .chain(after) + .take_while(|member| member.start_byte() <= self.last.start_byte()) + { + budget.step()?; members_materialized::record(); members.push(member); } - members + Ok(members) } pub(crate) fn members_from<'c>( @@ -883,17 +1138,42 @@ pub(crate) fn positional_run<'a, T: Checker>( ancestors: Ancestors<'a, '_>, view: CandidateView<'_>, ) -> Option> { + infallible(positional_run_with_budget::, _>( + comment, code, ancestors, view, &NoBudget, + )) +} + +pub(crate) fn positional_run_with_budget<'a, R: SourceRules, B: WorkBudget>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + view: CandidateView<'_>, + budget: &B, +) -> Result>, B::Error> { use crate::documentation::streaming::positional::RunEnd; - let next = ancestors.siblings_after(comment).next(); - let continuous = - view.covers(comment.start_byte()..next.map_or(comment.end_byte(), |n| n.end_byte())); - if continuous && next.is_some_and(|n| run_continues_to::(comment, &n, code)) { - return None; + let next = ancestors + .siblings_after_with_budget(comment, budget)? + .next(); + let continuous = view.covers_with_budget( + comment.start_byte()..next.map_or(comment.end_byte(), |n| n.end_byte()), + budget, + )?; + if continuous + && let Some(next) = next + && run_continues_with_budget::(comment, &next, code, budget)? + { + return Ok(None); } - let below = next.filter(|n| T::doc_target_start_row(n) == comment.end_row().saturating_add(1)); + let below = if let Some(next) = next + && R::start_row(&next, budget)? == comment.end_row().saturating_add(1) + { + Some(next) + } else { + None + }; let end = if !continuous { RunEnd::ExcludedGap - } else if T::ends_doc_run(comment, code) { + } else if R::ends(comment, code, budget)? { RunEnd::Terminator } else if next.is_none() { RunEnd::EndOfScope @@ -902,21 +1182,22 @@ pub(crate) fn positional_run<'a, T: Checker>( } else { RunEnd::Token }; - let mut run = collect_positional_prefix::(comment, code, ancestors, view); + let mut run = collect_positional_prefix::(comment, code, ancestors, view, budget)?; run.next = next; run.below = below.filter(|_| continuous); - run.suffix_gap = - next.is_none() && suffix_gap(comment, comment.end_byte(), code, ancestors, view); + run.suffix_gap = next.is_none() + && suffix_gap_with_budget(comment, comment.end_byte(), code, ancestors, view, budget)?; run.end = end; - Some(run) + Ok(Some(run)) } -fn collect_positional_prefix<'a, T: Checker>( +fn collect_positional_prefix<'a, R: SourceRules, B: WorkBudget>( comment: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, view: CandidateView<'_>, -) -> PositionalRun<'a> { + budget: &B, +) -> Result, B::Error> { // bca: suppress(cognitive, halstead) -- one reverse state machine preserves clean rows, same-row comments, trailing rows and excluded boundaries. positional_runs_collected::record(); let mut run = PositionalRun { @@ -933,14 +1214,15 @@ fn collect_positional_prefix<'a, T: Checker>( let mut clean_first = None; let mut row_first = *comment; let mut stopped = false; - for prev in ancestors.siblings_before(comment) { + for prev in ancestors.siblings_before_with_budget(comment, budget)? { + budget.step()?; positional_predecessors::record(); - if !view.covers(prev.start_byte()..row_first.end_byte()) { + if !view.covers_with_budget(prev.start_byte()..row_first.end_byte(), budget)? { run.prefix_gap = true; stopped = true; break; } - if !T::is_comment(&prev) { + if !R::Checker::is_comment(&prev) { run.code_before = Some(prev); if prev.end_row() >= row_first.start_row() { run.first_eligible = clean_first; @@ -948,7 +1230,7 @@ fn collect_positional_prefix<'a, T: Checker>( stopped = true; break; } - if !run_continues_to::(&prev, &row_first, code) { + if !run_continues_with_budget::(&prev, &row_first, code, budget)? { run.code_before = Some(prev); stopped = true; break; @@ -961,10 +1243,10 @@ fn collect_positional_prefix<'a, T: Checker>( } if !stopped && matches!(view, CandidateView::Source(_)) { let start = source_scope_bounds(comment, code, ancestors).start; - run.prefix_gap = !view.covers(start..row_first.start_byte()); + run.prefix_gap = !view.covers_with_budget(start..row_first.start_byte(), budget)?; } run.first = row_first; - run + Ok(run) } /// The trailing comment that heads `first`'s LDoc group, when `first` sits @@ -974,17 +1256,6 @@ fn collect_positional_prefix<'a, T: Checker>( /// a `---` row under `x = 1 -- note` belongs to that `--` group. The run /// `leading_doc_run` hands over leaves such a comment out, as go/doc does, /// so it is looked up here. -pub(crate) fn lua_group_head_above<'a, T: Checker>( - first: &Node<'a>, - code: &[u8], - ancestors: Ancestors<'a, '_>, -) -> Option> { - ancestors - .siblings_before(first) - .next() - .filter(|above| T::is_comment(above) && run_continues_to::(above, first, code)) -} - #[cfg(test)] mod tests { use super::*; diff --git a/big-code-analysis-ast/src/lang_helpers/doc_text.rs b/big-code-analysis-ast/src/lang_helpers/doc_text.rs index 543885227..e417d3b5b 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_text.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_text.rs @@ -25,6 +25,9 @@ //! comments they accept document, and what, is the binding walk's //! question in [`super::doc_comment`] (#1649). +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::documentation::byte_scan as scan; + /// `/**` opened by a byte that is neither `*` nor `/`: the Javadoc / /// JSDoc / Doxygen block form. Rejects the empty `/**/` and the banner /// `/***`, as JSDoc ("more than 3 stars will be ignored"), Doxygen @@ -101,10 +104,10 @@ pub(crate) fn csharp_doc(s: &[u8]) -> bool { /// A doc comment's line with the delimiters JSDoc's `unwrap` strips: the /// indent, one leading `*` and the space after it. -fn jsdoc_line(line: &[u8]) -> &[u8] { - let line = line.trim_ascii_start(); +fn jsdoc_line<'s, B: WorkBudget>(line: &'s [u8], budget: &B) -> Result<&'s [u8], B::Error> { + let line = scan::trim_start(line, budget)?; let line = line.strip_prefix(b"*").unwrap_or(line); - line.strip_prefix(b" ").unwrap_or(line) + Ok(line.strip_prefix(b" ").unwrap_or(line)) } /// The lines of a `/** … */` body, delimiters and the extra stars at @@ -112,48 +115,66 @@ fn jsdoc_line(line: &[u8]) -> &[u8] { /// ([`jsdoc_line`]). `Clone`, so a tag's text — every line up to the next /// tag, as JSDoc's `toTags` reads it — can be read in place from the line /// that opened it. -fn jsdoc_lines(s: &[u8]) -> impl Iterator + Clone { +fn jsdoc_lines<'s, 'b, B: WorkBudget>( + s: &'s [u8], + budget: &'b B, +) -> Result> + Clone + use<'s, 'b, B>, B::Error> { let body = s.strip_prefix(b"/**").unwrap_or(s); let body = body.strip_suffix(b"*/").unwrap_or(body); - let start = body.iter().position(|&b| b != b'*').unwrap_or(body.len()); - let end = body - .iter() - .rposition(|&b| b != b'*') - .map_or(start, |at| at + 1); - body[start..end].split(|&b| b == b'\n').map(jsdoc_line) + let start = scan::position(body, |b| b != b'*', budget)?.unwrap_or(body.len()); + let end = scan::rposition(body, |b| b != b'*', budget)?.map_or(start, |at| at + 1); + Ok(scan::lines(&body[start..end], budget).map(move |line| jsdoc_line(line?, budget))) } /// The `(title, text)` a line opens when it starts a tag. -fn jsdoc_tag_open(line: &[u8]) -> Option<(&[u8], &[u8])> { - let tag = line.trim_ascii_start().strip_prefix(b"@")?; - let title = tag.iter().take_while(|b| !b.is_ascii_whitespace()).count(); - (title > 0).then(|| tag.split_at(title)) +#[allow(clippy::type_complexity)] +fn jsdoc_tag_open<'s, B: WorkBudget>( + line: &'s [u8], + budget: &B, +) -> Result, B::Error> { + let Some(tag) = scan::trim_start(line, budget)?.strip_prefix(b"@") else { + return Ok(None); + }; + let title = + scan::position(tag, |byte| byte.is_ascii_whitespace(), budget)?.unwrap_or(tag.len()); + Ok((title > 0).then(|| tag.split_at(title))) } /// Whether a JSDoc tag's text names a symbol: anything left once the /// `{type}` that may lead it is set aside. -fn jsdoc_names<'a>(lines: impl IntoIterator) -> bool { +fn jsdoc_names<'a, B: WorkBudget>( + lines: impl IntoIterator>, + budget: &B, +) -> Result { // The lines joined, read once without joining them: a `{type}` is // skipped by brace depth, and anything non-blank after it names. - let mut bytes = lines - .into_iter() - .flat_map(|line| line.iter().copied()) - .skip_while(u8::is_ascii_whitespace) - .peekable(); - if bytes.peek() == Some(&b'{') { - let mut depth = 0_usize; - for b in bytes.by_ref() { - match b { - b'{' => depth += 1, - b'}' => depth -= 1, - _ => {} + let mut leading = true; + let mut depth = 0_usize; + for line in lines { + for &byte in line? { + budget.bytes(1)?; + if leading && byte.is_ascii_whitespace() { + continue; + } + if leading { + leading = false; + if byte == b'{' { + depth = 1; + continue; + } } - if depth == 0 { - break; + if depth > 0 { + match byte { + b'{' => depth += 1, + b'}' => depth -= 1, + _ => {} + } + } else if !byte.is_ascii_whitespace() { + return Ok(true); } } } - bytes.any(|b| !b.is_ascii_whitespace()) + Ok(false) } /// A JSDoc *virtual* comment, which stands alone: it documents the symbol @@ -165,6 +186,13 @@ fn jsdoc_names<'a>(lines: impl IntoIterator) -> bool { /// Titles match in any case, as the tag dictionary's `normalize` does. #[must_use] pub(crate) fn jsdoc_virtual(s: &[u8]) -> bool { + infallible(jsdoc_virtual_with_budget(s, &NoBudget)) +} + +pub(crate) fn jsdoc_virtual_with_budget( + s: &[u8], + budget: &B, +) -> Result { const ALWAYS: [&[u8]; 4] = [b"file", b"fileoverview", b"overview", b"module"]; const NAMING: [&[u8]; 18] = [ b"name", @@ -187,29 +215,56 @@ pub(crate) fn jsdoc_virtual(s: &[u8]) -> bool { b"callback", ]; let is = |title: &[u8], names: &[&[u8]]| names.iter().any(|n| title.eq_ignore_ascii_case(n)); - let mut lines = jsdoc_lines(s); + let mut lines = jsdoc_lines(s, budget)?; while let Some(line) = lines.next() { - let Some((title, text)) = jsdoc_tag_open(line) else { + budget.step()?; + let Some((title, text)) = jsdoc_tag_open(line?, budget)? else { continue; }; if is(title, &ALWAYS) { - return true; + return Ok(true); } // The tag's text runs over every line up to the next tag. - let rest = lines.clone().take_while(|l| jsdoc_tag_open(l).is_none()); - if is(title, &NAMING) && jsdoc_names(std::iter::once(text).chain(rest)) { - return true; + if is(title, &NAMING) { + let mut ended = false; + let rest = lines.clone().scan(&mut ended, |ended, line| { + if **ended { + return None; + } + match line.and_then(|line| Ok((line, jsdoc_tag_open(line, budget)?.is_some()))) { + Ok((_, true)) => { + **ended = true; + None + } + Ok((line, false)) => Some(Ok(line)), + Err(error) => { + **ended = true; + Some(Err(error)) + } + } + }); + if jsdoc_names(std::iter::once(Ok(text)).chain(rest), budget)? { + return Ok(true); + } } } - false + Ok(false) } -pub(crate) fn jsdoc_file(s: &[u8]) -> bool { - jsdoc_lines(s).filter_map(jsdoc_tag_open).any(|(title, _)| { - [b"file".as_slice(), b"fileoverview", b"overview", b"module"] - .iter() - .any(|name| title.eq_ignore_ascii_case(name)) - }) +pub(crate) fn jsdoc_file_with_budget( + s: &[u8], + budget: &B, +) -> Result { + for line in jsdoc_lines(s, budget)? { + if let Some((title, _)) = jsdoc_tag_open(line?, budget)? + && [b"file".as_slice(), b"fileoverview", b"overview", b"module"] + .iter() + .any(|name| title.eq_ignore_ascii_case(name)) + { + return Ok(true); + } + } + Ok(false) } /// A TypeDoc module comment: one carrying `@module` or @@ -217,9 +272,21 @@ pub(crate) fn jsdoc_file(s: &[u8]) -> bool { /// declaration and reads as the file's documentation (#1613). #[must_use] pub(crate) fn tsdoc_module(s: &[u8]) -> bool { - jsdoc_lines(s) - .filter_map(jsdoc_tag_open) - .any(|(title, _)| title == b"module" || title == b"packageDocumentation") + infallible(tsdoc_module_with_budget(s, &NoBudget)) +} + +pub(crate) fn tsdoc_module_with_budget( + s: &[u8], + budget: &B, +) -> Result { + for line in jsdoc_lines(s, budget)? { + if let Some((title, _)) = jsdoc_tag_open(line?, budget)? + && (title == b"module" || title == b"packageDocumentation") + { + return Ok(true); + } + } + Ok(false) } /// A go/doc directive line, part of a lead comment group but not of @@ -228,21 +295,30 @@ pub(crate) fn tsdoc_module(s: &[u8]) -> bool { /// `//[a-z0-9]+:[a-z0-9]` form. A directive has no space after `//`. #[must_use] pub(crate) fn go_directive(s: &[u8]) -> bool { + infallible(go_directive_with_budget(s, &NoBudget)) +} + +pub(crate) fn go_directive_with_budget( + s: &[u8], + budget: &B, +) -> Result { let Some(rest) = s.strip_prefix(b"//") else { - return false; + return Ok(false); }; if rest.starts_with(b"line ") || rest.starts_with(b"extern ") || rest.starts_with(b"export ") { - return true; + return Ok(true); } - let word = rest - .iter() - .take_while(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) - .count(); - word > 0 + let word = scan::position( + rest, + |b| !b.is_ascii_lowercase() && !b.is_ascii_digit(), + budget, + )? + .unwrap_or(rest.len()); + Ok(word > 0 && rest.get(word) == Some(&b':') && rest .get(word.saturating_add(1)) - .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) + .is_some_and(|b| b.is_ascii_lowercase() || b.is_ascii_digit())) } /// A Ruby comment that opens a documentation block whatever follows it: @@ -254,14 +330,21 @@ pub(crate) fn go_directive(s: &[u8]) -> bool { /// `####…` banner or a `##### Helpers #####` divider opens nothing. #[must_use] pub(crate) fn ruby_directive_opener(s: &[u8]) -> bool { + infallible(ruby_directive_opener_with_budget(s, &NoBudget)) +} + +pub(crate) fn ruby_directive_opener_with_budget( + s: &[u8], + budget: &B, +) -> Result { if s.starts_with(b"##") && s.get(2) != Some(&b'#') { - return true; + return Ok(true); } - s.strip_prefix(b"#").is_some_and(|rest| { - rest.iter() - .position(|b| *b != b' ' && *b != b'\t') - .is_some_and(|at| rest[at..].starts_with(b"@!")) - }) + let Some(rest) = s.strip_prefix(b"#") else { + return Ok(false); + }; + Ok(scan::position(rest, |b| b != b' ' && b != b'\t', budget)? + .is_some_and(|at| rest[at..].starts_with(b"@!"))) } /// The comment lines YARD drops before documenting: a shebang, an @@ -276,52 +359,63 @@ pub(crate) fn ruby_directive_opener(s: &[u8]) -> bool { /// comment that repeats a magic line mid-file. #[must_use] pub(crate) fn ruby_magic_comment(s: &[u8]) -> bool { - if s.starts_with(b"#!") { - return true; - } - s.strip_prefix(b"#") - .map(<[u8]>::trim_ascii) - .is_some_and(|body| ruby_modeline(body) || ruby_magic_setting(body)) + infallible(ruby_magic_comment_with_budget(s, &NoBudget)) } -fn contains_ci(hay: &[u8], needle: &[u8]) -> bool { - hay.windows(needle.len()) - .any(|window| window.eq_ignore_ascii_case(needle)) +pub(crate) fn ruby_magic_comment_with_budget( + s: &[u8], + budget: &B, +) -> Result { + if s.starts_with(b"#!") { + return Ok(true); + } + let Some(body) = s.strip_prefix(b"#") else { + return Ok(false); + }; + let body = scan::trim(body, budget)?; + Ok(ruby_modeline(body, budget)? || ruby_magic_setting(body, budget)?) } /// An Emacs (`-*- … -*-`) or Vim (`vim: …`) modeline that carries the /// magic setting among others: an encoding, or for Emacs the /// frozen-string flag. A modeline's key is never a magic one, so /// `ruby_magic_setting` cannot also match it. -fn ruby_modeline(body: &[u8]) -> bool { +fn ruby_modeline(body: &[u8], budget: &B) -> Result { if body.len() >= 6 && body.starts_with(b"-*-") && body.ends_with(b"-*-") { - return contains_ci(body, b"coding") || contains_ci(body, b"frozen"); + return Ok(scan::contains_ci(body, b"coding", budget)? + || scan::contains_ci(body, b"frozen", budget)?); } - body.get(..4) + Ok(body + .get(..4) .is_some_and(|head| head.eq_ignore_ascii_case(b"vim:")) - && contains_ci(body, b"coding") + && scan::contains_ci(body, b"coding", budget)?) } /// A comment that is one magic setting and nothing else: `key: value` /// or `key=value`, the key a magic one and the value a single word. -fn ruby_magic_setting(body: &[u8]) -> bool { - let Some(separator) = body.iter().position(|b| matches!(b, b':' | b'=')) else { - return false; +fn ruby_magic_setting(body: &[u8], budget: &B) -> Result { + let Some(separator) = scan::position(body, |b| matches!(b, b':' | b'='), budget)? else { + return Ok(false); }; let (key, value) = body.split_at(separator); - let value = value.get(1..).unwrap_or_default().trim_ascii_start(); - [ + let value = scan::trim_start(value.get(1..).unwrap_or_default(), budget)?; + let key = scan::trim_end(key, budget)?; + let known = [ &b"coding"[..], b"encoding", b"frozen_string_literal", b"frozen-string-literal", ] .iter() - .any(|known| key.trim_ascii_end().eq_ignore_ascii_case(known)) + .any(|known| key.eq_ignore_ascii_case(known)); + Ok(known && !value.is_empty() - && value - .iter() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + && scan::position( + value, + |b| !b.is_ascii_alphanumeric() && !matches!(b, b'-' | b'_' | b'.'), + budget, + )? + .is_none()) } /// A POD block that is nothing but `comment` regions — `=begin comment` @@ -389,39 +483,50 @@ fn is_comment_format(format: &[u8]) -> bool { /// non-dash (`end_comment_ = '[^%-]%-%-+[^-]*\n$'` — `--- x ---` is an /// end marker), or a long comment whose body opens with a dash /// (`block_comment = '^%-%-%[=*%[%-+'`). -#[must_use] -pub(crate) fn ldoc_opener(s: &[u8]) -> bool { - if let Some(body) = lua_long_comment_body(s) { - return body.first() == Some(&b'-'); +pub(crate) fn ldoc_opener_with_budget( + s: &[u8], + budget: &B, +) -> Result { + if let Some(body) = lua_long_comment_body(s, budget)? { + return Ok(body.first() == Some(&b'-')); } - s.starts_with(b"---") && !ldoc_end_marker(s) + Ok(s.starts_with(b"---") && !ldoc_end_marker(s, budget)?) } /// A Lua long comment, `--[[ … ]]` or a levelled `--[==[ … ]==]`, as /// opposed to a line comment that merely starts `--[`. #[must_use] pub(crate) fn lua_long_comment(s: &[u8]) -> bool { - lua_long_comment_body(s).is_some() + infallible(lua_long_comment_with_budget(s, &NoBudget)) +} + +pub(crate) fn lua_long_comment_with_budget( + s: &[u8], + budget: &B, +) -> Result { + Ok(lua_long_comment_body(s, budget)?.is_some()) } /// The text after a long comment's opening bracket, or `None` when `s` /// is not a long comment. -fn lua_long_comment_body(s: &[u8]) -> Option<&[u8]> { - let rest = s.strip_prefix(b"--[")?; - let levels = rest.iter().take_while(|b| **b == b'=').count(); - rest.get(levels..)?.strip_prefix(b"[") +fn lua_long_comment_body<'s, B: WorkBudget>( + s: &'s [u8], + budget: &B, +) -> Result, B::Error> { + let Some(rest) = s.strip_prefix(b"--[") else { + return Ok(None); + }; + let levels = scan::position(rest, |b| b != b'=', budget)?.unwrap_or(rest.len()); + Ok(rest[levels..].strip_prefix(b"[")) } /// `[^-]--+[^-]*$`: the line's final dash run has two or more dashes and /// something other than a dash before it. -fn ldoc_end_marker(s: &[u8]) -> bool { - let trimmed = s.len() - s.iter().rev().take_while(|b| **b != b'-').count(); - let dashes = s[..trimmed] - .iter() - .rev() - .take_while(|b| **b == b'-') - .count(); - dashes >= 2 && trimmed > dashes +fn ldoc_end_marker(s: &[u8], budget: &B) -> Result { + let trimmed = scan::rposition(s, |b| b == b'-', budget)?.map_or(0, |at| at + 1); + let start = scan::rposition(&s[..trimmed], |b| b != b'-', budget)?.map_or(0, |at| at + 1); + let dashes = trimmed - start; + Ok(dashes >= 2 && trimmed > dashes) } #[cfg(test)] diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index 209391505..d98c088d9 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -6,7 +6,9 @@ //! differently. use crate::checker::Checker; -use crate::lang_helpers::doc_comment::{node_bytes, outside_function_bodies}; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::documentation::byte_scan as scan; +use crate::lang_helpers::doc_comment::node_bytes; use crate::node::{Ancestors, MemoQuestion, Node, NodeMemo}; /// A Doxygen block written after the member it documents: `/**<`, @@ -40,24 +42,35 @@ pub(crate) fn doxygen_member_after(s: &[u8]) -> bool { /// does. #[must_use] pub(crate) fn doxygen_standalone(s: &[u8]) -> bool { - structural_command_at(s).is_some() + infallible(doxygen_standalone_with_budget(s, &NoBudget)) } -pub(crate) fn structural_command(s: &[u8]) -> Option<(&[u8], &[u8])> { - let (word, at) = structural_command_at(s)?; - let end = s[at..] - .iter() - .position(|byte| *byte == b'\n') - .map_or(s.len(), |end| at + end); - let argument = s[at..end].trim_ascii(); - let argument = argument - .strip_suffix(b"*/") - .unwrap_or(argument) - .trim_ascii_end(); - Some((word, argument)) +pub(crate) fn doxygen_standalone_with_budget( + s: &[u8], + budget: &B, +) -> Result { + Ok(structural_command_at(s, budget)?.is_some()) +} + +#[allow(clippy::type_complexity)] +pub(crate) fn structural_command_with_budget<'s, B: WorkBudget>( + s: &'s [u8], + budget: &B, +) -> Result, B::Error> { + let Some((word, at)) = structural_command_at(s, budget)? else { + return Ok(None); + }; + let end = + scan::position(&s[at..], |byte| byte == b'\n', budget)?.map_or(s.len(), |end| at + end); + let argument = scan::trim(&s[at..end], budget)?; + let argument = scan::trim_end(argument.strip_suffix(b"*/").unwrap_or(argument), budget)?; + Ok(Some((word, argument))) } -fn structural_command_at(s: &[u8]) -> Option<(&[u8], usize)> { +fn structural_command_at<'s, B: WorkBudget>( + s: &'s [u8], + budget: &B, +) -> Result, B::Error> { const ALWAYS: &[&[u8]] = &[ b"file", b"mainpage", @@ -90,20 +103,21 @@ fn structural_command_at(s: &[u8]) -> Option<(&[u8], usize)> { ]; let mut at = 0; while at < s.len() { - if let Some(end) = literal_end(s, at) { + budget.bytes(1)?; + if let Some(end) = literal_end(s, at, budget)? { at = end; continue; } - let Some(word) = doxygen_command(s, at) else { + let Some(word) = doxygen_command(s, at, budget)? else { at += 1; continue; }; at += 1 + word.len(); - if ALWAYS.contains(&word) || (NAMED.contains(&word) && names_something(&s[at..])) { - return Some((word, at)); + if ALWAYS.contains(&word) || (NAMED.contains(&word) && names_something(&s[at..], budget)?) { + return Ok(Some((word, at))); } } - None + Ok(None) } /// Where the text Doxygen does not read for commands ends, when such text @@ -118,51 +132,58 @@ fn structural_command_at(s: &[u8]) -> Option<(&[u8], usize)> { /// ([`format_block_end`]). The /// fence is asked before the span so ```` ``` ```` is never read as a /// backtick span opened on an empty one. -fn literal_end(s: &[u8], at: usize) -> Option { +fn literal_end(s: &[u8], at: usize, budget: &B) -> Result, B::Error> { let rest = &s[at..]; - if let Some(end) = delimited_end(s, at) { - return Some(end); + if let Some(end) = delimited_end(s, at, budget)? { + return Ok(Some(end)); } if let Some(span) = rest.strip_prefix(b"`") { - return code_span_close(span).map(|close| at + close + 2); + return Ok(code_span_close(span, budget)?.map(|close| at + close + 2)); } if let Some(quoted) = rest.strip_prefix(b"\"") { - return quoted_text_close(quoted).map(|close| at + close + 2); + return Ok(quoted_text_close(quoted, budget)?.map(|close| at + close + 2)); } if matches!(rest, [b'@', b'@', ..] | [b'\\', b'\\', ..]) { - return Some(at + 2); + return Ok(Some(at + 2)); } - format_block_end(s, at) + format_block_end(s, at, budget) } /// Where a literal that runs to a closing delimiter or the end of the /// block ends, when one opens at `s[at]`: a ```` ``` ```` fence, an HTML /// comment, or a ` Option { +fn delimited_end( + s: &[u8], + at: usize, + budget: &B, +) -> Result, B::Error> { let rest = &s[at..]; if rest.starts_with(b"`, or at the end of the comment when it has none. Doxygen 1.13.2 /// closes it on neither `--->` nor `--!>`. -fn html_comment_end(s: &[u8], from: usize) -> usize { - (from..s.len()) - .find(|&at| s[at..].starts_with(b"-->") && (at == from || s[at - 1] != b'-')) - .map_or(s.len(), |at| at + 3) +fn html_comment_end(s: &[u8], from: usize, budget: &B) -> Result { + for at in from..s.len() { + budget.bytes(4)?; + if s[at..].starts_with(b"-->") && (at == from || s[at - 1] != b'-') { + return Ok(at + 3); + } + } + Ok(s.len()) } /// Where a format block opened at `s[at]` ends: after its `end` command, /// or at the end of the comment when it has none. -fn block_end(s: &[u8], at: usize, end: &[u8]) -> usize { - (at + 1..s.len()) - .find(|&after| doxygen_command(s, after) == Some(end)) - .map_or(s.len(), |after| after + 1 + end.len()) +fn block_end( + s: &[u8], + at: usize, + end: &[u8], + budget: &B, +) -> Result { + for after in at + 1..s.len() { + budget.bytes(1)?; + if doxygen_command(s, after, budget)? == Some(end) { + return Ok(after + 1 + end.len()); + } + } + Ok(s.len()) } /// Whether a naming command has an argument: anything on the rest of its /// line but the comment's closing `*/`. -fn names_something(after: &[u8]) -> bool { - let line = after.split(|&b| b == b'\n').next().unwrap_or_default(); - let line = line.trim_ascii(); - !line - .strip_suffix(b"*/") - .unwrap_or(line) - .trim_ascii() - .is_empty() +fn names_something(after: &[u8], budget: &B) -> Result { + let end = scan::position(after, |b| b == b'\n', budget)?.unwrap_or(after.len()); + let line = scan::trim(&after[..end], budget)?; + Ok(!scan::trim(line.strip_suffix(b"*/").unwrap_or(line), budget)?.is_empty()) } /// The command word at `s[at]` when a Doxygen command starts there: `@` or /// `\` followed by letters, the word ending at a non-word byte. An `@` in /// a mail address (`a@file.com`) is not a command. -fn doxygen_command(s: &[u8], at: usize) -> Option<&[u8]> { +fn doxygen_command<'s, B: WorkBudget>( + s: &'s [u8], + at: usize, + budget: &B, +) -> Result, B::Error> { if !matches!(s.get(at), Some(b'@' | b'\\')) { - return None; + return Ok(None); } let rest = &s[at + 1..]; - let len = rest - .iter() - .take_while(|b| b.is_ascii_alphabetic() || **b == b'_') - .count(); + let len = scan::position(rest, |b| !b.is_ascii_alphabetic() && b != b'_', budget)? + .unwrap_or(rest.len()); if len == 0 { - return None; + return Ok(None); + } + if s[at] == b'@' && at > 0 && s[at - 1].is_ascii_alphanumeric() { + for &byte in &rest[len..] { + budget.bytes(1)?; + if !byte.is_ascii_alphanumeric() && !matches!(byte, b'-' | b'.') { + break; + } + if byte == b'.' { + return Ok(None); + } + } } - let mail = s[at] == b'@' - && at > 0 - && s[at - 1].is_ascii_alphanumeric() - && rest - .iter() - .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.')) - .skip(len) - .any(|&b| b == b'.'); - (!mail).then(|| &rest[..len]) + Ok(Some(&rest[..len])) } /// A preprocessor conditional or one of its branches, under any alias of @@ -301,12 +339,22 @@ crate::observation::counter!(conditionals_read); /// each is read once per walk; any other caller reads the nest afresh. #[must_use] pub(crate) fn conditional_declares(node: &Node, ancestors: Ancestors) -> bool { + infallible(conditional_declares_with_budget::( + node, ancestors, &NoBudget, + )) +} + +pub(crate) fn conditional_declares_with_budget( + node: &Node, + ancestors: Ancestors, + budget: &B, +) -> Result { let unshared = NodeMemo::default(); let memo = ancestors .node_memo(MemoQuestion::ConditionalDeclares) .unwrap_or(&unshared); if let Some(answer) = memo.get(node) { - return answer; + return Ok(answer); } // Post-order: a conditional's answer is complete once each nested one // has folded its own in. `answers[i]` holds the answer, so far, of the @@ -317,6 +365,7 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest outer: None, }]; while let Some(visit) = stack.pop() { + budget.step()?; match visit { Visit::Read { conditional, outer } => { conditionals_read::record(); @@ -326,7 +375,7 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest outer, own, }); - answers.push(children_declare::( + answers.push(children_declare::( &conditional, ancestors, memo, @@ -336,7 +385,8 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest outer: Some(own), }); }, - )); + budget, + )?); } Visit::Answer { conditional, @@ -350,7 +400,7 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest } } } - memo.get(node) == Some(true) + Ok(memo.get(node) == Some(true)) } /// A step of [`conditional_declares`]'s walk over a nest. @@ -377,26 +427,28 @@ enum Visit<'a> { /// the memo answers `true` for. Each nested conditional the memo has no /// answer for is handed to `defer`, so the walk reads it and folds its /// answer in later. Each child is classified once, here (#1795). -fn children_declare<'a, T: DoxygenRow>( +fn children_declare<'a, T: DoxygenRow, B: WorkBudget>( conditional: &Node<'a>, ancestors: Ancestors<'a, '_>, memo: &NodeMemo, mut defer: impl FnMut(Node<'a>), -) -> bool { + budget: &B, +) -> Result { let parent = [*conditional]; let below = chain_below(ancestors, &parent); let mut declares = false; for child in conditional.children() { + budget.step()?; if preproc_conditional::(&child) { match memo.get(&child) { Some(answer) => declares |= answer, None => defer(child), } } else if !declares { - declares = non_conditional_entry::(&child, below); + declares = non_conditional_entry::(&child, below, budget)?; } } - declares + Ok(declares) } /// The context a conditional's children are asked with: a chain of one @@ -488,12 +540,25 @@ pub(crate) const DOXYGEN_SKIP_KINDS: &[&str] = &[ /// grammar had to end itself ([`unterminated`]). #[must_use] pub(crate) fn doxygen_skips(node: &Node, ancestors: Ancestors) -> bool { - match node.kind() { + infallible(doxygen_skips_with_budget::( + node, ancestors, &NoBudget, + )) +} + +pub(crate) fn doxygen_skips_with_budget( + node: &Node, + ancestors: Ancestors, + budget: &B, +) -> Result { + Ok(match node.kind() { kind if DOXYGEN_SKIP_KINDS.contains(&kind) => true, - "expression_statement" => !statement_is_macro_call(node), - "ERROR" => no_entry_inside::(node, ancestors), - _ => preproc_conditional::(node) && !conditional_declares::(node, ancestors), - } + "expression_statement" => !statement_with_budget(node, budget)?, + "ERROR" => no_entry_with_budget::(node, ancestors, budget)?, + _ => { + preproc_conditional::(node) + && !conditional_declares_with_budget::(node, ancestors, budget)? + } + }) } /// A parse error Doxygen reads no entry from: one holding, past comments @@ -504,17 +569,37 @@ pub(crate) fn doxygen_skips(node: &Node, ancestors: Ancestors) -> /// ending in the error, as a conditional's children are /// ([`chain_below`]), not with the error's own, under which its /// `parent` would be the error's (lesson 103). +#[cfg(test)] pub(crate) fn no_entry_inside(error: &Node, ancestors: Ancestors) -> bool { - let mut named = error - .children() - .filter(|child| child.is_named() && !child.is_error() && child.kind() != "comment"); - match (named.next(), named.next()) { - (None, _) => true, - (Some(only), None) => { + infallible(no_entry_with_budget::(error, ancestors, &NoBudget)) +} + +fn no_entry_with_budget( + error: &Node, + ancestors: Ancestors, + budget: &B, +) -> Result { + let mut only = None; + for child in error.children() { + budget.step()?; + if !child.is_named() || child.is_error() || child.kind() == "comment" { + continue; + } + if only.is_some() { + return Ok(false); + } + only = Some(child); + } + match only { + None => Ok(true), + Some(only) => { let parent = [*error]; - !doxygen_entry::(&only, chain_below(ancestors, &parent)) + Ok(!doxygen_entry::( + &only, + chain_below(ancestors, &parent), + budget, + )?) } - _ => false, } } @@ -522,8 +607,13 @@ pub(crate) fn no_entry_inside(error: &Node, ancestors: Ancestors) /// `end` of `@end` in a `.h` read as C or C++, or a stray `@end` in /// Objective-C. Doxygen reads no entry from it and documents the entry /// after it; `FOO;` with its `;` is a variable to Doxygen. -fn unterminated(statement: &Node) -> bool { - statement.children().last().is_some_and(|c| c.is_missing()) +fn unterminated_with_budget(statement: &Node, budget: &B) -> Result { + let mut last = None; + for child in statement.children() { + budget.step()?; + last = Some(child); + } + Ok(last.is_some_and(|child| child.is_missing())) } /// Whether an `expression_statement` outside a body is a macro call @@ -535,7 +625,11 @@ fn unterminated(statement: &Node) -> bool { /// what `doxygen_skips` reads past. #[must_use] pub(crate) fn statement_is_macro_call(statement: &Node) -> bool { - statement.child_count() > 1 && !unterminated(statement) + infallible(statement_with_budget(statement, &NoBudget)) +} + +fn statement_with_budget(statement: &Node, budget: &B) -> Result { + Ok(statement.child_count() > 1 && !unterminated_with_budget(statement, budget)?) } /// What Doxygen documents from a doc block before it: the dialect's @@ -551,10 +645,27 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { + infallible(doxygen_target_with_budget::( + node, code, ancestors, &NoBudget, + )) +} + +pub(crate) fn doxygen_target_with_budget<'a, T: DoxygenRow, B: WorkBudget>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { // role-bypass: allow(DocTarget) — the `ERROR` sentinel holding an // entry: recovery, not a kind a row can own - T::doc_target_row(node, code, ancestors) - || (node.is_error() && !no_entry_inside::(node, ancestors)) + if preproc_conditional::(node) { + return conditional_declares_with_budget::(node, ancestors, budget); + } + if node.kind() == "expression_statement" { + return statement_with_budget(node, budget); + } + Ok(T::doc_target_row(node, code, ancestors) + || (node.is_error() && !no_entry_with_budget::(node, ancestors, budget)?)) } /// What Doxygen documents from a doc block before it, short of a @@ -572,8 +683,12 @@ pub(crate) fn doxygen_target<'a, T: DoxygenRow>( /// preprocessor would expand, is given the benefit of the doubt, as /// before #1613, rather than dropping the block on a parse failure; an /// error holding no entry is read past (`doxygen_skips`). -fn doxygen_entry(node: &Node, ancestors: Ancestors) -> bool { - !preproc_conditional::(node) && non_conditional_entry::(node, ancestors) +fn doxygen_entry( + node: &Node, + ancestors: Ancestors, + budget: &B, +) -> Result { + Ok(!preproc_conditional::(node) && non_conditional_entry::(node, ancestors, budget)?) } /// [`doxygen_entry`] of a node its caller has already found is no @@ -589,11 +704,18 @@ fn doxygen_entry(node: &Node, ancestors: Ancestors) -> bool { /// `ERROR` clause this fn already handles, and a dialect that someday /// hand-writes a byte-reading `is_doc_target` would otherwise slip past /// the row's assertion. -fn non_conditional_entry(node: &Node, ancestors: Ancestors) -> bool { +fn non_conditional_entry( + node: &Node, + ancestors: Ancestors, + budget: &B, +) -> Result { if node.is_error() { - return !no_entry_inside::(node, ancestors); + return Ok(!no_entry_with_budget::(node, ancestors, budget)?); } - T::doc_target_row(node, &[], ancestors) + if node.kind() == "expression_statement" { + return statement_with_budget(node, budget); + } + Ok(T::doc_target_row(node, &[], ancestors)) } /// The `DocTarget` row of a C-family dialect, and its conditional owners @@ -623,13 +745,26 @@ pub(crate) fn doxygen_binds_forward<'a, T: Checker + DoxygenRow>( code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { + infallible(doxygen_forward_with_budget::( + comment, code, ancestors, &NoBudget, + )) +} + +pub(crate) fn doxygen_forward_with_budget<'a, T: Checker + DoxygenRow, B: WorkBudget>( + comment: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { let bytes = node_bytes(comment, code); - !doxygen_member_after(bytes) - && !doxygen_standalone(bytes) + Ok(!doxygen_member_after(bytes) + && !doxygen_standalone_with_budget(bytes, budget)? && ancestors .parent(comment) .is_some_and(|parent| doxygen_container::(&parent)) - && outside_function_bodies::(comment, code, ancestors) + && crate::lang_helpers::doc_comment::outside_function_bodies_with_budget::( + comment, code, ancestors, budget, + )?) } #[cfg(test)] @@ -912,7 +1047,9 @@ mod tests { // climbing context through unchanged. for uncached in [Ancestors::known(&[]), Ancestors::unknown()] { let before = conditionals_read::observed(); - assert!(!doxygen_entry::(&outermost, uncached)); + assert!(!infallible(doxygen_entry::( + &outermost, uncached, &NoBudget + ))); assert_eq!( conditionals_read::observed() - before, 0, diff --git a/big-code-analysis-ast/src/lang_helpers/ruby.rs b/big-code-analysis-ast/src/lang_helpers/ruby.rs index a8856911a..9af10a2c7 100644 --- a/big-code-analysis-ast/src/lang_helpers/ruby.rs +++ b/big-code-analysis-ast/src/lang_helpers/ruby.rs @@ -10,17 +10,23 @@ //! a reader of the comparison expects, but nothing checks it (#1701). use crate::Ruby; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; use crate::lang_helpers::doc_comment::node_bytes; use crate::node::{Ancestors, FoldLane, Node}; /// YARD 0.9.45 `META_MATCH` after `on_comment` hash-line cleanup: remove /// the hash run and at most one whitespace byte, then require `@!((\w\.?)+)` /// followed by whitespace or end of line. Indented examples remain prose. -pub(crate) fn source_yard_directive(node: &Node<'_>, code: &[u8]) -> bool { +pub(crate) fn source_yard_directive_with_budget( + node: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { let bytes = node_bytes(node, code); - let hashes = bytes.iter().take_while(|&&byte| byte == b'#').count(); + let hashes = crate::documentation::byte_scan::position(bytes, |byte| byte != b'#', budget)? + .unwrap_or(bytes.len()); if hashes == 0 { - return false; + return Ok(false); } let body = &bytes[hashes..]; let body = if body.first().is_some_and(u8::is_ascii_whitespace) { @@ -29,10 +35,11 @@ pub(crate) fn source_yard_directive(node: &Node<'_>, code: &[u8]) -> bool { body }; let Some(mut identifier) = body.strip_prefix(b"@!") else { - return false; + return Ok(false); }; let mut found = false; while let Some(byte) = identifier.first() { + budget.bytes(2)?; if !byte.is_ascii_alphanumeric() && *byte != b'_' { break; } @@ -42,7 +49,7 @@ pub(crate) fn source_yard_directive(node: &Node<'_>, code: &[u8]) -> bool { identifier = &identifier[1..]; } } - found && identifier.first().is_none_or(u8::is_ascii_whitespace) + Ok(found && identifier.first().is_none_or(u8::is_ascii_whitespace)) } /// Whether `node` — a `Block` / `DoBlock` — is the body of a stabby @@ -81,10 +88,18 @@ pub(crate) fn is_stabby_lambda_body<'a>(node: &Node<'a>, ancestors: Ancestors<'a /// run; `private :m` re-scopes a method documented at its `def`, so a /// comment above it is not documentation either. pub(crate) fn ruby_documented_call(node: &Node, code: &[u8]) -> bool { + infallible(ruby_documented_call_with_budget(node, code, &NoBudget)) +} + +pub(crate) fn ruby_documented_call_with_budget( + node: &Node, + code: &[u8], + budget: &B, +) -> Result { let Some(method) = node.child_by_field_name("method") else { - return false; + return Ok(false); }; - match node_bytes(&method, code) { + Ok(match node_bytes(&method, code) { // `alias_method :new, :old` is the call form of `alias`, which the // same YARD handler documents. b"attr" | b"attr_reader" | b"attr_writer" | b"attr_accessor" | b"alias_method" => true, @@ -94,23 +109,25 @@ pub(crate) fn ruby_documented_call(node: &Node, code: &[u8]) -> bool { | b"module_function" | b"private_class_method" | b"public_class_method" => { + let argument = if let Some(arguments) = node.child_by_field_name("arguments") { + crate::documentation::budget::child(&arguments, Node::is_named, budget)? + } else { + None + }; node.child_by_field_name("receiver").is_none() - && node - .child_by_field_name("arguments") - .and_then(|arguments| arguments.children().find(Node::is_named)) - .is_some_and(|argument| { - // role-bypass: allow(FuncOpener, DocTarget) — whether a visibility - // call's argument is a `def` (not a class or an alias, which - // `private` does not take): the call's shape, read by the - // `DocTarget` row's gate, not membership - matches!( - argument.kind_id().into(), - Ruby::Method | Ruby::SingletonMethod - ) - }) + && argument.is_some_and(|argument| { + // role-bypass: allow(FuncOpener, DocTarget) — whether a visibility + // call's argument is a `def` (not a class or an alias, which + // `private` does not take): the call's shape, read by the + // `DocTarget` row's gate, not membership + matches!( + argument.kind_id().into(), + Ruby::Method | Ruby::SingletonMethod + ) + }) } _ => false, - } + }) } /// The scope a documented statement needs to sit in for YARD to read @@ -164,20 +181,24 @@ pub(crate) fn ruby_yard_reads<'a>( yard_reads(needs, scope, ancestors, false) } -pub(crate) fn ruby_source_yard_reads<'a>( +fn yard_reads<'a>( needs: YardScope, scope: &Node<'a>, ancestors: Ancestors<'a, '_>, + source: bool, ) -> bool { - yard_reads(needs, scope, ancestors, true) + infallible(yard_reads_with_budget( + needs, scope, ancestors, source, &NoBudget, + )) } -fn yard_reads<'a>( +pub(crate) fn yard_reads_with_budget<'a, B: WorkBudget>( needs: YardScope, scope: &Node<'a>, ancestors: Ancestors<'a, '_>, source: bool, -) -> bool { + budget: &B, +) -> Result { // Read upward, the rule is: the nearest namespace admits the // statement; a method body met first rejects it if it needs a // namespace; a singleton class or conditional on the way makes it @@ -188,7 +209,7 @@ fn yard_reads<'a>( const DEF_READS: u8 = 0b01; const NAMESPACED_READS: u8 = 0b10; const BOTH: u8 = DEF_READS | NAMESPACED_READS; - let reads = ancestors.fold_down( + let reads = ancestors.fold_down_with_budget( scope, 0, if source { @@ -199,42 +220,50 @@ fn yard_reads<'a>( BOTH, // Where YARD reads a doc comment, not whether a node opens a space: // each arm below that names a space opener is exempt for that. - |above, ancestor, outer, _| match ancestor.kind_id().into() { - _ if source && crate::roles::ruby::closure::owns(ancestor, &[], outer) => 0, - // role-bypass: allow(Container) — the file, where YARD reads - Ruby::Program => BOTH, - // Each opens a namespace only where one already reads it. For a - // class or module — Ruby rejects one in a method body — that - // closes it only under a `case`, `begin` or loop, whose bodies - // YARD never parses; a singleton class or conditional in a - // method body closes as before. - // role-bypass: allow(Container, Branch, ElseIf, DocTarget) — the namespaces - // and the conditionals, where YARD reads: the scope a target is read in, - // context over the `DocTarget` row, not membership - Ruby::Class - | Ruby::Module - | Ruby::SingletonClass - | Ruby::If - | Ruby::Unless - | Ruby::Elsif => { - if above & NAMESPACED_READS == 0 { - 0 - } else { - BOTH + |above, ancestor, outer, _| { + Ok(match ancestor.kind_id().into() { + _ if source && crate::roles::ruby::closure::owns(ancestor, &[], outer) => 0, + // role-bypass: allow(Container) — the file, where YARD reads + Ruby::Program => BOTH, + // Each opens a namespace only where one already reads it. For a + // class or module — Ruby rejects one in a method body — that + // closes it only under a `case`, `begin` or loop, whose bodies + // YARD never parses; a singleton class or conditional in a + // method body closes as before. + // role-bypass: allow(Container, Branch, ElseIf, DocTarget) — the namespaces + // and the conditionals, where YARD reads: the scope a target is read in, + // context over the `DocTarget` row, not membership + Ruby::Class + | Ruby::Module + | Ruby::SingletonClass + | Ruby::If + | Ruby::Unless + | Ruby::Elsif => { + if above & NAMESPACED_READS == 0 { + 0 + } else { + BOTH + } } - } - // role-bypass: allow(FuncOpener, DocTarget) — a `def` body, where YARD - // reads a `def` and nothing else: context over the row, not membership - Ruby::Method | Ruby::SingletonMethod => above & DEF_READS, - // role-bypass: allow(Switch, Loop) — the bodies YARD never parses; - // doc attachment, not membership - Ruby::Case | Ruby::CaseMatch | Ruby::Begin | Ruby::While | Ruby::Until | Ruby::For => 0, - _ => above, + // role-bypass: allow(FuncOpener, DocTarget) — a `def` body, where YARD + // reads a `def` and nothing else: context over the row, not membership + Ruby::Method | Ruby::SingletonMethod => above & DEF_READS, + // role-bypass: allow(Switch, Loop) — the bodies YARD never parses; + // doc attachment, not membership + Ruby::Case + | Ruby::CaseMatch + | Ruby::Begin + | Ruby::While + | Ruby::Until + | Ruby::For => 0, + _ => above, + }) }, - ); + budget, + )?; let need = match needs { YardScope::DefBody => DEF_READS, YardScope::Namespace => NAMESPACED_READS, }; - reads & need != 0 + Ok(reads & need != 0) } diff --git a/big-code-analysis-ast/src/node/ancestors/folds.rs b/big-code-analysis-ast/src/node/ancestors/folds.rs index 48c1ec550..cde63148c 100644 --- a/big-code-analysis-ast/src/node/ancestors/folds.rs +++ b/big-code-analysis-ast/src/node/ancestors/folds.rs @@ -11,6 +11,7 @@ use std::collections::HashMap; use super::Ancestors; use super::chain::Chain; use crate::checker::Checker; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; use crate::node::Node; impl<'tree, 'chain> Ancestors<'tree, 'chain> { @@ -51,8 +52,27 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { init: u8, step: impl Fn(u8, &Node<'tree>, Ancestors<'tree, 'chain>, &Node<'tree>) -> u8, ) -> u8 { + infallible(self.fold_down_with_budget( + node, + skip, + lane, + init, + |state, ancestor, outer, below| Ok(step(state, ancestor, outer, below)), + &NoBudget, + )) + } + + pub(crate) fn fold_down_with_budget( + self, + node: &Node<'tree>, + skip: usize, + lane: FoldLane, + init: u8, + step: impl Fn(u8, &Node<'tree>, Ancestors<'tree, 'chain>, &Node<'tree>) -> Result, + budget: &B, + ) -> Result { let Some(chain) = self.chain else { - return fold_climbed(node, skip, init, step); + return fold_climbed(node, skip, init, step, budget); }; let end = chain.len().saturating_sub(skip); // The cache travels into `outer`, as it does through @@ -69,8 +89,11 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { ) }; match self.folds { - Some(cache) => cache.fold(lane, chain, end, init, step_at), - None => (0..end).fold(init, step_at), + Some(cache) => cache.fold(lane, chain, end, init, step_at, budget), + None => (0..end).try_fold(init, |state, depth| { + budget.step()?; + step_at(state, depth) + }), } } @@ -278,15 +301,24 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { node: &Node<'_>, answer: impl FnOnce() -> bool, ) -> bool { + infallible(self.try_memoised(question, node, || Ok(answer()))) + } + + pub(crate) fn try_memoised( + self, + question: MemoQuestion, + node: &Node<'_>, + answer: impl FnOnce() -> Result, + ) -> Result { let memo = self.node_memo(question); if let Some(known) = memo.and_then(|memo| memo.get(node)) { - return known; + return Ok(known); } - let answer = answer(); + let answer = answer()?; if let Some(memo) = memo { memo.set(node, answer); } - answer + Ok(answer) } /// [`memoised`](Self::memoised) on a [`NodeQuestion`], for the metric @@ -319,6 +351,15 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { node: &Node<'_>, classify: impl FnOnce() -> u8, ) -> u8 { + infallible(self.try_classified(slot, node, || Ok(classify()))) + } + + pub(crate) fn try_classified( + self, + slot: WordSlot, + node: &Node<'_>, + classify: impl FnOnce() -> Result, + ) -> Result { let Some(cache) = self.folds.filter(|cache| cache.visited.get() == node.id()) else { return classify(); }; @@ -327,11 +368,11 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { // Id 0 marks an empty slot: a tree-sitter node id is its address, // never 0. if id == node.id() { - return answer; + return Ok(answer); } - let answer = classify(); + let answer = classify()?; cell.set((node.id(), answer)); - answer + Ok(answer) } /// Whether [`fold_down`](Self::fold_down) is memoised on this chain: @@ -346,30 +387,43 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { // The deepest depth at or above `from` whose slot still holds the state of // the ancestor the chain has there, or 0 when none does: a node fixes its // ancestry, so a matching id is an exact state. -fn deepest_stored(slots: &[(usize, u8)], chain: Chain<'_, '_>, from: usize) -> usize { - (1..=from) - .rev() - .find(|&depth| { - fold_slot_probes::record(); - slots[depth].0 == chain[depth].id() - }) - .unwrap_or(0) +fn deepest_stored( + slots: &[(usize, u8)], + chain: Chain<'_, '_>, + from: usize, + budget: &B, +) -> Result { + for depth in (1..=from).rev() { + budget.step()?; + fold_slot_probes::record(); + if slots[depth].0 == chain[depth].id() { + return Ok(depth); + } + } + Ok(0) } // `Ancestors::fold_down` for a caller that holds no chain: the ancestry is // climbed first and folded unmemoised. -fn fold_climbed<'tree, 'chain>( +fn fold_climbed<'tree, 'chain, B: WorkBudget>( node: &Node<'tree>, skip: usize, init: u8, - step: impl Fn(u8, &Node<'tree>, Ancestors<'tree, 'chain>, &Node<'tree>) -> u8, -) -> u8 + step: impl Fn(u8, &Node<'tree>, Ancestors<'tree, 'chain>, &Node<'tree>) -> Result, + budget: &B, +) -> Result where 'tree: 'chain, { - let climbed = climbed_chain(node); + let mut climbed = Vec::new(); + for ancestor in std::iter::successors(node.parent(), Node::parent) { + budget.step()?; + climbed.push(ancestor); + } + crate::documentation::budget::reverse(&mut climbed, budget)?; let end = climbed.len().saturating_sub(skip); - (0..end).fold(init, |state, depth| { + (0..end).try_fold(init, |state, depth| { + budget.step()?; let below = climbed.get(depth + 1).unwrap_or(node); step(state, &climbed[depth], Ancestors::unknown(), below) }) @@ -378,6 +432,7 @@ where // `node`'s ancestors, root first, climbed with `Node::parent` for a caller // that holds no chain. tree-sitter finds a parent by descending from the // root, so the climb is `O(depth²)`. +#[cfg(test)] pub(super) fn climbed_chain<'tree>(node: &Node<'tree>) -> Vec> { let mut climbed: Vec<_> = std::iter::successors(node.parent(), Node::parent).collect(); climbed.reverse(); @@ -540,14 +595,20 @@ pub(crate) enum MemoQuestion { CodeBeforeOnLine, /// [`LevelQuestion::InConstBinding`]. InConstBinding, + /// Source-only documentation target; never shared with legacy selection. + SourceDocTarget, + /// Ruby's wrapper-normalized candidate, independent of source scope. + DocCoreTarget, + /// Whether the wrapper-normalized Ruby candidate needs namespace scope. + DocCoreNamespace, } impl MemoQuestion { /// How many memos a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 11; + const COUNT: usize = 14; } -const _: () = assert!(MemoQuestion::InConstBinding as usize + 1 == MemoQuestion::COUNT); +const _: () = assert!(MemoQuestion::DocCoreNamespace as usize + 1 == MemoQuestion::COUNT); /// The per-node questions the metric crate memoises through /// [`Ancestors::memoised_answer`], one per [`MemoQuestion`] memo of the @@ -730,41 +791,48 @@ impl FoldCache { // can store cuts the recursion short. Neither shows as a wrong answer, // so debug builds refuse the shape: the whole test corpus then guards // the contract. - fn fold( + fn fold( &self, lane: FoldLane, chain: Chain<'_, '_>, end: usize, init: u8, - step: impl Fn(u8, usize) -> u8, - ) -> u8 { + step: impl Fn(u8, usize) -> Result, + budget: &B, + ) -> Result { let Ok(mut slots) = self.lanes[lane as usize].try_borrow_mut() else { debug_assert!( same_lane_reentry::allowed(), "a fold step re-entered its own lane {lane:?}" ); - return (0..end).fold(init, step); + return (0..end).try_fold(init, |state, depth| { + budget.step()?; + step(state, depth) + }); }; // `slots[d]` is the state at `chain[d]`: folded over `chain[..d]`. // Depth 0 is `init`; the state at `node` itself is never stored. let memo_end = end.min(chain.len().saturating_sub(1)); - if slots.len() <= memo_end { + while slots.len() <= memo_end { // Id 0 marks an empty slot: a tree-sitter node id is its // address, never 0. - slots.resize(memo_end + 1, (0, 0)); + budget.step()?; + slots.push((0, 0)); } - let mut depth = deepest_stored(&slots, chain, memo_end); + let mut depth = deepest_stored(&slots, chain, memo_end, budget)?; let mut state = if depth == 0 { init } else { slots[depth].1 }; while depth < memo_end { + budget.step()?; fold_steps::record(); - state = step(state, depth); + state = step(state, depth)?; depth += 1; slots[depth] = (chain[depth].id(), state); } if end > memo_end { - state = step(state, memo_end); + budget.step()?; + state = step(state, memo_end)?; } - state + Ok(state) } } diff --git a/big-code-analysis-ast/src/node/ancestors/siblings.rs b/big-code-analysis-ast/src/node/ancestors/siblings.rs index 45a7f50a7..c9b840cb0 100644 --- a/big-code-analysis-ast/src/node/ancestors/siblings.rs +++ b/big-code-analysis-ast/src/node/ancestors/siblings.rs @@ -4,6 +4,7 @@ //! Tested in the parent module's `tests`. use super::Ancestors; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; use crate::node::Node; impl<'tree, 'chain> Ancestors<'tree, 'chain> { @@ -93,12 +94,20 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { self, node: &Node<'tree>, ) -> impl Iterator> + use<'tree, 'chain> { - let (wide, narrow) = match self.lookup(node) { + infallible(self.siblings_after_with_budget(node, &NoBudget)) + } + + pub(crate) fn siblings_after_with_budget( + self, + node: &Node<'tree>, + budget: &B, + ) -> Result> + use<'tree, 'chain, B>, B::Error> { + let (wide, narrow) = match self.lookup_with_budget(node, budget)? { Lookup::Wide(children, index) => (index.map(|index| &children[index + 1..]), None), Lookup::Narrow(parent) => (None, parent.map(|parent| parent.children_after(node))), }; let wide = wide.into_iter().flatten().copied(); - wide.chain(narrow.into_iter().flatten()) + Ok(wide.chain(narrow.into_iter().flatten())) } /// The siblings before `node`, nearest first: what @@ -120,18 +129,34 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { self, node: &Node<'tree>, ) -> impl Iterator> + use<'tree, 'chain> { - let (wide, narrow) = match self.lookup(node) { + infallible(self.siblings_before_with_budget(node, &NoBudget)) + } + + pub(crate) fn siblings_before_with_budget( + self, + node: &Node<'tree>, + budget: &B, + ) -> Result> + use<'tree, 'chain, B>, B::Error> { + let (wide, narrow) = match self.lookup_with_budget(node, budget)? { Lookup::Wide(children, index) => (index.map(|index| &children[..index]), None), Lookup::Narrow(parent) => (None, parent.map(|parent| parent.children_before(node))), }; let wide = wide.into_iter().flatten().rev().copied(); - wide.chain(narrow.into_iter().flatten()) + Ok(wide.chain(narrow.into_iter().flatten())) } // Where `node`'s siblings are read from: its parent's children as the // walk recorded them and `node`'s index among them, or the parent to // seek in when the walk recorded none. pub(super) fn lookup(self, node: &Node<'tree>) -> Lookup<'tree, 'chain> { + infallible(self.lookup_with_budget(node, &NoBudget)) + } + + fn lookup_with_budget( + self, + node: &Node<'tree>, + budget: &B, + ) -> Result, B::Error> { let parent = self.parent(node); let recorded = match (self.siblings, self.chain, parent) { (Some(cache), Some(chain), Some(parent)) => { @@ -153,12 +178,15 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { }; if let Some(children) = recorded { sibling_cache_reads::record(); - return Lookup::Wide(children, position_by_start(children, node)); + return Ok(Lookup::Wide( + children, + position_with_budget(children, node, budget)?, + )); } if self.chain.is_some() && parent.is_some() { sibling_seeks::record(); } - Lookup::Narrow(parent) + Ok(Lookup::Narrow(parent)) } } @@ -181,13 +209,37 @@ pub const WIDE_PARENT: usize = 64; // bytes never decrease, so a binary search lands on the first child // starting where `node` does; only zero-width children, which recovery // inserts, can share that byte with it. +#[cfg(test)] pub(super) fn position_by_start(children: &[Node], node: &Node) -> Option { - let first = children.partition_point(|child| child.start_byte() < node.start_byte()); - children[first..] - .iter() - .take_while(|child| child.start_byte() == node.start_byte()) - .position(|child| child.id() == node.id()) - .map(|offset| first + offset) + infallible(position_with_budget(children, node, &NoBudget)) +} + +fn position_with_budget( + children: &[Node], + node: &Node, + budget: &B, +) -> Result, B::Error> { + let mut first = 0; + let mut end = children.len(); + while first < end { + budget.step()?; + let middle = first + (end - first) / 2; + if children[middle].start_byte() < node.start_byte() { + first = middle + 1; + } else { + end = middle; + } + } + for (at, child) in children.iter().enumerate().skip(first) { + budget.step()?; + if child.start_byte() != node.start_byte() { + break; + } + if child.id() == node.id() { + return Ok(Some(at)); + } + } + Ok(None) } /// The children of each wide node on a walk's chain, recorded as the @@ -241,6 +293,20 @@ impl<'tree> SiblingCache<'tree> { depth: usize, children: impl IntoIterator>, budget: &B, + ) -> Result<(), B::Error> { + crate::documentation::budget::in_phase( + budget, + crate::documentation::budget::WorkPhase::Batch, + || self.record_batch(node, depth, children, budget), + ) + } + + fn record_batch( + &mut self, + node: &Node<'tree>, + depth: usize, + children: impl IntoIterator>, + budget: &B, ) -> Result<(), B::Error> { if node.child_count() <= WIDE_PARENT { return Ok(()); diff --git a/big-code-analysis-ast/src/roles/go.rs b/big-code-analysis-ast/src/roles/go.rs index 565bbaffe..cce85373b 100644 --- a/big-code-analysis-ast/src/roles/go.rs +++ b/big-code-analysis-ast/src/roles/go.rs @@ -18,19 +18,34 @@ use crate::{Ancestors, FoldLane, Go, Node}; /// the walk's cache, so nested struct types cost one step each rather /// than a climb per field (#1597). fn outside_function_body<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { + crate::documentation::budget::infallible(outside_function_body_with_budget( + node, + ancestors, + &crate::documentation::budget::NoBudget, + )) +} + +fn outside_function_body_with_budget<'a, B: crate::documentation::budget::WorkBudget>( + node: &Node<'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { // role-bypass: allow(Container) — the doc scope's top, not whether // the file opens a space - ancestors.fold_down( + Ok(ancestors.fold_down_with_budget( node, 0, FoldLane::DocScope, 0, - |outside, ancestor, _, _| match ancestor.kind_id().into() { - Go::SourceFile => 1, - Go::StatementList | Go::Block => 0, - _ => outside, + |outside, ancestor, _, _| { + Ok(match ancestor.kind_id().into() { + Go::SourceFile => 1, + Go::StatementList | Go::Block => 0, + _ => outside, + }) }, - ) == 1 + budget, + )? == 1) } /// Whether an interface's `type_elem` is one go/doc documents: an @@ -42,14 +57,41 @@ fn outside_function_body<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> b /// documents, so only an interface's own elements qualify — and only /// outside a function body. fn interface_element_opens_with_a_name<'a>(node: &Node<'a>, ancestors: Ancestors<'a, '_>) -> bool { - ancestors.parent_has_kind(node, Go::InterfaceType as u16) + crate::documentation::budget::infallible(interface_element_with_budget( + node, + ancestors, + &crate::documentation::budget::NoBudget, + )) +} + +fn interface_element_with_budget<'a, B: crate::documentation::budget::WorkBudget>( + node: &Node<'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + Ok(ancestors.parent_has_kind(node, Go::InterfaceType as u16) && node.child(0).is_some_and(|first| { matches!( first.kind_id().into(), Go::TypeIdentifier | Go::QualifiedType | Go::GenericType ) }) - && outside_function_body(node, ancestors) + && outside_function_body_with_budget(node, ancestors, budget)?) +} + +pub(crate) fn doc_target_with_budget<'a, B: crate::documentation::budget::WorkBudget>( + node: &Node<'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + if !doc_target::lists_kind(node.kind_id()) { + return Ok(false); + } + match node.kind_id().into() { + Go::PackageClause | Go::FunctionDeclaration | Go::MethodDeclaration => Ok(true), + Go::TypeElem => interface_element_with_budget(node, ancestors, budget), + _ => outside_function_body_with_budget(node, ancestors, budget), + } } // Whether a comment is a go/doc directive (`//go:generate`, `//line`, diff --git a/big-code-analysis-ast/src/roles/js_family.rs b/big-code-analysis-ast/src/roles/js_family.rs index 268ae280a..09f2e6d87 100644 --- a/big-code-analysis-ast/src/roles/js_family.rs +++ b/big-code-analysis-ast/src/roles/js_family.rs @@ -395,10 +395,23 @@ macro_rules! js_family_doc_gates { /// declarator binds a plain identifier — what JSDoc and tsc /// name; a destructuring declaration documents no binding. fn first_declarator_binds_a_name(node: &$crate::Node<'_>) -> bool { - node.children() - .find(|c| c.kind_id() == $lang::VariableDeclarator as u16) - .and_then(|d| d.child_by_field_name("name")) - .is_some_and(|name| name.kind_id() == $lang::Identifier as u16) + $crate::documentation::budget::infallible(first_declarator_with_budget( + node, + &$crate::documentation::budget::NoBudget, + )) + } + + fn first_declarator_with_budget( + node: &$crate::Node<'_>, + budget: &B, + ) -> Result { + Ok($crate::documentation::budget::child( + node, + |c| c.kind_id() == $lang::VariableDeclarator as u16, + budget, + )? + .and_then(|d| d.child_by_field_name("name")) + .is_some_and(|name| name.kind_id() == $lang::Identifier as u16)) } }; } @@ -410,23 +423,70 @@ macro_rules! js_family_doc_gates { macro_rules! js_doc_gates { ($lang:ident) => { fn export_declares(node: &$crate::Node<'_>) -> bool { - !node.is_child($lang::ExportClause as u16) + $crate::documentation::budget::infallible(export_with_budget( + node, + &$crate::documentation::budget::NoBudget, + )) + } + + fn export_with_budget( + node: &$crate::Node<'_>, + budget: &B, + ) -> Result { + Ok($crate::documentation::budget::child( + node, + |child| child.kind_id() == $lang::ExportClause as u16, + budget, + )? + .is_none()) } fn assigns_to_a_name_or_member(node: &$crate::Node<'_>) -> bool { + $crate::documentation::budget::infallible(assignment_with_budget( + node, + &$crate::documentation::budget::NoBudget, + )) + } + + fn assignment_with_budget( + node: &$crate::Node<'_>, + budget: &B, + ) -> Result { use $lang::*; let mut expr = node.child(0); while let Some(e) = expr.filter(|e| e.kind_id() == ParenthesizedExpression) { - expr = e.children().find(|c| c.is_named() && !c.is_extra()); + budget.step()?; + expr = $crate::documentation::budget::child( + &e, + |c| c.is_named() && !c.is_extra(), + budget, + )?; + } + Ok(expr + .filter(|e| { + matches!( + e.kind_id().into(), + AssignmentExpression | AugmentedAssignmentExpression + ) + }) + .and_then(|e| e.child_by_field_name("left")) + .is_some_and(|left| !matches!(left.kind_id().into(), ObjectPattern | ArrayPattern))) + } + + pub(crate) fn doc_target_with_budget<'s, B: $crate::documentation::budget::WorkBudget>( + node: &$crate::Node<'s>, + code: &[u8], + ancestors: $crate::Ancestors<'s, '_>, + budget: &B, + ) -> Result { + match node.kind_id().into() { + $lang::VariableDeclaration | $lang::LexicalDeclaration => { + first_declarator_with_budget(node, budget) + } + $lang::ExportStatement => export_with_budget(node, budget), + $lang::ExpressionStatement => assignment_with_budget(node, budget), + _ => Ok(doc_target::owns(node, code, ancestors)), } - expr.filter(|e| { - matches!( - e.kind_id().into(), - AssignmentExpression | AugmentedAssignmentExpression - ) - }) - .and_then(|e| e.child_by_field_name("left")) - .is_some_and(|left| !matches!(left.kind_id().into(), ObjectPattern | ArrayPattern)) } }; } @@ -491,6 +551,10 @@ macro_rules! ts_doc_gates { node: &$crate::Node<'a>, ancestors: $crate::Ancestors<'a, '_>, ) -> bool { + $crate::documentation::budget::infallible(export_with_budget(node, ancestors, &$crate::documentation::budget::NoBudget)) + } + + fn export_with_budget<'a, B: $crate::documentation::budget::WorkBudget>(node: &$crate::Node<'a>, ancestors: $crate::Ancestors<'a, '_>, budget: &B) -> Result { use $lang::*; // A plain gate has no bytes to hand the child; the pin sits // beside the forward it protects (#1874). @@ -498,21 +562,17 @@ macro_rules! ts_doc_gates { !$crate::roles::$roles::doc_target::TEXT_GATED, "a TS `DocTarget` row reads bytes; `export_declares_to_tsc` cannot forward with `&[]`" ); - node.child_by_field_name("declaration").map_or_else( - || { - node.is_child(ExportClause as u16) + if let Some(inner) = node.child_by_field_name("declaration") { + Ok(doc_target_with_budget(&inner, &[], ancestors, budget)? || inner.kind_id() == InternalModule as u16) + } else { + Ok($crate::documentation::budget::child(node, |child| child.kind_id() == ExportClause as u16, budget)?.is_some() || node.child_by_field_name("value").is_some_and(|value| { matches!( value.kind_id().into(), FunctionExpression | GeneratorFunction | Class ) - }) - }, - |inner| { - $crate::roles::$roles::doc_target::owns(&inner, &[], ancestors) - || inner.kind_id() == InternalModule as u16 - }, - ) + })) + } } /// The grammar parses `using x = f()` as an assignment its @@ -521,23 +581,36 @@ macro_rules! ts_doc_gates { /// `internal_module` statement (`namespace N { }` after a /// modifier) is a declaration too. fn using_declares(node: &$crate::Node<'_>) -> bool { + $crate::documentation::budget::infallible(using_with_budget(node, &$crate::documentation::budget::NoBudget)) + } + + fn using_with_budget(node: &$crate::Node<'_>, budget: &B) -> Result { use $lang::*; - node.child(0).is_some_and(|e| { + if let Some(e) = node.child(0) { if e.kind_id() == InternalModule { - return true; + return Ok(true); } let assignment = if e.kind_id() == AwaitExpression { - e.children().find(|c| c.is_named() && !c.is_extra()) + $crate::documentation::budget::child(&e, |c| c.is_named() && !c.is_extra(), budget)? } else { Some(e) }; - assignment.is_some_and(|a| { + Ok(assignment.is_some_and(|a| { a.kind_id() == AssignmentExpression && a.child(0).is_some_and(|u| u.kind_id() == Using) && a.child_by_field_name("left") .is_some_and(|left| left.kind_id() == Identifier) - }) - }) + })) + } else { Ok(false) } + } + + pub(crate) fn doc_target_with_budget<'s, B: $crate::documentation::budget::WorkBudget>(node: &$crate::Node<'s>, code: &[u8], ancestors: $crate::Ancestors<'s, '_>, budget: &B) -> Result { + if matches!(node.kind_id().into(), $lang::VariableDeclaration | $lang::LexicalDeclaration) { + return first_declarator_with_budget(node, budget); + } + if node.kind_id() == $lang::ExportStatement { return export_with_budget(node, ancestors, budget); } + if node.kind_id() == $lang::ExpressionStatement { return using_with_budget(node, budget); } + Ok(doc_target::owns(node, code, ancestors)) } }; } diff --git a/big-code-analysis-ast/src/roles/lua.rs b/big-code-analysis-ast/src/roles/lua.rs index 0f2fd2279..20e2ce189 100644 --- a/big-code-analysis-ast/src/roles/lua.rs +++ b/big-code-analysis-ast/src/roles/lua.rs @@ -5,9 +5,8 @@ //! `Catch`, `ElseIf`, `Exit` (#1697) — and //! the documentation rows (#1699) are declared. -use crate::lang_helpers::doc_comment::{ - documents_where_it_sits, ldoc_opener, lua_group_head_above, node_bytes, -}; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::lang_helpers::doc_comment::node_bytes; use crate::role_table; use crate::{Ancestors, Lua, LuaCode, Node}; @@ -15,33 +14,85 @@ use crate::{Ancestors, Lua, LuaCode, Node}; /// `M.x = 1`): LDoc's `get_fun_name` stops at `,`, `<` and `[`, so /// `local a, b = …`, `local x = …` and `M[1] = …` name no item. fn assigns_one_name(node: &Node<'_>) -> bool { + infallible(assigns_one_name_with_budget(node, &NoBudget)) +} + +fn assigns_one_name_with_budget( + node: &Node<'_>, + budget: &B, +) -> Result { // The grammar always emits the `variable_list` first, empty when // recovery had to invent the target (`= 1` on its own). - node.child(0).is_some_and(|targets| { - let mut names = targets.children().filter(Node::is_named); - names.next().is_some_and(|name| is_dotted_name(&name)) && names.next().is_none() - }) + let Some(targets) = node.child(0) else { + return Ok(false); + }; + let mut first = None; + for child in targets.children() { + budget.step()?; + if !child.is_named() { + continue; + } + if first.is_some() { + return Ok(false); + } + if !is_dotted_name(&child, budget)? { + return Ok(false); + } + first = Some(child); + } + Ok(first.is_some()) } /// An identifier, or a `.` index of one (`M.a.b`). -fn is_dotted_name(node: &Node) -> bool { - node.preorder().filter(Node::is_named).all(|part| { - matches!( - part.kind_id().into(), - Lua::Identifier | Lua::DotIndexExpression | Lua::DotIndexExpression2 - ) - }) +fn is_dotted_name(node: &Node, budget: &B) -> Result { + let mut cursor = node.as_tree_sitter().walk(); + loop { + budget.step()?; + let part = cursor.node(); + if part.is_named() + && !matches!( + part.kind_id().into(), + Lua::Identifier | Lua::DotIndexExpression | Lua::DotIndexExpression2 + ) + { + return Ok(false); + } + if cursor.goto_first_child() { + continue; + } + loop { + budget.step()?; + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return Ok(true); + } + } + } } /// Whether a `local` declaration assigns one name (`local x = 1`, not /// a bare `local x`). fn declares_one_name(node: &Node<'_>) -> bool { - node.children().any(|child| { - matches!( + infallible(declares_one_name_with_budget(node, &NoBudget)) +} + +fn declares_one_name_with_budget( + node: &Node<'_>, + budget: &B, +) -> Result { + for child in node.children() { + budget.step()?; + if matches!( child.kind_id().into(), Lua::AssignmentStatement | Lua::AssignmentStatement2 - ) && assigns_one_name(&child) - }) + ) && assigns_one_name_with_budget(&child, budget)? + { + return Ok(true); + } + } + Ok(false) } /// Whether a table field has a name (`new = function … end`): the @@ -55,22 +106,53 @@ fn field_has_a_name(node: &Node<'_>) -> bool { /// Whether a `return` returns a function or a table — the module /// shapes LDoc documents as an item, not an exit. fn returns_a_function_or_table(node: &Node<'_>) -> bool { - node.children() - .find(|child| { - matches!( - child.kind_id().into(), - Lua::ExpressionList | Lua::ExpressionList2 - ) - }) - .and_then(|list| list.children().find(Node::is_named)) - // role-bypass: allow(Closure) — what a returned value documents - // as, not whether it is a closure - .is_some_and(|value| { - matches!( + infallible(returns_with_budget(node, &NoBudget)) +} + +fn returns_with_budget(node: &Node<'_>, budget: &B) -> Result { + for list in node.children() { + budget.step()?; + if !matches!( + list.kind_id().into(), + Lua::ExpressionList | Lua::ExpressionList2 + ) { + continue; + } + for value in list.children() { + budget.step()?; + if !value.is_named() { + continue; + } + // role-bypass: allow(Closure) — what a returned value documents + // as, not whether it is a closure + return Ok(matches!( value.kind_id().into(), Lua::FunctionDefinition | Lua::TableConstructor - ) - }) + )); + } + break; + } + Ok(false) +} + +pub(crate) fn target_with_budget( + node: &Node<'_>, + budget: &B, +) -> Result { + if !doc_target::lists_kind(node.kind_id()) { + return Ok(false); + } + match node.kind_id().into() { + Lua::AssignmentStatement | Lua::AssignmentStatement2 => { + assigns_one_name_with_budget(node, budget) + } + Lua::VariableDeclaration | Lua::VariableDeclaration2 => { + declares_one_name_with_budget(node, budget) + } + Lua::Field => Ok(field_has_a_name(node)), + Lua::ReturnStatement => returns_with_budget(node, budget), + _ => Ok(true), + } } /// Whether a comment opens an LDoc block where LDoc reads one: it opens @@ -87,10 +169,47 @@ fn opens_an_ldoc_block_where_ldoc_reads<'a>( code: &[u8], ancestors: Ancestors<'a, '_>, ) -> bool { - ldoc_opener(node_bytes(node, code)) - && documents_where_it_sits::(node, code, ancestors) - && lua_group_head_above::(node, code, ancestors) - .is_none_or(|head| ldoc_opener(node_bytes(&head, code))) + infallible(opens_with_budget(node, code, ancestors, &NoBudget)) +} + +pub(crate) fn opens_with_budget<'a, B: WorkBudget>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + use crate::Checker; + if !crate::lang_helpers::doc_text::ldoc_opener_with_budget(node_bytes(node, code), budget)? { + return Ok(false); + } + let held = ancestors.fold_down_with_budget( + node, + 0, + crate::FoldLane::DocInBody, + 0, + |held, ancestor, outer, below| { + Ok(u8::from( + held != 0 || LuaCode::holds_doc_comment_in_body(ancestor, code, outer, below), + )) + }, + budget, + )?; + if held != 0 { + return Ok(false); + } + if let Some(head) = ancestors.siblings_before_with_budget(node, budget)?.next() + && LuaCode::is_comment(&head) + && crate::lang_helpers::doc_comment::run_continues_with_budget::< + crate::documentation::recognition::NativeRules, + _, + >(&head, node, code, budget)? + { + return crate::lang_helpers::doc_text::ldoc_opener_with_budget( + node_bytes(&head, code), + budget, + ); + } + Ok(true) } /// Whether a `function_call` is `error(…)` or `os.exit(…)`, by the text diff --git a/big-code-analysis-ast/src/roles/php.rs b/big-code-analysis-ast/src/roles/php.rs index 03f3c1619..7d6b06e9b 100644 --- a/big-code-analysis-ast/src/roles/php.rs +++ b/big-code-analysis-ast/src/roles/php.rs @@ -32,29 +32,60 @@ crate::roles::byte_gate!(opens_with_docblock_marker, phpdoc); /// reads no `use` declarations: that spelling, and the reverse `use /// function define as make;`, read as written (#1646). fn is_define_call(node: &Node<'_>, code: &[u8]) -> bool { - let mut expression = node.children().find(|child| { - matches!( - child.kind_id().into(), - Php::FunctionCallExpression | Php::ParenthesizedExpression - ) - }); - while let Some(parenthesized) = - expression.filter(|e| e.kind_id() == Php::ParenthesizedExpression as u16) - { - expression = parenthesized.children().find(|child| { - matches!( + crate::documentation::budget::infallible(define_with_budget( + node, + code, + &crate::documentation::budget::NoBudget, + )) +} + +fn define_with_budget( + node: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + let mut current = *node; + let expression = loop { + budget.step()?; + let mut expression = None; + for child in current.children() { + budget.step()?; + if matches!( child.kind_id().into(), Php::FunctionCallExpression | Php::ParenthesizedExpression - ) - }); - } - expression + ) { + expression = Some(child); + break; + } + } + if let Some(parenthesized) = + expression.filter(|e| e.kind_id() == Php::ParenthesizedExpression as u16) + { + current = parenthesized; + } else { + break expression; + } + }; + Ok(expression .and_then(|call| call.child_by_field_name("function")) .is_some_and(|callee| match callee.kind_id().into() { Php::Name => node_bytes(&callee, code) == b"define", Php::QualifiedName => node_bytes(&callee, code) == b"\\define", _ => false, - }) + })) +} + +pub(crate) fn target_with_budget<'a, B: crate::documentation::budget::WorkBudget>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + if node.kind_id() == Php::ExpressionStatement { + define_with_budget(node, code, budget) + } else { + Ok(doc_target::owns(node, code, ancestors)) + } } /// Whether an `if_statement` continues a two-word `else if`: its parent diff --git a/big-code-analysis-ast/src/roles/rust.rs b/big-code-analysis-ast/src/roles/rust.rs index e056ede9e..e659558a6 100644 --- a/big-code-analysis-ast/src/roles/rust.rs +++ b/big-code-analysis-ast/src/roles/rust.rs @@ -81,7 +81,23 @@ const DOC_MARKERS: [u16; 4] = [ /// at most its two delimiters as children, so the count spares every /// one of them the cursor the child scan allocates. fn has_doc_marker_child(node: &Node<'_>) -> bool { - node.child_count() > 2 && node.wraps_any(&DOC_MARKERS) + crate::documentation::budget::infallible(doc_marker_with_budget( + node, + &crate::documentation::budget::NoBudget, + )) +} + +pub(crate) fn doc_marker_with_budget( + node: &Node<'_>, + budget: &B, +) -> Result { + Ok(node.child_count() > 2 + && crate::documentation::budget::child( + node, + |child| DOC_MARKERS.contains(&child.kind_id()), + budget, + )? + .is_some()) } role_table! { diff --git a/big-code-analysis-bench/Cargo.toml b/big-code-analysis-bench/Cargo.toml index 5470b1084..18cec90af 100644 --- a/big-code-analysis-bench/Cargo.toml +++ b/big-code-analysis-bench/Cargo.toml @@ -34,6 +34,7 @@ workspace = true # `vcs` is on so the harness can time `vcs::score::apply_percentile` # (#1267), the one hot path here that is not a walk over an AST. big-code-analysis = { path = "..", features = ["vcs"] } +big-code-analysis-ast = { path = "../big-code-analysis-ast", features = ["test-support"] } # For the `verbatim-oracle` record lines (#1744); the root's own # serialisers are what the record carries. serde_json.workspace = true @@ -42,7 +43,6 @@ serde_json.workspace = true # Test-only, path-only like the root dependency above: the shape tests # read `node::WIDE_PARENT` so a fixture sized to the walk's sibling-cache # threshold cannot go narrow if the threshold is raised. -big-code-analysis-ast = { path = "../big-code-analysis-ast", default-features = false } # `html_reports` writes `target/criterion/report/index.html`, which is # what makes a measurement reviewable after the fact rather than a # number pasted into a commit message. @@ -66,3 +66,7 @@ harness = false [[bench]] name = "scaling" harness = false + +[[bench]] +name = "documentation" +harness = false diff --git a/big-code-analysis-bench/benches/documentation.rs b/big-code-analysis-bench/benches/documentation.rs new file mode 100644 index 000000000..20751bfdc --- /dev/null +++ b/big-code-analysis-bench/benches/documentation.rs @@ -0,0 +1,222 @@ +//! Direct-AST source documentation workloads; parsing is outside timed regions. + +use std::hint::black_box; + +use big_code_analysis_ast::documentation::{DocumentationContext, DocumentationOptions}; +use big_code_analysis_ast::{AnyParser, LANG}; +use criterion::{BenchmarkId, Criterion}; + +fn main() { + let mut criterion = Criterion::default().configure_from_args(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + for size in [256, 512, 1024] { + cold(&mut criterion, size, &context, options); + prepared(&mut criterion, size, &context, options); + included_ranges(&mut criterion, size, &context, options); + } + criterion.final_summary(); +} + +fn included_ranges( + criterion: &mut Criterion, + size: usize, + context: &DocumentationContext, + options: DocumentationOptions, +) { + use big_code_analysis_ast::tree_sitter; + let source = "///audit\nfn f() {}\n".repeat(size).into_bytes(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language( + &LANG::Rust + .tree_sitter_language() + .unwrap_or_else(|error| panic!("grammar: {error}")), + ) + .unwrap_or_else(|error| panic!("grammar: {error}")); + let ranges: Vec<_> = (0..size) + .map(|at| tree_sitter::Range { + start_byte: at * 18, + end_byte: (at + 1) * 18, + start_point: tree_sitter::Point::new(at * 2, 0), + end_point: tree_sitter::Point::new((at + 1) * 2, 0), + }) + .collect(); + parser + .set_included_ranges(&ranges) + .unwrap_or_else(|error| panic!("ranges: {error}")); + let tree = parser + .parse(&source, None) + .unwrap_or_else(|| panic!("complete parse")); + let mut group = criterion.benchmark_group("documentation/ranges"); + group.bench_function(BenchmarkId::new("cold", size), |bencher| { + bencher.iter(|| { + black_box( + big_code_analysis_ast::documentation::collect( + LANG::Rust, + &tree, + &source, + context, + &options, + ) + .unwrap_or_else(|error| panic!("collect: {error:?}")), + ) + }); + }); + group.finish(); +} + +fn cold( + criterion: &mut Criterion, + size: usize, + context: &DocumentationContext, + options: DocumentationOptions, +) { + let workloads = [ + ( + "depth", + LANG::Rust, + format!( + "{}///audit\nfn leaf() {{}}{}", + "mod m {".repeat(size), + "}".repeat(size) + ), + ), + ("width", LANG::Rust, "///audit\nfn f() {}\n".repeat(size)), + ( + "fragments", + LANG::Go, + format!("package p\n{}func F() {{}}", "// audit\n".repeat(size)), + ), + ( + "single-line-lua", + LANG::Lua, + format!( + "module(\"m\")\n---{}\nfunction f() end", + "audit ".repeat(size) + ), + ), + ( + "single-line-jsdoc", + LANG::Javascript, + format!("/**{}*/\nfunction f() {{}}", "audit ".repeat(size)), + ), + ( + "c-slots", + LANG::C, + format!( + "/**audit*/\nint {};", + (0..size) + .map(|at| format!("v{at}")) + .collect::>() + .join(",") + ), + ), + ( + "wide-error", + LANG::C, + format!("/**audit*/\nstruct {{\n{}", "int x;\n".repeat(size)), + ), + ( + "missing", + LANG::Rust, + format!( + "fn f() {{ {}0{}; }}", + "(".repeat(size), + ")".repeat(size - 1) + ), + ), + ("names", LANG::Cpp, names_source(size)), + ]; + let mut group = criterion.benchmark_group("documentation/cold"); + for (name, language, source) in workloads { + let parser = AnyParser::parse(language, source.into_bytes(), None, None) + .unwrap_or_else(|error| panic!("{name}: {error}")); + group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { + bencher.iter(|| { + black_box( + parser + .documentation(context, &options) + .unwrap_or_else(|error| panic!("collection: {error:?}")), + ) + }); + }); + } + group.finish(); +} + +fn names_source(size: usize) -> String { + use std::fmt::Write; + let mut source = String::new(); + for at in 0..size { + let _ = writeln!(source, "/** @fn void f{at}() */\nvoid f{at}() {{}}"); + } + source +} + +fn prepared( + criterion: &mut Criterion, + size: usize, + context: &DocumentationContext, + options: DocumentationOptions, +) { + let parser = AnyParser::parse( + LANG::Rust, + "///a\n" + .repeat(size) + .into_bytes() + .into_iter() + .chain(b"fn f() {}".iter().copied()) + .collect(), + None, + None, + ) + .unwrap_or_else(|error| panic!("parse: {error}")); + let index = parser + .documentation(context, &options) + .unwrap_or_else(|error| panic!("collection: {error:?}")); + let document = index + .documents() + .next() + .unwrap_or_else(|| panic!("fixture has a document")); + let text = index + .complete_text(document) + .unwrap_or_else(|error| panic!("text: {error:?}")) + .unwrap_or_else(|| panic!("complete text")); + let owner = parser + .root_node() + .children() + .last() + .unwrap_or_else(|| panic!("fixture has a function")); + let mut group = criterion.benchmark_group("documentation/prepared"); + group.bench_function(BenchmarkId::new("owner", size), |bencher| { + bencher.iter(|| { + black_box( + index + .node_associations(owner.as_tree_sitter()) + .unwrap_or_else(|error| panic!("owner: {error:?}")) + .associations() + .count(), + ) + }); + }); + group.bench_function(BenchmarkId::new("late-map", size), |bencher| { + bencher.iter(|| { + black_box( + text.origins(text.text().len() - 1..text.text().len()) + .unwrap_or_else(|error| panic!("map: {error:?}")) + .count(), + ) + }); + }); + group.bench_function(BenchmarkId::new("retained", size), |bencher| { + bencher.iter(|| { + black_box( + index + .complete_text(document) + .unwrap_or_else(|error| panic!("text: {error:?}")), + ) + }); + }); + group.finish(); +} diff --git a/utils/documentation-collector-perturb.json b/utils/documentation-collector-perturb.json index ff42c271e..fb2a910a6 100644 --- a/utils/documentation-collector-perturb.json +++ b/utils/documentation-collector-perturb.json @@ -3,6 +3,48 @@ "runner": "cargo", "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], "cases": [ + { + "name": "collector-bypasses-fallible-marker-kernel", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "markers::source_comment_with_budget::, _>(", + "new": "markers::source_comment_with_budget::, _>(", + "expect": ["documentation::collector::cancellation_tests::jsdoc_single_line_cancels_inside_virtual_classifier"] + }, + { + "name": "collector-bypasses-fallible-positional-kernel", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "positional::source_comment_with_budget::, _>(", + "new": "positional::source_comment_with_budget::, _>(", + "expect": ["documentation::collector::cancellation_tests::lua_single_line_cancels_inside_content_classifier"] + }, + { + "name": "source-target-cache-disabled", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": "ancestors.try_memoised(crate::node::MemoQuestion::SourceDocTarget, node, || {", + "new": "Ancestors::known(&[]).try_memoised(crate::node::MemoQuestion::SourceDocTarget, node, || {", + "expect": ["documentation::collector::cost_tests::deep_and_wide_source_walks_visit_every_node_once"] + }, + { + "name": "kotlin-owner-pending-hides-text", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": "let content = if attribute {", + "new": "let content = if attribute || draft.pending {", + "expect": ["documentation::collector::assessment_tests::kotlin_local_pending_owner_keeps_complete_text_and_known_leading_association"] + }, + { + "name": "definition-name-index-disabled", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "if self.index.profile == Profile::Doxygen && node.kind() == \"function_definition\" {", + "new": "if false && self.index.profile == Profile::Doxygen && node.kind() == \"function_definition\" {", + "expect": ["documentation::collector::tests::doxygen_static_names_resolve_unique_missing_and_ambiguous_targets"] + }, + { + "name": "java-prelex-fabricates-resolved-owner", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": "draft.unresolved = Some(UnresolvedReason::GrammarBoundary);", + "new": "draft.unresolved = None;", + "expect": ["documentation::collector::assessment_tests::java_prelex_keeps_source_cleaned_evidence_and_uncertain_association"] + }, { "name": "raw-grammar-validation-disabled", "file": "big-code-analysis-ast/src/documentation/collector.rs", @@ -12,7 +54,7 @@ }, { "name": "pending-composition-becomes-empty-complete", - "file": "big-code-analysis-ast/src/documentation/collector.rs", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", "old": "let content = if attribute {\n Content::PendingAdapter", "new": "let content = if attribute {\n Content::Complete { text: String::new(), mappings: Vec::new() }", "expect": ["documentation::collector::tests::rust_pending_attributes_never_report_complete_partial_text"] @@ -20,8 +62,8 @@ { "name": "foreign-document-handles-accepted", "file": "big-code-analysis-ast/src/documentation/index.rs", - "old": " self.facts.check_scope(document)?;", - "new": " let _ = document;", + "old": " self.facts.check_scope(document)?;\n Ok(match &self.facts.documents[document.ordinal].content {", + "new": " let _ = document;\n Ok(match &self.facts.documents[document.ordinal].content {", "expect": ["documentation::collector::tests::document_handles_are_index_qualified_even_for_one_shared_parse"] }, { diff --git a/utils/documentation-form-matrix.json b/utils/documentation-form-matrix.json new file mode 100644 index 000000000..c04176d8f --- /dev/null +++ b/utils/documentation-form-matrix.json @@ -0,0 +1,93 @@ +{ + "contract": "documentation_extraction_cases.md plus PROPOSAL_V3 and approved Kotlin erratum", + "publication": "Unknown for every implemented profile; Rust doc/cfg_attr additionally retains pending publication assessment", + "variants": { + "Rust": { + "implemented": ["basic outer line/block", "adjacent comment composition", "inner root/module/function", "macro Expansion", "comments across ordinary attributes", "raw fragments and exact local comment maps"], + "ineligible": ["plain comments", "document/test/rustfmt::skip attribute paths"], + "pending": ["doc assignment/raw/cooked/metadata attributes", "cfg_attr", "mixed comment/attribute composition", "field/variant/tuple slots", "other local contexts"] + }, + "Java": { + "implemented": ["traditional/Markdown basic declaration", "empty block", "four-slash Markdown", "last selection", "annotation-bearing declaration", "prelex unavailable plus source-cleaned evidence"], + "ineligible": ["ordinary comments", "signature/accessor trivia without a target", "body working notes"], + "pending": ["filename publication", "full module/record/constructor inventory", "semantic Unicode prelexing"] + }, + "Kotlin": { + "implemented": ["basic KDoc function", "last selection across plain comments", "annotation-bearing function", "selected Local raw/text/maps"], + "ineligible": ["ordinary comments", "line-comment documentation"], + "pending": ["Local signature/modifier/accessor/constructor projection", "parameter/property slots", "full declaration inventory"] + }, + "Groovy": { + "implemented": ["basic Groovydoc type", "nearest selection", "annotation-bearing type"], + "ineligible": ["ordinary comments", "plain comment detaches nearest block", "Local placement is not emitted"], + "pending": ["full member/constructor/record inventory", "publication"] + }, + "Csharp": { + "implemented": ["basic XML type", "leading trivia selection", "attribute-bearing declaration", "literal XML markup"], + "ineligible": ["ordinary comments", "four-slash banner", "accessor trivia", "Local placement is not emitted"], + "pending": ["full field/event/property/indexer/operator inventory", "conditional member projections", "publication"] + }, + "Php": { + "implemented": ["basic function/class", "one/two/three-block precedence", "enum declaration-before-file", "file preamble", "last selection"], + "ineligible": ["non-PHPDoc markers", "superseded blocks", "unsupported qualified call spellings"], + "pending": ["signature/promoted slots", "define constant slots and imported callees", "PhpDocumentor alternate", "publication"] + }, + "Javascript": { + "implemented": ["basic function/class", "export declaration projection", "nested forward docs", "file/fileoverview/overview/module", "leading selection"], + "ineligible": ["ordinary comments", "body working notes without a target", "destructuring declaration"], + "pending": ["virtual naming directives", "variable/assignment/member slots", "full export/member inventory", "publication"] + }, + "Mozjs": { + "implemented": ["basic function/class", "export declaration projection", "nested forward docs", "file/fileoverview/overview/module", "leading selection"], + "ineligible": ["ordinary comments", "body working notes without a target", "destructuring declaration"], + "pending": ["virtual naming directives", "variable/assignment/member slots", "full export/member inventory", "publication"] + }, + "Typescript": { + "implemented": ["basic function", "export/ambient declaration projection", "module/packageDocumentation file precedence", "leading selection"], + "ineligible": ["ordinary comments", "after-code non-parameter comments", "destructuring declarations", "unsupported assignments"], + "pending": ["parameter/binding slots", "virtual forms", "full overload/namespace/type/member inventory", "publication"] + }, + "Tsx": { + "implemented": ["basic JSX-returning function", "export/ambient declaration projection", "module/packageDocumentation file precedence", "leading selection"], + "ineligible": ["ordinary comments", "after-code non-parameter comments", "destructuring declarations", "unsupported assignments"], + "pending": ["parameter/binding slots", "virtual forms", "full overload/namespace/type/member inventory", "publication"] + }, + "C": { + "implemented": ["basic definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures", "line/block phase-two splicing"], + "ineligible": ["ordinary comments", "quoted/CDATA structural lookalikes", "banner markers"], + "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery projections", "complex declarators", "publication"] + }, + "Cpp": { + "implemented": ["basic definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures including definitions", "line/block phase-two splicing"], + "ineligible": ["ordinary comments", "quoted/CDATA structural lookalikes", "banner markers"], + "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery/template projections", "complex declarators", "publication"] + }, + "Mozcpp": { + "implemented": ["basic definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures", "line/block phase-two splicing"], + "ineligible": ["ordinary comments", "quoted/CDATA structural lookalikes", "banner markers"], + "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery/template projections", "complex declarators", "publication"] + }, + "Objc": { + "implemented": ["basic C definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures", "line/block phase-two splicing"], + "ineligible": ["ordinary comments", "quoted/CDATA structural lookalikes", "banner markers"], + "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery projections", "full method/property/protocol inventory", "publication"] + }, + "Go": { + "implemented": ["basic function/package", "declaration group and spec", "positional runs", "directive filtering", "literal block stars"], + "ineligible": ["local declarations", "ordinary trailing comments", "source blank-line-separated run", "directive-only prose"], + "pending": ["multi-name field slots", "interface elements", "publication"] + }, + "Ruby": { + "implemented": ["basic method/type", "modifier/body wrapper projections", "native YARD scope", "magic/directive filtering", "begin/end block cleanup"], + "ineligible": ["call-block source scope", "magic/shebang prose", "source blank-line-separated run"], + "pending": ["Explicit virtual/## owners", "attribute/alias/visibility slots", "RDoc alternate", "publication"] + }, + "Lua": { + "implemented": ["basic following function", "block wrapper", "FirstFile opener", "marked lines and long comments", "local text/maps"], + "ineligible": ["ordinary standalone leading run", "empty marked block", "function-body annotation"], + "pending": ["tagged virtual/table forms", "native table-field/parameter comments", "full assignment/return inventory", "publication"] + } + }, + "deferred": ["Python", "Perl", "Elixir", "Bash", "Tcl", "Irules"], + "helpers": ["Ccomment", "Preproc"] +} diff --git a/utils/documentation-markers-perturb.json b/utils/documentation-markers-perturb.json index f722d2cf1..1d95d38af 100644 --- a/utils/documentation-markers-perturb.json +++ b/utils/documentation-markers-perturb.json @@ -27,8 +27,8 @@ { "name": "source-candidates-precede-last-selection", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "Self::Source(_) => T::is_source_doc_comment(node, code),", - "new": "Self::Source(_) => T::is_doc_comment(node, code),", + "old": "Self::Source(_) => R::marker(node, code, budget)?,", + "new": "Self::Source(_) => R::Checker::is_doc_comment(node, code),", "expect": ["documentation::streaming::markers::tests::java_source_selects_empty_new_block_before_legacy_selection"] }, { @@ -90,15 +90,15 @@ { "name": "source-included-byte-barriers-precede-selection", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "Self::Source(context) => context.covers(span),", - "new": "Self::Source(_context) => true,", + "old": "Self::Source(context) => context.covers_with_budget(span, budget),", + "new": "Self::Source(_context) => Ok(true),", "expect": ["documentation::streaming::markers::regressions::excluded_marker_cannot_supersede_genuine_documentation", "documentation::streaming::markers::regressions::excluded_attachment_and_target_bytes_are_barriers", "documentation::streaming::markers::regressions::excluded_code_keeps_unrelated_later_docs_and_splits_comment_runs"] }, { "name": "opaque-token-retains-unknown-evidence", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "if request.retain_unbound && T::is_comment(node) {", - "new": "if false && request.retain_unbound && T::is_comment(node) {", + "old": "if request.retain_unbound && R::Checker::is_comment(node) {", + "new": "if false && request.retain_unbound && R::Checker::is_comment(node) {", "expect": ["documentation::streaming::markers::regressions::excluded_marker_byte_never_becomes_a_native_marker"] }, { @@ -111,15 +111,15 @@ { "name": "lone-cr-is-source-content", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "let lf = if context.covers(end - 1..end) && code.get(end - 1) == Some(&b'\\n') {", - "new": "let lf = if code.get(end - 1) == Some(&b'\\r') { return end - 1; } else if context.covers(end - 1..end) && code.get(end - 1) == Some(&b'\\n') {", + "old": "let lf = if context.covers_with_budget(end.saturating_sub(1)..end, budget)?", + "new": "let lf = if code.get(end.wrapping_sub(1)) == Some(&b'\\r') { return Ok(end - 1); } else if context.covers_with_budget(end.saturating_sub(1)..end, budget)?", "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] }, { "name": "excluded-lf-does-not-strip-included-cr", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": "if context.covers(lf..lf + 1) && code.get(lf) == Some(&b'\\n') {\n if context.covers(lf - 1..lf + 1) && code.get(lf - 1) == Some(&b'\\r') {", - "new": "if code.get(lf) == Some(&b'\\n') {\n if code.get(lf - 1) == Some(&b'\\r') {", + "old": "if context.covers_with_budget(lf..lf + 1, budget)? && code.get(lf) == Some(&b'\\n') {\n if context.covers_with_budget(lf.saturating_sub(1)..lf + 1, budget)?\n && code.get(lf.wrapping_sub(1)) == Some(&b'\\r')\n {", + "new": "if code.get(lf) == Some(&b'\\n') {\n if code.get(lf.wrapping_sub(1)) == Some(&b'\\r') {", "expect": ["documentation::streaming::markers::regressions::rust_verbatim_line_terminators", "documentation::streaming::markers::regressions::java_verbatim_line_terminators"] }, { @@ -132,8 +132,8 @@ { "name": "gatherer-search-must-not-repeat", "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", - "old": ".map(|gathers| doc_comment::bind_gathered(stretch, code, gathers, marker, forward));", - "new": ".map(|gathers| { let _ = doc_comment::bind_gathered(stretch, code, gathers, marker, forward); doc_comment::bind_gathered(stretch, code, gathers, marker, forward) });", + "old": "let result = if binding.gathers.is_some() {\n Some(doc_comment::bind_gathered_with_budget(", + "new": "let result = if binding.gathers.is_some() {\n let _ = doc_comment::bind_gathered_with_budget(stretch, code, |node| R::gathers(node, code, budget), &marker, &forward, budget)?;\n Some(doc_comment::bind_gathered_with_budget(", "expect": ["documentation::streaming::markers::regressions::c_gatherer_search_is_once_per_stretch", "documentation::streaming::markers::regressions::cpp_gatherer_search_is_once_per_stretch", "documentation::streaming::markers::regressions::mozcpp_gatherer_search_is_once_per_stretch", "documentation::streaming::markers::regressions::objc_gatherer_search_is_once_per_stretch"] }, { @@ -160,8 +160,8 @@ { "name": "first-source-token-keeps-excluded-prefix", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "prefix_gap = !view.covers(start..boundary);", - "new": "prefix_gap = false && !view.covers(start..boundary);", + "old": "prefix_gap = !view.covers_with_budget(start..boundary, budget)?;", + "new": "prefix_gap = false && !view.covers_with_budget(start..boundary, budget)?;", "expect": ["documentation::streaming::markers::regressions::typescript_source_prefix_gap_is_not_preceding_code", "documentation::streaming::markers::regressions::tsx_source_prefix_gap_is_not_preceding_code"] }, { @@ -181,8 +181,8 @@ { "name": "php-file-scan-checks-before-first-node", "file": "big-code-analysis-ast/src/checker/php.rs", - "old": "if !view.covers(0..boundary) {", - "new": "if false && !view.covers(0..boundary) {", + "old": "if !view.covers_with_budget(0..boundary, budget)? {", + "new": "if false && !view.covers_with_budget(0..boundary, budget)? {", "expect": ["documentation::streaming::markers::regressions::php_source_prefix_gap_keeps_unknown_direction_out_of_selection"] }, { @@ -195,7 +195,7 @@ { "name": "marker-exhaustion-after-skipped-trivia-is-not-eof", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "None => exhausted_stretch(comment, boundary, code, ancestors, view),", + "old": "None => exhausted_stretch(comment, boundary, code, ancestors, view, budget)?,", "new": "None => StretchEnd::Elsewhere,", "expect": ["documentation::streaming::markers::regressions::suffix::marker_exhaustion_checks_after_final_skipped_trivia"] }, diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json index 837e1d2e8..39d7e4188 100644 --- a/utils/documentation-positional-perturb.json +++ b/utils/documentation-positional-perturb.json @@ -6,14 +6,14 @@ { "name": "ruby-source-opener-leaks-call-block-scope", "file": "big-code-analysis-ast/src/checker/ruby.rs", - "old": "&& ruby_source_yard_reads(YardScope::Namespace, first, ancestors)", - "new": "&& ruby_yard_reads(YardScope::Namespace, first, ancestors)", + "old": " ancestors,\n true,\n budget,\n )?)", + "new": " ancestors,\n false,\n budget,\n )?)", "expect": ["documentation::streaming::positional::tests::ruby_yard_scope_uses_actual_wrapper_context"] }, { "name": "lua-first-file-scan-crosses-excluded-siblings", "file": "big-code-analysis-ast/src/checker/lua.rs", - "old": " if source.is_some_and(|source| !source.covers(sibling.start_byte()..earliest.end_byte())) {\n return Err(crate::documentation::UnresolvedReason::ExcludedGap);\n }\n if source.is_some_and(|source| {\n before\n .peek()\n .is_some_and(|above| !source.covers(above.start_byte()..sibling.end_byte()))\n }) {\n return Err(crate::documentation::UnresolvedReason::ExcludedGap);\n }\n", + "old": " if let Some(source) = source\n && !source.covers_with_budget(sibling.start_byte()..earliest.end_byte(), budget)?\n {\n return Ok(Err(crate::documentation::UnresolvedReason::ExcludedGap));\n }\n if let Some(source) = source\n && let Some(above) = before.peek()\n && !source.covers_with_budget(above.start_byte()..sibling.end_byte(), budget)?\n {\n return Ok(Err(crate::documentation::UnresolvedReason::ExcludedGap));\n }\n", "new": "", "expect": ["documentation::streaming::positional::tests::lua_gap_never_fabricates_first_file_context"] }, @@ -34,8 +34,8 @@ { "name": "source-drop-recovered-candidate", "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", - "old": ".filter(|n| T::is_source_doc_target(n, source.bytes(), ancestors));", - "new": ".filter(|n| !n.has_error() && T::is_source_doc_target(n, source.bytes(), ancestors));", + "old": "&& R::target(&node, source.bytes(), ancestors, budget)?", + "new": "&& !node.has_error() && R::target(&node, source.bytes(), ancestors, budget)?", "expect": ["documentation::streaming::positional::tests::go_missing_target_retains_uncertain_canonical_candidate"] }, { @@ -55,8 +55,8 @@ { "name": "positional-final-member-deferral", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "if continuous && next.is_some_and(|n| run_continues_to::(comment, &n, code)) {", - "new": "if false && continuous && next.is_some_and(|n| run_continues_to::(comment, &n, code)) {", + "old": "if continuous\n && let Some(next) = next", + "new": "if false && continuous\n && let Some(next) = next", "expect": ["documentation::streaming::positional::tests::go_completed_run_is_scanned_once", "documentation::streaming::positional::tests::ruby_completed_run_is_scanned_once", "documentation::streaming::positional::tests::lua_completed_run_is_scanned_once"] }, { @@ -76,7 +76,7 @@ { "name": "lua-ordinary-comment-is-not-inference", "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", - "old": "Ok(None) if T::SOURCE_POSITIONAL_TARGETS && decision.target.is_some() => {", + "old": "Ok(None) if R::Checker::SOURCE_POSITIONAL_TARGETS && decision.target.is_some() => {", "new": "Ok(None) if decision.target.is_some() => {", "expect": ["documentation::streaming::positional::tests::lua_plain_marked_first_file_and_later_contexts"] }, @@ -125,8 +125,8 @@ { "name": "exhausted-positional-suffix-is-not-eof", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "!view.covers(last_examined_end..scope_end)", - "new": "false && !view.covers(last_examined_end..scope_end)", + "old": "!view.covers_with_budget(last_examined_end..scope_end, budget)?", + "new": "false && !view.covers_with_budget(last_examined_end..scope_end, budget)?", "expect": ["documentation::streaming::positional::tests::remediation::go_exhaustion_reports_unknown_suffix", "documentation::streaming::positional::tests::remediation::ruby_exhaustion_preserves_explicit_selection", "documentation::streaming::positional::tests::remediation::lua_exhaustion_preserves_known_file_and_tagged_selection"] }, { @@ -139,8 +139,8 @@ { "name": "yard-later-member-is-not-first-only", "file": "big-code-analysis-ast/src/checker/ruby.rs", - "old": "|| run.members.iter().skip(1).any(|member| {", - "new": "|| run.members.iter().skip(1).take(0).any(|member| {", + "old": "for member in run.members.iter().skip(1) {", + "new": "for member in run.members.iter().skip(1).take(0) {", "expect": ["documentation::streaming::positional::tests::remediation::yard_later_directives_follow_trivia_or_prose"] }, { @@ -181,7 +181,7 @@ { "name": "uncertain-prefix-must-cover-the-first-multiline-ending-row", "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", - "old": "let mut connected_end_row = nodes[eligible_start].end_row();\n while let Some(node) = nodes.get(eligible_start)\n && node.start_row() <= connected_end_row\n {\n connected_end_row = connected_end_row.max(node.end_row());\n eligible_start += 1;\n }", + "old": "let mut connected_end_row = nodes[eligible_start].end_row();\n while let Some(node) = nodes.get(eligible_start)\n && node.start_row() <= connected_end_row\n {\n budget.step().map_err(Into::into)?;\n connected_end_row = connected_end_row.max(node.end_row());\n eligible_start += 1;\n }", "new": "let row = nodes[eligible_start].start_row();\n eligible_start += nodes[eligible_start..].iter().take_while(|node| node.start_row() == row).count();", "expect": ["documentation::streaming::positional::tests::cycle2::uncertain_multiline_prefix_excludes_all_row_connected_members"] }, @@ -195,8 +195,8 @@ { "name": "trailing-only-keeps-its-known-candidate", "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", - "old": "if collected.eligible_start == collected.nodes.len() {\n return decision;", - "new": "if collected.eligible_start == collected.nodes.len() {\n decision.target = None;\n return decision;", + "old": "if collected.eligible_start == collected.nodes.len() {\n return Ok(decision);", + "new": "if collected.eligible_start == collected.nodes.len() {\n decision.target = None;\n return Ok(decision);", "expect": ["documentation::streaming::positional::tests::cycle2::go_trailing_only_keeps_candidate_without_selection", "documentation::streaming::positional::tests::cycle2::ruby_trailing_only_keeps_candidate_without_selection", "documentation::streaming::positional::tests::cycle2::lua_trailing_only_keeps_candidate_without_selection"] }, { @@ -209,8 +209,8 @@ { "name": "legacy-exhaustion-must-bypass-source-scope-bounds", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", - "old": "if matches!(view, CandidateView::Legacy) {\n return false;", - "new": "if false && matches!(view, CandidateView::Legacy) {\n return false;", + "old": "if matches!(view, CandidateView::Legacy) {\n return Ok(false);", + "new": "if false && matches!(view, CandidateView::Legacy) {\n return Ok(false);", "expect": ["documentation::streaming::positional::tests::remediation::go_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::ruby_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::lua_legacy_materializes_no_members"] } ] From 5808df534da584ce5abd41a9f8353caeea3b4e9d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:56:32 -0800 Subject: [PATCH 037/221] test(documentation): retarget positional mutations to fallible kernels --- utils/documentation-positional-perturb.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/documentation-positional-perturb.json b/utils/documentation-positional-perturb.json index 39d7e4188..ccc1bbe7f 100644 --- a/utils/documentation-positional-perturb.json +++ b/utils/documentation-positional-perturb.json @@ -21,7 +21,7 @@ "name": "lua-prose-only-in-opener-member", "file": "big-code-analysis-ast/src/checker/lua.rs", "old": "if !text.text {", - "new": "if !{ let mut first_text = LdocText::default(); first_text.read(first, run.code); first_text.text } {", + "new": "if !{ let mut first_text = LdocText::default(); first_text.read_with_budget(first, run.code, budget)?; first_text.text } {", "expect": ["documentation::streaming::positional::tests::lua_plain_marked_first_file_and_later_contexts"] }, { @@ -112,7 +112,7 @@ "name": "legacy-must-not-materialize-before-acceptance", "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", "old": "let Some(first) = run.first_eligible else {", - "new": "let _members = run.materialize(ancestors);\n let Some(first) = run.first_eligible else {", + "new": "let _members = infallible(run.materialize_with_budget(ancestors, &NoBudget));\n let Some(first) = run.first_eligible else {", "expect": ["documentation::streaming::positional::tests::remediation::go_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::ruby_legacy_materializes_no_members", "documentation::streaming::positional::tests::remediation::lua_legacy_materializes_no_members", "metrics::loc::documentation_tests::documentation_go_positional_exact_rows"] }, { From 5c13db75729459b25b31de95bf07bd4bbfef4e47 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:38:30 -0800 Subject: [PATCH 038/221] fix(documentation): qualify pending projections and exact local cleanup --- .bca-baseline.toml | 164 ++++++-- CHANGELOG.md | 3 + big-code-analysis-ast/src/documentation.rs | 29 ++ .../src/documentation/collector.rs | 78 ++-- .../src/documentation/collector/assembly.rs | 79 +++- .../collector/assessment_tests.rs | 44 ++ .../src/documentation/collector/cost_tests.rs | 82 ++++ .../src/documentation/collector/form_tests.rs | 201 +++++++++ .../collector/projection_tests.rs | 85 ++++ .../documentation/collector/projections.rs | 44 +- .../src/documentation/forms.rs | 38 +- .../src/documentation/index.rs | 95 ++++- .../src/documentation/source.rs | 20 + .../src/documentation/text.rs | 2 + .../src/documentation/text/cleanup.rs | 398 ++++++++++++++++++ .../src/documentation/text/comments.rs | 68 ++- .../src/documentation/text/literals.rs | 342 ++++++++++++--- .../src/documentation/text/tests.rs | 4 + big-code-analysis-ast/src/node.rs | 8 + big-code-analysis-ast/src/node/ancestors.rs | 4 + .../src/node/ancestors/folds.rs | 2 + .../src/node/ancestors/siblings.rs | 7 + .../benches/documentation.rs | 116 +++++ utils/documentation-collector-perturb.json | 35 ++ utils/documentation-form-matrix.json | 18 +- 25 files changed, 1764 insertions(+), 202 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/collector/form_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/text/cleanup.rs diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 880a8b69e..37712dea8 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,13 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 882.0 +value = 901.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 123.0 +value = 127.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -472,14 +472,20 @@ value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::register" -metric = "cyclomatic" +metric = "cognitive" value = 15.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "cyclomatic" +value = 16.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::register" metric = "halstead.effort" -value = 70341.82893047434 +value = 75856.64234451539 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -491,25 +497,25 @@ value = 6.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::rust_attribute" metric = "abc" -value = 50.21951811795888 +value = 38.948684188300895 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::rust_attribute" -metric = "cognitive" -value = 22.0 +metric = "halstead.effort" +value = 127301.51843197798 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::rust_attribute" -metric = "halstead.effort" -value = 192758.27410592738 +metric = "nexits" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::rust_attribute" +qualified = "Builder<'s>::rust_carrier" metric = "nexits" -value = 6.0 +value = 7.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -569,13 +575,13 @@ value = 58161.637831875196 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "abc" -value = 47.01063709417264 +value = 42.67317658670374 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cognitive" -value = 25.0 +value = 20.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -587,12 +593,18 @@ value = 19.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "halstead.effort" -value = 135337.94741648942 +value = 106857.85979066297 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::named_document" +metric = "nexits" value = 7.0 [[entry]] @@ -617,7 +629,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "abc" -value = 51.24451190127583 +value = 53.749418601506754 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" @@ -629,37 +641,37 @@ value = 20.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "halstead.effort" -value = 139186.7870688173 +value = 118991.71741040709 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "nexits" -value = 6.0 +value = 9.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cognitive" -value = 19.0 +value = 21.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cyclomatic" -value = 18.0 +value = 21.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "halstead.effort" -value = 101368.16786835015 +value = 110018.09239923891 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "nexits" -value = 6.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" @@ -683,13 +695,13 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/forms.rs" qualified = "assess" metric = "cyclomatic" -value = 17.0 +value = 21.0 [[entry]] path = "big-code-analysis-ast/src/documentation/forms.rs" qualified = "assess" metric = "halstead.effort" -value = 48579.95593242823 +value = 64239.10958745882 [[entry]] path = "big-code-analysis-ast/src/documentation/forms.rs" @@ -835,6 +847,84 @@ qualified = "TextBuilder<'s>::copied_pieces" metric = "nexits" value = 8.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "Projection<'_, 's>::copy" +metric = "halstead.effort" +value = 76728.81532849002 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "abc" +value = 60.08327554319921 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "cognitive" +value = 26.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "cyclomatic" +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "halstead.effort" +value = 215562.59407539252 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "nexits" +value = 9.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "ruff" +metric = "abc" +value = 62.321745803531535 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "ruff" +metric = "cognitive" +value = 27.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "ruff" +metric = "cyclomatic" +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "ruff" +metric = "halstead.effort" +value = 282150.07375396066 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "ruff" +metric = "nexits" +value = 10.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "" +metric = "loc.ploc" +value = 541.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "append_range" @@ -845,25 +935,25 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "abc" -value = 62.68173577685928 +value = 66.70832032063167 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "cognitive" -value = 36.0 +value = 38.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "cyclomatic" -value = 26.0 +value = 28.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "halstead.effort" -value = 350711.9003697722 +value = 383332.4051257595 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -875,7 +965,7 @@ value = 15.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "blank" metric = "nexits" -value = 7.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -959,25 +1049,25 @@ value = 9.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "abc" -value = 72.53275122315436 +value = 68.18357573492314 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "cognitive" -value = 56.0 +value = 50.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "cyclomatic" -value = 25.0 +value = 22.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "halstead.effort" -value = 270557.5417208994 +value = 242315.44217119092 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -995,25 +1085,25 @@ value = 16.0 path = "big-code-analysis-ast/src/documentation/text/literals.rs" qualified = "decode" metric = "abc" -value = 87.55569655939013 +value = 72.00694410957877 [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" qualified = "decode" metric = "cognitive" -value = 42.0 +value = 19.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" qualified = "decode" metric = "cyclomatic" -value = 38.0 +value = 31.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" qualified = "decode" metric = "halstead.effort" -value = 430739.9986277097 +value = 267982.30459387787 [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" @@ -1025,7 +1115,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/text/literals.rs" qualified = "decode" metric = "nexits" -value = 17.0 +value = 16.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d2a045a3..d0564cd28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,9 @@ for historical reference. Source recognition uses fallible work-budget kernels shared with legacy wrappers. Kotlin local KDoc retains complete text with pending owner evidence; Java prelexing limitations retain separately labeled source-cleaned spelling. + Prepared node projections expose multi-owner and pending forms. Complex + declarators remain pending, and gathered Doxygen references use their + structural member. Reusable Python/Tcl cleanup preserves token origins. (#1660, #1661) - Added unstable AST positional-run evidence for Go, Ruby and Lua, including diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index f615d4c85..68d895a2b 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -5,6 +5,17 @@ //! and content state, and associations add profile-qualified attachment. //! Collection retains immutable source facts, local text and prepared owner queries. //! All items are unstable direct-AST plumbing; no root facade is introduced. +//! +//! The collector stores flat node, occurrence and membership arenas. Text and +//! maps are materialized once per document. Structural work is linear in visits, +//! contributing bytes and memberships, with separate range lookups +//! `O((N + F) log(R + 1) + I)`, cached sibling-position searches, and dependency +//! field-lookup costs. Numeric document/association/fragment ordering adds its +//! respective `O(M log M)` terms. Name indexing hashes and compares spelling bytes +//! incrementally; equal spellings share a bucket entry. Prepared owner queries +//! inspect only their indexed associations and linked pending scopes. Individual +//! dependency calls and allocation are not internally interruptible; crate-owned +//! scans use the collection work budget. pub(crate) mod budget; pub(crate) mod byte_scan; @@ -61,6 +72,18 @@ pub struct Observations { pub target_computations: usize, /// Byte visits in shared classifier scans. pub classifier_bytes: usize, + /// Pending-scope query links and records visited. + pub assessment_scope_reads: usize, + /// Dependency field lookups made by recognition callbacks. + pub field_lookups: usize, + /// Dependency indexed child lookups made by recognition callbacks. + pub child_lookups: usize, + /// Cached per-node answers probed, including source classification. + pub memo_probes: usize, + /// Ancestor fold state slots examined. + pub fold_slot_probes: usize, + /// Recorded sibling positions compared. + pub sibling_slot_probes: usize, } /// Read qualification counters without resetting other consumers' observations. @@ -82,6 +105,12 @@ pub fn observations() -> Observations { target_queries: recognition::target_queries::observed(), target_computations: recognition::target_computations::observed(), classifier_bytes: byte_scan::bytes_read::observed(), + assessment_scope_reads: index::assessment_scope_reads::observed(), + field_lookups: crate::node::field_lookups::observed(), + child_lookups: crate::node::child_lookups::observed(), + memo_probes: crate::node::memo_probes::observed(), + fold_slot_probes: crate::node::fold_slot_probes::observed(), + sibling_slot_probes: crate::node::sibling_slot_probes::observed(), } } diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index ce2816f05..06b4c3a33 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -303,7 +303,7 @@ impl<'s> Builder<'s> { } else { NativeRules::::target(node, self.index.source.bytes(), ancestors, budget)? }; - if qualifies { + if qualifies || super::forms::slot_candidate(self.index.profile, node.kind()) { if is_wrapper(self.index.profile, node.kind()) || needs_slot(self.index.profile, node.kind()) || super::forms::owner_pending(self.index.profile, node, ancestors) @@ -319,7 +319,7 @@ impl<'s> Builder<'s> { | "template_declaration" | "expression_statement" )) - || node.is_error() + || node.has_error() || node.is_missing() { self.index.canonical.nodes[id.0].projection = Projection::Pending; @@ -659,31 +659,8 @@ impl<'s> Builder<'s> { node: &Node<'s>, budget: &CollectionBudget, ) -> Result<(), CollectionError> { - let mut is_doc = false; - for child in node.children() { - budget.step()?; - if child.kind() != "attribute" { - continue; - } - let mut cursor = child.cursor(); - for path in child.children_with(&mut cursor) { - budget.step()?; - if !path.is_named() { - continue; - } - if path.kind() == "identifier" - && self - .index - .source - .covers_with_budget(path.start_byte()..path.end_byte(), budget)? - { - let bytes = &self.index.source.bytes()[path.start_byte()..path.end_byte()]; - is_doc = matches!(bytes, b"doc" | b"cfg_attr"); - } - break; - } - } - if !is_doc { + let carrier = self.rust_carrier(node, budget)?; + if carrier == Some(false) { return Ok(()); } let mut target = if node.kind() == "attribute_item" { @@ -717,7 +694,11 @@ impl<'s> Builder<'s> { let assessment = self.index.assessments.len(); self.index.assessments.push(Assessment { axis: AssessmentAxis::Occurrence, - reason: "Structured Rust doc/cfg_attr carrier awaits interpretation", + reason: if carrier.is_none() { + "Excluded or recovered Rust attribute path may carry documentation" + } else { + "Structured Rust doc/cfg_attr carrier awaits interpretation" + }, node: Some(self.index.canonical.nodes[id.0].evidence), document: None, }); @@ -737,6 +718,9 @@ impl<'s> Builder<'s> { self.index.canonical.nodes[pending_scope.0] .pending .push(publication); + if carrier.is_none() { + return Ok(()); + } let source = self .index .source @@ -750,6 +734,42 @@ impl<'s> Builder<'s> { Ok(()) } + fn rust_carrier( + &self, + node: &Node<'s>, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + for child in node.children() { + budget.step()?; + bounds(child.as_tree_sitter(), self.index.source.bytes().len())?; + if child.kind() != "attribute" { + continue; + } + for path in child.children() { + budget.step()?; + bounds(path.as_tree_sitter(), self.index.source.bytes().len())?; + if !path.is_named() { + continue; + } + if !self + .index + .source + .covers_with_budget(path.start_byte()..path.end_byte(), budget)? + { + return Ok(None); + } + return Ok(Some( + path.kind() == "identifier" + && matches!( + &self.index.source.bytes()[path.start_byte()..path.end_byte()], + b"doc" | b"cfg_attr" + ), + )); + } + } + Ok((!node.has_error()).then_some(false)) + } + fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { self.combine_pending(budget)?; for draft in std::mem::take(&mut self.drafts) { @@ -919,6 +939,8 @@ mod cancellation_tests; #[cfg(test)] mod cost_tests; #[cfg(test)] +mod form_tests; +#[cfg(test)] mod projection_tests; #[cfg(test)] mod tests; diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index 1ac7450d1..afad1d19a 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -10,7 +10,12 @@ impl<'s> Builder<'s> { let mut by_target = std::collections::HashMap::new(); for (index, draft) in self.drafts.iter().enumerate() { budget.step()?; - if let Some(target) = draft.target && matches!(draft.role, DocumentRole::Primary | DocumentRole::FilePackage) { + if let Some(target) = draft.target + && matches!( + draft.role, + DocumentRole::Primary | DocumentRole::FilePackage + ) + { by_target.insert(target, index); } } @@ -85,21 +90,14 @@ impl<'s> Builder<'s> { let mut owners = Vec::new(); let mut pending = draft.pending; let mut named_resolution = None; - if self.index.profile == Profile::Doxygen && draft.target.is_none() { - let fragment = - &self.index.facts.fragments[self.index.facts.documents[document.0].fragments[0].0]; - if let Some(node) = fragment.node { - let raw = &self.index.source.bytes()[node.node().byte_range()]; - if let Some((b"fn", name)) = - crate::lang_helpers::doxygen::structural_command_with_budget(raw, budget)? - { - let (found, reason) = self.names.resolve(name, budget)?; - owners = found; - named_resolution = - Some(reason.map_or(Resolution::Resolved, Resolution::Unresolved)); - pending = false; - } - } + if self.index.profile == Profile::Doxygen + && draft.target.is_none() + && !draft.gap + && let Some((found, resolution)) = self.named_document(document, budget)? + { + owners = found; + named_resolution = Some(resolution); + pending = false; } if let Some(target) = draft.target { match &self.index.canonical.nodes[target.0].projection { @@ -124,11 +122,11 @@ impl<'s> Builder<'s> { self.index.facts.associations.push(Association { document, owners, - resolution: named_resolution.unwrap_or_else(|| { - draft - .unresolved - .map_or(Resolution::Resolved, Resolution::Unresolved) - }), + resolution: draft + .unresolved + .map(Resolution::Unresolved) + .or(named_resolution) + .unwrap_or(Resolution::Resolved), convention: Convention(self.index.profile.name()), binding: draft.binding, lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence, @@ -173,6 +171,45 @@ impl<'s> Builder<'s> { Ok(()) } + fn named_document( + &self, + document: DocumentId, + budget: &CollectionBudget, + ) -> Result, Resolution)>, CollectionError> { + for id in self.index.facts.documents[document.0] + .fragments + .iter() + .rev() + { + budget.step()?; + let fragment = &self.index.facts.fragments[id.0]; + let Some(node) = fragment.node else { + continue; + }; + if !self + .index + .source + .covers_with_budget(node.node().byte_range(), budget)? + { + return Ok(None); + } + let raw = &self.index.source.bytes()[node.node().byte_range()]; + if let Some((command, name)) = + crate::lang_helpers::doxygen::structural_command_with_budget(raw, budget)? + { + if command != b"fn" { + return Ok(None); + } + let (owners, reason) = self.names.resolve(name, budget)?; + return Ok(Some(( + owners, + reason.map_or(Resolution::Resolved, Resolution::Unresolved), + ))); + } + } + Ok(None) + } + fn render_draft( &self, draft: &mut Draft<'s>, diff --git a/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs index 4d5304ec3..e8f9260ff 100644 --- a/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs @@ -351,3 +351,47 @@ fn nested_collection_cancellation_restores_outer_flag_after_unwind() { ); }); } + +#[cfg(feature = "rust")] +#[test] +fn excluded_attribute_name_keeps_pending_occurrence_without_establishing_doc_text() { + let source = b"#[doc = \"audit\"]\nfn f() {}"; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser + .set_included_ranges(&[ + tree_sitter::Range { + start_byte: 0, + end_byte: 3, + start_point: tree_sitter::Point::new(0, 0), + end_point: tree_sitter::Point::new(0, 3), + }, + tree_sitter::Range { + start_byte: 4, + end_byte: source.len(), + start_point: tree_sitter::Point::new(0, 4), + end_point: tree_sitter::Point::new(1, 9), + }, + ]) + .unwrap(); + let tree = parser.parse(source, None).unwrap(); + let index = collect( + LANG::Rust, + &tree, + source, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 0); + let function = tree.root_node().named_child(1).unwrap(); + assert_eq!(function.kind(), "function_item"); + let query = index.node_associations(function).unwrap(); + assert!( + query + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Occurrence) + ); +} diff --git a/big-code-analysis-ast/src/documentation/collector/cost_tests.rs b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs index 0b33b183b..9297a78c8 100644 --- a/big-code-analysis-ast/src/documentation/collector/cost_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs @@ -84,3 +84,85 @@ fn pending_scope_relations_are_shared_instead_of_copied_per_owner() { assert_eq!(query.associations().count(), 0); assert_eq!(query.assessments().count(), 2); } + +#[cfg(feature = "java")] +#[test] +fn java_undocumented_registry_charges_actual_memo_queries() { + for size in [16, 32, 64] { + let source = format!( + "{}void f() {{}}{}", + "class C {".repeat(size), + "}".repeat(size) + ); + let parser = AnyParser::parse(LANG::Java, source.into_bytes(), None, None).unwrap(); + let nodes = parser.root_node().preorder().count(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + assert_eq!(index.facts().owners().len(), size + 2); + assert_eq!( + after.target_computations - before.target_computations, + nodes - 1 + ); + assert_eq!(after.memo_probes - before.memo_probes, nodes - 1); + assert_eq!(after.field_lookups - before.field_lookups, 0); + assert_eq!(after.fold_slot_probes - before.fold_slot_probes, 0); + } +} + +#[cfg(feature = "c")] +#[test] +fn hidden_declarator_fields_are_read_once_per_child_batch() { + for size in [16, 32, 64] { + let source = format!("/**audit*/\nint a{};", "[1]".repeat(size)); + let parser = AnyParser::parse(LANG::C, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + // Each array declarator has four children; the declaration has three. + assert_eq!(after.field_requests - before.field_requests, size * 4 + 3); + assert_eq!(index.associations().len(), 1); + assert_eq!(after.renders - before.renders, 1); + } +} + +#[cfg(feature = "rust")] +#[test] +fn late_owner_queries_never_scan_other_owners_or_empty_ancestor_scopes() { + for size in [16, 32, 64] { + let source = format!( + "#![doc(hidden)]\n{}///audit\nfn last() {{}}", + "fn f() {}\n".repeat(size) + ); + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let node = parser.root_node().children().last().unwrap(); + let before = observations(); + let query = index.node_associations(node.as_tree_sitter()).unwrap(); + assert_eq!(query.associations().len(), 1); + assert_eq!(query.assessments().count(), 2); + let after = observations(); + assert_eq!(after.identity_probes - before.identity_probes, 1); + assert_eq!( + after.assessment_scope_reads - before.assessment_scope_reads, + 4 + ); + assert_eq!(after.renders - before.renders, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/form_tests.rs b/big-code-analysis-ast/src/documentation/collector/form_tests.rs new file mode 100644 index 000000000..3356bf347 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/form_tests.rs @@ -0,0 +1,201 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(any( + feature = "java", + feature = "kotlin", + feature = "groovy", + feature = "csharp", + feature = "php", + feature = "javascript", + feature = "mozjs", + feature = "typescript", + feature = "ruby", + feature = "lua" +))] +fn assert_pending_form(language: LANG, source: &str, owner_kind: &str) { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let node = parser + .root_node() + .preorder() + .find(|node| node.kind() == owner_kind) + .unwrap(); + let projection = index.node_projection(node.as_tree_sitter()).unwrap(); + assert!(projection.pending(), "{language:?}: {source}"); + assert!( + projection + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Owner) + ); + assert_eq!(index.associations().len(), 0, "{language:?}: {source}"); +} + +#[cfg(feature = "java")] +#[test] +fn java_field_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Java, + "class C { /**audit*/ int x; }", + "field_declaration", + ); +} +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_parameter_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Kotlin, + "class C(/**audit*/ val x: Int)", + "class_parameter", + ); +} +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Groovy, + "class C {\n/**audit*/\nint x\n}", + "field_declaration", + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_same_row_constructor_retains_pending_scope_assessment() { + let parser = AnyParser::parse( + LANG::Groovy, + b"class C { /**audit*/ C() {} }".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 0); + assert!( + index + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Selection) + ); + let constructor = parser + .root_node() + .preorder() + .find(|node| node.kind() == "constructor_declaration") + .unwrap(); + assert!( + index + .node_associations(constructor.as_tree_sitter()) + .unwrap() + .assessments() + .any(|assessment| assessment.get().axis == AssessmentAxis::Selection) + ); +} +#[cfg(feature = "csharp")] +#[test] +fn csharp_field_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Csharp, + "class C {\n///audit\nint x;\n}", + "field_declaration", + ); +} +#[cfg(feature = "php")] +#[test] +fn php_promoted_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Php, + " 1;", + "lexical_declaration", + ); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_binding_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Mozjs, + "/**audit*/\nconst f = () => 1;", + "lexical_declaration", + ); +} +#[cfg(feature = "typescript")] +#[test] +fn typescript_parameter_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Typescript, + "function f(/**audit*/ x: number) {}", + "required_parameter", + ); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_parameter_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Tsx, + "function f(/**audit*/ x: number) {}", + "required_parameter", + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_attribute_and_visibility_forms_are_pending_in_default_queries() { + assert_pending_form(LANG::Ruby, "# audit\nattr_reader :x", "call"); + assert_pending_form( + LANG::Ruby, + "class C\n# audit\nprivate def f; end\nend", + "call", + ); +} +#[cfg(feature = "lua")] +#[test] +fn lua_assignment_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Lua, + "module(\"m\")\n---audit\nvalue = 1", + "assignment_statement", + ); +} + +#[cfg(feature = "c")] +#[test] +fn multi_slot_projection_exposes_each_owner_and_its_shared_document() { + let parser = AnyParser::parse(LANG::C, b"/**audit*/\nint a, b;".to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let declaration = parser.root_node().children().last().unwrap(); + let projection = index.node_projection(declaration.as_tree_sitter()).unwrap(); + assert!(!projection.pending()); + assert_eq!(projection.owners().len(), 2); + for owner in projection.owners() { + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.associations().len(), 1); + assert_eq!( + index + .facts() + .associated_document(query.associations().next().unwrap()) + .unwrap(), + index.documents().next().unwrap() + ); + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/projection_tests.rs b/big-code-analysis-ast/src/documentation/collector/projection_tests.rs index d7704a084..c15d1c5f9 100644 --- a/big-code-analysis-ast/src/documentation/collector/projection_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/projection_tests.rs @@ -179,3 +179,88 @@ fn doxygen_file_gathering_is_one_document_and_page_remains_pending() { } } } + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn incomplete_declarators(language: LANG) { + for source in [ + "/**audit*/\nint a, (*callback)(void);", + "/**audit*/\nint (*only)(void);", + "/**audit*/\nint a, f(void);", + ] { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let declaration = parser.root_node().children().last().unwrap(); + assert!( + index + .node_associations(declaration.as_tree_sitter()) + .unwrap() + .projection_pending(), + "{source}" + ); + assert_eq!(index.associations().len(), 0, "{source}"); + assert_eq!( + index.facts().owners().len(), + 1, + "only the file owner is established" + ); + let document = index.documents().next().unwrap(); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + "audit" + ); + assert!( + index + .assessments() + .any(|assessment| index.assessed_document(assessment).unwrap() == Some(document)) + ); + } + for source in [ + "void f(void);\n/**lead*/\n/**@fn void f(void)*/", + "void f(void) {}\n/**lead*/\n/**@fn void f(void)*/", + ] { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 2); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + "lead\n@fn void f(void)" + ); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), 1); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_incomplete_declarators_and_gathered_names() { + incomplete_declarators(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_incomplete_declarators_and_gathered_names() { + incomplete_declarators(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_incomplete_declarators_and_gathered_names() { + incomplete_declarators(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_incomplete_declarators_and_gathered_names() { + incomplete_declarators(LANG::Objc); +} diff --git a/big-code-analysis-ast/src/documentation/collector/projections.rs b/big-code-analysis-ast/src/documentation/collector/projections.rs index 0f5f9c919..89bd67f80 100644 --- a/big-code-analysis-ast/src/documentation/collector/projections.rs +++ b/big-code-analysis-ast/src/documentation/collector/projections.rs @@ -10,6 +10,15 @@ impl Builder<'_> { ) -> Result<(), CollectionError> { budget.step()?; let node = self.index.canonical.nodes[id.0].evidence.node(); + if node.has_error() + || node.is_missing() + || !self + .index + .source + .covers_with_budget(node.byte_range(), budget)? + { + return Ok(()); + } if self.index.profile == Profile::Doxygen && node.kind() == "function_definition" { self.index_function_definition(id, budget)?; } @@ -100,33 +109,34 @@ impl Builder<'_> { } fn c_slots(&mut self, id: NodeId, budget: &CollectionBudget) -> Result<(), CollectionError> { - let enclosing = OwnerId(self.index.facts.owners.len()); - self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); - let mut slots = Vec::new(); let mut work = Vec::new(); for &child in &self.index.canonical.children[self.index.canonical.nodes[id.0].children.clone()] { budget.step()?; if self.index.canonical.nodes[child.0].field == Some("declarator") { - work.push(child); + let Some(declared) = self.declared_name(child, budget)? else { + return Ok(()); + }; + work.push(declared); } } + if work.is_empty() { + return Ok(()); + } if work.len() > 1 { - for &child in &work { - if self - .declared_name(child, budget)? - .is_some_and(|(_, function)| function) - { - self.index.canonical.nodes[id.0].projection = Projection::Pending; + for &(_, function) in &work { + budget.step()?; + if function { return Ok(()); } } } - for child in work { - let Some((name, function)) = self.declared_name(child, budget)? else { - continue; - }; + let enclosing = OwnerId(self.index.facts.owners.len()); + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + let mut slots = Vec::new(); + for (name, function) in work { + budget.step()?; let node = self.index.canonical.nodes[name.0].evidence.node(); if function { slots.push(enclosing); @@ -159,11 +169,7 @@ impl Builder<'_> { slots.push(slot); } } - self.index.canonical.nodes[id.0].projection = if slots.is_empty() { - Projection::Pending - } else { - Projection::Ready(slots) - }; + self.index.canonical.nodes[id.0].projection = Projection::Ready(slots); Ok(()) } diff --git a/big-code-analysis-ast/src/documentation/forms.rs b/big-code-analysis-ast/src/documentation/forms.rs index c8aaade67..4dd643d87 100644 --- a/big-code-analysis-ast/src/documentation/forms.rs +++ b/big-code-analysis-ast/src/documentation/forms.rs @@ -24,6 +24,15 @@ pub(super) fn assess<'s, B: super::budget::WorkBudget>( )); } let bytes = &source.bytes()[node.start_byte()..node.end_byte()]; + if profile == Profile::Groovydoc + && bytes.starts_with(b"/**") + && let Some(next) = ancestors.siblings_after_with_budget(node, budget)?.next() + && next.start_row() == node.end_row() + { + return Ok(CommentAssessment::Pending( + "Groovydoc same-row declaration placement awaits source selection", + )); + } Ok(match profile { Profile::Rust if matches!(parent, Some("ordered_field_declaration_list")) => { CommentAssessment::Pending( @@ -103,9 +112,14 @@ pub(super) fn owner_pending( "field_declaration" | "enum_variant" | "associated_type" ) } + Profile::Javadoc => matches!(node.kind(), "field_declaration" | "constant_declaration"), + Profile::Groovydoc => matches!(node.kind(), "field_declaration"), + Profile::CsharpXml => { + matches!(node.kind(), "field_declaration" | "event_field_declaration") + } Profile::Kdoc => matches!( node.kind(), - "class_parameter" | "parameter" | "primary_constructor" + "class_parameter" | "parameter" | "primary_constructor" | "property_declaration" ), Profile::BcaPhpSource => matches!( node.kind(), @@ -113,11 +127,33 @@ pub(super) fn owner_pending( | "simple_parameter" | "variadic_parameter" | "expression_statement" + | "property_declaration" + | "const_declaration" ), Profile::GoDoc => matches!( node.kind(), "field_declaration" | "method_elem" | "type_elem" ), + Profile::Yard => matches!(node.kind(), "call" | "assignment" | "alias"), + Profile::Ldoc => matches!( + node.kind(), + "assignment_statement" | "variable_declaration" | "return_statement" | "field" + ), + _ => false, + } +} + +pub(super) fn slot_candidate(profile: Profile, kind: &str) -> bool { + match profile { + Profile::Kdoc => matches!( + kind, + "class_parameter" | "parameter" | "primary_constructor" + ), + Profile::BcaPhpSource => matches!( + kind, + "property_promotion_parameter" | "simple_parameter" | "variadic_parameter" + ), + Profile::BcaTypescriptSource => matches!(kind, "required_parameter" | "optional_parameter"), _ => false, } } diff --git a/big-code-analysis-ast/src/documentation/index.rs b/big-code-analysis-ast/src/documentation/index.rs index 1e8a0a047..178340a77 100644 --- a/big-code-analysis-ast/src/documentation/index.rs +++ b/big-code-analysis-ast/src/documentation/index.rs @@ -89,6 +89,65 @@ pub struct OwnerAssociations<'i, 's> { projection_pending: bool, } +/// A canonical syntax projection with its known owners and pending assessment. +/// Multi-slot declarations retain all owners without choosing one implicitly. +pub struct NodeProjection<'i, 's> { + index: &'i DocumentationIndex<'s>, + id: super::canonical::NodeId, + owners: &'i [OwnerId], + pending: bool, +} + +impl<'i, 's> NodeProjection<'i, 's> { + /// Whether semantic normalization remains incomplete. + #[must_use] + pub fn pending(&self) -> bool { + self.pending + } + + /// Known semantic owners, in stored source/slot order. + pub fn owners(&self) -> impl ExactSizeIterator>> + '_ { + self.owners.iter().map(|id| FactRef { + scope: &self.index.facts.scope, + ordinal: id.0, + fact: &self.index.facts.owners[id.0], + }) + } + + /// Scope assessments affecting the queried syntax, including pending owners. + pub fn assessments(&self) -> impl Iterator>> + '_ { + scope_assessments(self.index, Some(self.id)).map(|ordinal| FactRef { + scope: &self.index.facts.scope, + ordinal, + fact: &self.index.assessments[ordinal], + }) + } +} + +fn scope_assessments<'i>( + index: &'i DocumentationIndex<'_>, + mut scope: Option, +) -> impl Iterator + 'i { + let mut at = 0; + std::iter::from_fn(move || { + loop { + assessment_scope_reads::record(); + let node = &index.canonical.nodes[scope?.0]; + if let Some(&assessment) = node.pending.get(at) { + at += 1; + return Some(assessment); + } + scope = node.pending_parent; + at = 0; + } + }) +} + +crate::observation::counter!( + assessment_scope_reads, + cfg(any(test, feature = "test-support")) +); + impl<'i, 's> OwnerAssociations<'i, 's> { /// Whether the queried syntax still requires a semantic owner projection. /// Known associations and pending assessment records remain accessible. @@ -107,22 +166,10 @@ impl<'i, 's> OwnerAssociations<'i, 's> { /// Pending assessments affecting this owner, visible under default options. pub fn assessments(&self) -> impl Iterator>> + '_ { - let mut scope = self.scope; - let mut at = 0; self.assessments .iter() .copied() - .chain(std::iter::from_fn(move || { - loop { - let node = &self.index.canonical.nodes[scope?.0]; - if let Some(&assessment) = node.pending.get(at) { - at += 1; - return Some(assessment); - } - scope = node.pending_parent; - at = 0; - } - })) + .chain(scope_assessments(self.index, self.scope)) .map(|ordinal| FactRef { scope: &self.index.facts.scope, ordinal, @@ -335,6 +382,28 @@ impl<'s> DocumentationIndex<'s> { })) } + /// Inspect a canonical node's complete or pending owner projection. + /// + /// # Errors + /// Rejects foreign/noncanonical nodes and syntax outside the declaration model. + pub fn node_projection( + &self, + node: tree_sitter::Node<'_>, + ) -> Result, OwnerError> { + let id = self.canonical.lookup(node).map_err(OwnerError::Source)?; + let (owners, pending) = match &self.canonical.nodes[id.0].projection { + Projection::Ready(owners) => (owners.as_slice(), false), + Projection::Pending => (&[][..], true), + Projection::Unsupported => return Err(OwnerError::UnsupportedOwner), + }; + Ok(NodeProjection { + index: self, + id, + owners, + pending, + }) + } + fn prepared_owner(&self, ordinal: usize) -> OwnerAssociations<'_, 's> { let id = self.owner_nodes[ordinal]; let node = &self.canonical.nodes[id.0]; diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index 339b26006..a016ad0a2 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -45,6 +45,26 @@ pub struct SourcePieces<'s> { } impl<'s> SourcePieces<'s> { + pub(in crate::documentation) fn from_included_pieces(pieces: Vec>) -> Self { + Self { + pieces, + has_excluded_gap: false, + } + } + pub(in crate::documentation) fn copy_with_budget( + &self, + budget: &B, + ) -> Result { + let mut pieces = Vec::new(); + for piece in &self.pieces { + budget.step()?; + pieces.push(piece.clone()); + } + Ok(Self { + pieces, + has_excluded_gap: self.has_excluded_gap, + }) + } pub(super) fn single(piece: SourcePiece<'s>) -> Self { Self { pieces: vec![piece], diff --git a/big-code-analysis-ast/src/documentation/text.rs b/big-code-analysis-ast/src/documentation/text.rs index c09e0d901..557bad4e3 100644 --- a/big-code-analysis-ast/src/documentation/text.rs +++ b/big-code-analysis-ast/src/documentation/text.rs @@ -8,6 +8,8 @@ use super::{ UnavailableReason, }; +#[allow(dead_code)] +pub(super) mod cleanup; pub(super) mod comments; #[allow(dead_code)] pub(super) mod literals; diff --git a/big-code-analysis-ast/src/documentation/text/cleanup.rs b/big-code-analysis-ast/src/documentation/text/cleanup.rs new file mode 100644 index 000000000..4fffff5ff --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/cleanup.rs @@ -0,0 +1,398 @@ +//! Mapping-preserving cleanup of decoded values supplied by language adapters. + +use super::{TextBuilder, TextError}; +use crate::documentation::budget::WorkBudget; +use crate::documentation::{Content, Mapping, Origin, SourcePieces, TextRange, UnavailableReason}; +use std::ops::Range; + +struct Projection<'i, 's> { + text: &'i str, + mappings: &'i [Mapping<'s>], + at: usize, +} + +impl<'s> Projection<'_, 's> { + fn copy( + &mut self, + range: Range, + output: &mut TextBuilder<'s>, + budget: &B, + ) -> Result<(), TextError> { + let start = output.text.len(); + output.append_utf8(self.text[range.clone()].as_bytes(), budget)?; + while let Some(mapping) = self.mappings.get(self.at) { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let span = mapping.output.range(); + if span.start >= range.end { + break; + } + if span.end > range.start { + let selected = span.start.max(range.start)..span.end.min(range.end); + let origin = match &mapping.origin { + Origin::Copied(pieces) => { + let piece = &pieces.pieces()[0]; + let source = piece.range().start + selected.start - span.start; + Origin::Copied(SourcePieces::single( + piece.slice(source..source + selected.len()), + )) + } + Origin::Decoded(pieces) => Origin::Decoded(copy_pieces(pieces, budget)?), + Origin::Expanded(pieces) => Origin::Expanded(copy_pieces(pieces, budget)?), + Origin::Synthetic => Origin::Synthetic, + }; + output.mappings.push(Mapping { + output: TextRange::validated( + start + selected.start - range.start..start + selected.end - range.start, + ), + origin, + }); + } + if span.end > range.end { + break; + } + self.at += 1; + } + Ok(()) + } + + fn expand( + &mut self, + at: usize, + spaces: usize, + output: &mut TextBuilder<'s>, + budget: &B, + ) -> Result<(), TextError> { + while self.mappings[self.at].output.range().end <= at { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + self.at += 1; + } + let mapping = &self.mappings[self.at]; + let origin = match &mapping.origin { + Origin::Copied(pieces) => { + let piece = &pieces.pieces()[0]; + let start = piece.range().start + at - mapping.output.range().start; + Origin::Expanded(SourcePieces::single(piece.slice(start..start + 1))) + } + Origin::Decoded(pieces) | Origin::Expanded(pieces) => { + Origin::Expanded(copy_pieces(pieces, budget)?) + } + Origin::Synthetic => Origin::Synthetic, + }; + output.transformed(&" "[..spaces], origin, budget) + } + + fn newline( + &mut self, + ending: Range, + output: &mut TextBuilder<'s>, + budget: &B, + ) -> Result<(), TextError> { + if ending.len() != 2 { + return self.copy(ending, output, budget); + } + let mut newline = TextBuilder::default(); + self.copy(ending, &mut newline, budget)?; + let mut pieces = Vec::new(); + for mapping in newline.mappings { + let source = match mapping.origin { + Origin::Copied(pieces) | Origin::Decoded(pieces) | Origin::Expanded(pieces) => { + pieces + } + Origin::Synthetic => continue, + }; + for piece in source.pieces() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + pieces.push(piece.clone()); + } + } + output.transformed( + "\n", + Origin::Decoded(SourcePieces::from_included_pieces(pieces)), + budget, + ) + } +} + +fn copy_pieces<'s, B: WorkBudget>( + pieces: &SourcePieces<'s>, + budget: &B, +) -> Result, TextError> { + pieces + .copy_with_budget(budget) + .map_err(|error| TextError::Source(error.into())) +} + +pub(super) fn python<'s, B: WorkBudget>( + value: Content<'s>, + budget: &B, +) -> Result, TextError> { + let Content::Complete { text, mappings } = value else { + return Ok(value); + }; + let mut input = Projection { + text: &text, + mappings: &mappings, + at: 0, + }; + let mut output = TextBuilder::default(); + let mut start = 0; + let mut column = 0; + for (at, scalar) in text.char_indices() { + budget + .bytes(scalar.len_utf8()) + .map_err(|error| TextError::Source(error.into()))?; + match scalar { + '\t' => { + input.copy(start..at, &mut output, budget)?; + let spaces = 8 - column % 8; + input.expand(at, spaces, &mut output, budget)?; + column += spaces; + start = at + 1; + } + '\n' | '\r' => column = 0, + _ => column += 1, + } + } + input.copy(start..text.len(), &mut output, budget)?; + python_margin(output.finish(), budget) +} + +fn python_margin<'s, B: WorkBudget>( + value: Content<'s>, + budget: &B, +) -> Result, TextError> { + let Content::Complete { text, mappings } = value else { + return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)); + }; + let mut lines = Vec::new(); + let mut start = 0; + for (at, byte) in text.bytes().enumerate() { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + if byte == b'\n' { + lines.push(start..at); + start = at + 1; + } + } + lines.push(start..text.len()); + let mut margin = usize::MAX; + for (position, line) in lines.iter_mut().enumerate() { + let mut indent = 0; + let mut prefix_bytes = 0; + for scalar in text[line.clone()].chars() { + budget + .bytes(scalar.len_utf8()) + .map_err(|error| TextError::Source(error.into()))?; + if !scalar.is_whitespace() { + break; + } + indent += 1; + prefix_bytes += scalar.len_utf8(); + } + if position == 0 { + line.start += prefix_bytes; + } else if prefix_bytes < line.len() { + margin = margin.min(indent); + } + } + if margin != usize::MAX { + for line in lines.iter_mut().skip(1) { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let mut removed = 0; + for scalar in text[line.clone()].chars().take(margin) { + budget + .bytes(scalar.len_utf8()) + .map_err(|error| TextError::Source(error.into()))?; + removed += scalar.len_utf8(); + } + line.start += removed; + } + } + let mut first = 0; + let mut end = lines.len(); + while first < end && lines[first].is_empty() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + first += 1; + } + while end > first && lines[end - 1].is_empty() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + end -= 1; + } + let mut input = Projection { + text: &text, + mappings: &mappings, + at: 0, + }; + let mut output = TextBuilder::default(); + for (position, line) in lines[first..end].iter().enumerate() { + if position != 0 { + let newline = lines[first + position - 1].end; + input.copy(newline..newline + 1, &mut output, budget)?; + } + input.copy(line.clone(), &mut output, budget)?; + } + Ok(output.finish()) +} + +pub(super) fn ruff<'s, B: WorkBudget>( + value: Content<'s>, + budget: &B, +) -> Result, TextError> { + let Content::Complete { text, mappings } = value else { + return Ok(value); + }; + let mut lines = Vec::new(); + let mut start = 0; + for (at, byte) in text.bytes().enumerate() { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + if byte == b'\n' { + let end = if at > start && text.as_bytes()[at - 1] == b'\r' { + at - 1 + } else { + at + }; + lines.push((start..end, end..at + 1)); + start = at + 1; + } + } + lines.push((start..text.len(), text.len()..text.len())); + let mut prefix = ""; + for (line, _) in &lines { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let bytes = &text.as_bytes()[line.clone()]; + let margin = crate::documentation::byte_scan::position( + bytes, + |byte| !matches!(byte, b' ' | b'\t'), + budget, + ) + .map_err(|error| TextError::Source(error.into()))? + .unwrap_or(bytes.len()); + if margin < bytes.len() { + prefix = &text[line.start..line.start + margin]; + break; + } + } + for (line, _) in &mut lines { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + let mut matching = line.len() >= prefix.len(); + for (actual, expected) in text.as_bytes()[line.clone()].iter().zip(prefix.bytes()) { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + if *actual != expected { + matching = false; + break; + } + } + if matching { + line.start += prefix.len(); + } + } + let mut first = 0; + let mut end = lines.len(); + while first < end && lines[first].0.is_empty() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + first += 1; + } + while end > first && lines[end - 1].0.is_empty() { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + end -= 1; + } + let mut input = Projection { + text: &text, + mappings: &mappings, + at: 0, + }; + let mut output = TextBuilder::default(); + for (position, (line, ending)) in lines[first..end].iter().enumerate() { + input.copy(line.clone(), &mut output, budget)?; + if position + first + 1 < end { + input.newline(ending.clone(), &mut output, budget)?; + } + } + Ok(output.finish()) +} + +#[cfg(all(test, feature = "python"))] +mod tests { + use super::*; + use crate::documentation::budget::NoBudget; + use crate::documentation::text::literals::{LiteralPolicy, decode}; + use crate::documentation::{CompleteText, OriginView, SourceContext}; + use crate::{AnyParser, LANG}; + + #[test] + fn whole_python_document_cleanup_keeps_escape_and_tab_origins() { + let source = "\"\"\" first\\n\\tsecond \\n\\t third\\n\"\"\""; + let parser = + AnyParser::parse(LANG::Python, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut builder = TextBuilder::default(); + decode( + &context, + 3..source.len() - 3, + LiteralPolicy::PythonCooked, + &mut builder, + &NoBudget, + ) + .unwrap(); + let Content::Complete { text, mappings } = python(builder.finish(), &NoBudget).unwrap() + else { + panic!("complete value") + }; + assert_eq!(text, "first\nsecond \n third"); + let view = CompleteText { + text: &text, + mappings: &mappings, + }; + let OriginView::Decoded(pieces) = view.origins(5..6).unwrap().next().unwrap().origin else { + panic!("decoded newline") + }; + assert_eq!(pieces[0].bytes(), b"\\n"); + assert_eq!(view.origins(15..17).unwrap().next().unwrap().output, 15..17); + } + + #[test] + fn python_cleanup_counts_unicode_margin_in_characters() { + let source = "\"\"\"\n\u{2003}alpha\n beta\n\"\"\""; + let parser = + AnyParser::parse(LANG::Python, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut builder = TextBuilder::default(); + decode( + &context, + 3..source.len() - 3, + LiteralPolicy::Raw, + &mut builder, + &NoBudget, + ) + .unwrap(); + let Content::Complete { text, .. } = python(builder.finish(), &NoBudget).unwrap() else { + panic!("complete value") + }; + assert_eq!(text, "alpha\nbeta"); + } +} diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs index 2da70394c..ee741b841 100644 --- a/big-code-analysis-ast/src/documentation/text/comments.rs +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -309,17 +309,7 @@ fn render_local<'s, B: WorkBudget>( blocks.push(prepare(profile, context, fragment, budget, source_cleaned)?); } if profile == Profile::Rust { - for block in &mut blocks { - beautify(block, context.bytes(), budget)?; - if block.lines.len() > 1 - && block - .lines - .last() - .is_some_and(|line| line.content.is_empty()) - { - block.lines.pop(); - } - } + rust_fragments(&mut blocks, context.bytes(), budget)?; } if profile == Profile::Rust || blocks.first().is_some_and(|block| block.markdown) { let mut minimum = usize::MAX; @@ -404,6 +394,9 @@ fn render_local<'s, B: WorkBudget>( } fn blank(bytes: &[u8], unicode: bool, budget: &B) -> Result { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; if !unicode { return Ok(crate::documentation::byte_scan::position( bytes, @@ -438,9 +431,47 @@ fn blank(bytes: &[u8], unicode: bool, budget: &B) -> Result(block: &mut Block, bytes: &[u8], budget: &B) -> Result<(), TextError> { - if block.lines.len() < 2 { - return Ok(()); +fn rust_fragments( + blocks: &mut [Block], + bytes: &[u8], + budget: &B, +) -> Result<(), TextError> { + for block in blocks { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + // str::lines omits a terminal empty line both before beautification + // and when rustdoc reads the changed, joined fragment. + if block.lines.len() > 1 + && block + .lines + .last() + .is_some_and(|line| line.content.is_empty()) + { + block.lines.pop(); + } + let changed = beautify(block, bytes, budget)?; + if changed + && block.lines.len() > 1 + && block + .lines + .last() + .is_some_and(|line| line.content.is_empty()) + { + block.lines.pop(); + } + } + Ok(()) +} + +fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Result { + if block.lines.len() < 2 + && block + .lines + .first() + .is_none_or(|line| line.ending.is_empty()) + { + return Ok(false); } let all_stars = |range: Range| -> Result { for byte in &bytes[range] { @@ -459,6 +490,7 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul { end -= 1; } + let changed = first != 0 || end != block.lines.len(); let mut selected = Vec::new(); for line in block.lines.drain(..).skip(first).take(end - first) { budget @@ -489,15 +521,15 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul if line.content.start + indent >= line.content.end || bytes[line.content.start + indent] != b'*' { - return Ok(()); + return Ok(changed); } if star_column.is_some_and(|column| column != indent) { - return Ok(()); + return Ok(changed); } star_column = Some(indent); } let Some(column) = star_column else { - return Ok(()); + return Ok(changed); }; let prefix = &bytes[block.lines[start].content.start..block.lines[start].content.start + column]; @@ -524,5 +556,5 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul } } } - Ok(()) + Ok(true) } diff --git a/big-code-analysis-ast/src/documentation/text/literals.rs b/big-code-analysis-ast/src/documentation/text/literals.rs index b1282f0a1..c000a5e40 100644 --- a/big-code-analysis-ast/src/documentation/text/literals.rs +++ b/big-code-analysis-ast/src/documentation/text/literals.rs @@ -13,7 +13,6 @@ pub(super) enum LiteralPolicy { TclBraced, } -#[allow(clippy::too_many_lines)] pub(super) fn decode<'s, B: WorkBudget>( context: &SourceContext<'s>, interior: Range, @@ -34,7 +33,9 @@ pub(super) fn decode<'s, B: WorkBudget>( budget .bytes(1) .map_err(|error| TextError::Source(error.into()))?; - if matches!(policy, LiteralPolicy::TclQuoted) && matches!(bytes[at], b'$' | b'[') { + if matches!(policy, LiteralPolicy::TclQuoted) + && (bytes[at] == b'[' || tcl_variable(&bytes[at..interior.end])) + { return Err(TextError::Unavailable(UnavailableReason::Dynamic)); } if bytes[at] != b'\\' || matches!(policy, LiteralPolicy::Raw) { @@ -50,25 +51,22 @@ pub(super) fn decode<'s, B: WorkBudget>( at += 2; continue; } + if matches!(policy, LiteralPolicy::TclBraced) + && next == b'\r' + && bytes.get(at + 2).filter(|_| at + 2 < interior.end) != Some(&b'\n') + { + at += 2; + continue; + } output.source(context, copied..at, budget)?; let start = at; at += 2; let scalar = match next { b'\n' | b'\r' => { - if next == b'\r' && bytes.get(at) == Some(&b'\n') { - at += 1; - } - if matches!(policy, LiteralPolicy::TclQuoted | LiteralPolicy::TclBraced) { - while at < interior.end && matches!(bytes[at], b' ' | b'\t') { - budget - .bytes(1) - .map_err(|error| TextError::Source(error.into()))?; - at += 1; - } - Some(' ') - } else { - None - } + let (scalar, consumed) = + continuation(&bytes[at..interior.end], next, policy, budget)?; + at += consumed; + scalar } b'n' => Some('\n'), b'r' => Some('\r'), @@ -86,53 +84,28 @@ pub(super) fn decode<'s, B: WorkBudget>( )); } b'x' | b'u' | b'U' => { - let width = match next { - b'x' => 2, - b'u' => 4, - _ => 8, - }; - let end = at - .checked_add(width) - .filter(|end| *end <= interior.end) - .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; - let mut value = 0_u32; - for &digit in &bytes[at..end] { - budget - .bytes(1) - .map_err(|error| TextError::Source(error.into()))?; - value = value - .checked_mul(16) - .and_then(|value| char::from(digit).to_digit(16).map(|digit| value + digit)) - .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; - } - at = end; - Some( - char::from_u32(value) - .ok_or(TextError::Unavailable(UnavailableReason::NonScalar))?, - ) + let (scalar, count) = hexadecimal(&bytes[at..interior.end], next, policy, budget)?; + at += count; + Some(scalar) } b'0'..=b'7' => { - let mut value = u32::from(next - b'0'); - for _ in 0..2 { - if at >= interior.end || !matches!(bytes[at], b'0'..=b'7') { - break; - } - budget - .bytes(1) - .map_err(|error| TextError::Source(error.into()))?; - value = value * 8 + u32::from(bytes[at] - b'0'); - at += 1; - } - Some( - char::from_u32(value) - .ok_or(TextError::Unavailable(UnavailableReason::NonScalar))?, - ) + let (scalar, consumed) = octal(&bytes[at..interior.end], next, policy, budget)?; + at += consumed; + Some(scalar) } _ if matches!(policy, LiteralPolicy::PythonCooked) => { + at = start + 1 + scalar_width(&bytes[start + 1..interior.end])?; output.source(context, start..at, budget)?; None } - _ => Some(char::from(next)), + _ => { + let width = scalar_width(&bytes[start + 1..interior.end])?; + at = start + 1 + width; + std::str::from_utf8(&bytes[start + 1..at]) + .map_err(|_| TextError::Unavailable(UnavailableReason::InvalidEncoding))? + .chars() + .next() + } }; if let Some(scalar) = scalar { let mut buffer = [0; 4]; @@ -147,6 +120,123 @@ pub(super) fn decode<'s, B: WorkBudget>( output.source(context, copied..interior.end, budget) } +fn continuation( + tail: &[u8], + ending: u8, + policy: LiteralPolicy, + budget: &B, +) -> Result<(Option, usize), TextError> { + let mut consumed = usize::from(ending == b'\r' && tail.first() == Some(&b'\n')); + if matches!(policy, LiteralPolicy::PythonCooked) { + return Ok((None, consumed)); + } + if ending == b'\r' && consumed == 0 { + return Ok((Some('\r'), 0)); + } + while tail + .get(consumed) + .is_some_and(|byte| matches!(byte, b' ' | b'\t')) + { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + consumed += 1; + } + Ok((Some(' '), consumed)) +} + +fn octal( + tail: &[u8], + first: u8, + policy: LiteralPolicy, + budget: &B, +) -> Result<(char, usize), TextError> { + let mut value = u32::from(first - b'0'); + let mut consumed = 0; + for &byte in tail.iter().take(2) { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + if !matches!(byte, b'0'..=b'7') { + break; + } + let next = value * 8 + u32::from(byte - b'0'); + if matches!(policy, LiteralPolicy::TclQuoted) && next > 255 { + break; + } + value = next; + consumed += 1; + } + Ok(( + char::from_u32(value).ok_or(TextError::Unavailable(UnavailableReason::NonScalar))?, + consumed, + )) +} + +fn tcl_variable(bytes: &[u8]) -> bool { + bytes.first() == Some(&b'$') + && bytes.get(1).is_some_and(|byte| { + byte.is_ascii_alphanumeric() + || matches!(byte, b'_' | b'{' | b'(') + || bytes.get(1..3) == Some(b"::") + }) +} + +fn scalar_width(bytes: &[u8]) -> Result { + let width = match bytes.first() { + Some(0..=0x7f) => 1, + Some(0xc2..=0xdf) => 2, + Some(0xe0..=0xef) => 3, + Some(0xf0..=0xf4) => 4, + _ => return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)), + }; + let scalar = bytes + .get(..width) + .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + std::str::from_utf8(scalar) + .map_err(|_| TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + Ok(width) +} + +fn hexadecimal( + bytes: &[u8], + marker: u8, + policy: LiteralPolicy, + budget: &B, +) -> Result<(char, usize), TextError> { + let width = match marker { + b'x' => 2, + b'u' => 4, + _ => 8, + }; + let python = matches!(policy, LiteralPolicy::PythonCooked); + let mut count = 0; + let mut value = 0_u32; + for &byte in bytes.iter().take(width) { + budget + .bytes(1) + .map_err(|error| TextError::Source(error.into()))?; + let Some(digit) = char::from(byte).to_digit(16) else { + break; + }; + let next = value * 16 + digit; + if !python && marker == b'U' && next > 0x10_ffff { + break; + } + value = next; + count += 1; + } + if python && count != width { + return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)); + } + if count == 0 { + return Ok((char::from(marker), 0)); + } + let scalar = + char::from_u32(value).ok_or(TextError::Unavailable(UnavailableReason::NonScalar))?; + Ok((scalar, count)) +} + pub(super) fn expand_tabs<'s, B: WorkBudget>( context: &SourceContext<'s>, interior: Range, @@ -305,4 +395,144 @@ mod tests { }) )); } + + #[cfg(feature = "python")] + #[test] + fn python_unknown_unicode_escape_is_copied_and_invalid_scalars_stay_unavailable() { + for (source, expected) in [ + ("\"\\é\"", Ok("\\é")), + ("\"\\x4\"", Err(UnavailableReason::InvalidEncoding)), + ("\"\\ud800\"", Err(UnavailableReason::NonScalar)), + ("\"\\Uffffffff\"", Err(UnavailableReason::NonScalar)), + ( + "\"\\N{COMMERCIAL AT}audit\"", + Err(UnavailableReason::UnsupportedDecoding), + ), + ] { + let parser = + AnyParser::parse(LANG::Python, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut output = TextBuilder::default(); + let result = decode( + &context, + 1..source.len() - 1, + LiteralPolicy::PythonCooked, + &mut output, + &NoBudget, + ); + match expected { + Ok(expected) => { + result.unwrap(); + let content = output.finish(); + assert_eq!(view(&content).text(), expected); + assert!(matches!( + view(&content) + .origins(0..expected.len()) + .unwrap() + .next() + .unwrap() + .origin, + OriginView::Copied(_) + )); + } + Err(reason) => assert!( + matches!(result, Err(TextError::Unavailable(actual)) if actual == reason) + ), + } + } + } + + #[cfg(any(feature = "tcl", feature = "irules"))] + fn tcl_escapes(language: LANG) { + for (source, expected, token) in [ + ("\"\\x4!\"", "\u{4}!", 1..4), + ("\"\\u41!\"", "A!", 1..5), + ("\"\\U00000041!\"", "A!", 1..11), + ("\"\\777\"", "?7", 1..4), + ("\"\\é\"", "é", 1..4), + ("\"\\xZ\"", "xZ", 1..3), + ("\"\\\r\n b\"", " b", 1..6), + ] { + let parser = + AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut output = TextBuilder::default(); + decode( + &context, + 1..source.len() - 1, + LiteralPolicy::TclQuoted, + &mut output, + &NoBudget, + ) + .unwrap(); + let content = output.finish(); + let Content::Complete { text, mappings } = &content else { + panic!("complete literal") + }; + assert_eq!(text, expected); + let Origin::Decoded(pieces) = &mappings[0].origin else { + panic!("decoded token") + }; + assert_eq!(pieces.pieces()[0].range(), token); + } + } + + #[cfg(feature = "tcl")] + #[test] + fn tcl_variable_width_escapes_preserve_token_origins() { + tcl_escapes(LANG::Tcl); + } + #[cfg(feature = "irules")] + #[test] + fn irules_variable_width_escapes_preserve_token_origins() { + tcl_escapes(LANG::Irules); + } + + #[cfg(feature = "tcl")] + #[test] + fn ruff_preamble_cleanup_preserves_hashes_relative_indent_and_crlf_tokens() { + for (source, policy) in [ + ( + "{\r\n # Heading\r\n detail\r\n}", + LiteralPolicy::TclBraced, + ), + ( + "\"\\n # Heading\\n detail\\n\"", + LiteralPolicy::TclQuoted, + ), + ] { + let parser = + AnyParser::parse(LANG::Tcl, source.as_bytes().to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source.as_bytes()); + let mut builder = TextBuilder::default(); + decode( + &context, + 1..source.len() - 1, + policy, + &mut builder, + &NoBudget, + ) + .unwrap(); + let content = + crate::documentation::text::cleanup::ruff(builder.finish(), &NoBudget).unwrap(); + let text = view(&content); + assert_eq!(text.text(), "# Heading\n detail"); + let OriginView::Decoded(pieces) = text.origins(9..10).unwrap().next().unwrap().origin + else { + panic!("decoded newline") + }; + assert_eq!( + pieces + .iter() + .flat_map(crate::documentation::SourcePiece::bytes) + .copied() + .collect::>(), + if source.starts_with('{') { + b"\r\n" + } else { + b"\\n" + } + ); + } + } } diff --git a/big-code-analysis-ast/src/documentation/text/tests.rs b/big-code-analysis-ast/src/documentation/text/tests.rs index fed049ab6..9ca378761 100644 --- a/big-code-analysis-ast/src/documentation/text/tests.rs +++ b/big-code-analysis-ast/src/documentation/text/tests.rs @@ -231,6 +231,10 @@ fn rust_cleanup_keeps_unicode_blank_lines_and_removes_only_assembly_newline() { ("/**\n * a \n * b\n */\nfn f() {}", "a \n b"), ("/// a\n///\u{a0}\n/// b\nfn f() {}", "a\n\u{a0}\n b"), ("/**a /* nested */ b*/\nfn f() {}", "a /* nested */ b"), + ("/**a\n\n*/\nfn f() {}", "a\n"), + ("/**\n\n*/\nfn f() {}", ""), + ("/**\n *a\n *b\n */\nfn f() {}", "*a\n*b"), + ("/**\n * a\n ***/\nfn f() {}", " a\n*"), ] { let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); let index = parser diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index 88439ed1a..b8b31ea31 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -13,6 +13,8 @@ //! Tree-sitter wrappers: `Tree`, [`Node`], [`Ancestors`], and the cursors. mod ancestors; +#[cfg(any(test, feature = "test-support"))] +pub(crate) use ancestors::{memo_probes, sibling_slot_probes}; mod parser_cache; pub use ancestors::{AncestorIter, Ancestors, ChildAncestors, FoldCache, SiblingCache}; @@ -491,6 +493,7 @@ impl<'a> Node<'a> { /// [`children`]: Self::children #[inline] pub fn child_by_field_name(&self, name: &str) -> Option> { + field_lookups::record(); self.0.child_by_field_name(name).map(Node) } @@ -506,6 +509,7 @@ impl<'a> Node<'a> { #[doc(hidden)] #[inline] pub fn child_by_field_id(&self, field: u16) -> Option> { + field_lookups::record(); self.0.child_by_field_id(field).map(Node) } @@ -543,6 +547,7 @@ impl<'a> Node<'a> { #[inline] #[must_use] pub fn child(&self, pos: usize) -> Option> { + child_lookups::record(); self.0.child(pos as u32).map(Node) } @@ -781,6 +786,9 @@ impl<'a> Node<'a> { } } +crate::observation::counter!(field_lookups, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(child_lookups, cfg(any(test, feature = "test-support"))); + /// Pre-order iterator over a node and its descendants, returned by /// [`Node::preorder`]. /// diff --git a/big-code-analysis-ast/src/node/ancestors.rs b/big-code-analysis-ast/src/node/ancestors.rs index 339821fd5..a838414f4 100644 --- a/big-code-analysis-ast/src/node/ancestors.rs +++ b/big-code-analysis-ast/src/node/ancestors.rs @@ -15,11 +15,15 @@ mod folds; mod siblings; use chain::{Chain, HeldChain}; +#[cfg(any(test, feature = "test-support"))] +pub(crate) use folds::memo_probes; pub use folds::{ FoldCache, GateLane, KindLane, LevelQuestion, NodeQuestion, fold_slot_probes, fold_steps, }; pub(crate) use folds::{FoldLane, MemoQuestion, NodeMemo, WordSlot}; use siblings::NOTHING_RECORDED; +#[cfg(any(test, feature = "test-support"))] +pub(crate) use siblings::sibling_slot_probes; pub use siblings::{SiblingCache, WIDE_PARENT, sibling_cache_reads, sibling_seeks}; /// The chain of a node's children, held by a consumer that reads them diff --git a/big-code-analysis-ast/src/node/ancestors/folds.rs b/big-code-analysis-ast/src/node/ancestors/folds.rs index cde63148c..983563546 100644 --- a/big-code-analysis-ast/src/node/ancestors/folds.rs +++ b/big-code-analysis-ast/src/node/ancestors/folds.rs @@ -762,6 +762,7 @@ pub(crate) struct NodeMemo(RefCell>); impl NodeMemo { /// The stored answer for `node`, if any. pub(crate) fn get(&self, node: &Node<'_>) -> Option { + memo_probes::record(); self.0.borrow().get(&node.id()).copied() } @@ -842,6 +843,7 @@ impl FoldCache { // crate's tests through `test-support`, since most walks that lend the // cache live there. crate::observation::counter!(fold_steps, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(memo_probes, cfg(any(test, feature = "test-support"))); // Stored states a memoised fold compares against the chain to find where // to resume. `fold_steps` cannot see a search that reads more slots than diff --git a/big-code-analysis-ast/src/node/ancestors/siblings.rs b/big-code-analysis-ast/src/node/ancestors/siblings.rs index c9b840cb0..484dfb420 100644 --- a/big-code-analysis-ast/src/node/ancestors/siblings.rs +++ b/big-code-analysis-ast/src/node/ancestors/siblings.rs @@ -223,6 +223,7 @@ fn position_with_budget( let mut end = children.len(); while first < end { budget.step()?; + sibling_slot_probes::record(); let middle = first + (end - first) / 2; if children[middle].start_byte() < node.start_byte() { first = middle + 1; @@ -232,6 +233,7 @@ fn position_with_budget( } for (at, child) in children.iter().enumerate().skip(first) { budget.step()?; + sibling_slot_probes::record(); if child.start_byte() != node.start_byte() { break; } @@ -242,6 +244,11 @@ fn position_with_budget( Ok(None) } +crate::observation::counter!( + sibling_slot_probes, + cfg(any(test, feature = "test-support")) +); + /// The children of each wide node on a walk's chain, recorded as the /// walk pushes them, so that [`Ancestors::siblings_after`] and /// [`Ancestors::siblings_before`] find a sibling in a flat `ERROR`, or diff --git a/big-code-analysis-bench/benches/documentation.rs b/big-code-analysis-bench/benches/documentation.rs index 20751bfdc..987430230 100644 --- a/big-code-analysis-bench/benches/documentation.rs +++ b/big-code-analysis-bench/benches/documentation.rs @@ -12,7 +12,9 @@ fn main() { let options = DocumentationOptions::default(); for size in [256, 512, 1024] { cold(&mut criterion, size, &context, options); + secondary(&mut criterion, size, &context, options); prepared(&mut criterion, size, &context, options); + late_owner(&mut criterion, size, &context, options); included_ranges(&mut criterion, size, &context, options); } criterion.final_summary(); @@ -145,6 +147,120 @@ fn cold( group.finish(); } +fn secondary( + criterion: &mut Criterion, + size: usize, + context: &DocumentationContext, + options: DocumentationOptions, +) { + let slots = (0..size) + .map(|at| format!("v{at}")) + .collect::>() + .join(","); + let workloads = [ + ( + "single-line-php", + LANG::Php, + format!(" String { use std::fmt::Write; let mut source = String::new(); diff --git a/utils/documentation-collector-perturb.json b/utils/documentation-collector-perturb.json index fb2a910a6..49b6a9905 100644 --- a/utils/documentation-collector-perturb.json +++ b/utils/documentation-collector-perturb.json @@ -3,6 +3,41 @@ "runner": "cargo", "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], "cases": [ + { + "name": "partial-c-declarator-projection-is-not-complete", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "let Some(declared) = self.declared_name(child, budget)? else {\n return Ok(());", + "new": "let Some(declared) = self.declared_name(child, budget)? else {\n continue;", + "expect": ["documentation::collector::projection_tests::c_incomplete_declarators_and_gathered_names", "documentation::collector::projection_tests::cpp_incomplete_declarators_and_gathered_names", "documentation::collector::projection_tests::mozcpp_incomplete_declarators_and_gathered_names", "documentation::collector::projection_tests::objc_incomplete_declarators_and_gathered_names"] + }, + { + "name": "gathered-name-reference-is-not-first-fragment-only", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": "for id in self.index.facts.documents[document.0]\n .fragments\n .iter()\n .rev()", + "new": "for id in self.index.facts.documents[document.0]\n .fragments\n .iter()\n .take(1)", + "expect": ["documentation::collector::projection_tests::c_incomplete_declarators_and_gathered_names"] + }, + { + "name": "tcl-hex-is-variable-width", + "file": "big-code-analysis-ast/src/documentation/text/literals.rs", + "old": "if python && count != width {", + "new": "if count != width {", + "expect": ["documentation::text::literals::tests::tcl_variable_width_escapes_preserve_token_origins", "documentation::text::literals::tests::irules_variable_width_escapes_preserve_token_origins"] + }, + { + "name": "python-cleanup-applies-whole-document-margin", + "file": "big-code-analysis-ast/src/documentation/text/cleanup.rs", + "old": "if margin != usize::MAX {", + "new": "if false && margin != usize::MAX {", + "expect": ["documentation::text::cleanup::tests::whole_python_document_cleanup_keeps_escape_and_tab_origins", "documentation::text::cleanup::tests::python_cleanup_counts_unicode_margin_in_characters"] + }, + { + "name": "pending-slots-are-not-unsupported", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "if qualifies || super::forms::slot_candidate(self.index.profile, node.kind()) {", + "new": "if qualifies {", + "expect": ["documentation::collector::form_tests::kotlin_parameter_form_is_pending_in_default_queries", "documentation::collector::form_tests::php_promoted_form_is_pending_in_default_queries"] + }, { "name": "collector-bypasses-fallible-marker-kernel", "file": "big-code-analysis-ast/src/documentation/collector.rs", diff --git a/utils/documentation-form-matrix.json b/utils/documentation-form-matrix.json index c04176d8f..adeb299aa 100644 --- a/utils/documentation-form-matrix.json +++ b/utils/documentation-form-matrix.json @@ -10,27 +10,27 @@ "Java": { "implemented": ["traditional/Markdown basic declaration", "empty block", "four-slash Markdown", "last selection", "annotation-bearing declaration", "prelex unavailable plus source-cleaned evidence"], "ineligible": ["ordinary comments", "signature/accessor trivia without a target", "body working notes"], - "pending": ["filename publication", "full module/record/constructor inventory", "semantic Unicode prelexing"] + "pending": ["filename publication", "field/constant slot projections", "semantic Unicode prelexing"] }, "Kotlin": { "implemented": ["basic KDoc function", "last selection across plain comments", "annotation-bearing function", "selected Local raw/text/maps"], "ineligible": ["ordinary comments", "line-comment documentation"], - "pending": ["Local signature/modifier/accessor/constructor projection", "parameter/property slots", "full declaration inventory"] + "pending": ["Local signature/modifier/accessor/constructor projection", "parameter/property slots", "publication"] }, "Groovy": { "implemented": ["basic Groovydoc type", "nearest selection", "annotation-bearing type"], "ineligible": ["ordinary comments", "plain comment detaches nearest block", "Local placement is not emitted"], - "pending": ["full member/constructor/record inventory", "publication"] + "pending": ["same-row block/declaration source selection", "field slot projection", "publication"] }, "Csharp": { "implemented": ["basic XML type", "leading trivia selection", "attribute-bearing declaration", "literal XML markup"], "ineligible": ["ordinary comments", "four-slash banner", "accessor trivia", "Local placement is not emitted"], - "pending": ["full field/event/property/indexer/operator inventory", "conditional member projections", "publication"] + "pending": ["field/event slot projection", "conditional member projections", "publication"] }, "Php": { "implemented": ["basic function/class", "one/two/three-block precedence", "enum declaration-before-file", "file preamble", "last selection"], "ineligible": ["non-PHPDoc markers", "superseded blocks", "unsupported qualified call spellings"], - "pending": ["signature/promoted slots", "define constant slots and imported callees", "PhpDocumentor alternate", "publication"] + "pending": ["signature/promoted/property/constant slots", "define constant slots and imported callees", "PhpDocumentor alternate", "publication"] }, "Javascript": { "implemented": ["basic function/class", "export declaration projection", "nested forward docs", "file/fileoverview/overview/module", "leading selection"], @@ -45,12 +45,12 @@ "Typescript": { "implemented": ["basic function", "export/ambient declaration projection", "module/packageDocumentation file precedence", "leading selection"], "ineligible": ["ordinary comments", "after-code non-parameter comments", "destructuring declarations", "unsupported assignments"], - "pending": ["parameter/binding slots", "virtual forms", "full overload/namespace/type/member inventory", "publication"] + "pending": ["parameter/binding slots", "virtual forms", "publication"] }, "Tsx": { "implemented": ["basic JSX-returning function", "export/ambient declaration projection", "module/packageDocumentation file precedence", "leading selection"], "ineligible": ["ordinary comments", "after-code non-parameter comments", "destructuring declarations", "unsupported assignments"], - "pending": ["parameter/binding slots", "virtual forms", "full overload/namespace/type/member inventory", "publication"] + "pending": ["parameter/binding slots", "virtual forms", "publication"] }, "C": { "implemented": ["basic definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures", "line/block phase-two splicing"], @@ -70,7 +70,7 @@ "Objc": { "implemented": ["basic C definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures", "line/block phase-two splicing"], "ineligible": ["ordinary comments", "quoted/CDATA structural lookalikes", "banner markers"], - "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery projections", "full method/property/protocol inventory", "publication"] + "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery projections", "complex declarators", "publication"] }, "Go": { "implemented": ["basic function/package", "declaration group and spec", "positional runs", "directive filtering", "literal block stars"], @@ -85,7 +85,7 @@ "Lua": { "implemented": ["basic following function", "block wrapper", "FirstFile opener", "marked lines and long comments", "local text/maps"], "ineligible": ["ordinary standalone leading run", "empty marked block", "function-body annotation"], - "pending": ["tagged virtual/table forms", "native table-field/parameter comments", "full assignment/return inventory", "publication"] + "pending": ["tagged virtual/table forms", "native table-field/parameter comments", "assignment/return/field slots", "publication"] } }, "deferred": ["Python", "Perl", "Elixir", "Bash", "Tcl", "Irules"], From 6b3d4c6fe0a858ff93a6c2907ad6c15ba5dcf7e7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:41:38 -0800 Subject: [PATCH 039/221] test(documentation): exercise both pending-slot registration paths --- utils/documentation-collector-perturb.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/documentation-collector-perturb.json b/utils/documentation-collector-perturb.json index 49b6a9905..6d58c4f54 100644 --- a/utils/documentation-collector-perturb.json +++ b/utils/documentation-collector-perturb.json @@ -35,7 +35,7 @@ "name": "pending-slots-are-not-unsupported", "file": "big-code-analysis-ast/src/documentation/collector.rs", "old": "if qualifies || super::forms::slot_candidate(self.index.profile, node.kind()) {", - "new": "if qualifies {", + "new": "if qualifies && !super::forms::slot_candidate(self.index.profile, node.kind()) {", "expect": ["documentation::collector::form_tests::kotlin_parameter_form_is_pending_in_default_queries", "documentation::collector::form_tests::php_promoted_form_is_pending_in_default_queries"] }, { From 62925abf3d0f91a048e2817401569678afdf32d5 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:02:41 -0800 Subject: [PATCH 040/221] refactor(documentation): build prepared owner associations once --- .bca-baseline.toml | 20 +++++++++---------- .../src/documentation/collector.rs | 4 ---- .../src/documentation/collector/assembly.rs | 5 ----- .../src/lang_helpers/doc_comment.rs | 7 ------- big-code-analysis-bench/Cargo.toml | 3 --- 5 files changed, 10 insertions(+), 29 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 37712dea8..761798042 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,13 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 901.0 +value = 897.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 127.0 +value = 126.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -431,19 +431,19 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::order_results" metric = "abc" -value = 53.600373133029585 +value = 50.635955604688654 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::order_results" metric = "halstead.effort" -value = 121251.12650557018 +value = 113120.37181131 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::order_results" metric = "nexits" -value = 13.0 +value = 12.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -575,31 +575,31 @@ value = 58161.637831875196 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "abc" -value = 42.67317658670374 +value = 39.11521443121589 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cognitive" -value = 20.0 +value = 18.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cyclomatic" -value = 19.0 +value = 18.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "halstead.effort" -value = 106857.85979066297 +value = 92864.2122735224 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "nexits" -value = 6.0 +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 06b4c3a33..3e6e1397b 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -857,10 +857,6 @@ impl<'s> Builder<'s> { budget.step()?; self.index.associations_ordered.push(ordinal); } - for owners in &mut self.index.associations_by_owner { - budget.step()?; - owners.clear(); - } for &ordinal in &self.index.associations_ordered { budget.step()?; for &owner in &self.index.facts.associations[ordinal].owners { diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index afad1d19a..323935850 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -114,11 +114,6 @@ impl<'s> Builder<'s> { self.pending_document(&draft, document, &owners, attribute, budget)?; } if !owners.is_empty() || draft.unresolved.is_some() || named_resolution.is_some() { - let association = self.index.facts.associations.len(); - for owner in &owners { - budget.step()?; - self.index.associations_by_owner[owner.0].push(association); - } self.index.facts.associations.push(Association { document, owners, diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 24fc639b6..7e9caeffa 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -1249,13 +1249,6 @@ fn collect_positional_prefix<'a, R: SourceRules, B: WorkBudget>( Ok(run) } -/// The trailing comment that heads `first`'s LDoc group, when `first` sits -/// directly under a row that ends in one: LDoc lexes a line comment with -/// its newline and gathers every consecutive comment token into one group -/// whose first token decides whether it is an LDoc block (`parse.lua`), so -/// a `---` row under `x = 1 -- note` belongs to that `--` group. The run -/// `leading_doc_run` hands over leaves such a comment out, as go/doc does, -/// so it is looked up here. #[cfg(test)] mod tests { use super::*; diff --git a/big-code-analysis-bench/Cargo.toml b/big-code-analysis-bench/Cargo.toml index 18cec90af..78b826cfc 100644 --- a/big-code-analysis-bench/Cargo.toml +++ b/big-code-analysis-bench/Cargo.toml @@ -40,9 +40,6 @@ big-code-analysis-ast = { path = "../big-code-analysis-ast", features = ["test-s serde_json.workspace = true [dev-dependencies] -# Test-only, path-only like the root dependency above: the shape tests -# read `node::WIDE_PARENT` so a fixture sized to the walk's sibling-cache -# threshold cannot go narrow if the threshold is raised. # `html_reports` writes `target/criterion/report/index.html`, which is # what makes a measurement reviewable after the fact rather than a # number pasted into a commit message. From 22d9c71646ef66ece73bf5a53236b8cd64bf025f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:12:47 -0800 Subject: [PATCH 041/221] test(documentation): enforce cancellation and benchmark outcomes --- .../collector/cancellation_tests.rs | 12 +- .../src/documentation/collector/cost_tests.rs | 37 +++ .../src/documentation/collector/form_tests.rs | 11 + .../src/documentation/collector/tests.rs | 125 +++++++++ .../src/documentation/ordering.rs | 17 ++ .../benches/documentation.rs | 53 +++- .../benches/documentation/validation.rs | 241 ++++++++++++++++++ utils/documentation-audit-perturb.json | 49 ++++ utils/documentation-facts-perturb.json | 8 +- 9 files changed, 541 insertions(+), 12 deletions(-) create mode 100644 big-code-analysis-bench/benches/documentation/validation.rs create mode 100644 utils/documentation-audit-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs b/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs index e7cc817f2..b74b7d618 100644 --- a/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/cancellation_tests.rs @@ -169,16 +169,16 @@ fn many_included_ranges_cancel_inside_normalization() { .collect(); parser.set_included_ranges(&ranges).unwrap(); let tree = parser.parse(&bytes, None).unwrap(); - let result = cancel_in_phase(WorkPhase::Ranges, || { - collect( - LANG::Rust, + // The first two checkpoints bracket the dependency's range-array copy. + // The third must be reached by the normalization loop itself. + let result = crate::documentation::budget::cancel_after(3, || { + SourceContext::with_budget( &tree, &bytes, - &DocumentationContext::default(), - &DocumentationOptions::default(), + &crate::documentation::budget::CollectionBudget::default(), ) }); - assert!(matches!(result, Err(CollectionError::Cancelled))); + assert!(matches!(result, Err(SourceError::Cancelled))); assert_eq!( collect( LANG::Rust, diff --git a/big-code-analysis-ast/src/documentation/collector/cost_tests.rs b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs index 9297a78c8..e75675326 100644 --- a/big-code-analysis-ast/src/documentation/collector/cost_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs @@ -166,3 +166,40 @@ fn late_owner_queries_never_scan_other_owners_or_empty_ancestor_scopes() { assert_eq!(after.field_lookups - before.field_lookups, 0); } } + +#[cfg(feature = "c")] +#[test] +fn growing_text_at_fixed_fanout_is_built_once_in_bounded_chunks() { + use crate::documentation::budget::BYTE_INTERVAL; + for length in [BYTE_INTERVAL - 1, BYTE_INTERVAL, BYTE_INTERVAL * 2 + 1] { + let source = format!("/**{}*/\nint a, b;", "x".repeat(length)); + let parser = AnyParser::parse(LANG::C, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + assert_eq!(index.associations().next().unwrap().get().owner_count(), 2); + let document = index.documents().next().unwrap(); + let text = index.complete_text(document).unwrap().unwrap(); + assert_eq!(text.text(), "x".repeat(length)); + assert_eq!(text.mappings().len(), 1); + let after = observations(); + assert_eq!(after.renders - before.renders, 1); + assert_eq!( + after.copy_chunks - before.copy_chunks, + length.div_ceil(BYTE_INTERVAL) + ); + for _ in 0..32 { + let retained = index.complete_text(document).unwrap().unwrap(); + assert!(std::ptr::eq(retained.text(), text.text())); + assert!(std::ptr::eq(retained.mappings(), text.mappings())); + } + assert_eq!(observations().renders, after.renders); + assert_eq!(observations().copy_chunks, after.copy_chunks); + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/form_tests.rs b/big-code-analysis-ast/src/documentation/collector/form_tests.rs index 3356bf347..4a33038f8 100644 --- a/big-code-analysis-ast/src/documentation/collector/form_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/form_tests.rs @@ -34,6 +34,17 @@ fn assert_pending_form(language: LANG, source: &str, owner_kind: &str) { .any(|assessment| assessment.get().axis == AssessmentAxis::Owner) ); assert_eq!(index.associations().len(), 0, "{language:?}: {source}"); + assert_eq!(index.documents().len(), 1, "{language:?}: {source}"); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 1); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + "audit" + ); + assert!(index.assessments().any(|assessment| { + assessment.get().axis == AssessmentAxis::Owner + && index.assessed_document(assessment).unwrap() == Some(document) + })); } #[cfg(feature = "java")] diff --git a/big-code-analysis-ast/src/documentation/collector/tests.rs b/big-code-analysis-ast/src/documentation/collector/tests.rs index c0eb40f5b..0e1ffbabf 100644 --- a/big-code-analysis-ast/src/documentation/collector/tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/tests.rs @@ -1055,3 +1055,128 @@ fn document_handles_are_index_qualified_even_for_one_shared_parse() { "audit" ); } + +#[cfg(any( + feature = "bash", + feature = "c", + feature = "c-family-helpers", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript" +))] +#[test] +fn named_profiles_distinguish_deferred_incompatible_and_available() { + let defaults = [ + (LANG::Rust, Profile::Rust), + (LANG::Python, Profile::Python), + (LANG::Java, Profile::Javadoc), + (LANG::Kotlin, Profile::Kdoc), + (LANG::Groovy, Profile::Groovydoc), + (LANG::Csharp, Profile::CsharpXml), + (LANG::Php, Profile::BcaPhpSource), + (LANG::Javascript, Profile::Jsdoc), + (LANG::Mozjs, Profile::Jsdoc), + (LANG::Typescript, Profile::BcaTypescriptSource), + (LANG::Tsx, Profile::BcaTypescriptSource), + (LANG::C, Profile::Doxygen), + (LANG::Cpp, Profile::Doxygen), + (LANG::Mozcpp, Profile::Doxygen), + (LANG::Objc, Profile::Doxygen), + (LANG::Go, Profile::GoDoc), + (LANG::Ruby, Profile::Yard), + (LANG::Lua, Profile::Ldoc), + (LANG::Perl, Profile::Pod), + (LANG::Elixir, Profile::Elixir), + (LANG::Bash, Profile::Shdoc), + (LANG::Tcl, Profile::Ruff), + (LANG::Irules, Profile::Irules), + (LANG::Ccomment, Profile::Helper), + (LANG::Preproc, Profile::Helper), + ]; + assert_eq!(defaults.len(), LANG::into_enum_iter().count()); + assert!(LANG::into_enum_iter().any(|language| language.is_enabled())); + let context = DocumentationContext::default(); + for (language, default) in defaults { + let parser = language + .is_enabled() + .then(|| AnyParser::parse(language, Vec::new(), None, None).unwrap()); + for requested in defaults.iter().map(|(_, profile)| *profile).chain([ + Profile::Default, + Profile::Rdoc, + Profile::PhpDocumentor, + ]) { + let profile = if requested == Profile::Default { + default + } else { + requested + }; + let alternate = (language == LANG::Ruby && profile == Profile::Rdoc) + || (language == LANG::Php && profile == Profile::PhpDocumentor); + let expected = if profile != default && !alternate { + Err(CollectionError::UnsupportedProfile { language, profile }) + } else if alternate + || [ + LANG::Python, + LANG::Perl, + LANG::Elixir, + LANG::Bash, + LANG::Tcl, + LANG::Irules, + ] + .contains(&language) + { + Err(CollectionError::AdapterUnavailable { language, profile }) + } else { + Ok(profile) + }; + assert_eq!(requested.resolve(language), expected); + if let Some(parser) = &parser { + let options = DocumentationOptions { + profile: requested, + ..DocumentationOptions::default() + }; + assert_eq!( + parser + .documentation(&context, &options) + .map(|index| index.profile()), + expected + ); + assert_eq!( + collect( + language, + parser.ts_tree(), + parser.code(), + &context, + &options + ) + .map(|index| index.profile()), + expected + ); + } + } + if let Some(parser) = &parser { + for disabled in LANG::into_enum_iter().filter(|language| !language.is_enabled()) { + assert!( + matches!(collect(disabled, parser.ts_tree(), parser.code(), &context, &DocumentationOptions::default()), Err(CollectionError::LanguageDisabled(actual)) if actual == disabled) + ); + } + } + } +} diff --git a/big-code-analysis-ast/src/documentation/ordering.rs b/big-code-analysis-ast/src/documentation/ordering.rs index 78cc3921a..a8d650f89 100644 --- a/big-code-analysis-ast/src/documentation/ordering.rs +++ b/big-code-analysis-ast/src/documentation/ordering.rs @@ -135,6 +135,23 @@ mod tests { #[test] fn chunk_sort_cancellation_latches_without_corrupting_comparator_order() { + let budget = StopAt { + work: Cell::new(0), + stop: 2, + }; + let comparisons = Comparisons { + budget: &budget, + error: RefCell::new(None), + }; + assert_eq!(comparisons.compare(&1, &2), std::cmp::Ordering::Less); + assert_eq!(comparisons.compare(&2, &1), std::cmp::Ordering::Greater); + assert_eq!(comparisons.compare(&1, &2), std::cmp::Ordering::Less); + assert_eq!(comparisons.compare(&1, &1), std::cmp::Ordering::Equal); + assert_eq!(budget.work.get(), 2); + assert_eq!( + comparisons.check(), + Err(crate::documentation::SourceError::Cancelled) + ); let budget = StopAt { work: Cell::new(0), stop: 3, diff --git a/big-code-analysis-bench/benches/documentation.rs b/big-code-analysis-bench/benches/documentation.rs index 987430230..bd18fd5a7 100644 --- a/big-code-analysis-bench/benches/documentation.rs +++ b/big-code-analysis-bench/benches/documentation.rs @@ -6,6 +6,9 @@ use big_code_analysis_ast::documentation::{DocumentationContext, DocumentationOp use big_code_analysis_ast::{AnyParser, LANG}; use criterion::{BenchmarkId, Criterion}; +#[path = "documentation/validation.rs"] +mod validation; + fn main() { let mut criterion = Criterion::default().configure_from_args(); let context = DocumentationContext::default(); @@ -38,8 +41,8 @@ fn included_ranges( .unwrap_or_else(|error| panic!("grammar: {error}")); let ranges: Vec<_> = (0..size) .map(|at| tree_sitter::Range { - start_byte: at * 18, - end_byte: (at + 1) * 18, + start_byte: at * 19, + end_byte: (at + 1) * 19, start_point: tree_sitter::Point::new(at * 2, 0), end_point: tree_sitter::Point::new((at + 1) * 2, 0), }) @@ -50,6 +53,17 @@ fn included_ranges( let tree = parser .parse(&source, None) .unwrap_or_else(|| panic!("complete parse")); + assert_eq!(tree.included_ranges().len(), size); + let checked = big_code_analysis_ast::documentation::collect( + LANG::Rust, + &tree, + &source, + context, + &options, + ) + .unwrap_or_else(|error| panic!("collect: {error:?}")); + validation::documents(&checked, size, 1, 1, "audit"); + drop(checked); let mut group = criterion.benchmark_group("documentation/ranges"); group.bench_function(BenchmarkId::new("cold", size), |bencher| { bencher.iter(|| { @@ -134,6 +148,7 @@ fn cold( for (name, language, source) in workloads { let parser = AnyParser::parse(language, source.into_bytes(), None, None) .unwrap_or_else(|error| panic!("{name}: {error}")); + validation::fixture(name, size, &parser, context, options); group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { bencher.iter(|| { black_box( @@ -212,6 +227,7 @@ fn secondary( for (name, language, source) in workloads { let parser = AnyParser::parse(language, source.into_bytes(), None, None) .unwrap_or_else(|error| panic!("{name}: {error}")); + validation::fixture(name, size, &parser, context, options); group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { bencher.iter(|| { black_box( @@ -246,6 +262,17 @@ fn late_owner( .children() .last() .unwrap_or_else(|| panic!("last function")); + validation::documents(&index, size, 1, 1, "audit"); + assert_eq!(node.kind(), "function_item"); + assert_eq!(node.start_byte(), (size - 1) * 19 + 9); + assert_eq!( + index + .node_associations(node.as_tree_sitter()) + .unwrap_or_else(|error| panic!("owner: {error:?}")) + .associations() + .len(), + 1 + ); let mut group = criterion.benchmark_group("documentation/prepared"); group.bench_function(BenchmarkId::new("late-owner", size), |bencher| { bencher.iter(|| { @@ -304,6 +331,28 @@ fn prepared( .children() .last() .unwrap_or_else(|| panic!("fixture has a function")); + validation::documents( + &index, + 1, + size, + 1, + &std::iter::repeat_n("a", size) + .collect::>() + .join("\n"), + ); + assert_eq!(owner.kind(), "function_item"); + assert_eq!(owner.start_byte(), 5 * size); + assert_eq!(text.mappings().len(), size * 2 - 1); + let portions: Vec<_> = text + .origins(size * 2 - 2..size * 2 - 1) + .unwrap_or_else(|error| panic!("map: {error:?}")) + .collect(); + assert_eq!(portions.len(), 1); + let big_code_analysis_ast::documentation::OriginView::Copied(piece) = &portions[0].origin + else { + panic!("copied late origin") + }; + assert_eq!(piece.range(), (size - 1) * 5 + 3..(size - 1) * 5 + 4); let mut group = criterion.benchmark_group("documentation/prepared"); group.bench_function(BenchmarkId::new("owner", size), |bencher| { bencher.iter(|| { diff --git a/big-code-analysis-bench/benches/documentation/validation.rs b/big-code-analysis-bench/benches/documentation/validation.rs new file mode 100644 index 000000000..1efa59b62 --- /dev/null +++ b/big-code-analysis-bench/benches/documentation/validation.rs @@ -0,0 +1,241 @@ +//! Untimed semantic and grammar-shape checks for the documentation workloads. + +use big_code_analysis_ast::AnyParser; +use big_code_analysis_ast::documentation::{ + AssessmentAxis, Content, DocumentationContext, DocumentationIndex, DocumentationOptions, + OriginView, Owner, Resolution, UnresolvedReason, +}; + +pub(super) fn documents( + index: &DocumentationIndex<'_>, + count: usize, + fragments: usize, + owners: usize, + expected: &str, +) { + assert_eq!(index.documents().len(), count); + assert_eq!(index.associations().len(), count); + for association in index.associations() { + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), owners); + let document = index + .facts() + .associated_document(association) + .unwrap_or_else(|error| panic!("document: {error:?}")); + assert_eq!(document.get().fragment_count(), fragments); + let text = index + .complete_text(document) + .unwrap_or_else(|error| panic!("text: {error:?}")) + .unwrap_or_else(|| panic!("complete text")); + assert_eq!(text.text(), expected); + let mut end = 0; + for portion in text + .origins(0..expected.len()) + .unwrap_or_else(|error| panic!("map: {error:?}")) + { + assert_eq!(portion.output.start, end); + end = portion.output.end; + if let OriginView::Copied(piece) = portion.origin { + assert_eq!(piece.bytes(), &expected.as_bytes()[portion.output]); + } + } + assert_eq!(end, expected.len()); + for position in 0..owners { + let owner = index + .facts() + .associated_owner(association, position) + .unwrap_or_else(|error| panic!("owner: {error:?}")); + let query = index + .owner_associations(owner) + .unwrap_or_else(|error| panic!("query: {error:?}")); + assert_eq!(query.associations().collect::>(), [association]); + } + } +} + +fn shape(name: &str, size: usize, parser: &AnyParser) { + let root = parser.root_node(); + assert_eq!( + root.has_error(), + matches!(name, "wide-error" | "missing"), + "{name}" + ); + let nodes: Vec<_> = root.preorder().collect(); + let count = |kind| nodes.iter().filter(|node| node.kind() == kind).count(); + let mut depth = 0; + let mut cursor = parser.ts_tree().walk(); + let mut maximum = 0; + loop { + maximum = maximum.max(depth); + if cursor.goto_first_child() { + depth += 1; + continue; + } + while !cursor.goto_next_sibling() { + if !cursor.goto_parent() { + break; + } + depth -= 1; + } + if depth == 0 { + break; + } + } + match name { + "depth" => { + assert_eq!(count("mod_item"), size); + assert!(maximum >= 2 * size); + } + "width" => assert_eq!(root.child_count(), size * 2), + "fragments" => assert_eq!(count("comment"), size), + "c-slots" | "fanout-fixed-text" => assert_eq!(count("identifier"), size), + "hidden-fields" => { + assert_eq!(count("array_declarator"), size); + assert!(maximum >= size); + } + "ruby-modifiers" => { + assert_eq!(count("if_modifier"), size); + assert!(maximum >= size); + } + "java-undocumented" => { + assert_eq!(count("class_declaration"), size); + assert!(maximum >= 2 * size); + } + "pending-scope" => assert_eq!(count("function_item"), size), + "names" => assert_eq!(count("function_definition"), size), + "missing" => { + assert_eq!(nodes.iter().filter(|node| node.is_missing()).count(), 1); + assert!(maximum >= size); + } + "wide-error" => { + let error = nodes + .iter() + .find(|node| node.is_error()) + .unwrap_or_else(|| panic!("wide ERROR")); + assert!(error.child_count() >= size); + assert_eq!(count("field_declaration"), size); + } + _ => assert!(matches!( + name, + "single-line-lua" + | "single-line-jsdoc" + | "single-line-php" + | "single-line-ruby" + | "single-line-doxygen" + | "text-fixed-fanout" + )), + } +} + +#[allow(clippy::too_many_lines)] // One explicit expected outcome per benchmark workload. +pub(super) fn fixture( + name: &str, + size: usize, + parser: &AnyParser, + context: &DocumentationContext, + options: DocumentationOptions, +) { + shape(name, size, parser); + let index = parser + .documentation(context, &options) + .unwrap_or_else(|error| panic!("{name}: {error:?}")); + match name { + "depth" | "ruby-modifiers" | "hidden-fields" => documents(&index, 1, 1, 1, "audit"), + "width" => documents(&index, size, 1, 1, "audit"), + "fragments" => documents( + &index, + 1, + size, + 1, + &std::iter::repeat_n("audit", size) + .collect::>() + .join("\n"), + ), + "c-slots" => documents(&index, 1, 1, size, "audit"), + "single-line-lua" | "single-line-ruby" => { + documents(&index, 1, 1, 1, &"audit ".repeat(size)); + } + "single-line-jsdoc" | "single-line-php" | "single-line-doxygen" => { + documents(&index, 1, 1, 1, &"audit ".repeat(size)[..size * 6 - 1]); + } + "text-fixed-fanout" => documents(&index, 1, 1, 2, &"audit ".repeat(size)[..size * 6 - 1]), + "fanout-fixed-text" => documents(&index, 1, 1, size, &"audit ".repeat(1024)[..6143]), + "java-undocumented" => { + assert_eq!(index.documents().len(), 0); + assert_eq!(index.facts().owners().len(), size + 2); + } + "missing" => { + assert_eq!(index.documents().len(), 0); + assert_eq!(index.associations().len(), 0); + } + "wide-error" => { + assert_eq!(index.documents().len(), 1); + let association = index + .associations() + .next() + .unwrap_or_else(|| panic!("recovery association")); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + ); + assert_eq!(association.get().owner_count(), 0); + } + "pending-scope" => { + assert_eq!(index.documents().len(), 1); + let document = index + .documents() + .next() + .unwrap_or_else(|| panic!("pending attribute")); + assert!(matches!(document.get().content(), Content::PendingAdapter)); + assert_eq!(index.assessments().len(), 3); + let last = parser + .root_node() + .children() + .last() + .unwrap_or_else(|| panic!("last function")); + let query = index + .node_associations(last.as_tree_sitter()) + .unwrap_or_else(|error| panic!("query: {error:?}")); + assert_eq!(query.associations().len(), 0); + assert_eq!( + query + .assessments() + .map(|assessment| assessment.get().axis) + .collect::>(), + [AssessmentAxis::Occurrence, AssessmentAxis::Publication] + ); + } + "names" => { + assert_eq!(index.documents().len(), size); + assert_eq!(index.associations().len(), size); + for (ordinal, association) in index.associations().enumerate() { + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), 1); + let owner = index + .facts() + .associated_owner(association, 0) + .unwrap_or_else(|error| panic!("owner: {error:?}")); + let Owner::Node(node) = owner.get() else { + panic!("function definition") + }; + assert_eq!( + &parser.code()[node.node().byte_range()], + format!("void f{ordinal}() {{}}").as_bytes() + ); + let document = index + .facts() + .associated_document(association) + .unwrap_or_else(|error| panic!("document: {error:?}")); + assert_eq!( + index + .complete_text(document) + .unwrap_or_else(|error| panic!("text: {error:?}")) + .unwrap_or_else(|| panic!("complete text")) + .text(), + format!("@fn void f{ordinal}()") + ); + } + } + _ => panic!("unvalidated workload {name}"), + } +} diff --git a/utils/documentation-audit-perturb.json b/utils/documentation-audit-perturb.json new file mode 100644 index 000000000..7975a58d0 --- /dev/null +++ b/utils/documentation-audit-perturb.json @@ -0,0 +1,49 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "cancelled-comparator-returns-equal", + "file": "big-code-analysis-ast/src/documentation/ordering.rs", + "old": " left.cmp(right)", + "new": " if self.error.borrow().is_some() { std::cmp::Ordering::Equal } else { left.cmp(right) }", + "expect": ["documentation::ordering::tests::chunk_sort_cancellation_latches_without_corrupting_comparator_order"] + }, + { + "name": "normalization-loop-does-not-poll", + "file": "big-code-analysis-ast/src/documentation/source.rs", + "old": " for range in raw {\n budget.step()?;", + "new": " for range in raw {", + "expect": ["documentation::collector::cancellation_tests::many_included_ranges_cancel_inside_normalization"] + }, + { + "name": "pending-owner-documents-are-dropped", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " let (content, attribute) = self.render_draft(&mut draft, budget)?;", + "new": " if draft.target.is_some_and(|target| matches!(self.index.canonical.nodes[target.0].projection, Projection::Pending)) { return Ok(()); }\n let (content, attribute) = self.render_draft(&mut draft, budget)?;", + "expect": ["documentation::collector::form_tests::java_field_form_is_pending_in_default_queries", "documentation::collector::form_tests::javascript_binding_form_is_pending_in_default_queries"] + }, + { + "name": "deferred-perl-is-empty-success", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": "Self::Python | Self::Pod | Self::Elixir | Self::Shdoc | Self::Ruff | Self::Irules", + "new": "Self::Python | Self::Elixir | Self::Shdoc | Self::Ruff | Self::Irules", + "expect": ["documentation::collector::tests::named_profiles_distinguish_deferred_incompatible_and_available"] + }, + { + "name": "rdoc-alternate-becomes-incompatible", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": "(LANG::Php, Self::PhpDocumentor) | (LANG::Ruby, Self::Rdoc)", + "new": "(LANG::Php, Self::PhpDocumentor)", + "expect": ["documentation::collector::tests::named_profiles_distinguish_deferred_incompatible_and_available"] + }, + { + "name": "text-copied-twice", + "file": "big-code-analysis-ast/src/documentation/text.rs", + "old": " self.text.push_str(valid);", + "new": " self.text.push_str(valid);\n self.text.push_str(valid);", + "expect": ["documentation::collector::cost_tests::growing_text_at_fixed_fanout_is_built_once_in_bounded_chunks"] + } + ] +} diff --git a/utils/documentation-facts-perturb.json b/utils/documentation-facts-perturb.json index 797f9fa54..3d5dea91c 100644 --- a/utils/documentation-facts-perturb.json +++ b/utils/documentation-facts-perturb.json @@ -27,15 +27,15 @@ { "name": "empty-ranges-are-filtered-once", "file": "big-code-analysis-ast/src/documentation/source.rs", - "old": "included.retain(|range| range.start_byte < range.end_byte);", - "new": "included.retain(|_| true);", + "old": "if start == end {\n continue;", + "new": "if false && start == end {\n continue;", "expect": ["documentation::tests::ranges::empty_included_ranges_do_not_add_per_query_scan_work"] }, { "name": "late-intersection-uses-indexed-start", "file": "big-code-analysis-ast/src/documentation/source.rs", - "old": "let first = self\n .included\n .partition_point(|range| range.end_byte <= spelling.start);", - "new": "let first = 0;", + "old": "for range in &self.included[first..] {", + "new": "for range in &self.included[0..] {", "expect": ["documentation::tests::ranges::late_intersection_seeks_past_earlier_nonempty_ranges"] }, { From f23abf8eb4c4e3b14d4210d25e31e2064ece1c2b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:26:49 -0800 Subject: [PATCH 042/221] fix(documentation): preserve composition provenance and bound source work --- .bca-baseline.toml | 264 ++++- CHANGELOG.md | 4 + big-code-analysis-ast/src/documentation.rs | 21 + .../src/documentation/budget.rs | 1 + .../src/documentation/canonical.rs | 6 + .../src/documentation/collector.rs | 131 ++- .../src/documentation/collector/assembly.rs | 130 ++- .../documentation/collector/projections.rs | 130 ++- .../collector/remediation_tests.rs | 938 ++++++++++++++++++ .../src/documentation/names.rs | 183 +++- .../src/documentation/names/tokens.rs | 88 ++ .../src/documentation/recognition.rs | 1 + .../src/documentation/source.rs | 6 + .../src/documentation/text.rs | 1 + .../src/documentation/text/comments.rs | 99 +- .../src/documentation/text/source_cursor.rs | 72 ++ .../src/documentation/text/tests.rs | 35 + .../src/lang_helpers/doxygen.rs | 20 +- big-code-analysis-bench/Cargo.toml | 2 +- .../benches/documentation.rs | 260 ++++- .../benches/documentation/validation.rs | 6 +- utils/documentation-form-matrix.json | 4 +- utils/documentation-remediation-perturb.json | 21 + 23 files changed, 2243 insertions(+), 180 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/collector/remediation_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/names/tokens.rs create mode 100644 big-code-analysis-ast/src/documentation/text/source_cursor.rs create mode 100644 utils/documentation-remediation-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 761798042..ec4a67d39 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,19 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 897.0 +value = 956.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 126.0 +value = 138.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::finish" +metric = "nexits" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -401,31 +407,31 @@ value = 6.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "abc" -value = 55.97320787662612 +value = 52.478567053607705 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "cognitive" -value = 48.0 +value = 43.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "cyclomatic" -value = 20.0 +value = 19.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "halstead.effort" -value = 232144.35747298473 +value = 223259.64032932615 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::marker_run" metric = "nexits" -value = 5.0 +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -469,6 +475,12 @@ qualified = "Builder<'s>::record_children" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "abc" +value = 38.28837943815329 + [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::register" @@ -479,13 +491,13 @@ value = 15.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::register" metric = "cyclomatic" -value = 16.0 +value = 17.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::register" metric = "halstead.effort" -value = 75856.64234451539 +value = 77748.62342197515 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -521,31 +533,37 @@ value = 7.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "abc" -value = 47.56048780237646 +value = 49.85980344927164 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "cognitive" +value = 17.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "halstead.effort" -value = 110827.26177270018 +value = 182593.08399265425 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "nexits" -value = 8.0 +value = 9.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "abc" -value = 53.291650377896914 +value = 53.41348144429457 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "halstead.effort" -value = 87295.73158561725 +value = 90175.5563699593 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -561,39 +579,45 @@ value = 13.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" -qualified = "Builder<'s>::combine_pending" -metric = "cognitive" -value = 15.0 +qualified = "Builder<'s>" +metric = "wmc" +value = 73.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::coalesce_rust" +metric = "halstead.effort" +value = 48218.38058500087 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::combine_pending" metric = "halstead.effort" -value = 58161.637831875196 +value = 58850.75713727861 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "abc" -value = 39.11521443121589 +value = 51.12729212465687 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cognitive" -value = 18.0 +value = 23.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cyclomatic" -value = 18.0 +value = 23.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "halstead.effort" -value = 92864.2122735224 +value = 163794.80999271595 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -601,6 +625,12 @@ qualified = "Builder<'s>::document" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::named_document" +metric = "cognitive" +value = 17.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::named_document" @@ -625,59 +655,83 @@ qualified = "Builder<'s>::render_draft" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>" +metric = "wmc" +value = 67.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "abc" -value = 53.749418601506754 +value = 56.2672195865408 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "cognitive" -value = 20.0 +value = 23.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "halstead.effort" -value = 118991.71741040709 +value = 148400.19270030435 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "nexits" -value = 9.0 +value = 10.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "abc" +value = 44.15880433163923 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cognitive" -value = 21.0 +value = 27.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cyclomatic" -value = 21.0 +value = 29.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "halstead.effort" -value = 110018.09239923891 +value = 191098.72458144272 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "nexits" -value = 8.0 +value = 11.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::index_function_definition" +metric = "halstead.effort" +value = 53216.35692536166 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::index_function_definition" metric = "nexits" -value = 8.0 +value = 9.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::index_recovered_name" +metric = "nexits" +value = 7.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/tests.rs" @@ -711,7 +765,85 @@ value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" -qualified = "Names::resolve" +qualified = "Names::insert_candidate" +metric = "halstead.effort" +value = 53324.76224742121 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::insert_candidate" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::insert_candidate" +metric = "nexits" +value = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "abc" +value = 53.27288240746881 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "cognitive" +value = 35.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "cyclomatic" +value = 19.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "halstead.effort" +value = 152988.29680210442 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "nexits" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "reference_name" +metric = "cognitive" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "reference_name" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "tokens" +metric = "cognitive" +value = 23.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "tokens" +metric = "cyclomatic" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "tokens" +metric = "halstead.effort" +value = 96833.3962353417 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "tokens" metric = "nexits" value = 5.0 @@ -725,13 +857,13 @@ value = 6.0 path = "big-code-analysis-ast/src/documentation/recognition.rs" qualified = "NativeRules::target" metric = "halstead.effort" -value = 62580.37535783485 +value = 66174.94088354147 [[entry]] path = "big-code-analysis-ast/src/documentation/recognition.rs" qualified = "NativeRules::target::" metric = "cyclomatic" -value = 15.0 +value = 17.0 [[entry]] path = "big-code-analysis-ast/src/documentation/recognition.rs" @@ -923,19 +1055,19 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "" metric = "loc.ploc" -value = 541.0 +value = 583.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "append_range" metric = "nargs" -value = 5.0 +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "abc" -value = 66.70832032063167 +value = 69.28924880528002 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -953,13 +1085,13 @@ value = 28.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "halstead.effort" -value = 383332.4051257595 +value = 409210.04703845707 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "nexits" -value = 15.0 +value = 16.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -997,6 +1129,42 @@ qualified = "delimiters" metric = "nexits" value = 11.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "abc" +value = 46.776062254106 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "cognitive" +value = 34.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "cyclomatic" +value = 19.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "halstead.effort" +value = 135842.98435141143 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "nexits" +value = 10.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "lines" @@ -1045,29 +1213,17 @@ qualified = "prepare" metric = "nexits" value = 9.0 -[[entry]] -path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render_local" -metric = "abc" -value = 68.18357573492314 - [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "cognitive" -value = 50.0 - -[[entry]] -path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "render_local" -metric = "cyclomatic" -value = 22.0 +value = 27.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "halstead.effort" -value = 242315.44217119092 +value = 74922.20406534027 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1079,7 +1235,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "render_local" metric = "nexits" -value = 16.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index d0564cd28..0f9dddc3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,10 @@ for historical reference. Prepared node projections expose multi-owner and pending forms. Complex declarators remain pending, and gathered Doxygen references use their structural member. Reusable Python/Tcl cleanup preserves token origins. + Rust outer/inner contributors coalesce by semantic target; root/module docs use + file/package roles. Exact wrapper selection, conditional name provenance, helper + node identity, logical boundary trimming and retained-intersection text emission + preserve pending results without redirected or partial-complete claims. (#1660, #1661) - Added unstable AST positional-run evidence for Go, Ruby and Lua, including diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index 68d895a2b..65d5468e4 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -16,6 +16,12 @@ //! inspect only their indexed associations and linked pending scopes. Individual //! dependency calls and allocation are not internally interruptible; crate-owned //! scans use the collection work budget. +//! Complex C-family headers retain pending named matching; simple keys preserve +//! lexical token boundaries and stay within the canonical source scope. Conditional +//! and recovery provenance qualifies named candidates. Comment rendering clips the +//! fragment's retained intersections monotonically rather than searching global +//! included ranges for each emitted segment. Cancellation checks bound work between +//! polls; releasing accumulated partial state still costs its retained storage. pub(crate) mod budget; pub(crate) mod byte_scan; @@ -66,12 +72,22 @@ pub struct Observations { pub name_bytes: usize, /// Distinct name candidates compared inside hash buckets. pub name_candidates: usize, + /// Normalized name/signature key bytes retained across distinct entries. + pub key_bytes_stored: usize, /// Actual source-target requests, including binding callbacks. pub target_queries: usize, /// Source-target cache misses that execute classification. pub target_computations: usize, /// Byte visits in shared classifier scans. pub classifier_bytes: usize, + /// Outer Doxygen structural scanner iterations. + pub structural_bytes: usize, + /// Doxygen structural classifier calls. + pub structural_calls: usize, + /// Global source-intersection binary-search comparisons. + pub intersection_searches: usize, + /// Monotone retained-fragment piece visits during text emission. + pub fragment_piece_visits: usize, /// Pending-scope query links and records visited. pub assessment_scope_reads: usize, /// Dependency field lookups made by recognition callbacks. @@ -102,9 +118,14 @@ pub fn observations() -> Observations { copy_chunks: text::copy_chunks::observed(), name_bytes: names::name_bytes::observed(), name_candidates: names::name_candidates::observed(), + key_bytes_stored: names::key_bytes_stored::observed(), target_queries: recognition::target_queries::observed(), target_computations: recognition::target_computations::observed(), classifier_bytes: byte_scan::bytes_read::observed(), + structural_bytes: crate::lang_helpers::doxygen::structural_bytes::observed(), + structural_calls: crate::lang_helpers::doxygen::structural_calls::observed(), + intersection_searches: source::intersection_searches::observed(), + fragment_piece_visits: text::source_cursor::fragment_piece_visits::observed(), assessment_scope_reads: index::assessment_scope_reads::observed(), field_lookups: crate::node::field_lookups::observed(), child_lookups: crate::node::child_lookups::observed(), diff --git a/big-code-analysis-ast/src/documentation/budget.rs b/big-code-analysis-ast/src/documentation/budget.rs index 8df873061..15f86f036 100644 --- a/big-code-analysis-ast/src/documentation/budget.rs +++ b/big-code-analysis-ast/src/documentation/budget.rs @@ -46,6 +46,7 @@ pub(crate) enum WorkPhase { Ranges, Batch, Text, + Decoration, Names, Ordering, } diff --git a/big-code-analysis-ast/src/documentation/canonical.rs b/big-code-analysis-ast/src/documentation/canonical.rs index 75fe163c9..d06ceb45e 100644 --- a/big-code-analysis-ast/src/documentation/canonical.rs +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -29,6 +29,9 @@ pub(super) struct CanonicalNode<'s> { pub(super) pending_parent: Option, pub(super) following: Option, pub(super) owner_context: NodeId, + pub(super) name_scope: NodeId, + pub(super) qualification: Option, + pub(super) signature_complex: bool, } #[derive(Debug)] @@ -71,6 +74,9 @@ impl<'s> CanonicalNodes<'s> { pending_parent: None, following: None, owner_context: id, + name_scope: NodeId(0), + qualification: None, + signature_complex: false, }); id } diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 3e6e1397b..07103e983 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -78,7 +78,9 @@ pub(crate) fn collect_typed<'s, T: Checker + crate::traits::LanguageInfo>( .insert(builder.index.source.node(root)?, None, 0); if profile != Profile::Helper { builder.add_owner(root_id, Owner::File(builder.index.source.node(root)?)); - builder.walk::(&budget)?; + } + builder.walk::(&budget)?; + if profile != Profile::Helper { builder.finish(&budget)?; } budget.checkpoint()?; @@ -176,7 +178,21 @@ impl<'s> Builder<'s> { match visit { Visit::Exit(id, depth) => { chain.truncate(depth); - self.finalize_projection(id, budget)?; + if self.index.profile != Profile::Helper { + self.finalize_projection(id, budget)?; + } + let record = &self.index.canonical.nodes[id.0]; + let complex = record.signature_complex + || matches!( + record.evidence.node().kind(), + "lambda_expression" + | "optional_parameter_declaration" + | "function_definition" + | "declaration" + ); + if let Some(parent) = record.parent { + self.index.canonical.nodes[parent.0].signature_complex |= complex; + } } Visit::Enter(id, depth) => { visits::record(); @@ -184,7 +200,8 @@ impl<'s> Builder<'s> { let node = Node::from_tree_sitter(self.index.canonical.nodes[id.0].evidence.node()); bounds(node.as_tree_sitter(), self.index.source.bytes().len())?; - if transparent_doc_context(node.kind()) + self.inherit_context(id, &node); + if transparent_doc_context(self.index.profile, node.kind()) && let Some(parent) = self.index.canonical.nodes[id.0].parent { self.index.canonical.nodes[id.0].owner_context = @@ -195,6 +212,9 @@ impl<'s> Builder<'s> { budget, super::budget::WorkPhase::Classification, || { + if self.index.profile == Profile::Helper { + return Ok(()); + } self.register::(id, &node, ancestors, budget)?; self.recognize::(id, &node, ancestors, budget) }, @@ -320,6 +340,7 @@ impl<'s> Builder<'s> { | "expression_statement" )) || node.has_error() + || conditional_kind(node.kind()) || node.is_missing() { self.index.canonical.nodes[id.0].projection = Projection::Pending; @@ -330,6 +351,35 @@ impl<'s> Builder<'s> { Ok(()) } + fn inherit_context(&mut self, id: NodeId, node: &Node<'s>) { + if let Some(parent) = self.index.canonical.nodes[id.0].parent { + let outer = &self.index.canonical.nodes[parent.0]; + let scope = if matches!( + outer.evidence.node().kind(), + "namespace_definition" + | "class_specifier" + | "struct_specifier" + | "union_specifier" + | "function_definition" + | "lambda_expression" + | "compound_statement" + ) { + parent + } else { + outer.name_scope + }; + let qualification = outer.qualification; + self.index.canonical.nodes[id.0].name_scope = scope; + self.index.canonical.nodes[id.0].qualification = qualification; + } + let record = &mut self.index.canonical.nodes[id.0]; + if node.is_error() || node.is_missing() { + record.qualification = Some(UnresolvedReason::GrammarBoundary); + } else if conditional_kind(node.kind()) && record.qualification.is_none() { + record.qualification = Some(UnresolvedReason::Conditional); + } + } + fn recognize( &mut self, id: NodeId, @@ -427,8 +477,7 @@ impl<'s> Builder<'s> { let target = self.evidence_id(run.target)?; let scope = self.evidence_id(run.containing)?.unwrap_or(NodeId(0)); let code_before = self.evidence_id(run.code_before)?; - let mut local: std::collections::HashMap = std::collections::HashMap::new(); - let mut gathered: std::collections::HashMap = + let mut structural_drafts: std::collections::HashMap = std::collections::HashMap::new(); let mut forward = Draft { fragments: Vec::new(), @@ -459,22 +508,37 @@ impl<'s> Builder<'s> { forward.fragments.push(id); forward.unresolved = forward.unresolved.or(member.uncertainty); } else { + let local_node = + if let markers::MarkerPlacement::Gathered(gatherer) = member.placement { + gatherer + } else { + member.node + }; + let gatherer = if matches!( + member.placement, + markers::MarkerPlacement::Gatherer | markers::MarkerPlacement::Gathered(_) + ) { + Some(self.index.canonical.lookup(local_node.node())?) + } else { + None + }; + if let Some(&index) = gatherer.as_ref().and_then(|id| structural_drafts.get(id)) { + let draft = &mut self.drafts[index]; + draft.fragments.push(id); + draft.unresolved = draft.unresolved.or(member.uncertainty); + draft.gap |= run.prefix_gap || run.suffix_gap; + continue; + } let mut draft = Draft { fragments: vec![id], target: None, scope, - binding: run.target, + binding: None, role: DocumentRole::Primary, unresolved: member.uncertainty, pending: false, gap: run.prefix_gap || run.suffix_gap, }; - let local_node = - if let markers::MarkerPlacement::Gathered(gatherer) = member.placement { - gatherer - } else { - member.node - }; self.local_target(&mut draft, local_node, member.placement, budget)?; if self.index.profile == Profile::BcaPhpSource && draft.role == DocumentRole::FilePackage @@ -483,6 +547,7 @@ impl<'s> Builder<'s> { let kind = self.index.canonical.nodes[target.0].evidence.node().kind(); if matches!(kind, "enum_declaration" | "expression_statement") { draft.target = Some(target); + draft.binding = run.target; draft.role = DocumentRole::Primary; draft.pending = kind == "expression_statement"; } @@ -491,31 +556,14 @@ impl<'s> Builder<'s> { let raw = &self.index.source.bytes()[member.node.node().byte_range()]; if matches!(raw.get(..4), Some(b"///<" | b"//!<" | b"/**<" | b"/*!<")) { draft.target = code_before; + draft.binding = run.code_before; draft.pending = code_before.is_none(); } } - if matches!( - member.placement, - markers::MarkerPlacement::Gatherer | markers::MarkerPlacement::Gathered(_) - ) { - if let Some(&index) = gathered.get(&local_node.node().id()) { - self.drafts[index].fragments.push(id); - } else { - gathered.insert(local_node.node().id(), self.drafts.len()); - self.drafts.push(draft); - } - } else if self.index.profile == Profile::Rust - && let Some(target) = draft.target - { - if let Some(&index) = local.get(&target) { - self.drafts[index].fragments.push(id); - } else { - local.insert(target, self.drafts.len()); - self.drafts.push(draft); - } - } else { - self.drafts.push(draft); + if let Some(gatherer) = gatherer { + structural_drafts.insert(gatherer, self.drafts.len()); } + self.drafts.push(draft); } } if !forward.fragments.is_empty() { @@ -564,12 +612,14 @@ impl<'s> Builder<'s> { positional::RunSelection::Opener(positional::OpenerReason::FirstFile) => { draft.target = Some(NodeId(0)); draft.role = DocumentRole::FilePackage; + draft.binding = None; } positional::RunSelection::Opener( positional::OpenerReason::Explicit | positional::OpenerReason::Tagged, ) => { draft.target = None; draft.pending = true; + draft.binding = None; } _ => {} } @@ -771,6 +821,7 @@ impl<'s> Builder<'s> { } fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + self.coalesce_rust(budget)?; self.combine_pending(budget)?; for draft in std::mem::take(&mut self.drafts) { budget.step()?; @@ -882,6 +933,13 @@ fn is_wrapper(profile: Profile, kind: &str) -> bool { } } +pub(super) fn conditional_kind(kind: &str) -> bool { + matches!( + kind, + "preproc_if" | "preproc_ifdef" | "preproc_else" | "preproc_elif" | "preproc_elifdef" + ) +} + fn needs_slot(profile: Profile, kind: &str) -> bool { match profile { Profile::Doxygen => matches!(kind, "declaration" | "field_declaration"), @@ -909,7 +967,10 @@ fn fields_needed(profile: Profile, kind: &str) -> bool { || (profile == Profile::Yard && matches!(kind, "if_modifier" | "unless_modifier")) } -fn transparent_doc_context(kind: &str) -> bool { +fn transparent_doc_context(profile: Profile, kind: &str) -> bool { + if profile == Profile::Kdoc && matches!(kind, "primary_constructor" | "getter" | "setter") { + return true; + } matches!( kind, "parameters" @@ -939,4 +1000,6 @@ mod form_tests; #[cfg(test)] mod projection_tests; #[cfg(test)] +mod remediation_tests; +#[cfg(test)] mod tests; diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index 323935850..2b6ceef2a 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -3,6 +3,51 @@ use super::*; impl<'s> Builder<'s> { + pub(super) fn coalesce_rust( + &mut self, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + if self.index.profile != Profile::Rust { + return Ok(()); + } + let mut groups = std::collections::HashMap::::new(); + for mut draft in std::mem::take(&mut self.drafts) { + budget.step()?; + if let Some(target) = draft.target + && matches!(draft.unresolved, None | Some(UnresolvedReason::ExcludedGap)) + { + draft.role = self.rust_role(target); + draft.scope = self.index.canonical.nodes[target.0] + .parent + .unwrap_or(NodeId(0)); + if let Some(&index) = groups.get(&target) { + let composed = &mut self.drafts[index]; + for fragment in draft.fragments { + budget.step()?; + composed.fragments.push(fragment); + } + composed.pending |= draft.pending; + composed.gap |= draft.gap; + composed.unresolved = composed.unresolved.or(draft.unresolved); + composed.binding = composed.binding.or(draft.binding); + continue; + } + groups.insert(target, self.drafts.len()); + } + self.drafts.push(draft); + } + Ok(()) + } + + fn rust_role(&self, target: NodeId) -> DocumentRole { + if target.0 == 0 + || self.index.canonical.nodes[target.0].evidence.node().kind() == "mod_item" + { + DocumentRole::FilePackage + } else { + DocumentRole::Primary + } + } pub(super) fn combine_pending( &mut self, budget: &CollectionBudget, @@ -11,6 +56,7 @@ impl<'s> Builder<'s> { for (index, draft) in self.drafts.iter().enumerate() { budget.step()?; if let Some(target) = draft.target + && matches!(draft.unresolved, None | Some(UnresolvedReason::ExcludedGap)) && matches!( draft.role, DocumentRole::Primary | DocumentRole::FilePackage @@ -25,7 +71,7 @@ impl<'s> Builder<'s> { self.drafts[index].fragments.push(fragment); self.drafts[index].pending = true; } else { - let scope = self.index.canonical.nodes[node.0] + let scope = self.index.canonical.nodes[target.unwrap_or(node).0] .parent .unwrap_or(NodeId(0)); if let Some(target) = target { @@ -35,15 +81,13 @@ impl<'s> Builder<'s> { fragments: vec![fragment], target, scope, - binding: target.map(|id| self.index.canonical.nodes[id.0].evidence), - role: if target.is_some_and(|id| { - id.0 == 0 - || self.index.canonical.nodes[id.0].evidence.node().kind() == "mod_item" - }) { - DocumentRole::FilePackage - } else { - DocumentRole::Primary - }, + binding: target + .filter(|_| { + self.index.canonical.nodes[node.0].evidence.node().kind() + == "attribute_item" + }) + .map(|id| self.index.canonical.nodes[id.0].evidence), + role: target.map_or(DocumentRole::Primary, |id| self.rust_role(id)), unresolved: None, pending: true, gap: false, @@ -93,15 +137,21 @@ impl<'s> Builder<'s> { if self.index.profile == Profile::Doxygen && draft.target.is_none() && !draft.gap - && let Some((found, resolution)) = self.named_document(document, budget)? + && let Some(result) = self.named_document(document, draft.scope, budget)? { - owners = found; - named_resolution = Some(resolution); - pending = false; + owners = result.owners; + named_resolution = result + .reason + .map(Resolution::Unresolved) + .or_else(|| (!result.pending).then_some(Resolution::Resolved)); + pending = result.pending; } if let Some(target) = draft.target { match &self.index.canonical.nodes[target.0].projection { Projection::Ready(ids) => { + draft.unresolved = draft + .unresolved + .or(self.index.canonical.nodes[target.0].qualification); for &id in ids { budget.step()?; owners.push(id); @@ -112,8 +162,26 @@ impl<'s> Builder<'s> { } if pending { self.pending_document(&draft, document, &owners, attribute, budget)?; + if self.index.profile == Profile::CsharpXml + && let Some(target) = draft.target + && conditional_kind(self.index.canonical.nodes[target.0].evidence.node().kind()) + { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Selection, + reason: "Conditional XML documentation selection awaits branch interpretation", + node: Some(self.index.canonical.nodes[target.0].evidence), + document: Some(document), + }); + self.index.canonical.nodes[target.0] + .pending + .push(assessment); + } } - if !owners.is_empty() || draft.unresolved.is_some() || named_resolution.is_some() { + if (!owners.is_empty() && (!pending || draft.target.is_some())) + || draft.unresolved.is_some() + || named_resolution.is_some() + { self.index.facts.associations.push(Association { document, owners, @@ -159,9 +227,10 @@ impl<'s> Builder<'s> { self.index.assessments_by_owner[owner.0].push(assessment); } if owners.is_empty() { - self.index.canonical.nodes[draft.target.unwrap_or(draft.scope).0] - .pending - .push(assessment); + let scope = draft + .target + .unwrap_or(self.index.canonical.nodes[draft.scope.0].owner_context); + self.index.canonical.nodes[scope.0].pending.push(assessment); } Ok(()) } @@ -169,8 +238,9 @@ impl<'s> Builder<'s> { fn named_document( &self, document: DocumentId, + scope: NodeId, budget: &CollectionBudget, - ) -> Result, Resolution)>, CollectionError> { + ) -> Result, CollectionError> { for id in self.index.facts.documents[document.0] .fragments .iter() @@ -195,11 +265,23 @@ impl<'s> Builder<'s> { if command != b"fn" { return Ok(None); } - let (owners, reason) = self.names.resolve(name, budget)?; - return Ok(Some(( - owners, - reason.map_or(Resolution::Resolved, Resolution::Unresolved), - ))); + let record = &self.index.canonical.nodes[scope.0]; + let scope = if matches!( + record.evidence.node().kind(), + "namespace_definition" + | "class_specifier" + | "struct_specifier" + | "compound_statement" + ) { + scope + } else { + record.name_scope + }; + let mut result = self.names.resolve_in(name, scope, budget)?; + if let Some(reason) = record.qualification { + result.reason = Some(reason); + } + return Ok(Some(result)); } } Ok(None) diff --git a/big-code-analysis-ast/src/documentation/collector/projections.rs b/big-code-analysis-ast/src/documentation/collector/projections.rs index 89bd67f80..73cd2a01a 100644 --- a/big-code-analysis-ast/src/documentation/collector/projections.rs +++ b/big-code-analysis-ast/src/documentation/collector/projections.rs @@ -10,6 +10,15 @@ impl Builder<'_> { ) -> Result<(), CollectionError> { budget.step()?; let node = self.index.canonical.nodes[id.0].evidence.node(); + if self.index.profile == Profile::Doxygen + && node.has_error() + && matches!( + node.kind(), + "function_definition" | "declaration" | "field_declaration" + ) + { + self.index_recovered_name(id, budget)?; + } if node.has_error() || node.is_missing() || !self @@ -58,13 +67,29 @@ impl Builder<'_> { { continue; } - if let Projection::Ready(ids) = &record.projection { - for &owner in ids { - budget.step()?; - owners.push(owner); + if (self.index.profile == Profile::Ldoc + || matches!(node.kind(), "then" | "ambient_declaration")) + && !record.evidence.node().is_named() + { + continue; + } + match &record.projection { + Projection::Ready(ids) => { + for &owner in ids { + budget.step()?; + owners.push(owner); + } + } + Projection::Pending => { + self.index.canonical.nodes[id.0].projection = Projection::Pending; + return Ok(()); + } + Projection::Unsupported => { + self.index.canonical.nodes[id.0].projection = Projection::Unsupported; + return Ok(()); } - break; } + break; } if !owners.is_empty() { self.index.canonical.nodes[id.0].projection = Projection::Ready(owners); @@ -145,12 +170,21 @@ impl Builder<'_> { if self.index.source.bytes().get(end.saturating_sub(1)) == Some(&b';') { end -= 1; } - self.names.insert( + let complex = self.complex_header(id, budget)?; + let record = &self.index.canonical.nodes[id.0]; + self.names.insert_candidate( &self.index.source.bytes()[node.byte_range()], - &self.index.source.bytes()[declaration.start_byte()..end], - enclosing, + (!complex).then(|| &self.index.source.bytes()[declaration.start_byte()..end]), + record.name_scope, + super::super::names::NamedOwner { + owner: enclosing, + qualification: record.qualification, + }, budget, )?; + if complex { + self.pending_name(id); + } } else { let source = self .index @@ -200,16 +234,90 @@ impl Builder<'_> { .source .covers_with_budget(node.start_byte()..end, budget)? { - self.names.insert( + let complex = self.complex_header(id, budget)?; + let record = &self.index.canonical.nodes[id.0]; + self.names.insert_candidate( &self.index.source.bytes()[self.index.canonical.nodes[name.0] .evidence .node() .byte_range()], - &self.index.source.bytes()[node.start_byte()..end], - owner, + (!complex).then(|| &self.index.source.bytes()[node.start_byte()..end]), + record.name_scope, + super::super::names::NamedOwner { + owner, + qualification: record.qualification, + }, budget, )?; + if complex { + self.pending_name(id); + } + } + Ok(()) + } + + fn pending_name(&mut self, id: NodeId) { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Owner, + reason: "Complex signature awaits exact named matching", + node: Some(self.index.canonical.nodes[id.0].evidence), + document: None, + }); + self.index.canonical.nodes[id.0].pending.push(assessment); + } + + fn complex_header( + &self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result { + for &child in + &self.index.canonical.children[self.index.canonical.nodes[id.0].children.clone()] + { + budget.step()?; + let record = &self.index.canonical.nodes[child.0]; + if record.field != Some("body") && record.signature_complex { + return Ok(true); + } } + Ok(false) + } + + fn index_recovered_name( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let Some(declarator) = self.declarator_child(id, budget)? else { + return Ok(()); + }; + let Some((name, true)) = self.declared_name(declarator, budget)? else { + return Ok(()); + }; + let name_node = self.index.canonical.nodes[name.0].evidence.node(); + if name_node.is_missing() + || !self + .index + .source + .covers_with_budget(name_node.byte_range(), budget)? + { + return Ok(()); + } + let owner = OwnerId(self.index.facts.owners.len()); + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + self.index.canonical.nodes[id.0].projection = Projection::Pending; + self.names.insert_candidate( + &self.index.source.bytes()[name_node.byte_range()], + None, + self.index.canonical.nodes[id.0].name_scope, + super::super::names::NamedOwner { + owner, + qualification: Some(UnresolvedReason::GrammarBoundary), + }, + budget, + )?; + self.pending_name(id); Ok(()) } } diff --git a/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs b/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs new file mode 100644 index 000000000..6312f311f --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs @@ -0,0 +1,938 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(feature = "rust")] +#[test] +#[allow(clippy::too_many_lines)] +fn rust_same_target_composition_and_roles_are_independent_of_placement() { + for (source, kind, expected, fragments, role) in [ + ( + "/// outer\nmod m { //! inner\n}\n", + "mod_item", + Some("outer\ninner"), + 2, + DocumentRole::FilePackage, + ), + ( + "/// outer\nfn f() { //! inner\n}\n", + "function_item", + Some("outer\ninner"), + 2, + DocumentRole::Primary, + ), + ( + "/// outer\n#[doc = \"attribute\"]\nfn f() { //! inner\n}\n", + "function_item", + None, + 3, + DocumentRole::Primary, + ), + ( + "/// outer\nmod m {}", + "mod_item", + Some("outer"), + 1, + DocumentRole::FilePackage, + ), + ( + "mod m { //! inner\n}", + "mod_item", + Some("inner"), + 1, + DocumentRole::FilePackage, + ), + ( + "//! first\n#![allow(unused)]\n//! second\n", + "source_file", + Some("first\nsecond"), + 2, + DocumentRole::FilePackage, + ), + ( + "//! first\n#![doc = \"middle\"]\n//! second\n", + "source_file", + None, + 3, + DocumentRole::FilePackage, + ), + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + for retain_unbound in [false, true] { + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Rust, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + assert_eq!(index.documents().len(), 1, "{source}"); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), fragments); + assert_eq!(document.get().role(), role); + assert_eq!( + index + .complete_text(document) + .unwrap() + .map(CompleteText::text), + expected + ); + if expected.is_none() { + assert!(matches!(document.get().content(), Content::PendingAdapter)); + } + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let (Owner::Node(node) | Owner::File(node)) = owner.get() else { + panic!("node owner") + }; + assert_eq!(node.node().kind(), kind); + if source == "/// outer\nmod m { //! inner\n}\n" { + assert_eq!(node.node().byte_range(), 10..29); + let text = index.complete_text(document).unwrap().unwrap(); + let origins: Vec<_> = text.origins(0..11).unwrap().collect(); + assert_eq!(origins.len(), 3); + let OriginView::Copied(first) = &origins[0].origin else { + panic!("copy") + }; + let OriginView::Copied(last) = &origins[2].origin else { + panic!("copy") + }; + assert_eq!(first.range(), 4..9); + assert_eq!(last.range(), 22..27); + assert_eq!(origins[1].origin, OriginView::Synthetic); + } + } + } + } +} + +#[cfg(any(feature = "ruby", feature = "lua"))] +fn pending_first(language: LANG, source: &str) { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 0); + let doc = index.documents().next().unwrap(); + assert_eq!(index.complete_text(doc).unwrap().unwrap().text(), "audit"); + assert!( + index + .assessments() + .any(|a| index.assessed_document(a).unwrap() == Some(doc)) + ); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_pending_first_statement_never_redirects_to_later_method() { + pending_first(LANG::Ruby, "class C\n# audit\nX = 1\ndef later; end\nend"); +} +#[cfg(feature = "lua")] +#[test] +fn lua_pending_first_statement_never_redirects_to_later_function() { + pending_first( + LANG::Lua, + "module(\"m\")\ndo\n---audit\nvalue = 1\nfunction later() end\nend", + ); +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_signature_context_exposes_document_linked_owner_assessment() { + for (source, kind) in [ + ( + "public /**audit*/ inline fun f() {}", + "function_declaration", + ), + ( + "class C private /**audit*/ constructor()", + "class_declaration", + ), + ("public /**audit*/ fun f() {}", "function_declaration"), + ("class C /**audit*/ constructor()", "class_declaration"), + ] { + let parser = + AnyParser::parse(LANG::Kotlin, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let document = index.documents().next().unwrap(); + let node = parser + .root_node() + .preorder() + .find(|n| n.kind() == kind) + .unwrap(); + assert_eq!(index.associations().len(), 0); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + "audit" + ); + assert!( + index + .node_associations(node.as_tree_sitter()) + .unwrap() + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner + && index.assessed_document(a).unwrap() == Some(document)), + "{source}" + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_conditional_docs_remain_pending_only_in_affected_scope() { + for doc in ["///audit", "/**audit*/"] { + let source = format!( + "{doc}\n#if FLAG\nclass C {{}}\n#elif OTHER\nclass D {{}}\n#else\nclass E {{}}\n#endif\nclass Later {{}}" + ); + let parser = AnyParser::parse(LANG::Csharp, source.into_bytes(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 0); + let doc = index.documents().next().unwrap(); + assert_eq!(index.complete_text(doc).unwrap().unwrap().text(), "audit"); + let classes: Vec<_> = parser + .root_node() + .preorder() + .filter(|n| n.kind() == "class_declaration") + .collect(); + assert_eq!(classes.len(), 4); + for class in &classes[..3] { + assert!( + index + .node_associations(class.as_tree_sitter()) + .unwrap() + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Selection + && index.assessed_document(a).unwrap() == Some(doc)) + ); + } + assert_eq!( + index + .node_associations(classes[3].as_tree_sitter()) + .unwrap() + .assessments() + .count(), + 0 + ); + } +} + +#[cfg(feature = "c-family-helpers")] +#[test] +fn helpers_validate_all_canonical_nodes_before_unsupported_owner() { + for (language, source) in [ + (LANG::Ccomment, b"/**audit*/".as_slice()), + (LANG::Preproc, b"#define X 1\n".as_slice()), + (LANG::Ccomment, b"".as_slice()), + ] { + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.capability(), Capability::NoDeclarationModel); + assert_eq!(index.facts().owners().len(), 0); + for node in parser.root_node().preorder() { + assert!(matches!( + index.node_associations(node.as_tree_sitter()), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_owners(node.as_tree_sitter()), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_projection(node.as_tree_sitter()), + Err(OwnerError::UnsupportedOwner) + )); + } + let foreign = parser.ts_tree().clone(); + assert!(matches!( + index.node_projection(foreign.root_node()), + Err(OwnerError::Source(SourceError::ForeignTree)) + )); + let mut edited = parser.ts_tree().root_node(); + edited.edit(&tree_sitter::InputEdit { + start_byte: 0, + old_end_byte: 0, + new_end_byte: 1, + start_position: tree_sitter::Point::new(0, 0), + old_end_position: tree_sitter::Point::new(0, 0), + new_end_position: tree_sitter::Point::new(0, 1), + }); + assert!(matches!( + index.node_projection(edited), + Err(OwnerError::Source(SourceError::NoncanonicalNode)) + )); + assert!(matches!( + index.node_owners(edited), + Err(OwnerError::Source(SourceError::NoncanonicalNode)) + )); + assert!(matches!( + index.node_associations(edited), + Err(OwnerError::Source(SourceError::NoncanonicalNode)) + )); + } +} + +#[cfg(feature = "c-family-helpers")] +#[test] +fn helper_canonical_walk_cancels_and_tears_down_on_small_stack() { + use crate::documentation::budget::cancel_after; + let parser = + AnyParser::parse(LANG::Preproc, b"#define X 1\n".repeat(2048), None, None).unwrap(); + assert!(matches!( + cancel_after(4, || parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + )), + Err(CollectionError::Cancelled) + )); + std::thread::Builder::new() + .stack_size(128 * 1024) + .spawn(move || { + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 0); + assert!(matches!( + index.node_projection( + parser + .root_node() + .children() + .last() + .unwrap() + .as_tree_sitter() + ), + Err(OwnerError::UnsupportedOwner) + )); + drop(index); + drop(parser); + }) + .unwrap() + .join() + .unwrap(); +} + +#[cfg(feature = "cpp")] +#[test] +fn exact_signatures_preserve_tokens_scope_and_complex_competitors() { + for (source, reason, count) in [ + ( + "struct intx {};\nvoid f(intx);\n/**@fn void f(int x)*/", + Some(UnresolvedReason::MissingName), + 0, + ), + ( + "typedef int intx;\nvoid f(int x);\n/**@fn void f(intx)*/", + Some(UnresolvedReason::MissingName), + 0, + ), + ( + "struct intx {};\nvoid f(intx); void f(int x);\n/**@fn void f(int x)*/", + None, + 1, + ), + ( + "void f ( int /*type*/ x );\n/**@fn void f(int x)*/", + None, + 1, + ), + ( + "namespace A { void f(int x); }\n/**@fn void f(int x)*/", + Some(UnresolvedReason::MissingName), + 0, + ), + ( + "namespace A { void f(int x); /**@fn void f(int x)*/ }\nnamespace B { void f(int x); }", + None, + 1, + ), + ( + "void f(int x); void f(int x = [] { return 1; }());\n/**@fn void f(int x)*/", + Some(UnresolvedReason::Ambiguous), + 2, + ), + ] { + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error(), "{source}"); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + reason.map_or(Resolution::Resolved, Resolution::Unresolved), + "{source}" + ); + assert_eq!(association.get().owner_count(), count, "{source}"); + } + for source in [ + "/**own*/\nvoid f(int x = [] { return 1; }());\n/**@fn void f(int x)*/", + "void f();\n/**@fn void f(int x = 1)*/", + "namespace A { void f(); }\n/**@fn void A::f()*/", + ] { + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let reference = index.documents().last().unwrap(); + assert!( + index + .assessments() + .any(|a| index.assessed_document(a).unwrap() == Some(reference)), + "{source}" + ); + assert!( + !index + .associations() + .any( + |a| index.facts().associated_document(a).unwrap() == reference + && a.get().resolution == Resolution::Resolved + ) + ); + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn qualified_names(language: LANG) { + for declaration in ["void f(void);", "void f(void) {}"] { + let source = format!("/**@fn void f(void)*/\n#if FLAG\n{declaration}\n#endif"); + let parser = AnyParser::parse(language, source.into_bytes(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::Conditional) + ); + assert_eq!(association.get().owner_count(), 1); + } +} +#[cfg(feature = "c")] +#[test] +fn c_named_candidates_retain_conditional_provenance() { + qualified_names(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_named_candidates_retain_conditional_provenance() { + qualified_names(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_named_candidates_retain_conditional_provenance() { + qualified_names(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_named_candidates_retain_conditional_provenance() { + qualified_names(LANG::Objc); +} + +#[cfg(feature = "cpp")] +#[test] +fn nested_default_lambda_signature_work_is_linear_in_primary_facts() { + for depth in [8, 16, 32, 64, 128] { + let source = format!( + "{}void leaf();{}", + "void f(int x = [] { ".repeat(depth), + " return 1; }());".repeat(depth) + ); + let parser = AnyParser::parse(LANG::Cpp, source.into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + assert_eq!(index.documents().len(), 0); + assert_eq!( + index + .assessments() + .filter(|a| a.get().reason == "Complex signature awaits exact named matching") + .count(), + depth + ); + // Each complex declaration stores its one-byte name twice, never its header. + assert_eq!( + after.key_bytes_stored - before.key_bytes_stored, + 2 * depth + 17 + ); + assert_eq!(after.name_bytes - before.name_bytes, 2 * depth + 40); + } +} + +#[cfg(any(feature = "go", feature = "ruby", feature = "java"))] +fn boundary_members(language: LANG, source: &str, expected: &str) { + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + assert_eq!(text.text(), expected); + let mut end = 0; + for portion in text.origins(0..expected.len()).unwrap() { + assert_eq!(portion.output.start, end); + end = portion.output.end; + } + assert_eq!(end, expected.len()); +} +#[cfg(feature = "go")] +#[test] +fn go_trims_logical_boundary_members_only() { + boundary_members( + LANG::Go, + "package p\n//\n// audit\n//\nfunc F() {}", + "audit", + ); + boundary_members(LANG::Go, "package p\n// a\n//\n// b\nfunc F() {}", "a\n\nb"); + boundary_members(LANG::Go, "package p\n//\n//\nfunc F() {}", ""); +} +#[cfg(feature = "ruby")] +#[test] +fn ruby_trims_logical_boundary_members_only() { + boundary_members(LANG::Ruby, "#\n# audit\n#\ndef f; end", "audit"); +} +#[cfg(feature = "java")] +#[test] +fn java_trims_logical_boundary_members_only() { + boundary_members(LANG::Java, "///\n///audit\n///\nclass C {}", "audit"); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn inline_cost(language: LANG) { + let mut counts = Vec::new(); + for size in [8, 16, 32, 64, 128] { + let source = format!("/**{}*/\nvoid f() {{}}", "`x` ".repeat(size)); + let parser = AnyParser::parse(language, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let after = observations(); + counts.push(( + after.classifier_bytes - before.classifier_bytes, + after.structural_bytes - before.structural_bytes, + )); + } + for pair in counts.windows(3) { + assert_eq!(pair[2].0 - pair[1].0, 2 * (pair[1].0 - pair[0].0)); + assert_eq!(pair[2].1 - pair[1].1, 2 * (pair[1].1 - pair[0].1)); + } +} +#[cfg(feature = "c")] +#[test] +fn c_inline_code_scan_is_linear() { + inline_cost(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_inline_code_scan_is_linear() { + inline_cost(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_inline_code_scan_is_linear() { + inline_cost(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_inline_code_scan_is_linear() { + inline_cost(LANG::Objc); +} + +#[cfg(feature = "cpp")] +#[test] +fn gathered_disposition_does_not_rescan_structural_member_per_fragment() { + let mut counts = Vec::new(); + for size in [8, 16, 32, 64, 128] { + let source = format!("{}/**{}@file*/", "/**a*/\n".repeat(size), "x ".repeat(size)); + let parser = AnyParser::parse(LANG::Cpp, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!( + index.documents().next().unwrap().get().fragment_count(), + size + 1 + ); + counts.push(observations().structural_bytes - before.structural_bytes); + } + for triple in counts.windows(3) { + assert_eq!(triple[2] - triple[1], 2 * (triple[1] - triple[0])); + } +} + +#[cfg(feature = "java")] +#[test] +fn multiline_text_reuses_retained_fragment_intersections() { + for size in [32, 64, 128, 256] { + let source = format!("/**\n{}*/\nclass C {{}}", " * é\n".repeat(size)); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Java.tree_sitter_language().unwrap()) + .unwrap(); + let mut point = tree_sitter::Point::new(0, 0); + let ranges: Vec<_> = source + .bytes() + .enumerate() + .map(|(at, byte)| { + let start_point = point; + if byte == b'\n' { + point.row += 1; + point.column = 0; + } else { + point.column += 1; + } + tree_sitter::Range { + start_byte: at, + end_byte: at + 1, + start_point, + end_point: point, + } + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(&source, None).unwrap(); + let before = observations(); + let index = collect( + LANG::Java, + &tree, + source.as_bytes(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + let text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + assert_eq!( + text.text(), + std::iter::repeat_n("é", size) + .collect::>() + .join("\n") + ); + // One fragment intersection binary-searches for byte zero; text emission performs none. + assert_eq!( + after.intersection_searches - before.intersection_searches, + (usize::BITS - source.len().leading_zeros()) as usize + ); + assert_eq!(text.origins(0..2).unwrap().count(), 2); + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn export_and_binding(language: LANG) { + let source = "/**audit*/\nexport function f() {}"; + let parser = AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + for index in [ + parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(), + collect( + language, + parser.ts_tree(), + parser.code(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(), + ] { + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().binding.unwrap().node().kind(), + "export_statement" + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("function") + }; + assert_eq!(node.node().kind(), "function_declaration"); + assert_eq!(node.node().byte_range(), 18..33); + assert_eq!( + index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap() + .text(), + "audit" + ); + } + let parser = AnyParser::parse( + language, + b"/** @file audit */\nfunction f() {}".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert!(index.associations().next().unwrap().get().binding.is_none()); +} +#[cfg(feature = "javascript")] +#[test] +fn javascript_export_projection_and_file_binding_are_exact() { + export_and_binding(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_export_projection_and_file_binding_are_exact() { + export_and_binding(LANG::Mozjs); +} + +#[cfg(feature = "rust")] +#[test] +fn rust_raw_two_fragment_smoke_and_file_binding() { + let source = b"///a\n///b\nfn f() {}"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let index = collect( + LANG::Rust, + parser.ts_tree(), + source, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let doc = index.documents().next().unwrap(); + assert_eq!(doc.get().fragment_count(), 2); + let text = index.complete_text(doc).unwrap().unwrap(); + assert_eq!(text.text(), "a\nb"); + let portions: Vec<_> = text.origins(0..3).unwrap().collect(); + assert_eq!(portions.len(), 3); + let OriginView::Copied(a) = &portions[0].origin else { + panic!("copy") + }; + let OriginView::Copied(b) = &portions[2].origin else { + panic!("copy") + }; + assert_eq!(a.range(), 3..4); + assert_eq!(b.range(), 8..9); + assert_eq!(portions[1].origin, OriginView::Synthetic); + let parser = AnyParser::parse( + LANG::Rust, + b"//! crate\n/// item\nfn f() {}".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let associations: Vec<_> = index.associations().collect(); + assert_eq!(associations.len(), 2); + assert!(associations[0].get().binding.is_none()); + assert_eq!( + associations[1].get().binding.unwrap().node().byte_range(), + 19..28 + ); +} + +#[cfg(feature = "c")] +#[test] +fn trailing_binding_is_the_preceding_declaration() { + let parser = AnyParser::parse( + LANG::C, + b"struct S { int x; /// = index.associations().collect(); + assert_eq!(associations[0].get().resolution, Resolution::Resolved); + assert_eq!( + associations[1].get().resolution, + Resolution::Unresolved(UnresolvedReason::Expansion) + ); + assert_eq!(associations[1].get().owner_count(), 0); + assert!(associations[1].get().binding.is_none()); +} + +#[cfg(feature = "cpp")] +#[test] +fn recovered_named_candidate_keeps_grammar_qualification() { + let source = "/**@fn f*/\nvoid f(int x = );"; + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(parser.root_node().has_error()); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + ); + assert_eq!(association.get().owner_count(), 1); +} + +#[cfg(all(feature = "go", feature = "ruby"))] +#[test] +fn source_scope_folds_compute_and_search_positive_states() { + for size in [8, 16, 32] { + for (language, source) in [ + ( + LANG::Go, + format!( + "package p\ntype S struct {{\n{}X int\n{} }}\n", + "X struct {\n".repeat(size), + "}\n".repeat(size) + ), + ), + ( + LANG::Ruby, + format!( + "{}# audit\ndef f; end\n{}", + "class C\n".repeat(size), + "end\n".repeat(size) + ), + ), + ] { + let parser = AnyParser::parse(language, source.into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let before = observations(); + let steps = crate::node::fold_steps::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + let (expected_steps, expected_probes) = if language == LANG::Go { + (3 * size + 4, 4 * size + 5) + } else { + (2 * size, 4 * size - 1) + }; + // Each nested Go field adds struct/list/field levels; Ruby adds class/body. + assert_eq!(crate::node::fold_steps::observed() - steps, expected_steps); + assert_eq!( + after.fold_slot_probes - before.fold_slot_probes, + expected_probes + ); + assert_eq!(index.documents().len(), usize::from(language == LANG::Ruby)); + } + } +} diff --git a/big-code-analysis-ast/src/documentation/names.rs b/big-code-analysis-ast/src/documentation/names.rs index 9d0e76a8b..d6a12aeb1 100644 --- a/big-code-analysis-ast/src/documentation/names.rs +++ b/big-code-analysis-ast/src/documentation/names.rs @@ -5,22 +5,39 @@ use std::collections::hash_map::RandomState; use std::hash::{BuildHasher, Hasher}; use super::budget::WorkBudget; +use super::canonical::NodeId; use super::{OwnerId, SourceError, UnresolvedReason}; +mod tokens; + #[derive(Default)] pub(super) struct Names { - identifiers: HashMap>, - signatures: HashMap>, + identifiers: HashMap<(NodeId, u64), Vec>, + signatures: HashMap<(NodeId, u64), Vec>, + complex: HashMap<(NodeId, u64), Vec>, hasher: RandomState, } struct NameEntry { spelling: Vec, - owners: Vec, + owners: Vec, +} + +#[derive(Clone, Copy)] +pub(super) struct NamedOwner { + pub(super) owner: OwnerId, + pub(super) qualification: Option, +} + +pub(super) struct NameResolution { + pub(super) owners: Vec, + pub(super) reason: Option, + pub(super) pending: bool, } crate::observation::counter!(name_bytes, cfg(any(test, feature = "test-support"))); crate::observation::counter!(name_candidates, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(key_bytes_stored, cfg(any(test, feature = "test-support"))); fn key( bytes: &[u8], @@ -39,10 +56,17 @@ fn normalized_key( ) -> Result<(u64, Vec), SourceError> { let mut hash = hasher.build_hasher(); let mut key = Vec::new(); - for &byte in bytes { - budget.bytes(1).map_err(Into::into)?; - name_bytes::record(); - if !byte.is_ascii_whitespace() { + let Some(tokens) = tokens::tokens(bytes, budget)? else { + return Ok((0, Vec::new())); + }; + for (position, token) in tokens.iter().enumerate() { + if position != 0 { + hash.write_u8(0); + key.push(0); + } + for &byte in *token { + budget.bytes(1).map_err(Into::into)?; + name_bytes::record(); hash.write_u8(byte); key.push(byte); } @@ -72,7 +96,7 @@ fn same_spelling( fn insert_entry( bucket: &mut Vec, spelling: Vec, - owner: OwnerId, + owner: NamedOwner, budget: &B, ) -> Result<(), SourceError> { for entry in bucket.iter_mut() { @@ -86,27 +110,79 @@ fn insert_entry( spelling, owners: vec![owner], }); + for _ in bucket + .last() + .map_or(&[][..], |entry| entry.spelling.as_slice()) + { + budget.bytes(1).map_err(Into::into)?; + key_bytes_stored::record(); + } Ok(()) } impl Names { + #[cfg(test)] pub(super) fn insert( &mut self, name: &[u8], signature: &[u8], owner: OwnerId, budget: &B, + ) -> Result<(), SourceError> { + self.insert_candidate( + name, + Some(signature), + NodeId(0), + NamedOwner { + owner, + qualification: None, + }, + budget, + ) + } + + pub(super) fn insert_candidate( + &mut self, + name: &[u8], + signature: Option<&[u8]>, + scope: NodeId, + owner: NamedOwner, + budget: &B, ) -> Result<(), SourceError> { let (hash, name) = key(name, &self.hasher, budget)?; + let mut copied_name = Vec::new(); + for &byte in &name { + budget.bytes(1).map_err(Into::into)?; + copied_name.push(byte); + } insert_entry( - self.identifiers.entry(hash).or_default(), - name, + self.identifiers.entry((scope, hash)).or_default(), + copied_name, owner, budget, )?; - let (hash, signature) = key(signature, &self.hasher, budget)?; + let signature = match signature { + Some(signature) => { + if let Some(tokens) = tokens::tokens(signature, budget)? + && tokens::reference_name(&tokens, budget)?.is_some() + { + Some(key(signature, &self.hasher, budget)?) + } else { + None + } + } + None => None, + }; + let Some((hash, signature)) = signature.filter(|(_, key)| !key.is_empty()) else { + return insert_entry( + self.complex.entry((scope, hash)).or_default(), + name, + owner, + budget, + ); + }; insert_entry( - self.signatures.entry(hash).or_default(), + self.signatures.entry((scope, hash)).or_default(), signature, owner, budget, @@ -114,11 +190,36 @@ impl Names { Ok(()) } + #[cfg(test)] pub(super) fn resolve( &self, reference: &[u8], budget: &B, ) -> Result<(Vec, Option), SourceError> { + let result = self.resolve_in(reference, NodeId(0), budget)?; + Ok((result.owners, result.reason)) + } + + pub(super) fn resolve_in( + &self, + reference: &[u8], + scope: NodeId, + budget: &B, + ) -> Result { + let Some(tokens) = tokens::tokens(reference, budget)? else { + return Ok(NameResolution { + owners: Vec::new(), + reason: None, + pending: true, + }); + }; + let Some(name) = tokens::reference_name(&tokens, budget)? else { + return Ok(NameResolution { + owners: Vec::new(), + reason: None, + pending: true, + }); + }; let (hash, key) = key(reference, &self.hasher, budget)?; let mut signatures = false; for byte in &key { @@ -131,7 +232,7 @@ impl Names { &self.identifiers }; let mut owners = Vec::new(); - if let Some(candidates) = index.get(&hash) { + if let Some(candidates) = index.get(&(scope, hash)) { for entry in candidates { budget.step().map_err(Into::into)?; if same_spelling(&entry.spelling, &key, budget)? { @@ -143,12 +244,52 @@ impl Names { } } } + let (name_hash, name_key) = self.key_name(name, budget)?; + let mut pending = false; + if let Some(candidates) = self.complex.get(&(scope, name_hash)) { + for entry in candidates { + budget.step().map_err(Into::into)?; + if same_spelling(&entry.spelling, &name_key, budget)? { + pending = true; + if signatures { + for &owner in &entry.owners { + budget.step().map_err(Into::into)?; + owners.push(owner); + } + } + break; + } + } + } let reason = match owners.len() { 0 => Some(UnresolvedReason::MissingName), - 1 => None, + 1 => owners[0].qualification, _ => Some(UnresolvedReason::Ambiguous), }; - Ok((owners, reason)) + if owners.len() > 1 { + for owner in &owners { + budget.step().map_err(Into::into)?; + pending |= owner.qualification.is_some(); + } + } + let mut ids = Vec::new(); + for owner in owners { + budget.step().map_err(Into::into)?; + ids.push(owner.owner); + } + Ok(NameResolution { + owners: ids, + reason, + pending, + }) + } + + fn key_name( + &self, + name: &[u8], + budget: &B, + ) -> Result<(u64, Vec), SourceError> { + key(name, &self.hasher, budget) } } @@ -182,15 +323,21 @@ mod tests { let mut names = Names::default(); let (hash, _) = key(b"f", &names.hasher, &NoBudget).unwrap(); names.identifiers.insert( - hash, + (NodeId(0), hash), vec![ NameEntry { spelling: b"g".to_vec(), - owners: vec![OwnerId(0)], + owners: vec![NamedOwner { + owner: OwnerId(0), + qualification: None, + }], }, NameEntry { spelling: b"f".to_vec(), - owners: vec![OwnerId(1)], + owners: vec![NamedOwner { + owner: OwnerId(1), + qualification: None, + }], }, ], ); diff --git a/big-code-analysis-ast/src/documentation/names/tokens.rs b/big-code-analysis-ast/src/documentation/names/tokens.rs new file mode 100644 index 000000000..52f341309 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/names/tokens.rs @@ -0,0 +1,88 @@ +//! Narrow lexical keys for exact static C-family signatures. + +use crate::documentation::SourceError; +use crate::documentation::budget::WorkBudget; + +pub(super) fn tokens<'s, B: WorkBudget>( + bytes: &'s [u8], + budget: &B, +) -> Result>, SourceError> { + let mut result = Vec::new(); + let mut at = 0; + while at < bytes.len() { + budget.bytes(1).map_err(Into::into)?; + super::name_bytes::record(); + if bytes[at].is_ascii_whitespace() { + at += 1; + continue; + } + let start = at; + if bytes[at].is_ascii_alphanumeric() || bytes[at] == b'_' { + at += 1; + while at < bytes.len() && (bytes[at].is_ascii_alphanumeric() || bytes[at] == b'_') { + budget.bytes(1).map_err(Into::into)?; + super::name_bytes::record(); + at += 1; + } + } else if bytes[at..].starts_with(b"/*") { + at += 2; + while at + 1 < bytes.len() && !bytes[at..].starts_with(b"*/") { + budget.bytes(1).map_err(Into::into)?; + super::name_bytes::record(); + at += 1; + } + if at + 1 >= bytes.len() { + return Ok(None); + } + at += 2; + continue; + } else if bytes[at..].starts_with(b"&&") || bytes[at..].starts_with(b"::") { + at += 2; + } else if matches!(bytes[at], b'(' | b')' | b',' | b'*' | b'&') { + at += 1; + } else { + return Ok(None); + } + result.push(&bytes[start..at]); + } + Ok(Some(result)) +} + +pub(super) fn reference_name<'s, B: WorkBudget>( + tokens: &[&'s [u8]], + budget: &B, +) -> Result, SourceError> { + if tokens.len() == 1 && identifier(tokens[0]) { + return Ok(Some(tokens[0])); + } + let mut open = None; + for (at, token) in tokens.iter().enumerate() { + budget.step().map_err(Into::into)?; + if *token == b"::" { + return Ok(None); + } + if *token == b"(" { + if open.is_some() { + return Ok(None); + } + open = Some(at); + } + if *token == b")" && at + 1 != tokens.len() { + return Ok(None); + } + } + let Some(open) = open else { + return Ok(None); + }; + if open < 2 || tokens.last() != Some(&b")".as_slice()) { + return Ok(None); + } + let name = tokens[open - 1]; + Ok(identifier(name).then_some(name)) +} + +fn identifier(bytes: &[u8]) -> bool { + bytes + .first() + .is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_') +} diff --git a/big-code-analysis-ast/src/documentation/recognition.rs b/big-code-analysis-ast/src/documentation/recognition.rs index b08a0740b..d3f7c4573 100644 --- a/big-code-analysis-ast/src/documentation/recognition.rs +++ b/big-code-analysis-ast/src/documentation/recognition.rs @@ -79,6 +79,7 @@ impl SourceRules for NativeRules { ancestors.try_memoised(crate::node::MemoQuestion::SourceDocTarget, node, || { target_computations::record(); match T::lang() { + crate::LANG::Csharp if super::collector::conditional_kind(node.kind()) => Ok(true), crate::LANG::C => crate::lang_helpers::doxygen::doxygen_target_with_budget::< crate::CCode, _, diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index a016ad0a2..00108dd9c 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -186,6 +186,7 @@ impl<'s> SourceContext<'s> { let mut end = self.included.len(); while first < end { budget.step().map_err(Into::into)?; + intersection_searches::record(); let middle = first + (end - first) / 2; if self.included[middle].end_byte <= spelling.start { first = middle + 1; @@ -263,6 +264,11 @@ impl<'s> SourceContext<'s> { } } +crate::observation::counter!( + intersection_searches, + cfg(any(test, feature = "test-support")) +); + #[cfg(all(test, feature = "rust"))] mod coverage_tests { use super::*; diff --git a/big-code-analysis-ast/src/documentation/text.rs b/big-code-analysis-ast/src/documentation/text.rs index 557bad4e3..d2a915458 100644 --- a/big-code-analysis-ast/src/documentation/text.rs +++ b/big-code-analysis-ast/src/documentation/text.rs @@ -13,6 +13,7 @@ pub(super) mod cleanup; pub(super) mod comments; #[allow(dead_code)] pub(super) mod literals; +pub(super) mod source_cursor; #[derive(Debug)] pub(super) enum TextError { diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs index ee741b841..7f7bc8a21 100644 --- a/big-code-analysis-ast/src/documentation/text/comments.rs +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -1,5 +1,6 @@ //! Comment-local cleanup over source coordinates, before any output copying. +use super::source_cursor::SourceCursor; use super::{TextBuilder, TextError}; use crate::documentation::budget::WorkBudget; use crate::documentation::{Content, Fragment, Origin, Profile, SourceContext, UnavailableReason}; @@ -250,12 +251,13 @@ fn prepare( fn append_range<'s, B: WorkBudget>( builder: &mut TextBuilder<'s>, context: &SourceContext<'s>, + source: &mut SourceCursor<'_, 's>, range: Range, splices: bool, budget: &B, ) -> Result<(), TextError> { if !splices { - return builder.source(context, range, budget); + return source.copy(builder, range, budget); } let mut start = range.start; let mut at = start; @@ -269,11 +271,11 @@ fn append_range<'s, B: WorkBudget>( for _ in 1..removed { charge(budget)?; } - builder.source(context, start..at, budget)?; + source.copy(builder, start..at, budget)?; at += removed; start = at; } - builder.source(context, start..range.end, budget) + source.copy(builder, start..range.end, budget) } pub(in crate::documentation) fn render<'s, B: WorkBudget>( @@ -345,23 +347,46 @@ fn render_local<'s, B: WorkBudget>( } } } + emit_blocks(profile, context, fragments, &blocks, budget) +} + +fn emit_blocks<'s, B: WorkBudget>( + profile: Profile, + context: &SourceContext<'s>, + fragments: &[&Fragment<'s>], + blocks: &[Block], + budget: &B, +) -> Result, TextError> { let mut builder = TextBuilder::default(); - for (position, block) in blocks.iter().enumerate() { + let mut first_block = 0; + let mut last_block = blocks.len(); + if profile != Profile::Rust { + while first_block < last_block && empty_block(&blocks[first_block], budget)? { + first_block += 1; + } + while last_block > first_block && empty_block(&blocks[last_block - 1], budget)? { + last_block -= 1; + } + } + for (position, block) in blocks.iter().enumerate().take(last_block).skip(first_block) { budget .step() .map_err(|error| TextError::Source(error.into()))?; - if position != 0 { + if position != first_block { builder.transformed("\n", Origin::Synthetic, budget)?; } + let mut source = SourceCursor::new(&fragments[position].source); let mut first = 0; let mut end = block.lines.len(); - if profile != Profile::Rust { + if profile != Profile::Rust && position == first_block { while first < end && block.lines[first].content.is_empty() { budget .step() .map_err(|error| TextError::Source(error.into()))?; first += 1; } + } + if profile != Profile::Rust && position + 1 == last_block { while end > first && block.lines[end - 1].content.is_empty() { budget .step() @@ -373,6 +398,7 @@ fn render_local<'s, B: WorkBudget>( append_range( &mut builder, context, + &mut source, line.content.clone(), profile == Profile::Doxygen, budget, @@ -381,11 +407,11 @@ fn render_local<'s, B: WorkBudget>( if line.ending.len() == 2 { builder.transformed( "\n", - Origin::Decoded(context.pieces_with_budget(line.ending.clone(), budget)?), + Origin::Decoded(source.pieces(line.ending.clone(), budget)?), budget, )?; } else { - builder.source(context, line.ending.clone(), budget)?; + source.copy(&mut builder, line.ending.clone(), budget)?; } } } @@ -393,6 +419,18 @@ fn render_local<'s, B: WorkBudget>( Ok(builder.finish()) } +fn empty_block(block: &Block, budget: &B) -> Result { + for line in &block.lines { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + if !line.content.is_empty() { + return Ok(false); + } + } + Ok(true) +} + fn blank(bytes: &[u8], unicode: bool, budget: &B) -> Result { budget .step() @@ -517,6 +555,12 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul } let mut star_column = None; for line in &block.lines[start..end] { + crate::documentation::budget::in_phase( + budget, + crate::documentation::budget::WorkPhase::Decoration, + || budget.step(), + ) + .map_err(|error| TextError::Source(error.into()))?; let indent = margin(&bytes[line.content.clone()], budget)?; if line.content.start + indent >= line.content.end || bytes[line.content.start + indent] != b'*' @@ -558,3 +602,42 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul } Ok(true) } + +#[cfg(test)] +mod remediation_tests { + use super::*; + use crate::documentation::budget::{CollectionBudget, WorkPhase, cancel_in_phase}; + + #[test] + fn star_column_pass_cancels_on_line_budget_before_byte_budget() { + let bytes = b"*"; + let mut block = Block { + lines: (0..2048) + .map(|_| Line { + content: 0..1, + ending: 0..0, + }) + .collect(), + rust_decoration: false, + markdown: false, + }; + let result = cancel_in_phase(WorkPhase::Decoration, || { + beautify(&mut block, bytes, &CollectionBudget::default()) + }); + assert!(matches!( + result, + Err(TextError::Source( + crate::documentation::SourceError::Cancelled + )) + )); + let mut next = Block { + lines: vec![Line { + content: 0..1, + ending: 0..0, + }], + rust_decoration: false, + markdown: false, + }; + assert!(!beautify(&mut next, bytes, &CollectionBudget::default()).unwrap()); + } +} diff --git a/big-code-analysis-ast/src/documentation/text/source_cursor.rs b/big-code-analysis-ast/src/documentation/text/source_cursor.rs new file mode 100644 index 000000000..da696710d --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/source_cursor.rs @@ -0,0 +1,72 @@ +//! Monotone clipping within one fragment's already-retained intersections. + +use super::{TextBuilder, TextError}; +use crate::documentation::budget::WorkBudget; +use crate::documentation::{SourcePiece, SourcePieces, UnavailableReason}; +use std::ops::Range; + +pub(super) struct SourceCursor<'f, 's> { + pieces: &'f [SourcePiece<'s>], + at: usize, +} + +impl<'f, 's> SourceCursor<'f, 's> { + pub(super) fn new(source: &'f SourcePieces<'s>) -> Self { + Self { + pieces: source.pieces(), + at: 0, + } + } + + pub(super) fn pieces( + &mut self, + range: Range, + budget: &B, + ) -> Result, TextError> { + let mut pieces = Vec::new(); + let mut covered = range.start; + while let Some(piece) = self.pieces.get(self.at) { + budget + .step() + .map_err(|error| TextError::Source(error.into()))?; + fragment_piece_visits::record(); + let span = piece.range(); + if span.start >= range.end { + break; + } + if span.end > range.start { + let start = span.start.max(range.start); + if start != covered { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + } + covered = span.end.min(range.end); + pieces.push(piece.slice(start..covered)); + } + if span.end > range.end { + break; + } + self.at += 1; + } + if covered != range.end { + return Err(TextError::Unavailable(UnavailableReason::ExcludedGap)); + } + Ok(SourcePieces::from_included_pieces(pieces)) + } + + pub(super) fn copy( + &mut self, + builder: &mut TextBuilder<'s>, + range: Range, + budget: &B, + ) -> Result<(), TextError> { + if !range.is_empty() { + builder.copied(&self.pieces(range, budget)?, budget)?; + } + Ok(()) + } +} + +crate::observation::counter!( + fragment_piece_visits, + cfg(any(test, feature = "test-support")) +); diff --git a/big-code-analysis-ast/src/documentation/text/tests.rs b/big-code-analysis-ast/src/documentation/text/tests.rs index 9ca378761..672ca5ea8 100644 --- a/big-code-analysis-ast/src/documentation/text/tests.rs +++ b/big-code-analysis-ast/src/documentation/text/tests.rs @@ -62,6 +62,41 @@ fn copied_decoded_expanded_and_synthetic_origins_keep_exact_responsibility() { assert_eq!(portions[3].output, 7..8); } +#[cfg(feature = "rust")] +#[test] +fn transformed_queries_return_every_disjoint_responsible_piece() { + let source = b"abcdefgh"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = SourceContext::new(parser.ts_tree(), source); + let pieces = || { + SourcePieces::from_included_pieces(vec![ + context.pieces(0..2).unwrap().pieces()[0].clone(), + context.pieces(5..8).unwrap().pieces()[0].clone(), + ]) + }; + let mut builder = TextBuilder::default(); + builder + .transformed("é", Origin::Decoded(pieces()), &NoBudget) + .unwrap(); + builder + .transformed(" ", Origin::Expanded(pieces()), &NoBudget) + .unwrap(); + let content = builder.finish(); + let view = complete(&content); + for range in [0..2, 3..4] { + let part = view.origins(range.clone()).unwrap().next().unwrap(); + assert_eq!(part.output, range); + let (OriginView::Decoded(pieces) | OriginView::Expanded(pieces)) = part.origin else { + panic!("transformed") + }; + assert_eq!(pieces.len(), 2); + assert_eq!(pieces[0].range(), 0..2); + assert_eq!(pieces[1].range(), 5..8); + assert_eq!(pieces[0].bytes(), b"ab"); + assert_eq!(pieces[1].bytes(), b"fgh"); + } +} + #[cfg(feature = "rust")] #[test] fn utf8_carry_and_invalid_source_are_not_lossily_decoded() { diff --git a/big-code-analysis-ast/src/lang_helpers/doxygen.rs b/big-code-analysis-ast/src/lang_helpers/doxygen.rs index d98c088d9..0be63db0d 100644 --- a/big-code-analysis-ast/src/lang_helpers/doxygen.rs +++ b/big-code-analysis-ast/src/lang_helpers/doxygen.rs @@ -101,9 +101,11 @@ fn structural_command_at<'s, B: WorkBudget>( b"idlexcept", b"module", ]; + structural_calls::record(); let mut at = 0; while at < s.len() { budget.bytes(1)?; + structural_bytes::record(); if let Some(end) = literal_end(s, at, budget)? { at = end; continue; @@ -226,20 +228,26 @@ fn format_block_end( /// comes first. fn code_span_close(span: &[u8], budget: &B) -> Result, B::Error> { let mut start = 0; - for (index, line) in scan::lines(span, budget).enumerate() { - let line = line?; - if let Some(close) = scan::position(line, |b| b == b'`', budget)? { - return Ok(Some(start + close)); + while start < span.len() { + budget.step()?; + let end = scan::position(&span[start..], |b| matches!(b, b'`' | b'\n'), budget)? + .map_or(span.len(), |at| start + at); + if span.get(end) == Some(&b'`') { + return Ok(Some(end)); } + let line = &span[start..end]; let text = scan::trim(line, budget)?; - if index > 0 && scan::trim(text.strip_prefix(b"*").unwrap_or(text), budget)?.is_empty() { + if start > 0 && scan::trim(text.strip_prefix(b"*").unwrap_or(text), budget)?.is_empty() { return Ok(None); } - start += line.len() + 1; + start = end + 1; } Ok(None) } +crate::observation::counter!(structural_calls, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(structural_bytes, cfg(any(test, feature = "test-support"))); + /// Where an HTML comment whose text starts at `s[from]` ends: after its /// `-->`, or at the end of the comment when it has none. Doxygen 1.13.2 /// closes it on neither `--->` nor `--!>`. diff --git a/big-code-analysis-bench/Cargo.toml b/big-code-analysis-bench/Cargo.toml index 78b826cfc..b5cda3b80 100644 --- a/big-code-analysis-bench/Cargo.toml +++ b/big-code-analysis-bench/Cargo.toml @@ -34,7 +34,7 @@ workspace = true # `vcs` is on so the harness can time `vcs::score::apply_percentile` # (#1267), the one hot path here that is not a walk over an AST. big-code-analysis = { path = "..", features = ["vcs"] } -big-code-analysis-ast = { path = "../big-code-analysis-ast", features = ["test-support"] } +big-code-analysis-ast = { path = "../big-code-analysis-ast", default-features = false } # For the `verbatim-oracle` record lines (#1744); the root's own # serialisers are what the record carries. serde_json.workspace = true diff --git a/big-code-analysis-bench/benches/documentation.rs b/big-code-analysis-bench/benches/documentation.rs index bd18fd5a7..c682b0fc4 100644 --- a/big-code-analysis-bench/benches/documentation.rs +++ b/big-code-analysis-bench/benches/documentation.rs @@ -20,6 +20,10 @@ fn main() { late_owner(&mut criterion, size, &context, options); included_ranges(&mut criterion, size, &context, options); } + for size in [1024, 2048, 4096] { + remediation(&mut criterion, size, &context, options); + multiline_ranges(&mut criterion, size, &context, options); + } criterion.final_summary(); } @@ -70,10 +74,10 @@ fn included_ranges( black_box( big_code_analysis_ast::documentation::collect( LANG::Rust, - &tree, - &source, - context, - &options, + black_box(&tree), + black_box(&source), + black_box(context), + black_box(&options), ) .unwrap_or_else(|error| panic!("collect: {error:?}")), ) @@ -152,8 +156,8 @@ fn cold( group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { bencher.iter(|| { black_box( - parser - .documentation(context, &options) + black_box(parser) + .documentation(black_box(context), black_box(&options)) .unwrap_or_else(|error| panic!("collection: {error:?}")), ) }); @@ -199,7 +203,7 @@ fn secondary( format!("/**{}*/\nint {slots};", "audit ".repeat(1024)), ), ( - "hidden-fields", + "visible-declarator-depth", LANG::C, format!("/**audit*/\nint a{};", "[1]".repeat(size)), ), @@ -231,8 +235,8 @@ fn secondary( group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { bencher.iter(|| { black_box( - parser - .documentation(context, &options) + black_box(parser) + .documentation(black_box(context), black_box(&options)) .unwrap_or_else(|error| panic!("{name}: {error:?}")), ) }); @@ -277,8 +281,8 @@ fn late_owner( group.bench_function(BenchmarkId::new("late-owner", size), |bencher| { bencher.iter(|| { black_box( - index - .node_associations(node.as_tree_sitter()) + black_box(&index) + .node_associations(black_box(node.as_tree_sitter())) .unwrap_or_else(|error| panic!("owner: {error:?}")) .associations() .count(), @@ -357,8 +361,8 @@ fn prepared( group.bench_function(BenchmarkId::new("owner", size), |bencher| { bencher.iter(|| { black_box( - index - .node_associations(owner.as_tree_sitter()) + black_box(&index) + .node_associations(black_box(owner.as_tree_sitter())) .unwrap_or_else(|error| panic!("owner: {error:?}")) .associations() .count(), @@ -367,21 +371,237 @@ fn prepared( }); group.bench_function(BenchmarkId::new("late-map", size), |bencher| { bencher.iter(|| { - black_box( - text.origins(text.text().len() - 1..text.text().len()) - .unwrap_or_else(|error| panic!("map: {error:?}")) - .count(), - ) + for portion in black_box(text) + .origins(black_box(text.text().len() - 1..text.text().len())) + .unwrap_or_else(|error| panic!("map: {error:?}")) + { + black_box(portion); + } }); }); group.bench_function(BenchmarkId::new("retained", size), |bencher| { bencher.iter(|| { black_box( - index - .complete_text(document) + black_box(&index) + .complete_text(black_box(document)) .unwrap_or_else(|error| panic!("text: {error:?}")), ) }); }); group.finish(); } + +#[allow(clippy::too_many_lines)] // Each workload keeps its untimed semantic control next to its fixture. +fn remediation( + criterion: &mut Criterion, + size: usize, + context: &DocumentationContext, + options: DocumentationOptions, +) { + let depth = size / 16; + let workloads = [ + ( + "inline-spans", + LANG::Cpp, + format!("/**{}*/\nvoid f() {{}}", "`x` ".repeat(size)), + ), + ( + "gathered-disposition", + LANG::Cpp, + format!("{}/**{}@file*/", "/**a*/\n".repeat(size), "x ".repeat(size)), + ), + ( + "complex-signatures", + LANG::Cpp, + format!( + "{}void leaf();{}", + "void f(int x = [] { ".repeat(depth), + " return 1; }());".repeat(depth) + ), + ), + ( + "order-multiple-chunks", + LANG::Rust, + "///audit\nfn f() {}\n".repeat(size), + ), + ( + "text-budget-boundary", + LANG::Rust, + format!("///{}\nfn f() {{}}", "abcd".repeat(size * 2)), + ), + ( + "go-fold", + LANG::Go, + format!( + "package p\ntype S struct {{\n{}X int\n{} }}\n", + "X struct {\n".repeat(depth), + "}\n".repeat(depth) + ), + ), + ( + "ruby-fold", + LANG::Ruby, + format!( + "{}# audit\ndef f; end\n{}", + "class C\n".repeat(depth), + "end\n".repeat(depth) + ), + ), + ]; + let mut group = criterion.benchmark_group("documentation/remediation"); + for (name, language, source) in workloads { + let parser = AnyParser::parse(language, source.into_bytes(), None, None) + .unwrap_or_else(|error| panic!("{error}")); + assert!(!parser.root_node().has_error(), "{name}"); + let checked = parser + .documentation(context, &options) + .unwrap_or_else(|error| panic!("{error:?}")); + match name { + "inline-spans" => { + validation::documents(&checked, 1, 1, 1, &"`x` ".repeat(size)[..size * 4 - 1]); + } + "gathered-disposition" => { + assert_eq!(checked.documents().len(), 1); + assert_eq!( + checked + .documents() + .next() + .unwrap_or_else(|| panic!("doc")) + .get() + .fragment_count(), + size + 1 + ); + } + "complex-signatures" => { + assert_eq!(checked.documents().len(), 0); + assert_eq!( + parser + .root_node() + .preorder() + .filter(|node| node.kind() == "declaration") + .count(), + depth + 1 + ); + assert_eq!( + checked + .assessments() + .filter( + |a| a.get().reason == "Complex signature awaits exact named matching" + ) + .count(), + depth + ); + } + "go-fold" => { + assert_eq!(checked.documents().len(), 0); + assert_eq!( + parser + .root_node() + .preorder() + .filter(|node| node.kind() == "field_declaration") + .count(), + depth + 1 + ); + } + "order-multiple-chunks" => validation::documents(&checked, size, 1, 1, "audit"), + "text-budget-boundary" => { + validation::documents(&checked, 1, 1, 1, &"abcd".repeat(size * 2)); + } + "ruby-fold" => validation::documents(&checked, 1, 1, 1, "audit"), + _ => unreachable!(), + } + drop(checked); + group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { + bencher.iter(|| { + black_box( + black_box(parser) + .documentation(black_box(context), black_box(&options)) + .unwrap_or_else(|error| panic!("{error:?}")), + ) + }); + }); + } + group.finish(); +} + +fn multiline_ranges( + criterion: &mut Criterion, + size: usize, + context: &DocumentationContext, + options: DocumentationOptions, +) { + use big_code_analysis_ast::tree_sitter; + let source = format!("/**\n{}*/\nclass C {{}}", " * audit\n".repeat(size)); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language( + &LANG::Java + .tree_sitter_language() + .unwrap_or_else(|error| panic!("{error}")), + ) + .unwrap_or_else(|error| panic!("{error}")); + let mut point = tree_sitter::Point::new(0, 0); + let ranges: Vec<_> = source + .bytes() + .enumerate() + .map(|(at, byte)| { + let start_point = point; + if byte == b'\n' { + point.row += 1; + point.column = 0; + } else { + point.column += 1; + } + tree_sitter::Range { + start_byte: at, + end_byte: at + 1, + start_point, + end_point: point, + } + }) + .collect(); + parser + .set_included_ranges(&ranges) + .unwrap_or_else(|error| panic!("{error}")); + let tree = parser + .parse(&source, None) + .unwrap_or_else(|| panic!("parse")); + assert!(!tree.root_node().has_error()); + let checked = big_code_analysis_ast::documentation::collect( + LANG::Java, + &tree, + source.as_bytes(), + context, + &options, + ) + .unwrap_or_else(|error| panic!("{error:?}")); + validation::documents( + &checked, + 1, + 1, + 1, + &std::iter::repeat_n("audit", size) + .collect::>() + .join("\n"), + ); + drop(checked); + let mut group = criterion.benchmark_group("documentation/remediation"); + group.bench_function( + BenchmarkId::new("multiline-adjacent-ranges", size), + |bencher| { + bencher.iter(|| { + black_box( + big_code_analysis_ast::documentation::collect( + LANG::Java, + black_box(&tree), + black_box(source.as_bytes()), + black_box(context), + black_box(&options), + ) + .unwrap_or_else(|error| panic!("{error:?}")), + ) + }); + }, + ); + group.finish(); +} diff --git a/big-code-analysis-bench/benches/documentation/validation.rs b/big-code-analysis-bench/benches/documentation/validation.rs index 1efa59b62..f3b435b19 100644 --- a/big-code-analysis-bench/benches/documentation/validation.rs +++ b/big-code-analysis-bench/benches/documentation/validation.rs @@ -89,7 +89,7 @@ fn shape(name: &str, size: usize, parser: &AnyParser) { "width" => assert_eq!(root.child_count(), size * 2), "fragments" => assert_eq!(count("comment"), size), "c-slots" | "fanout-fixed-text" => assert_eq!(count("identifier"), size), - "hidden-fields" => { + "visible-declarator-depth" => { assert_eq!(count("array_declarator"), size); assert!(maximum >= size); } @@ -140,7 +140,9 @@ pub(super) fn fixture( .documentation(context, &options) .unwrap_or_else(|error| panic!("{name}: {error:?}")); match name { - "depth" | "ruby-modifiers" | "hidden-fields" => documents(&index, 1, 1, 1, "audit"), + "depth" | "ruby-modifiers" | "visible-declarator-depth" => { + documents(&index, 1, 1, 1, "audit"); + } "width" => documents(&index, size, 1, 1, "audit"), "fragments" => documents( &index, diff --git a/utils/documentation-form-matrix.json b/utils/documentation-form-matrix.json index adeb299aa..d1c93d9d6 100644 --- a/utils/documentation-form-matrix.json +++ b/utils/documentation-form-matrix.json @@ -3,7 +3,7 @@ "publication": "Unknown for every implemented profile; Rust doc/cfg_attr additionally retains pending publication assessment", "variants": { "Rust": { - "implemented": ["basic outer line/block", "adjacent comment composition", "inner root/module/function", "macro Expansion", "comments across ordinary attributes", "raw fragments and exact local comment maps"], + "implemented": ["basic outer line/block", "same-target outer/inner composition", "root/module FilePackage and other target Primary roles", "inner root/module/function", "macro Expansion", "comments across ordinary attributes", "raw fragments and exact local comment maps"], "ineligible": ["plain comments", "document/test/rustfmt::skip attribute paths"], "pending": ["doc assignment/raw/cooked/metadata attributes", "cfg_attr", "mixed comment/attribute composition", "field/variant/tuple slots", "other local contexts"] }, @@ -60,7 +60,7 @@ "Cpp": { "implemented": ["basic definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures including definitions", "line/block phase-two splicing"], "ineligible": ["ordinary comments", "quoted/CDATA structural lookalikes", "banner markers"], - "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery/template projections", "complex declarators", "publication"] + "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery/template projections", "complex declarators and exact default-expression signatures", "qualified/unsupported reference grammar", "publication"] }, "Mozcpp": { "implemented": ["basic definition", "simple multi-declarator slots", "simple trailing field", "file gathering", "exact fn names/signatures", "line/block phase-two splicing"], diff --git a/utils/documentation-remediation-perturb.json b/utils/documentation-remediation-perturb.json new file mode 100644 index 000000000..2f1a96b62 --- /dev/null +++ b/utils/documentation-remediation-perturb.json @@ -0,0 +1,21 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + {"name":"rust-decoration-line-checkpoint-omitted","file":"big-code-analysis-ast/src/documentation/text/comments.rs","old":"crate::documentation::budget::WorkPhase::Decoration,\n || budget.step(),","new":"crate::documentation::budget::WorkPhase::Decoration,\n || Ok::<(), B::Error>(()),","expect":["documentation::text::comments::remediation_tests::star_column_pass_cancels_on_line_budget_before_byte_budget"]}, + {"name":"text-emission-repeats-global-intersection-search","file":"big-code-analysis-ast/src/documentation/text/comments.rs","old":"return source.copy(builder, range, budget);","new":"return builder.source(context, range, budget);","expect":["documentation::collector::remediation_tests::multiline_text_reuses_retained_fragment_intersections"]}, + {"name":"csharp-conditional-selection-disappears","file":"big-code-analysis-ast/src/documentation/recognition.rs","old":"crate::LANG::Csharp if super::collector::conditional_kind(node.kind()) => Ok(true),","new":"crate::LANG::Csharp if super::collector::conditional_kind(node.kind()) => Ok(false),","expect":["documentation::collector::remediation_tests::csharp_conditional_docs_remain_pending_only_in_affected_scope"]}, + {"name":"rust-same-target-drafts-remain-split","file":"big-code-analysis-ast/src/documentation/collector.rs","old":" self.coalesce_rust(budget)?;","new":" let _ = budget;","expect":["documentation::collector::remediation_tests::rust_same_target_composition_and_roles_are_independent_of_placement"]}, + {"name":"pending-first-wrapper-seeks-later-ready","file":"big-code-analysis-ast/src/documentation/collector/projections.rs","old":"Projection::Pending => {\n self.index.canonical.nodes[id.0].projection = Projection::Pending;\n return Ok(());","new":"Projection::Pending => {\n continue;","expect":["documentation::collector::remediation_tests::ruby_pending_first_statement_never_redirects_to_later_method","documentation::collector::remediation_tests::lua_pending_first_statement_never_redirects_to_later_function"]}, + {"name":"lexical-key-token-boundaries-erased","file":"big-code-analysis-ast/src/documentation/names.rs","old":" hash.write_u8(0);\n key.push(0);","new":" let _ = position;","expect":["documentation::collector::remediation_tests::exact_signatures_preserve_tokens_scope_and_complex_competitors"]}, + {"name":"complex-headers-hashed-in-full","file":"big-code-analysis-ast/src/documentation/collector/projections.rs","old":"record.field != Some(\"body\") && record.signature_complex","new":"false && record.field != Some(\"body\") && record.signature_complex","expect":["documentation::collector::remediation_tests::nested_default_lambda_signature_work_is_linear_in_primary_facts"]}, + {"name":"conditional-name-qualification-lost","file":"big-code-analysis-ast/src/documentation/collector.rs","old":"record.qualification = Some(UnresolvedReason::Conditional);","new":"record.qualification = None;","expect":["documentation::collector::remediation_tests::c_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::cpp_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::mozcpp_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::objc_named_candidates_retain_conditional_provenance"]}, + {"name":"pending-owner-context-not-followed","file":"big-code-analysis-ast/src/documentation/collector/assembly.rs","old":".unwrap_or(self.index.canonical.nodes[draft.scope.0].owner_context)","new":".unwrap_or(draft.scope)","expect":["documentation::collector::remediation_tests::kotlin_signature_context_exposes_document_linked_owner_assessment"]}, + {"name":"helper-canonical-walk-skipped","file":"big-code-analysis-ast/src/documentation/collector.rs","old":" builder.walk::(&budget)?;","new":" if profile != Profile::Helper { builder.walk::(&budget)?; }","expect":["documentation::collector::remediation_tests::helpers_validate_all_canonical_nodes_before_unsupported_owner"]}, + {"name":"logical-boundary-empty-members-retained","file":"big-code-analysis-ast/src/documentation/text/comments.rs","old":"while first_block < last_block && empty_block(&blocks[first_block], budget)?","new":"while false && first_block < last_block && empty_block(&blocks[first_block], budget)?","expect":["documentation::collector::remediation_tests::go_trims_logical_boundary_members_only","documentation::collector::remediation_tests::ruby_trims_logical_boundary_members_only","documentation::collector::remediation_tests::java_trims_logical_boundary_members_only"]}, + {"name":"inline-code-scans-whole-remaining-line","file":"big-code-analysis-ast/src/lang_helpers/doxygen.rs","old":" let mut start = 0;\n while start < span.len() {","new":" let mut start = 0;\n let _ = scan::position(span, |b| b == b'\\n', budget)?;\n while start < span.len() {","expect":["documentation::collector::remediation_tests::c_inline_code_scan_is_linear","documentation::collector::remediation_tests::cpp_inline_code_scan_is_linear","documentation::collector::remediation_tests::mozcpp_inline_code_scan_is_linear","documentation::collector::remediation_tests::objc_inline_code_scan_is_linear"]}, + {"name":"gatherer-disposition-cache-bypassed","file":"big-code-analysis-ast/src/documentation/collector.rs","old":"gatherer.as_ref().and_then(|id| structural_drafts.get(id))","new":"gatherer.as_ref().and_then(|id| structural_drafts.get(id)).filter(|_| false)","expect":["documentation::collector::remediation_tests::gathered_disposition_does_not_rescan_structural_member_per_fragment"]}, + {"name":"file-opener-retains-unrelated-binding","file":"big-code-analysis-ast/src/documentation/collector.rs","old":"draft.role = DocumentRole::FilePackage;\n draft.binding = None;","new":"draft.role = DocumentRole::FilePackage;\n draft.binding = run.target;","expect":["documentation::collector::remediation_tests::lua_file_opener_has_no_following_binding"]} + ] +} From 9abf9720cd5d1506455cb94fed5b0009f4fc1a15 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 01:30:34 -0800 Subject: [PATCH 043/221] fix(documentation): validate named signatures and retain qualification facts --- .bca-baseline.toml | 106 +++-- CHANGELOG.md | 3 + big-code-analysis-ast/src/documentation.rs | 8 +- .../src/documentation/canonical.rs | 6 +- .../src/documentation/collector.rs | 18 +- .../src/documentation/collector/assembly.rs | 60 ++- .../documentation/collector/named_tests.rs | 398 ++++++++++++++++++ .../documentation/collector/projections.rs | 7 +- .../documentation/collector/qualifications.rs | 80 ++++ .../collector/remediation_tests.rs | 9 +- .../src/documentation/index.rs | 14 + .../src/documentation/names.rs | 211 +++++----- .../src/documentation/names/budget_tests.rs | 231 ++++++++++ .../src/documentation/names/grammar.rs | 287 +++++++++++++ .../src/documentation/names/tokens.rs | 35 +- .../src/documentation/qualifications.rs | 118 ++++++ utils/documentation-names-perturb.json | 18 + utils/documentation-remediation-perturb.json | 2 +- 18 files changed, 1433 insertions(+), 178 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/collector/named_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/qualifications.rs create mode 100644 big-code-analysis-ast/src/documentation/names/budget_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/names/grammar.rs create mode 100644 big-code-analysis-ast/src/documentation/qualifications.rs create mode 100644 utils/documentation-names-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index ec4a67d39..f4c449f99 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,13 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 956.0 +value = 966.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 138.0 +value = 137.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -437,19 +437,19 @@ value = 6.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::order_results" metric = "abc" -value = 50.635955604688654 +value = 52.61178575186362 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::order_results" metric = "halstead.effort" -value = 113120.37181131 +value = 116143.04627340646 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::order_results" metric = "nexits" -value = 12.0 +value = 13.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -557,13 +557,13 @@ value = 9.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "abc" -value = 53.41348144429457 +value = 57.3149195236284 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "halstead.effort" -value = 90175.5563699593 +value = 98332.32124623262 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -581,7 +581,7 @@ value = 13.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>" metric = "wmc" -value = 73.0 +value = 79.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -599,7 +599,7 @@ value = 58850.75713727861 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "abc" -value = 51.12729212465687 +value = 52.44044240850758 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -611,31 +611,37 @@ value = 23.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cyclomatic" -value = 23.0 +value = 22.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "halstead.effort" -value = 163794.80999271595 +value = 143957.07071732648 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "nexits" -value = 5.0 +value = 7.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::named_document" metric = "cognitive" -value = 17.0 +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::named_document" +metric = "halstead.effort" +value = 50409.859712723024 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::named_document" metric = "nexits" -value = 7.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -665,7 +671,7 @@ value = 67.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "abc" -value = 56.2672195865408 +value = 58.18934610390462 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" @@ -677,7 +683,7 @@ value = 23.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::c_slots" metric = "halstead.effort" -value = 148400.19270030435 +value = 154214.4489357133 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" @@ -763,12 +769,6 @@ qualified = "assess" metric = "nargs" value = 5.0 -[[entry]] -path = "big-code-analysis-ast/src/documentation/names.rs" -qualified = "Names::insert_candidate" -metric = "halstead.effort" -value = 53324.76224742121 - [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::insert_candidate" @@ -779,49 +779,85 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::insert_candidate" metric = "nexits" -value = 8.0 +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::resolve_in" metric = "abc" -value = 53.27288240746881 +value = 38.301436004411116 [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::resolve_in" metric = "cognitive" -value = 35.0 +value = 16.0 [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::resolve_in" -metric = "cyclomatic" -value = 19.0 +metric = "halstead.effort" +value = 89032.0985530095 [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" qualified = "Names::resolve_in" -metric = "halstead.effort" -value = 152988.29680210442 +metric = "nexits" +value = 10.0 [[entry]] path = "big-code-analysis-ast/src/documentation/names.rs" -qualified = "Names::resolve_in" +qualified = "insert_entry" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/grammar.rs" +qualified = "parameters" metric = "nexits" -value = 15.0 +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/grammar.rs" +qualified = "type_end" +metric = "cognitive" +value = 20.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/grammar.rs" +qualified = "type_end" +metric = "halstead.effort" +value = 83430.56013520907 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/grammar.rs" +qualified = "type_end" +metric = "nexits" +value = 12.0 [[entry]] path = "big-code-analysis-ast/src/documentation/names/tokens.rs" qualified = "reference_name" metric = "cognitive" -value = 16.0 +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "reference_name" +metric = "halstead.effort" +value = 67078.62485299908 [[entry]] path = "big-code-analysis-ast/src/documentation/names/tokens.rs" qualified = "reference_name" metric = "nexits" -value = 7.0 +value = 10.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "tokens" +metric = "abc" +value = 41.72529209005013 [[entry]] path = "big-code-analysis-ast/src/documentation/names/tokens.rs" @@ -839,13 +875,13 @@ value = 15.0 path = "big-code-analysis-ast/src/documentation/names/tokens.rs" qualified = "tokens" metric = "halstead.effort" -value = 96833.3962353417 +value = 96613.60694528196 [[entry]] path = "big-code-analysis-ast/src/documentation/names/tokens.rs" qualified = "tokens" metric = "nexits" -value = 5.0 +value = 9.0 [[entry]] path = "big-code-analysis-ast/src/documentation/recognition.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f9dddc3c..ea48a4e28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,9 @@ for historical reference. file/package roles. Exact wrapper selection, conditional name provenance, helper node identity, logical boundary trimming and retained-intersection text emission preserve pending results without redirected or partial-complete claims. + Exact named matching validates a narrow type/parameter grammar, interns names + once, and preserves structured candidate/reference qualifications alongside + ambiguity. Token scanning and key emission charge complete byte widths. (#1660, #1661) - Added unstable AST positional-run evidence for Go, Ruby and Lua, including diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index 65d5468e4..3f4119f94 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -22,6 +22,9 @@ //! fragment's retained intersections monotonically rather than searching global //! included ranges for each emitted segment. Cancellation checks bound work between //! polls; releasing accumulated partial state still costs its retained storage. +//! Known candidate/reference qualifications are separate immutable records, indexed +//! by document and owner. Ambiguity preserves each candidate's conditional/recovery +//! facts; pending assessments describe unsupported matching rather than those facts. pub(crate) mod budget; pub(crate) mod byte_scan; @@ -34,6 +37,7 @@ mod names; mod options; mod ordering; mod owners; +mod qualifications; pub(crate) mod recognition; mod source; #[doc(hidden)] @@ -44,6 +48,7 @@ pub use content::*; pub use index::*; pub use options::*; pub use owners::*; +pub use qualifications::{Qualification, QualificationSubject}; pub use source::*; /// Current-thread production work counters for source-path qualification. @@ -68,7 +73,8 @@ pub struct Observations { pub renders: usize, /// Bounded source-to-text copy chunks. pub copy_chunks: usize, - /// Name bytes hashed or compared during indexed finalization. + /// Consumed tokenizer bytes, key hashing/copying bytes (including separators), + /// and spelling-comparison bytes. Each key output byte charges hash and copy. pub name_bytes: usize, /// Distinct name candidates compared inside hash buckets. pub name_candidates: usize, diff --git a/big-code-analysis-ast/src/documentation/canonical.rs b/big-code-analysis-ast/src/documentation/canonical.rs index d06ceb45e..915b819b4 100644 --- a/big-code-analysis-ast/src/documentation/canonical.rs +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -26,11 +26,12 @@ pub(super) struct CanonicalNode<'s> { pub(super) children: Range, pub(super) projection: Projection, pub(super) pending: Vec, + pub(super) qualifications: Vec, pub(super) pending_parent: Option, pub(super) following: Option, pub(super) owner_context: NodeId, pub(super) name_scope: NodeId, - pub(super) qualification: Option, + pub(super) qualification: super::qualifications::QualificationSet, pub(super) signature_complex: bool, } @@ -71,11 +72,12 @@ impl<'s> CanonicalNodes<'s> { children: 0..0, projection: Projection::Unsupported, pending: Vec::new(), + qualifications: Vec::new(), pending_parent: None, following: None, owner_context: id, name_scope: NodeId(0), - qualification: None, + qualification: super::qualifications::QualificationSet::default(), signature_complex: false, }); id diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 07103e983..ed384e9ee 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -9,6 +9,7 @@ use crate::{Ancestors, Checker, FoldCache, Node, SiblingCache}; mod assembly; mod projections; +mod qualifications; enum Visit { Enter(NodeId, usize), @@ -67,6 +68,10 @@ pub(crate) fn collect_typed<'s, T: Checker + crate::traits::LanguageInfo>( documents_ordered: Vec::new(), associations_ordered: Vec::new(), source_cleaned: Vec::new(), + qualifications: Vec::new(), + qualifications_ordered: Vec::new(), + qualifications_by_document: Vec::new(), + qualifications_by_owner: Vec::new(), }, drafts: Vec::new(), pending_attributes: Vec::new(), @@ -157,6 +162,7 @@ impl<'s> Builder<'s> { self.index.facts.owners.push(owner); self.index.associations_by_owner.push(Vec::new()); self.index.assessments_by_owner.push(Vec::new()); + self.index.qualifications_by_owner.push(Vec::new()); self.index.owner_nodes.push(id); self.index.canonical.nodes[id.0].projection = Projection::Ready(vec![owner_id]); } @@ -374,9 +380,12 @@ impl<'s> Builder<'s> { } let record = &mut self.index.canonical.nodes[id.0]; if node.is_error() || node.is_missing() { - record.qualification = Some(UnresolvedReason::GrammarBoundary); - } else if conditional_kind(node.kind()) && record.qualification.is_none() { - record.qualification = Some(UnresolvedReason::Conditional); + record + .qualification + .insert(UnresolvedReason::GrammarBoundary); + } + if conditional_kind(node.kind()) { + record.qualification.insert(UnresolvedReason::Conditional); } } @@ -915,6 +924,7 @@ impl<'s> Builder<'s> { self.index.associations_by_owner[owner.0].push(ordinal); } } + self.order_qualifications(&ranks, budget)?; Ok(()) } } @@ -998,6 +1008,8 @@ mod cost_tests; #[cfg(test)] mod form_tests; #[cfg(test)] +mod named_tests; +#[cfg(test)] mod projection_tests; #[cfg(test)] mod remediation_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index 2b6ceef2a..c0a3d3663 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -125,6 +125,7 @@ impl<'s> Builder<'s> { Composition::CommentRun }; let document = DocumentId(self.index.facts.documents.len()); + self.index.qualifications_by_document.push(Vec::new()); self.index.facts.documents.push(Document { fragments: std::mem::take(&mut draft.fragments), composition, @@ -139,7 +140,11 @@ impl<'s> Builder<'s> { && !draft.gap && let Some(result) = self.named_document(document, draft.scope, budget)? { - owners = result.owners; + for candidate in result.owners { + budget.step()?; + self.candidate_qualifications(document, candidate, budget)?; + owners.push(candidate.owner); + } named_resolution = result .reason .map(Resolution::Unresolved) @@ -149,9 +154,9 @@ impl<'s> Builder<'s> { if let Some(target) = draft.target { match &self.index.canonical.nodes[target.0].projection { Projection::Ready(ids) => { - draft.unresolved = draft - .unresolved - .or(self.index.canonical.nodes[target.0].qualification); + draft.unresolved = draft.unresolved.or(self.index.canonical.nodes[target.0] + .qualification + .headline()); for &id in ids { budget.step()?; owners.push(id); @@ -160,23 +165,12 @@ impl<'s> Builder<'s> { Projection::Pending | Projection::Unsupported => pending = true, } } + if named_resolution == Some(Resolution::Unresolved(UnresolvedReason::Ambiguous)) { + draft.unresolved = None; + } if pending { self.pending_document(&draft, document, &owners, attribute, budget)?; - if self.index.profile == Profile::CsharpXml - && let Some(target) = draft.target - && conditional_kind(self.index.canonical.nodes[target.0].evidence.node().kind()) - { - let assessment = self.index.assessments.len(); - self.index.assessments.push(Assessment { - axis: AssessmentAxis::Selection, - reason: "Conditional XML documentation selection awaits branch interpretation", - node: Some(self.index.canonical.nodes[target.0].evidence), - document: Some(document), - }); - self.index.canonical.nodes[target.0] - .pending - .push(assessment); - } + self.pending_conditional_selection(draft.target, document); } if (!owners.is_empty() && (!pending || draft.target.is_some())) || draft.unresolved.is_some() @@ -216,6 +210,8 @@ impl<'s> Builder<'s> { }, reason: if attribute { "Rust doc/cfg_attr carrier awaits adapter composition" + } else if self.index.profile == Profile::Doxygen && draft.target.is_none() { + "Exact named matching awaits supported signature grammar" } else { "Selected local or wrapper form awaits owner projection" }, @@ -235,8 +231,26 @@ impl<'s> Builder<'s> { Ok(()) } + fn pending_conditional_selection(&mut self, target: Option, document: DocumentId) { + if self.index.profile == Profile::CsharpXml + && let Some(target) = target + && conditional_kind(self.index.canonical.nodes[target.0].evidence.node().kind()) + { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Selection, + reason: "Conditional XML documentation selection awaits branch interpretation", + node: Some(self.index.canonical.nodes[target.0].evidence), + document: Some(document), + }); + self.index.canonical.nodes[target.0] + .pending + .push(assessment); + } + } + fn named_document( - &self, + &mut self, document: DocumentId, scope: NodeId, budget: &CollectionBudget, @@ -277,9 +291,11 @@ impl<'s> Builder<'s> { } else { record.name_scope }; + let qualification = record.qualification; let mut result = self.names.resolve_in(name, scope, budget)?; - if let Some(reason) = record.qualification { - result.reason = Some(reason); + self.reference_qualifications(document, node, qualification, budget)?; + if result.reason != Some(UnresolvedReason::Ambiguous) && !result.pending { + result.reason = qualification.headline().or(result.reason); } return Ok(Some(result)); } diff --git a/big-code-analysis-ast/src/documentation/collector/named_tests.rs b/big-code-analysis-ast/src/documentation/collector/named_tests.rs new file mode 100644 index 000000000..30dbdf3b4 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/named_tests.rs @@ -0,0 +1,398 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(feature = "cpp")] +#[test] +fn narrow_signature_grammar_defers_malformed_and_unsupported_references() { + for reference in [ + "void f(,)", + "void f(int,)", + "void f(,int)", + "void f(int,,int)", + "void f(int x int y)", + "void f(12)", + "void f(int 12)", + "void f(int x y)", + "void f(void x)", + "void f(void,int)", + "void f((int))", + "void f(int", + "void f(int x[2])", + "void f(int x = 1)", + "void A::f()", + "void f(...)", + "void f() const", + "void int()", + "static f()", + "void f(unsigned float)", + "void f(int & &&)", + "void f(int * const const)", + "void f(const)", + "void f(void &)", + ] { + let source = format!("void f(int x);\n/**@fn {reference}*/"); + let parser = AnyParser::parse(LANG::Cpp, source.into_bytes(), None, None).unwrap(); + for retain_unbound in [false, true] { + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Cpp, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + assert_eq!(index.documents().len(), 1, "{reference}"); + assert_eq!(index.associations().len(), 0, "{reference}"); + let document = index.documents().next().unwrap(); + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + format!("@fn {reference}") + ); + assert!( + index + .assessments() + .any(|a| index.assessed_document(a).unwrap() == Some(document)), + "{reference}" + ); + } + } + } +} + +#[cfg(feature = "cpp")] +#[test] +fn narrow_signature_grammar_keeps_supported_types_exact() { + for signature in [ + "void f()", + "void f(void)", + "int f(int)", + "int f(int x)", + "T f(T x)", + "unsigned long long int f(const T * volatile x)", + "long double f(void *p, T const &x, volatile int &&y)", + "const T * const * f(T volatile * const p)", + "bool f(signed char x, unsigned short int, char16_t)", + ] { + let source = format!("{signature};\n/**@fn {signature}*/"); + let parser = AnyParser::parse(LANG::Cpp, source.into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error(), "{signature}"); + for retain_unbound in [false, true] { + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Cpp, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + assert_eq!(index.associations().len(), 1, "{signature}"); + assert_eq!( + index.associations().next().unwrap().get().resolution, + Resolution::Resolved, + "{signature}" + ); + assert_eq!(index.qualifications().len(), 0); + } + } + } +} + +#[cfg(feature = "cpp")] +#[test] +fn unsupported_declared_signature_keeps_owner_and_blocks_false_unique_match() { + let source = "/**local*/\nint f(int values[2]);\nint f(int x);\n/**@fn int f(int x)*/"; + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let associations: Vec<_> = index.associations().collect(); + assert_eq!(associations.len(), 2); + assert_eq!(associations[0].get().resolution, Resolution::Resolved); + assert_eq!( + associations[1].get().resolution, + Resolution::Unresolved(UnresolvedReason::Ambiguous) + ); + assert_eq!(associations[1].get().owner_count(), 2); + let reference = index.facts().associated_document(associations[1]).unwrap(); + assert!( + index + .assessments() + .any(|a| index.assessed_document(a).unwrap() == Some(reference)) + ); + assert_eq!(index.qualifications().len(), 0); +} + +#[cfg(feature = "cpp")] +#[test] +#[allow(clippy::too_many_lines)] // Candidate and reference matrices pin independent qualification axes. +fn ambiguous_candidates_keep_structured_qualification_and_reference_identity() { + for (source, expected) in [ + ("void f(void); void f(void);\n/**@fn f*/", vec![]), + ( + "#if FLAG\nvoid f(void);\n#endif\nvoid f(void);\n/**@fn f*/", + vec![UnresolvedReason::Conditional], + ), + ( + "void f(int x = );\nvoid f(void);\n/**@fn f*/", + vec![UnresolvedReason::GrammarBoundary], + ), + ( + "#if FLAG\nvoid f(int x = );\n#endif\nvoid f(void);\n/**@fn f*/", + vec![ + UnresolvedReason::Conditional, + UnresolvedReason::GrammarBoundary, + ], + ), + ( + "#if FLAG\nvoid f(void) {}\n#endif\nvoid f(void) {}\n/**@fn f*/", + vec![UnresolvedReason::Conditional], + ), + ] { + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + assert_eq!(parser.root_node().has_error(), source.contains("= )")); + for retain_unbound in [false, true] { + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Cpp, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::Ambiguous) + ); + assert_eq!(association.get().owner_count(), 2); + let document = index.facts().associated_document(association).unwrap(); + let qualifications: Vec<_> = + index.document_qualifications(document).unwrap().collect(); + assert_eq!( + qualifications + .iter() + .map(|q| q.get().reason) + .collect::>(), + expected, + "{source}" + ); + assert_eq!(index.qualifications().collect::>(), qualifications); + for qualification in qualifications { + assert_eq!(qualification.get().subject, QualificationSubject::Candidate); + assert_eq!(index.qualified_document(qualification).unwrap(), document); + let owner = index.qualified_owner(qualification).unwrap().unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("candidate") + }; + assert_eq!(node.node(), qualification.get().node.node()); + assert!( + index + .node_associations(node.node()) + .unwrap() + .qualifications() + .any(|q| q == qualification) + ); + assert!( + index + .owner_associations(owner) + .unwrap() + .qualifications() + .any(|q| q == qualification) + ); + } + let ordinary = index.facts().associated_owner(association, 0).unwrap(); + let ordinary = if expected.is_empty() { + ordinary + } else { + index.facts().associated_owner(association, 1).unwrap() + }; + assert_eq!( + index + .owner_associations(ordinary) + .unwrap() + .qualifications() + .count(), + 0 + ); + if !source.contains("= )") { + assert!( + !index + .owner_associations(ordinary) + .unwrap() + .projection_pending() + ); + assert_eq!( + index.document_qualifications(document).unwrap().len(), + expected.len() + ); + assert!( + !index + .assessments() + .any(|a| index.assessed_document(a).unwrap() == Some(document)) + ); + } + let foreign = parser.documentation(&context, &options).unwrap(); + assert!(matches!( + foreign.document_qualifications(document), + Err(FactError::ForeignIndex) + )); + if let Some(q) = index.qualifications().next() { + assert!(matches!( + foreign.qualified_document(q), + Err(FactError::ForeignIndex) + )); + assert!(matches!( + foreign.qualified_owner(q), + Err(FactError::ForeignIndex) + )); + } + } + } + } + let parser = AnyParser::parse( + LANG::Cpp, + b"void f(); void f();\n#if FLAG\n/**@fn f*/\n#endif".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::Ambiguous) + ); + let q = index.qualifications().next().unwrap(); + assert_eq!(q.get().subject, QualificationSubject::Reference); + assert_eq!(q.get().reason, UnresolvedReason::Conditional); + assert_eq!( + &index.source()[q.get().node.node().byte_range()], + b"/**@fn f*/" + ); + assert!(index.qualified_owner(q).unwrap().is_none()); + for position in 0..2 { + let owner = index + .facts() + .associated_owner(association, position) + .unwrap(); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .qualifications() + .count(), + 0 + ); + } +} + +#[cfg(feature = "cpp")] +#[test] +fn qualification_order_and_prepared_owner_memberships_follow_document_order() { + fn send_sync() {} + let source = "/**@fn f*/\n#if FLAG\nvoid f();\n#endif\n/**@fn f*/"; + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let documents: Vec<_> = index.documents().collect(); + let qualifications: Vec<_> = index.qualifications().collect(); + assert_eq!(documents.len(), 2); + assert_eq!(qualifications.len(), 2); + let owner = index.qualified_owner(qualifications[0]).unwrap().unwrap(); + for (qualification, document) in qualifications.iter().zip(&documents) { + assert_eq!(index.qualified_document(*qualification).unwrap(), *document); + assert_eq!( + index + .document_qualifications(*document) + .unwrap() + .collect::>(), + [*qualification] + ); + assert_eq!(index.qualified_owner(*qualification).unwrap(), Some(owner)); + } + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .qualifications() + .collect::>(), + qualifications + ); + send_sync::>(); + send_sync::>(); +} + +#[cfg(feature = "cpp")] +#[test] +fn overlapping_single_candidate_keeps_both_reasons_and_complex_assessment() { + let source = "#if FLAG\nvoid f(int x = );\n#endif\n/**@fn f*/"; + let parser = AnyParser::parse(LANG::Cpp, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(parser.root_node().has_error()); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.associations().len(), 1); + assert!(query.assessments().next().is_some()); + assert_eq!( + query + .qualifications() + .map(|q| q.get().reason) + .collect::>(), + [ + UnresolvedReason::Conditional, + UnresolvedReason::GrammarBoundary + ] + ); + let mut moved = Vec::new(); + moved.push(index); + let index = moved.pop().unwrap(); + assert_eq!(index.qualifications().len(), 2); +} diff --git a/big-code-analysis-ast/src/documentation/collector/projections.rs b/big-code-analysis-ast/src/documentation/collector/projections.rs index 73cd2a01a..0f688acb0 100644 --- a/big-code-analysis-ast/src/documentation/collector/projections.rs +++ b/big-code-analysis-ast/src/documentation/collector/projections.rs @@ -199,6 +199,7 @@ impl Builder<'_> { })); self.index.associations_by_owner.push(Vec::new()); self.index.assessments_by_owner.push(Vec::new()); + self.index.qualifications_by_owner.push(Vec::new()); self.index.owner_nodes.push(id); slots.push(slot); } @@ -313,7 +314,11 @@ impl Builder<'_> { self.index.canonical.nodes[id.0].name_scope, super::super::names::NamedOwner { owner, - qualification: Some(UnresolvedReason::GrammarBoundary), + qualification: { + let mut qualification = self.index.canonical.nodes[id.0].qualification; + qualification.insert(UnresolvedReason::GrammarBoundary); + qualification + }, }, budget, )?; diff --git a/big-code-analysis-ast/src/documentation/collector/qualifications.rs b/big-code-analysis-ast/src/documentation/collector/qualifications.rs new file mode 100644 index 000000000..c374d5677 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/qualifications.rs @@ -0,0 +1,80 @@ +//! Store semantic provenance once, then prepare document/owner adjacency in order. + +use super::*; +use crate::documentation::names::NamedOwner; +use crate::documentation::qualifications::QualificationSet; + +impl<'s> Builder<'s> { + pub(super) fn candidate_qualifications( + &mut self, + document: DocumentId, + candidate: NamedOwner, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let node = self.index.canonical.nodes[self.index.owner_nodes[candidate.owner.0].0].evidence; + for (rank, reason) in candidate.qualification.reasons() { + budget.step()?; + self.index.qualifications.push(Qualification { + subject: QualificationSubject::Candidate, + reason, + node, + document, + owner: Some(candidate.owner), + rank, + }); + } + Ok(()) + } + + pub(super) fn reference_qualifications( + &mut self, + document: DocumentId, + node: NodeEvidence<'s>, + qualification: QualificationSet, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + for (rank, reason) in qualification.reasons() { + budget.step()?; + self.index.qualifications.push(Qualification { + subject: QualificationSubject::Reference, + reason, + node, + document, + owner: None, + rank, + }); + } + Ok(()) + } + + pub(super) fn order_qualifications( + &mut self, + document_ranks: &[usize], + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let mut keys = Vec::new(); + for (ordinal, qualification) in self.index.qualifications.iter().enumerate() { + budget.step()?; + keys.push(( + document_ranks[qualification.document.0], + qualification.node.node().start_byte(), + qualification.node.node().end_byte(), + qualification.rank, + ordinal, + )); + } + for (_, _, _, _, ordinal) in super::super::ordering::ordered(keys, budget)? { + budget.step()?; + let qualification = &self.index.qualifications[ordinal]; + self.index.qualifications_ordered.push(ordinal); + self.index.qualifications_by_document[qualification.document.0].push(ordinal); + if let Some(owner) = qualification.owner { + self.index.qualifications_by_owner[owner.0].push(ordinal); + self.index.canonical.nodes[self.index.owner_nodes[owner.0].0] + .qualifications + .push(ordinal); + } + } + Ok(()) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs b/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs index 6312f311f..a389f5a5f 100644 --- a/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs @@ -494,12 +494,9 @@ fn nested_default_lambda_signature_work_is_linear_in_primary_facts() { .count(), depth ); - // Each complex declaration stores its one-byte name twice, never its header. - assert_eq!( - after.key_bytes_stored - before.key_bytes_stored, - 2 * depth + 17 - ); - assert_eq!(after.name_bytes - before.name_bytes, 2 * depth + 40); + // Each complex declaration stores one name; leaf stores its name and token key. + assert_eq!(after.key_bytes_stored - before.key_bytes_stored, depth + 17); + assert_eq!(after.name_bytes - before.name_bytes, 3 * depth + 60); } } diff --git a/big-code-analysis-ast/src/documentation/index.rs b/big-code-analysis-ast/src/documentation/index.rs index 178340a77..0d5b83412 100644 --- a/big-code-analysis-ast/src/documentation/index.rs +++ b/big-code-analysis-ast/src/documentation/index.rs @@ -77,6 +77,10 @@ pub struct DocumentationIndex<'s> { pub(super) documents_ordered: Vec, pub(super) associations_ordered: Vec, pub(super) source_cleaned: Vec>>, + pub(super) qualifications: Vec>, + pub(super) qualifications_ordered: Vec, + pub(super) qualifications_by_document: Vec>, + pub(super) qualifications_by_owner: Vec>, } /// Prepared results for one semantic owner, including known associations and @@ -87,6 +91,7 @@ pub struct OwnerAssociations<'i, 's> { assessments: &'i [usize], scope: Option, projection_pending: bool, + qualifications: &'i [usize], } /// A canonical syntax projection with its known owners and pending assessment. @@ -149,6 +154,13 @@ crate::observation::counter!( ); impl<'i, 's> OwnerAssociations<'i, 's> { + /// Known conditional/recovery facts for this candidate, independently of + /// association ambiguity and pending implementation assessments. + pub fn qualifications( + &self, + ) -> impl ExactSizeIterator>> + '_ { + self.index.qualification_refs(self.qualifications) + } /// Whether the queried syntax still requires a semantic owner projection. /// Known associations and pending assessment records remain accessible. #[must_use] @@ -350,6 +362,7 @@ impl<'s> DocumentationIndex<'s> { assessments: &[], scope: Some(id), projection_pending: true, + qualifications: &self.canonical.nodes[id.0].qualifications, }), Projection::Ready(owners) if owners.len() == 1 => { let ordinal = owners[0].0; @@ -418,6 +431,7 @@ impl<'s> DocumentationIndex<'s> { assessments: &self.assessments_by_owner[ordinal], scope, projection_pending: false, + qualifications: &self.qualifications_by_owner[ordinal], } } } diff --git a/big-code-analysis-ast/src/documentation/names.rs b/big-code-analysis-ast/src/documentation/names.rs index d6a12aeb1..cadd39247 100644 --- a/big-code-analysis-ast/src/documentation/names.rs +++ b/big-code-analysis-ast/src/documentation/names.rs @@ -6,31 +6,39 @@ use std::hash::{BuildHasher, Hasher}; use super::budget::WorkBudget; use super::canonical::NodeId; +use super::qualifications::QualificationSet; use super::{OwnerId, SourceError, UnresolvedReason}; +#[cfg(test)] +mod budget_tests; +mod grammar; mod tokens; #[derive(Default)] pub(super) struct Names { identifiers: HashMap<(NodeId, u64), Vec>, signatures: HashMap<(NodeId, u64), Vec>, - complex: HashMap<(NodeId, u64), Vec>, + candidates: Vec, hasher: RandomState, } struct NameEntry { spelling: Vec, - owners: Vec, + owners: Vec, + complex: Vec, } +#[derive(Clone, Copy)] +struct CandidateId(usize); + #[derive(Clone, Copy)] pub(super) struct NamedOwner { pub(super) owner: OwnerId, - pub(super) qualification: Option, + pub(super) qualification: QualificationSet, } pub(super) struct NameResolution { - pub(super) owners: Vec, + pub(super) owners: Vec, pub(super) reason: Option, pub(super) pending: bool, } @@ -54,18 +62,31 @@ fn normalized_key( hasher: &RandomState, budget: &B, ) -> Result<(u64, Vec), SourceError> { - let mut hash = hasher.build_hasher(); - let mut key = Vec::new(); let Some(tokens) = tokens::tokens(bytes, budget)? else { return Ok((0, Vec::new())); }; + emit_key(&tokens, hasher, budget) +} + +fn emit_key( + tokens: &[&[u8]], + hasher: &RandomState, + budget: &B, +) -> Result<(u64, Vec), SourceError> { + let mut hash = hasher.build_hasher(); + let mut key = Vec::new(); for (position, token) in tokens.iter().enumerate() { + budget.step().map_err(Into::into)?; if position != 0 { + budget.bytes(2).map_err(Into::into)?; + name_bytes::record(); + name_bytes::record(); hash.write_u8(0); key.push(0); } for &byte in *token { - budget.bytes(1).map_err(Into::into)?; + budget.bytes(2).map_err(Into::into)?; + name_bytes::record(); name_bytes::record(); hash.write_u8(byte); key.push(byte); @@ -96,30 +117,48 @@ fn same_spelling( fn insert_entry( bucket: &mut Vec, spelling: Vec, - owner: NamedOwner, + owner: CandidateId, + complex: bool, budget: &B, ) -> Result<(), SourceError> { for entry in bucket.iter_mut() { budget.step().map_err(Into::into)?; if same_spelling(&entry.spelling, &spelling, budget)? { entry.owners.push(owner); + if complex { + entry.complex.push(owner); + } return Ok(()); } } + for _ in &spelling { + budget.bytes(1).map_err(Into::into)?; + key_bytes_stored::record(); + } bucket.push(NameEntry { spelling, owners: vec![owner], + complex: if complex { vec![owner] } else { Vec::new() }, }); - for _ in bucket - .last() - .map_or(&[][..], |entry| entry.spelling.as_slice()) - { - budget.bytes(1).map_err(Into::into)?; - key_bytes_stored::record(); - } Ok(()) } +fn lookup<'a, B: WorkBudget>( + bucket: Option<&'a Vec>, + key: &[u8], + budget: &B, +) -> Result, SourceError> { + if let Some(bucket) = bucket { + for entry in bucket { + budget.step().map_err(Into::into)?; + if same_spelling(&entry.spelling, key, budget)? { + return Ok(Some(entry)); + } + } + } + Ok(None) +} + impl Names { #[cfg(test)] pub(super) fn insert( @@ -135,7 +174,7 @@ impl Names { NodeId(0), NamedOwner { owner, - qualification: None, + qualification: QualificationSet::default(), }, budget, ) @@ -150,20 +189,10 @@ impl Names { budget: &B, ) -> Result<(), SourceError> { let (hash, name) = key(name, &self.hasher, budget)?; - let mut copied_name = Vec::new(); - for &byte in &name { - budget.bytes(1).map_err(Into::into)?; - copied_name.push(byte); - } - insert_entry( - self.identifiers.entry((scope, hash)).or_default(), - copied_name, - owner, - budget, - )?; let signature = match signature { Some(signature) => { if let Some(tokens) = tokens::tokens(signature, budget)? + && tokens.len() > 1 && tokens::reference_name(&tokens, budget)?.is_some() { Some(key(signature, &self.hasher, budget)?) @@ -173,20 +202,25 @@ impl Names { } None => None, }; - let Some((hash, signature)) = signature.filter(|(_, key)| !key.is_empty()) else { - return insert_entry( - self.complex.entry((scope, hash)).or_default(), - name, - owner, - budget, - ); - }; + let signature = signature.filter(|(_, key)| !key.is_empty()); + let id = CandidateId(self.candidates.len()); + self.candidates.push(owner); insert_entry( - self.signatures.entry((scope, hash)).or_default(), - signature, - owner, + self.identifiers.entry((scope, hash)).or_default(), + name, + id, + signature.is_none(), budget, )?; + if let Some((hash, spelling)) = signature { + insert_entry( + self.signatures.entry((scope, hash)).or_default(), + spelling, + id, + false, + budget, + )?; + } Ok(()) } @@ -197,7 +231,10 @@ impl Names { budget: &B, ) -> Result<(Vec, Option), SourceError> { let result = self.resolve_in(reference, NodeId(0), budget)?; - Ok((result.owners, result.reason)) + Ok(( + result.owners.into_iter().map(|owner| owner.owner).collect(), + result.reason, + )) } pub(super) fn resolve_in( @@ -221,76 +258,54 @@ impl Names { }); }; let (hash, key) = key(reference, &self.hasher, budget)?; - let mut signatures = false; - for byte in &key { - budget.bytes(1).map_err(Into::into)?; - signatures |= *byte == b'('; - } + let signatures = tokens.len() > 1; let index = if signatures { &self.signatures } else { &self.identifiers }; let mut owners = Vec::new(); - if let Some(candidates) = index.get(&(scope, hash)) { - for entry in candidates { + let mut pending = false; + if let Some(entry) = lookup(index.get(&(scope, hash)), &key, budget)? { + if !signatures { + pending = !entry.complex.is_empty(); + } + for &owner in &entry.owners { budget.step().map_err(Into::into)?; - if same_spelling(&entry.spelling, &key, budget)? { - for &owner in &entry.owners { - budget.step().map_err(Into::into)?; - owners.push(owner); - } - break; - } + owners.push(self.candidates[owner.0]); } } - let (name_hash, name_key) = self.key_name(name, budget)?; - let mut pending = false; - if let Some(candidates) = self.complex.get(&(scope, name_hash)) { - for entry in candidates { - budget.step().map_err(Into::into)?; - if same_spelling(&entry.spelling, &name_key, budget)? { - pending = true; - if signatures { - for &owner in &entry.owners { - budget.step().map_err(Into::into)?; - owners.push(owner); - } - } - break; + if signatures { + let (name_hash, name_key) = key_name(name, &self.hasher, budget)?; + if let Some(entry) = + lookup(self.identifiers.get(&(scope, name_hash)), &name_key, budget)? + { + pending = !entry.complex.is_empty(); + for &owner in &entry.complex { + budget.step().map_err(Into::into)?; + owners.push(self.candidates[owner.0]); } } } let reason = match owners.len() { 0 => Some(UnresolvedReason::MissingName), - 1 => owners[0].qualification, + 1 => owners[0].qualification.headline(), _ => Some(UnresolvedReason::Ambiguous), }; - if owners.len() > 1 { - for owner in &owners { - budget.step().map_err(Into::into)?; - pending |= owner.qualification.is_some(); - } - } - let mut ids = Vec::new(); - for owner in owners { - budget.step().map_err(Into::into)?; - ids.push(owner.owner); - } Ok(NameResolution { - owners: ids, + owners, reason, pending, }) } +} - fn key_name( - &self, - name: &[u8], - budget: &B, - ) -> Result<(u64, Vec), SourceError> { - key(name, &self.hasher, budget) - } +fn key_name( + name: &[u8], + hasher: &RandomState, + budget: &B, +) -> Result<(u64, Vec), SourceError> { + key(name, hasher, budget) } #[cfg(test)] @@ -322,22 +337,28 @@ mod tests { fn hash_collision_does_not_substitute_another_name() { let mut names = Names::default(); let (hash, _) = key(b"f", &names.hasher, &NoBudget).unwrap(); + names.candidates = vec![ + NamedOwner { + owner: OwnerId(0), + qualification: QualificationSet::default(), + }, + NamedOwner { + owner: OwnerId(1), + qualification: QualificationSet::default(), + }, + ]; names.identifiers.insert( (NodeId(0), hash), vec![ NameEntry { spelling: b"g".to_vec(), - owners: vec![NamedOwner { - owner: OwnerId(0), - qualification: None, - }], + owners: vec![CandidateId(0)], + complex: Vec::new(), }, NameEntry { spelling: b"f".to_vec(), - owners: vec![NamedOwner { - owner: OwnerId(1), - qualification: None, - }], + owners: vec![CandidateId(1)], + complex: Vec::new(), }, ], ); diff --git a/big-code-analysis-ast/src/documentation/names/budget_tests.rs b/big-code-analysis-ast/src/documentation/names/budget_tests.rs new file mode 100644 index 000000000..1d3ed1c76 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/names/budget_tests.rs @@ -0,0 +1,231 @@ +use super::*; +use std::cell::Cell; + +#[derive(Default)] +struct Counting { + bytes: Cell, + stop: Option, +} + +impl WorkBudget for Counting { + type Error = SourceError; + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + fn step(&self) -> Result<(), SourceError> { + Ok(()) + } + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + if self.stop.is_some_and(|limit| self.bytes.get() >= limit) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } +} + +#[test] +fn tokenizer_accounts_for_every_consumed_delimiter_and_token_byte() { + for source in [ + "/**/".repeat(8000) + "void f()", + "/*".to_owned() + &"x".repeat(40_000) + "*/", + "a".repeat(40_000), + " && :: \t\n".repeat(4000), + "/*unterminated".to_owned(), + ] { + let budget = Counting::default(); + let result = tokens::tokens(source.as_bytes(), &budget).unwrap(); + assert_eq!(budget.bytes.get(), source.len()); + assert_eq!(result.is_none(), source == "/*unterminated"); + } +} + +#[test] +fn tokenizer_cancels_inside_long_identifier_comment_and_trivia() { + for source in [ + "a".repeat(40_000), + "/*".to_owned() + &"x".repeat(40_000) + "*/", + "/**/".repeat(10_000), + ] { + let budget = Counting { + stop: Some(16 * 1024), + ..Counting::default() + }; + assert!(matches!( + tokens::tokens(source.as_bytes(), &budget), + Err(SourceError::Cancelled) + )); + assert_eq!(budget.bytes.get(), 16 * 1024); + assert!( + tokens::tokens(b"void f()", &Counting::default()) + .unwrap() + .is_some() + ); + } +} + +#[test] +fn key_output_charges_separators_and_cancels_within_emission() { + let hasher = RandomState::new(); + let input = vec![b"a".as_slice(); 20_000]; + let budget = Counting::default(); + let (_, key) = emit_key(&input, &hasher, &budget).unwrap(); + assert_eq!(key.len(), 39_999); + assert_eq!(budget.bytes.get(), 2 * key.len()); + let cancel = Counting { + stop: Some(16 * 1024), + ..Counting::default() + }; + assert!(matches!( + emit_key(&input, &hasher, &cancel), + Err(SourceError::Cancelled) + )); + assert_eq!(cancel.bytes.get(), 16 * 1024); + let long = b"a".repeat(40_000); + let cancel = Counting { + stop: Some(16 * 1024), + ..Counting::default() + }; + assert!(matches!( + emit_key(&[&long], &hasher, &cancel), + Err(SourceError::Cancelled) + )); + assert_eq!(cancel.bytes.get(), 16 * 1024); +} + +#[test] +fn ordinary_and_complex_candidates_intern_name_once() { + let mut names = Names::default(); + let before = key_bytes_stored::observed(); + for ordinal in 0..64 { + names + .insert_candidate( + b"f", + (ordinal % 2 == 0).then_some(b"void f()".as_slice()), + NodeId(0), + NamedOwner { + owner: OwnerId(ordinal), + qualification: QualificationSet::default(), + }, + &super::super::budget::NoBudget, + ) + .unwrap(); + } + // f: 1 byte, and void\0f\0(\0): 10 bytes; candidates never duplicate spelling. + assert_eq!(key_bytes_stored::observed() - before, 11); + assert_eq!(names.identifiers.values().map(Vec::len).sum::(), 1); + let entry = &names.identifiers.values().next().unwrap()[0]; + assert_eq!(entry.owners.len(), 64); + assert_eq!(entry.complex.len(), 32); + let before = name_candidates::observed(); + let result = names + .resolve_in(b"void f()", NodeId(0), &super::super::budget::NoBudget) + .unwrap(); + assert_eq!(result.owners.len(), 64); + assert!(result.pending); + assert_eq!(result.reason, Some(UnresolvedReason::Ambiguous)); + assert_eq!(name_candidates::observed() - before, 2); + let before = key_bytes_stored::observed(); + names + .insert_candidate( + b"f", + None, + NodeId(1), + NamedOwner { + owner: OwnerId(64), + qualification: QualificationSet::default(), + }, + &super::super::budget::NoBudget, + ) + .unwrap(); + assert_eq!(key_bytes_stored::observed() - before, 1); + assert_eq!( + names + .resolve_in(b"f", NodeId(1), &super::super::budget::NoBudget) + .unwrap() + .owners + .len(), + 1 + ); +} + +#[test] +fn builtin_and_keyword_inventory_has_explicit_positive_and_negative_cases() { + let builtins = [ + "void", + "bool", + "_Bool", + "char", + "signed char", + "unsigned char", + "wchar_t", + "char8_t", + "char16_t", + "char32_t", + "short", + "short int", + "signed short", + "signed short int", + "unsigned short", + "unsigned short int", + "int", + "signed", + "signed int", + "unsigned", + "unsigned int", + "long", + "long int", + "signed long", + "signed long int", + "unsigned long", + "unsigned long int", + "long long", + "long long int", + "signed long long", + "signed long long int", + "unsigned long long", + "unsigned long long int", + "float", + "double", + "long double", + ]; + let budget = Counting::default(); + for base in builtins { + let signature = format!("{base} f()"); + let tokens = tokens::tokens(signature.as_bytes(), &budget) + .unwrap() + .unwrap(); + assert_eq!( + tokens::reference_name(&tokens, &budget).unwrap(), + Some(b"f".as_slice()), + "{base}" + ); + } + for bad in [ + "unsigned double", + "short long", + "long long long", + "signed unsigned", + "void int", + "int int", + "int unsigned", + "auto", + "class", + "typename", + "_Atomic", + "decltype", + "static", + "12", + ] { + let signature = format!("{bad} f()"); + let tokens = tokens::tokens(signature.as_bytes(), &budget) + .unwrap() + .unwrap(); + assert_eq!( + tokens::reference_name(&tokens, &budget).unwrap(), + None, + "{bad}" + ); + } +} diff --git a/big-code-analysis-ast/src/documentation/names/grammar.rs b/big-code-analysis-ast/src/documentation/names/grammar.rs new file mode 100644 index 000000000..5380f0ae8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/names/grammar.rs @@ -0,0 +1,287 @@ +//! Exact supported signature grammar, not a compiler type resolver. +//! +//! Base types are one non-keyword identifier or one of BUILTINS below. Each base +//! permits const/volatile before or after it, then pointer stars with pointer cv, +//! then at most one final &/&&. Parameters may append one non-keyword identifier. +//! Empty parameters and sole void are supported. Arrays, nested declarators, +//! qualified/template types, attributes, defaults and trailing qualifiers defer. + +use crate::documentation::SourceError; +use crate::documentation::budget::WorkBudget; + +const BUILTINS: &[&[&[u8]]] = &[ + &[b"void"], + &[b"bool"], + &[b"_Bool"], + &[b"char"], + &[b"signed", b"char"], + &[b"unsigned", b"char"], + &[b"wchar_t"], + &[b"char8_t"], + &[b"char16_t"], + &[b"char32_t"], + &[b"short"], + &[b"short", b"int"], + &[b"signed", b"short"], + &[b"signed", b"short", b"int"], + &[b"unsigned", b"short"], + &[b"unsigned", b"short", b"int"], + &[b"int"], + &[b"signed"], + &[b"signed", b"int"], + &[b"unsigned"], + &[b"unsigned", b"int"], + &[b"long"], + &[b"long", b"int"], + &[b"signed", b"long"], + &[b"signed", b"long", b"int"], + &[b"unsigned", b"long"], + &[b"unsigned", b"long", b"int"], + &[b"long", b"long"], + &[b"long", b"long", b"int"], + &[b"signed", b"long", b"long"], + &[b"signed", b"long", b"long", b"int"], + &[b"unsigned", b"long", b"long"], + &[b"unsigned", b"long", b"long", b"int"], + &[b"float"], + &[b"double"], + &[b"long", b"double"], +]; + +pub(super) fn identifier(token: &[u8]) -> bool { + token + .first() + .is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_') + && !keyword(token) +} + +#[allow(clippy::too_many_lines)] // Explicit C/C++ keyword exclusions for the narrow grammar. +fn keyword(token: &[u8]) -> bool { + matches!( + token, + b"alignas" + | b"alignof" + | b"and" + | b"and_eq" + | b"asm" + | b"auto" + | b"bitand" + | b"bitor" + | b"bool" + | b"break" + | b"case" + | b"catch" + | b"char" + | b"char8_t" + | b"char16_t" + | b"char32_t" + | b"class" + | b"compl" + | b"concept" + | b"const" + | b"consteval" + | b"constexpr" + | b"constinit" + | b"const_cast" + | b"continue" + | b"co_await" + | b"co_return" + | b"co_yield" + | b"decltype" + | b"default" + | b"delete" + | b"do" + | b"double" + | b"dynamic_cast" + | b"else" + | b"enum" + | b"explicit" + | b"export" + | b"extern" + | b"false" + | b"float" + | b"for" + | b"friend" + | b"goto" + | b"if" + | b"inline" + | b"int" + | b"long" + | b"mutable" + | b"namespace" + | b"new" + | b"noexcept" + | b"not" + | b"not_eq" + | b"nullptr" + | b"operator" + | b"or" + | b"or_eq" + | b"private" + | b"protected" + | b"public" + | b"register" + | b"reinterpret_cast" + | b"requires" + | b"return" + | b"short" + | b"signed" + | b"sizeof" + | b"static" + | b"static_assert" + | b"static_cast" + | b"struct" + | b"switch" + | b"template" + | b"this" + | b"thread_local" + | b"throw" + | b"true" + | b"try" + | b"typedef" + | b"typeid" + | b"typename" + | b"union" + | b"unsigned" + | b"using" + | b"virtual" + | b"void" + | b"volatile" + | b"wchar_t" + | b"while" + | b"xor" + | b"xor_eq" + | b"restrict" + | b"_Alignas" + | b"_Alignof" + | b"_Atomic" + | b"_Bool" + | b"_Complex" + | b"_Generic" + | b"_Imaginary" + | b"_Noreturn" + | b"_Static_assert" + | b"_Thread_local" + ) +} + +fn cv( + tokens: &[&[u8]], + at: &mut usize, + seen: &mut u8, + budget: &B, +) -> Result { + while let Some(token) = tokens.get(*at) { + budget.step().map_err(Into::into)?; + let bit = match *token { + b"const" => 1, + b"volatile" => 2, + _ => break, + }; + if *seen & bit != 0 { + return Ok(false); + } + *seen |= bit; + *at += 1; + } + Ok(true) +} + +fn type_end( + tokens: &[&[u8]], + budget: &B, +) -> Result, SourceError> { + let mut at = 0; + let mut seen = 0; + if !cv(tokens, &mut at, &mut seen, budget)? { + return Ok(None); + } + let Some(&base) = tokens.get(at) else { + return Ok(None); + }; + let start = at; + if identifier(base) { + at += 1; + } else { + while tokens.get(at).is_some_and(|token| { + matches!( + *token, + b"void" + | b"bool" + | b"_Bool" + | b"char" + | b"wchar_t" + | b"char8_t" + | b"char16_t" + | b"char32_t" + | b"short" + | b"signed" + | b"unsigned" + | b"int" + | b"long" + | b"float" + | b"double" + ) + }) { + budget.step().map_err(Into::into)?; + at += 1; + if at - start > 4 { + return Ok(None); + } + } + if !BUILTINS.contains(&&tokens[start..at]) { + return Ok(None); + } + } + if !cv(tokens, &mut at, &mut seen, budget)? { + return Ok(None); + } + let mut pointer = false; + while tokens.get(at) == Some(&b"*".as_slice()) { + budget.step().map_err(Into::into)?; + pointer = true; + at += 1; + if !cv(tokens, &mut at, &mut 0, budget)? { + return Ok(None); + } + } + if tokens + .get(at) + .is_some_and(|token| matches!(*token, b"&" | b"&&")) + { + at += 1; + if base == b"void" && !pointer { + return Ok(None); + } + } + Ok(Some((at, base == b"void" && !pointer))) +} + +pub(super) fn return_type( + tokens: &[&[u8]], + budget: &B, +) -> Result { + Ok(type_end(tokens, budget)?.is_some_and(|(at, _)| at == tokens.len())) +} + +pub(super) fn parameters(tokens: &[&[u8]], budget: &B) -> Result { + if tokens.is_empty() || tokens == [b"void".as_slice()] { + return Ok(true); + } + let mut start = 0; + for end in 0..=tokens.len() { + budget.step().map_err(Into::into)?; + if end < tokens.len() && tokens[end] != b"," { + continue; + } + let group = &tokens[start..end]; + let Some((at, void)) = type_end(group, budget)? else { + return Ok(false); + }; + if void || !(at == group.len() || (at + 1 == group.len() && identifier(group[at]))) { + return Ok(false); + } + start = end + 1; + } + Ok(true) +} diff --git a/big-code-analysis-ast/src/documentation/names/tokens.rs b/big-code-analysis-ast/src/documentation/names/tokens.rs index 52f341309..513b1f7bd 100644 --- a/big-code-analysis-ast/src/documentation/names/tokens.rs +++ b/big-code-analysis-ast/src/documentation/names/tokens.rs @@ -1,4 +1,5 @@ //! Narrow lexical keys for exact static C-family signatures. +//! Each consumed input byte is charged once in this scanner, including delimiters. use crate::documentation::SourceError; use crate::documentation::budget::WorkBudget; @@ -25,34 +26,45 @@ pub(super) fn tokens<'s, B: WorkBudget>( at += 1; } } else if bytes[at..].starts_with(b"/*") { + charge(1, budget)?; at += 2; - while at + 1 < bytes.len() && !bytes[at..].starts_with(b"*/") { - budget.bytes(1).map_err(Into::into)?; - super::name_bytes::record(); + while at < bytes.len() && !bytes[at..].starts_with(b"*/") { + charge(1, budget)?; at += 1; } - if at + 1 >= bytes.len() { + if at == bytes.len() { return Ok(None); } + charge(2, budget)?; at += 2; continue; } else if bytes[at..].starts_with(b"&&") || bytes[at..].starts_with(b"::") { + charge(1, budget)?; at += 2; } else if matches!(bytes[at], b'(' | b')' | b',' | b'*' | b'&') { at += 1; } else { return Ok(None); } + budget.step().map_err(Into::into)?; result.push(&bytes[start..at]); } Ok(Some(result)) } +fn charge(count: usize, budget: &B) -> Result<(), SourceError> { + budget.bytes(count).map_err(Into::into)?; + for _ in 0..count { + super::name_bytes::record(); + } + Ok(()) +} + pub(super) fn reference_name<'s, B: WorkBudget>( tokens: &[&'s [u8]], budget: &B, ) -> Result, SourceError> { - if tokens.len() == 1 && identifier(tokens[0]) { + if tokens.len() == 1 && super::grammar::identifier(tokens[0]) { return Ok(Some(tokens[0])); } let mut open = None; @@ -78,11 +90,10 @@ pub(super) fn reference_name<'s, B: WorkBudget>( return Ok(None); } let name = tokens[open - 1]; - Ok(identifier(name).then_some(name)) -} - -fn identifier(bytes: &[u8]) -> bool { - bytes - .first() - .is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_') + if !super::grammar::identifier(name) + || !super::grammar::return_type(&tokens[..open - 1], budget)? + { + return Ok(None); + } + Ok(super::grammar::parameters(&tokens[open + 1..tokens.len() - 1], budget)?.then_some(name)) } diff --git a/big-code-analysis-ast/src/documentation/qualifications.rs b/big-code-analysis-ast/src/documentation/qualifications.rs new file mode 100644 index 000000000..457b83a1b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/qualifications.rs @@ -0,0 +1,118 @@ +//! Known source qualifications, separate from unfinished adapter assessments. + +use super::*; + +#[derive(Clone, Copy, Debug, Default)] +pub(super) struct QualificationSet(u8); + +impl QualificationSet { + pub(super) fn insert(&mut self, reason: UnresolvedReason) { + self.0 |= match reason { + UnresolvedReason::Conditional => 1, + UnresolvedReason::GrammarBoundary => 2, + _ => 0, + }; + } + + pub(super) fn headline(self) -> Option { + if self.0 & 2 != 0 { + Some(UnresolvedReason::GrammarBoundary) + } else if self.0 & 1 != 0 { + Some(UnresolvedReason::Conditional) + } else { + None + } + } + + pub(super) fn reasons(self) -> impl Iterator { + [ + (0, UnresolvedReason::Conditional), + (1, UnresolvedReason::GrammarBoundary), + ] + .into_iter() + .filter(move |(rank, _)| self.0 & (1 << rank) != 0) + } +} + +/// Whether a known source qualification describes a candidate or the reference. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum QualificationSubject { + /// The named declaration candidate; consult its association before claiming it. + Candidate, + /// The occurrence containing the explicit documentation reference. + Reference, +} + +/// One known conditional/recovery fact for a document and source occurrence. +/// These records are available by default and do not imply pending implementation. +#[derive(Debug)] +pub struct Qualification<'s> { + /// Candidate provenance versus reference-context provenance. + pub subject: QualificationSubject, + /// Known reason; currently Conditional or GrammarBoundary. + pub reason: UnresolvedReason, + /// Canonical candidate declaration or reference comment. + pub node: NodeEvidence<'s>, + pub(super) document: DocumentId, + pub(super) owner: Option, + pub(super) rank: u8, +} + +impl<'s> DocumentationIndex<'s> { + /// All semantic qualifications in document, source and explicit reason order. + pub fn qualifications(&self) -> impl ExactSizeIterator>> { + self.qualification_refs(&self.qualifications_ordered) + } + + /// Known qualifications for one document, without scanning unrelated records. + /// + /// # Errors + /// Rejects a document handle from another index. + pub fn document_qualifications( + &self, + document: FactRef<'_, Document<'s>>, + ) -> Result>>, FactError> { + self.facts.check_scope(document)?; + Ok(self.qualification_refs(&self.qualifications_by_document[document.ordinal])) + } + + /// The document linked by a qualification. + /// + /// # Errors + /// Rejects a qualification handle from another index. + pub fn qualified_document( + &self, + qualification: FactRef<'_, Qualification<'s>>, + ) -> Result>, FactError> { + self.facts.check_scope(qualification)?; + self.facts + .reference(&self.facts.documents, qualification.get().document.0) + .ok_or(FactError::MissingRecord) + } + + /// The candidate owner, or None for reference-context qualification. + /// + /// # Errors + /// Rejects a qualification handle from another index. + pub fn qualified_owner( + &self, + qualification: FactRef<'_, Qualification<'s>>, + ) -> Result>>, FactError> { + self.facts.check_scope(qualification)?; + Ok(qualification + .get() + .owner + .and_then(|id| self.facts.reference(&self.facts.owners, id.0))) + } + + pub(super) fn qualification_refs<'i>( + &'i self, + ids: &'i [usize], + ) -> impl ExactSizeIterator>> { + ids.iter().map(|&ordinal| FactRef { + scope: &self.facts.scope, + ordinal, + fact: &self.qualifications[ordinal], + }) + } +} diff --git a/utils/documentation-names-perturb.json b/utils/documentation-names-perturb.json new file mode 100644 index 000000000..7f0952002 --- /dev/null +++ b/utils/documentation-names-perturb.json @@ -0,0 +1,18 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + {"name":"identifier-loop-defers-byte-checkpoints","file":"big-code-analysis-ast/src/documentation/names/tokens.rs","old":"while at < bytes.len() && (bytes[at].is_ascii_alphanumeric() || bytes[at] == b'_') {\n budget.bytes(1).map_err(Into::into)?;","new":"while at < bytes.len() && (bytes[at].is_ascii_alphanumeric() || bytes[at] == b'_') {","expect":["documentation::names::budget_tests::tokenizer_cancels_inside_long_identifier_comment_and_trivia"]}, + {"name":"comment-loop-defers-byte-checkpoints","file":"big-code-analysis-ast/src/documentation/names/tokens.rs","old":"while at < bytes.len() && !bytes[at..].starts_with(b\"*/\") {\n charge(1, budget)?;","new":"while at < bytes.len() && !bytes[at..].starts_with(b\"*/\") {","expect":["documentation::names::budget_tests::tokenizer_cancels_inside_long_identifier_comment_and_trivia"]}, + {"name":"key-token-loop-defers-byte-checkpoints","file":"big-code-analysis-ast/src/documentation/names.rs","old":"for &byte in *token {\n budget.bytes(2).map_err(Into::into)?;","new":"for &byte in *token {","expect":["documentation::names::budget_tests::key_output_charges_separators_and_cancels_within_emission"]}, + {"name":"parameter-grammar-not-validated","file":"big-code-analysis-ast/src/documentation/names/tokens.rs","old":"super::grammar::parameters(&tokens[open + 1..tokens.len() - 1], budget)?","new":"true","expect":["documentation::collector::named_tests::narrow_signature_grammar_defers_malformed_and_unsupported_references"]}, + {"name":"candidate-qualification-records-dropped","file":"big-code-analysis-ast/src/documentation/collector/qualifications.rs","old":"for (rank, reason) in candidate.qualification.reasons() {","new":"for (rank, reason) in candidate.qualification.reasons().take(0) {","expect":["documentation::collector::named_tests::ambiguous_candidates_keep_structured_qualification_and_reference_identity"]}, + {"name":"overlapping-qualification-replaced","file":"big-code-analysis-ast/src/documentation/qualifications.rs","old":"self.0 |= match reason {","new":"self.0 = match reason {","expect":["documentation::collector::named_tests::ambiguous_candidates_keep_structured_qualification_and_reference_identity","documentation::collector::named_tests::overlapping_single_candidate_keeps_both_reasons_and_complex_assessment"]}, + {"name":"reference-overwrites-ambiguity","file":"big-code-analysis-ast/src/documentation/collector/assembly.rs","old":"if result.reason != Some(UnresolvedReason::Ambiguous) && !result.pending {","new":"if !result.pending {","expect":["documentation::collector::named_tests::ambiguous_candidates_keep_structured_qualification_and_reference_identity"]}, + {"name":"comment-close-bytes-uncharged","file":"big-code-analysis-ast/src/documentation/names/tokens.rs","old":" charge(2, budget)?;","new":" charge(0, budget)?;","expect":["documentation::names::budget_tests::tokenizer_accounts_for_every_consumed_delimiter_and_token_byte"]}, + {"name":"key-separator-bytes-uncharged","file":"big-code-analysis-ast/src/documentation/names.rs","old":"if position != 0 {\n budget.bytes(2).map_err(Into::into)?;","new":"if position != 0 {","expect":["documentation::names::budget_tests::key_output_charges_separators_and_cancels_within_emission"]}, + {"name":"name-spelling-not-interned","file":"big-code-analysis-ast/src/documentation/names.rs","old":"if same_spelling(&entry.spelling, &spelling, budget)? {","new":"if false && same_spelling(&entry.spelling, &spelling, budget)? {","expect":["documentation::names::budget_tests::ordinary_and_complex_candidates_intern_name_once"]}, + {"name":"foreign-qualification-handle-accepted","file":"big-code-analysis-ast/src/documentation/qualifications.rs","old":"self.facts.check_scope(qualification)?;\n self.facts","new":"let _ = qualification;\n self.facts","expect":["documentation::collector::named_tests::ambiguous_candidates_keep_structured_qualification_and_reference_identity"]} + ] +} diff --git a/utils/documentation-remediation-perturb.json b/utils/documentation-remediation-perturb.json index 2f1a96b62..e96707e28 100644 --- a/utils/documentation-remediation-perturb.json +++ b/utils/documentation-remediation-perturb.json @@ -10,7 +10,7 @@ {"name":"pending-first-wrapper-seeks-later-ready","file":"big-code-analysis-ast/src/documentation/collector/projections.rs","old":"Projection::Pending => {\n self.index.canonical.nodes[id.0].projection = Projection::Pending;\n return Ok(());","new":"Projection::Pending => {\n continue;","expect":["documentation::collector::remediation_tests::ruby_pending_first_statement_never_redirects_to_later_method","documentation::collector::remediation_tests::lua_pending_first_statement_never_redirects_to_later_function"]}, {"name":"lexical-key-token-boundaries-erased","file":"big-code-analysis-ast/src/documentation/names.rs","old":" hash.write_u8(0);\n key.push(0);","new":" let _ = position;","expect":["documentation::collector::remediation_tests::exact_signatures_preserve_tokens_scope_and_complex_competitors"]}, {"name":"complex-headers-hashed-in-full","file":"big-code-analysis-ast/src/documentation/collector/projections.rs","old":"record.field != Some(\"body\") && record.signature_complex","new":"false && record.field != Some(\"body\") && record.signature_complex","expect":["documentation::collector::remediation_tests::nested_default_lambda_signature_work_is_linear_in_primary_facts"]}, - {"name":"conditional-name-qualification-lost","file":"big-code-analysis-ast/src/documentation/collector.rs","old":"record.qualification = Some(UnresolvedReason::Conditional);","new":"record.qualification = None;","expect":["documentation::collector::remediation_tests::c_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::cpp_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::mozcpp_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::objc_named_candidates_retain_conditional_provenance"]}, + {"name":"conditional-name-qualification-lost","file":"big-code-analysis-ast/src/documentation/collector.rs","old":"record.qualification.insert(UnresolvedReason::Conditional);","new":"let _ = record;","expect":["documentation::collector::remediation_tests::c_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::cpp_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::mozcpp_named_candidates_retain_conditional_provenance","documentation::collector::remediation_tests::objc_named_candidates_retain_conditional_provenance"]}, {"name":"pending-owner-context-not-followed","file":"big-code-analysis-ast/src/documentation/collector/assembly.rs","old":".unwrap_or(self.index.canonical.nodes[draft.scope.0].owner_context)","new":".unwrap_or(draft.scope)","expect":["documentation::collector::remediation_tests::kotlin_signature_context_exposes_document_linked_owner_assessment"]}, {"name":"helper-canonical-walk-skipped","file":"big-code-analysis-ast/src/documentation/collector.rs","old":" builder.walk::(&budget)?;","new":" if profile != Profile::Helper { builder.walk::(&budget)?; }","expect":["documentation::collector::remediation_tests::helpers_validate_all_canonical_nodes_before_unsupported_owner"]}, {"name":"logical-boundary-empty-members-retained","file":"big-code-analysis-ast/src/documentation/text/comments.rs","old":"while first_block < last_block && empty_block(&blocks[first_block], budget)?","new":"while false && first_block < last_block && empty_block(&blocks[first_block], budget)?","expect":["documentation::collector::remediation_tests::go_trims_logical_boundary_members_only","documentation::collector::remediation_tests::ruby_trims_logical_boundary_members_only","documentation::collector::remediation_tests::java_trims_logical_boundary_members_only"]}, From bd1d9ac5064c53702151dd2f60f4aa7de56adc12 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:41:15 -0800 Subject: [PATCH 044/221] feat(fuzz): add bounded source documentation property harness Register byte-exact tagged seeds for all language dispatch outcomes and source, identity, pending, qualification, and mapping edge cases. Reuse the held Ast source in ordinary fanout and keep typed cancellation provenance in the tagged path. Checkpoint before the parent-assigned heavy validation slot: formatting, seed metadata checks, and lightweight lints pass; Cargo builds/tests, fuzz campaigns, the full gate, and parent reviews remain pending. --- docs/development/fuzzing.md | 156 +++- fuzz/Cargo.lock | 3 + fuzz/Cargo.toml | 15 + fuzz/corpus/documentation/c-shared-owners | Bin 0 -> 23 bytes .../documentation/cpp-candidate-qualification | Bin 0 -> 61 bytes fuzz/corpus/documentation/cpp-gathered | Bin 0 -> 28 bytes fuzz/corpus/documentation/cpp-missing-name | Bin 0 -> 45 bytes fuzz/corpus/documentation/cpp-pending-name | Bin 0 -> 36 bytes .../documentation/cpp-reference-qualification | Bin 0 -> 43 bytes fuzz/corpus/documentation/dispatch-bash | Bin 0 -> 34 bytes fuzz/corpus/documentation/dispatch-c | Bin 0 -> 29 bytes fuzz/corpus/documentation/dispatch-ccomment | Bin 0 -> 13 bytes fuzz/corpus/documentation/dispatch-cpp | Bin 0 -> 25 bytes fuzz/corpus/documentation/dispatch-csharp | Bin 0 -> 41 bytes fuzz/corpus/documentation/dispatch-elixir | Bin 0 -> 55 bytes fuzz/corpus/documentation/dispatch-go | Bin 0 -> 33 bytes fuzz/corpus/documentation/dispatch-groovy | Bin 0 -> 24 bytes fuzz/corpus/documentation/dispatch-irules | Bin 0 -> 32 bytes fuzz/corpus/documentation/dispatch-java | Bin 0 -> 22 bytes fuzz/corpus/documentation/dispatch-javascript | Bin 0 -> 29 bytes fuzz/corpus/documentation/dispatch-kotlin | Bin 0 -> 24 bytes fuzz/corpus/documentation/dispatch-lua | Bin 0 -> 40 bytes fuzz/corpus/documentation/dispatch-mozcpp | Bin 0 -> 25 bytes fuzz/corpus/documentation/dispatch-mozjs | Bin 0 -> 29 bytes fuzz/corpus/documentation/dispatch-objc | Bin 0 -> 29 bytes fuzz/corpus/documentation/dispatch-perl | Bin 0 -> 34 bytes fuzz/corpus/documentation/dispatch-php | Bin 0 -> 37 bytes fuzz/corpus/documentation/dispatch-preproc | Bin 0 -> 15 bytes fuzz/corpus/documentation/dispatch-python | Bin 0 -> 32 bytes fuzz/corpus/documentation/dispatch-ruby | Bin 0 -> 20 bytes fuzz/corpus/documentation/dispatch-rust | Bin 0 -> 21 bytes fuzz/corpus/documentation/dispatch-tcl | Bin 0 -> 31 bytes fuzz/corpus/documentation/dispatch-tsx | Bin 0 -> 45 bytes fuzz/corpus/documentation/dispatch-typescript | Bin 0 -> 35 bytes fuzz/corpus/documentation/go-directive-off | Bin 0 -> 31 bytes fuzz/corpus/documentation/go-directive-on | 2 + .../documentation/java-crlf-token-pieces | Bin 0 -> 23 bytes fuzz/corpus/documentation/java-empty | Bin 0 -> 29 bytes fuzz/corpus/documentation/java-evidence | 3 + fuzz/corpus/documentation/java-scalar-pieces | Bin 0 -> 21 bytes fuzz/corpus/documentation/java-source-gap | Bin 0 -> 22 bytes .../documentation/kotlin-known-and-pending | Bin 0 -> 35 bytes .../corpus/documentation/kotlin-pending-owner | Bin 0 -> 33 bytes .../documentation/php-documentor-deferred | Bin 0 -> 37 bytes fuzz/corpus/documentation/ruby-rdoc-deferred | Bin 0 -> 20 bytes fuzz/corpus/documentation/rust-active-scope | Bin 0 -> 21 bytes fuzz/corpus/documentation/rust-attribute | Bin 0 -> 52 bytes .../corpus/documentation/rust-cancelled-scope | Bin 0 -> 21 bytes fuzz/corpus/documentation/rust-crlf | Bin 0 -> 47 bytes fuzz/corpus/documentation/rust-eof | Bin 0 -> 31 bytes .../documentation/rust-incompatible-profile | Bin 0 -> 21 bytes fuzz/corpus/documentation/rust-invalid-utf8 | Bin 0 -> 17 bytes fuzz/corpus/documentation/rust-join | Bin 0 -> 22 bytes .../documentation/rust-partial-delimiter | Bin 0 -> 6 bytes .../documentation/rust-recovery-neighbor | Bin 0 -> 57 bytes fuzz/corpus/documentation/rust-valid-neighbor | Bin 0 -> 58 bytes fuzz/documentation-seeds.json | 691 +++++++++++++++++ fuzz/fuzz_targets/documentation.rs | 9 + fuzz/generate_documentation_seeds.py | 319 ++++++++ fuzz/src/documentation/header.rs | 157 ++++ fuzz/src/documentation/maps.rs | 165 +++++ fuzz/src/documentation/mod.rs | 270 +++++++ fuzz/src/documentation/properties.rs | 700 ++++++++++++++++++ fuzz/src/documentation/tests.rs | 527 +++++++++++++ fuzz/src/lib.rs | 3 + 65 files changed, 3003 insertions(+), 17 deletions(-) create mode 100644 fuzz/corpus/documentation/c-shared-owners create mode 100644 fuzz/corpus/documentation/cpp-candidate-qualification create mode 100644 fuzz/corpus/documentation/cpp-gathered create mode 100644 fuzz/corpus/documentation/cpp-missing-name create mode 100644 fuzz/corpus/documentation/cpp-pending-name create mode 100644 fuzz/corpus/documentation/cpp-reference-qualification create mode 100644 fuzz/corpus/documentation/dispatch-bash create mode 100644 fuzz/corpus/documentation/dispatch-c create mode 100644 fuzz/corpus/documentation/dispatch-ccomment create mode 100644 fuzz/corpus/documentation/dispatch-cpp create mode 100644 fuzz/corpus/documentation/dispatch-csharp create mode 100644 fuzz/corpus/documentation/dispatch-elixir create mode 100644 fuzz/corpus/documentation/dispatch-go create mode 100644 fuzz/corpus/documentation/dispatch-groovy create mode 100644 fuzz/corpus/documentation/dispatch-irules create mode 100644 fuzz/corpus/documentation/dispatch-java create mode 100644 fuzz/corpus/documentation/dispatch-javascript create mode 100644 fuzz/corpus/documentation/dispatch-kotlin create mode 100644 fuzz/corpus/documentation/dispatch-lua create mode 100644 fuzz/corpus/documentation/dispatch-mozcpp create mode 100644 fuzz/corpus/documentation/dispatch-mozjs create mode 100644 fuzz/corpus/documentation/dispatch-objc create mode 100644 fuzz/corpus/documentation/dispatch-perl create mode 100644 fuzz/corpus/documentation/dispatch-php create mode 100644 fuzz/corpus/documentation/dispatch-preproc create mode 100644 fuzz/corpus/documentation/dispatch-python create mode 100644 fuzz/corpus/documentation/dispatch-ruby create mode 100644 fuzz/corpus/documentation/dispatch-rust create mode 100644 fuzz/corpus/documentation/dispatch-tcl create mode 100644 fuzz/corpus/documentation/dispatch-tsx create mode 100644 fuzz/corpus/documentation/dispatch-typescript create mode 100644 fuzz/corpus/documentation/go-directive-off create mode 100644 fuzz/corpus/documentation/go-directive-on create mode 100644 fuzz/corpus/documentation/java-crlf-token-pieces create mode 100644 fuzz/corpus/documentation/java-empty create mode 100644 fuzz/corpus/documentation/java-evidence create mode 100644 fuzz/corpus/documentation/java-scalar-pieces create mode 100644 fuzz/corpus/documentation/java-source-gap create mode 100644 fuzz/corpus/documentation/kotlin-known-and-pending create mode 100644 fuzz/corpus/documentation/kotlin-pending-owner create mode 100644 fuzz/corpus/documentation/php-documentor-deferred create mode 100644 fuzz/corpus/documentation/ruby-rdoc-deferred create mode 100644 fuzz/corpus/documentation/rust-active-scope create mode 100644 fuzz/corpus/documentation/rust-attribute create mode 100644 fuzz/corpus/documentation/rust-cancelled-scope create mode 100644 fuzz/corpus/documentation/rust-crlf create mode 100644 fuzz/corpus/documentation/rust-eof create mode 100644 fuzz/corpus/documentation/rust-incompatible-profile create mode 100644 fuzz/corpus/documentation/rust-invalid-utf8 create mode 100644 fuzz/corpus/documentation/rust-join create mode 100644 fuzz/corpus/documentation/rust-partial-delimiter create mode 100644 fuzz/corpus/documentation/rust-recovery-neighbor create mode 100644 fuzz/corpus/documentation/rust-valid-neighbor create mode 100644 fuzz/documentation-seeds.json create mode 100644 fuzz/fuzz_targets/documentation.rs create mode 100644 fuzz/generate_documentation_seeds.py create mode 100644 fuzz/src/documentation/header.rs create mode 100644 fuzz/src/documentation/maps.rs create mode 100644 fuzz/src/documentation/mod.rs create mode 100644 fuzz/src/documentation/properties.rs create mode 100644 fuzz/src/documentation/tests.rs diff --git a/docs/development/fuzzing.md b/docs/development/fuzzing.md index 0afb6de37..a737d730e 100644 --- a/docs/development/fuzzing.md +++ b/docs/development/fuzzing.md @@ -1,14 +1,16 @@ # Fuzzing `big-code-analysis` runs [cargo-fuzz][cf] against the parse-and-walk -layer: the `fuzz/` crate holds twelve [libFuzzer][lf] targets that feed -arbitrary bytes to `Ast::parse` and then run every public walk over the -result. Coverage-guided mutation reaches malformed and adversarial input +layer. The `fuzz/` crate holds [libFuzzer][lf] targets that feed +arbitrary bytes to the parser and exercise its walks and source-documentation +collector. Coverage-guided mutation reaches malformed and adversarial input shapes that a fixture suite samples only where someone thought to look. This page is for contributors running or extending the fuzz targets. It starts with running them and triaging a crash; the target design and the reasons the job runs outside `make pre-commit` follow. +It assumes familiarity with [Cargo](https://doc.rust-lang.org/cargo/) and the project's +test commands. A fuzz target is a function that libFuzzer repeatedly calls with mutated bytes. [cf]: https://rust-fuzz.github.io/book/cargo-fuzz.html [lf]: https://llvm.org/docs/LibFuzzer.html @@ -40,6 +42,7 @@ Then: ```bash make fuzz-check # fmt + clippy + test + build +make fuzz-replay # committed corpus, no mutation make fuzz-smoke # every target, FUZZ_RUNS each make fuzz-run FUZZ_TARGET=preproc_macro FUZZ_RUNS=1000000 make fuzz-run FUZZ_TARGET=parse_cpp FUZZ_INPUT=fuzz/artifacts/parse_cpp/ @@ -102,6 +105,16 @@ Those are byte-exact, and `.gitattributes` marks the directory `-text -diff` so git never normalises them. Several exist precisely to carry what it would otherwise rewrite. +The `documentation` corpus uses a +[tagged format](#documentation-properties) instead of raw source alone. +`fuzz/documentation-seeds.json` records each header, payload +[SHA-256](https://csrc.nist.gov/pubs/fips/180-4/upd1/final), +fixture provenance, and executed assertion class. Metadata stays outside the +corpus so libFuzzer never treats a registry file as a source seed. +`python3 -B fuzz/generate_documentation_seeds.py` regenerates the deliberate +seeds. Its inputs are the raw documentation fixtures and explicitly written +edge cases; it never obtains expected values from collector output. + `nested_depth`'s seeds are different in kind: that target decodes bytes into a generator input rather than treating them as source. Its layout is defined by a hand-written [`Arbitrary`](https://docs.rs/arbitrary) @@ -133,7 +146,7 @@ should each be explicable. the walk, because deliberately malformed source measures nothing and would put ERROR-node parses into `bca report`. -## Triaging a crash +## Triaging a crash {#triaging-a-crash} libFuzzer writes the offending input to `fuzz/artifacts//`. The CI workflow uploads that directory as the `fuzz-artifacts` artifact, and @@ -204,11 +217,14 @@ specific rationale. | `preproc_macro` | `preprocess` harvest → `Source::with_preproc` → the C-family macro-masking lexer | | `preproc_includes` | `preprocess` over several files → `fix_includes` → include-graph resolution, SCC collapse, candidate scoring | | `nested_depth` | A structured generator for the deep-nesting complexity class | +| `documentation` | Tagged language/profile selection, borrowed source collection, and bounded identity, owner, qualification, and map queries | Three design points are load-bearing. -**The bytes reach the parser unmodified.** Targets call -`Source::from_bytes`, which applies no normalisation. The file-reading +**The bytes reach the parser unmodified.** Full-walk targets call +`Source::from_bytes`, which applies no normalisation. The tagged documentation +target passes its unchanged payload to `AnyParser` or a raw included-range parser. +The file-reading path (`read_file`, `read_file_with_eol`, `normalize_eol`) runs `normalize_line_endings`, which guarantees a trailing newline. Tests using those readers cannot exercise a node ending at EOF, and that is @@ -217,24 +233,129 @@ would pass vacuously while looking like coverage. `Ast::from_path` normalises; no target uses it. **One parse, every walk.** `ops`, `dump` and comment removal are seams on -an already-built `Ast`, not separate entry points, so each target parses +an already-built `Ast`, not separate entry points, so each full-walk target parses once and then fans out over `metrics`, `ops`, `strip_comments`, `dump`, -`functions`, `suppressions`, `count` and `find`. It also serialises the +`functions`, `suppressions`, `count` and `find`. The documentation check uses +that same `Ast`'s language, tree, and held source buffer. Preprocessor targets +therefore supply the masked bytes that actually produced the tree. +The harness also serialises the results, which is the only thing in the fan-out that reaches `recursion::serialize_bounded` and `wire::map_tree`, the recursion bounded by #1056, after nested input was found able to abort the process from `Serialize`. **The C grammars are instrumented too.** cargo-fuzz sanitizes the Rust -side; the tree-sitter grammars are C compiled by build scripts and are -not covered unless asked, which would leave the largest body of -memory-unsafe code in the graph outside the sanitizer. `make fuzz-check` -sets `CFLAGS_`. It has to be the triple-qualified spelling: -`cc` resolves `_`, then `_`, +side; the [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars are C +compiled by build scripts and need separate instrumentation. +`make fuzz-check` sets `CFLAGS_`. It has to be the triple-qualified +spelling: `cc` resolves `_`, then `_`, then `_`, then bare ``, and picks `HOST_` rather than `TARGET_` for the build kind when it is not cross-compiling, so `TARGET_CFLAGS` is silently inert for a native fuzz build. +### Documentation properties {#documentation-properties} + +The documentation target has a handwritten version-one three-byte header. +The payload after byte 2 reaches the parser unchanged, including invalid +encoding, NUL bytes, CRLF, and a missing final newline. Unknown tags, +reserved bits, and unknown profile selectors produce distinct skips before +parsing. They never alias a supported language through a modulus. + +| Byte | Version-one meaning | +|---|---| +| 0 | Language tag in the stable table below | +| 1, bit 0 | Collect a second index on the same parse; compare results and reject foreign handles | +| 1, bit 1 | Check cloned-tree, shifted-node, and edited-node rejection | +| 1, bits 2–3 | `0`: ordinary collection; `1`: included ranges; `2`: cancelled collection scope followed by restored collection; `3`: active uncancelled scope | +| 1, bits 4–7 | Reserved; setting any bit skips the input | +| 2, bits 0–4 | Profile selector from `PROFILES` in `fuzz/src/documentation/header.rs`; `0` selects the language default | +| 2, bit 5 | Retain unbound candidate evidence | +| 2, bit 6 | Retain directive evidence | +| 2, bit 7 | Reserved version bit; setting it skips the input | + +The language tags are part of the corpus format, independent of enum +discriminants or iteration order: + +| Tags | Languages in tag order | +|---|---| +| 0–4 | Rust, Python, Java, Kotlin, Groovy | +| 5–9 | Csharp, Php, Javascript, Mozjs, Typescript | +| 10–14 | Tsx, C, Cpp, Mozcpp, Objc | +| 15–19 | Go, Ruby, Lua, Perl, Elixir | +| 20–24 | Bash, Tcl, Irules, Ccomment, Preproc | + +Registration tests compare the table with the `LANG` roster and execute every +registered seed through the real target. Positive seeds assert exact fragment +and owner ranges, parsed declaration kinds, text, and copied mappings from +`tests/fixtures/documentation/inventory.json`. Deferred adapters require +`AdapterUnavailable`; helper grammars require `NoDeclarationModel`. +Recognized deferred profiles differ from `UnsupportedProfile`. +These outcomes do not count as positive source extraction. Future adapters +must add their own positive seeds when their source paths become available. + +The checker validates raw pieces against the exact source and included ranges. +It checks observed document, association, and qualification ordering without +sorting the results. Bounded owner and canonical-cursor queries compare +prepared adjacency with enumeration. Pending assessments remain inspectable +alongside known associations; candidate and reference qualifications retain +their distinct identities and reasons. Cross-index handles and noncanonical +nodes must return the documented identity errors. + +Every complete document gets one map validation. Runs must cover its output; +copied origins match source bytes, transformed queries retain all responsible +token pieces, and synthetic output has no source. Stored runs may divide a +UTF-8 scalar when adjacent included pieces divide it. Query endpoints must +still be scalar boundaries. The query set includes reversed, out-of-bounds, +scalar-splitting, valid, late, and empty-EOF ranges. Unavailable, pending, +metadata, disabled, and explicit-absence content never becomes empty text. +Registered positives reach copied origins, synthetic comment joins, and decoded +CRLF tokens across included pieces. Expanded origins and source-produced metadata, +disabled, and explicit-absence states await their later adapters; defensive match +arms do not establish positive coverage of those forms. + +The resource limits are harness policy: + +- Inspect source buffers up to 32 KiB. Larger inputs skip only the added + documentation operation in the ordinary walk fanout; no source is truncated. +- Perform at most two ordinary collections over the same parse. +- Select at most eight owner/node positions and eight map ranges per input, + including late positions. +- Limit structured included-range inputs to 256 ranges. Each non-NUL payload + byte becomes one included range, so adjacent ranges can divide a scalar. + NUL bytes create excluded gaps. Parsing uses the original payload once. + +The checker makes linear or output-proportional passes and uses expected +constant-time hash indexing. Its included-byte prefix table costs linear +source space and avoids scanning every included range for every piece. +Bounded enumeration checks may scan associations for each selected owner; +the selected-owner count is constant. These limits bound harness work, not +library allocation or legitimate documentation fanout. They do not prove an +input fits `FUZZ_TIMEOUT`. + +Cancellation uses `AnyParser`'s retained completion state. Deterministic tests +pre-cancel a deliberately large parse and require `ParseCompletion::Cancelled` +after the flag scope ends. Tagged modes check active collection cancellation, +restoration, and an uncancelled flag. A tiny empty root is never evidence that +the parse callback aborted. Large phase-budget cancellation tests remain in +the AST crate; the fuzz target does not expose private phase hooks. + +Run the finite documentation validation sequence one heavy operation at a time: + +```bash +make fuzz-check +make fuzz-replay +make fuzz-smoke FUZZ_RUNS=1000 +make fuzz-run FUZZ_TARGET=documentation FUZZ_RUNS=10000 +``` + +Record the revision, nightly and cargo-fuzz versions, input timeout, registered +seed inventory, and actual run counts. A printed tool-availability skip is a +skipped stage. Preserve a failing input and stop investigation runs when a +production crash appears; follow [crash triage](#triaging-a-crash) before +promoting it to a seed. Local recovery seeds use a constructed valid/error pair +with an independently documented neighbor. Arbitrary random inputs do not +imply equivalent documentation after an unspecified source edit. + ### Fuzzing an order-dependent function `fix_includes` walks `HashMap`-ordered collections, which held @@ -256,15 +377,16 @@ that iterates an unordered collection, establish which of its outputs are order-stable. If a crash can depend on the order, the artifact is not a reproducer and the target is worse than nothing. -### Languages not fuzzed +### Language-specific walk targets -Recorded so the omission reads as a decision. `Mozjs` was measured +The tagged documentation target dispatches every enabled `LANG`. The +language-specific full-walk targets have a narrower scope. `Mozjs` was measured metric-equivalent to upstream JavaScript on real input (#507). `Preproc` is driven by `preproc_macro` and `preproc_includes`, whose first pass is a `PreprocParser` parse of the bytes; the C-family macro-masking lexer that `preproc_macro` then reaches is the same one `Mozcpp` runs, -reached there through `LANG::Cpp`, so no target parses the Gecko C++ -fork itself. The remaining grammars are +reached there through `LANG::Cpp`. The documentation target parses the Gecko +C++ fork through its own tag. The remaining full-walk omissions are upstream crates with no evidence pointing at them; adding one is a five-line file plus a `[[bin]]` stanza, and the bar for doing so is a reason, not a wish for symmetry. diff --git a/fuzz/Cargo.lock b/fuzz/Cargo.lock index 7adaeabd3..4b8969ae2 100644 --- a/fuzz/Cargo.lock +++ b/fuzz/Cargo.lock @@ -134,8 +134,11 @@ version = "0.0.0" dependencies = [ "arbitrary", "big-code-analysis", + "big-code-analysis-ast", "libfuzzer-sys", "serde_json", + "sha2", + "tree-sitter", ] [[package]] diff --git a/fuzz/Cargo.toml b/fuzz/Cargo.toml index 544c161b0..b39d88ca8 100644 --- a/fuzz/Cargo.toml +++ b/fuzz/Cargo.toml @@ -24,6 +24,10 @@ cargo-fuzz = true libfuzzer-sys = "0.4" arbitrary = { version = "1", features = ["derive"] } serde_json = "1" +tree-sitter = "=0.26.13" + +[dev-dependencies] +sha2 = "=0.11.1" # Path-only, with no `version` of its own: the fuzz crate is never published, # so pinning it would only add a second place to bump on every release. This @@ -37,6 +41,10 @@ serde_json = "1" path = ".." features = ["all-languages"] +[dependencies.big-code-analysis-ast] +path = "../big-code-analysis-ast" +features = ["all-languages"] + # Mirrors [workspace.lints] in ../Cargo.toml. This crate is excluded from # that workspace (see [workspace].exclude there), so it cannot inherit via # `lints.workspace = true` and needs its own copy — without it a crate @@ -142,3 +150,10 @@ path = "fuzz_targets/nested_depth.rs" test = false doc = false bench = false + +[[bin]] +name = "documentation" +path = "fuzz_targets/documentation.rs" +test = false +doc = false +bench = false diff --git a/fuzz/corpus/documentation/c-shared-owners b/fuzz/corpus/documentation/c-shared-owners new file mode 100644 index 0000000000000000000000000000000000000000..fc922f50c85fa64fb25e29b8db6edb7628f642c5 GIT binary patch literal 23 ecmd;PX3*EtN-RyuEYZ^E%FHWKNYqhCvIYP>wFSWd literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/cpp-candidate-qualification b/fuzz/corpus/documentation/cpp-candidate-qualification new file mode 100644 index 0000000000000000000000000000000000000000..25f5132e70aa69af9e38b04798f14346a84be103 GIT binary patch literal 61 zcmd;KW>C&dQ*iTfbmuC|&rDHB)5y##QK(R`RnWBNQclfF$xMSufaHOK`dV5JX?Y51 GTKWL=2oRkB literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/cpp-gathered b/fuzz/corpus/documentation/cpp-gathered new file mode 100644 index 0000000000000000000000000000000000000000..ef8450da39d5fff08eb7711cac3ed0c46c77ee88 GIT binary patch literal 28 gcmd;KWYE{rO4QQl0#Zppsw_V literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/cpp-pending-name b/fuzz/corpus/documentation/cpp-pending-name new file mode 100644 index 0000000000000000000000000000000000000000..f97c24a6ceee6220c7cdd99899254c2ab3a03dd4 GIT binary patch literal 36 mcmd;KWGKteOi@VF$jmEIsL-_L($~^*NXt`zit1=;=>q_-zzKu^ literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/cpp-reference-qualification b/fuzz/corpus/documentation/cpp-reference-qualification new file mode 100644 index 0000000000000000000000000000000000000000..9da8ee395940ebdf64bbcb26c54ac5c5479ed2c1 GIT binary patch literal 43 vcmd;KW+=S`KM>3TayUT*|3=DVb>i^pFd0 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-bash b/fuzz/corpus/documentation/dispatch-bash new file mode 100644 index 0000000000000000000000000000000000000000..b5d2b036cf6f5e05238b5870d4d2866ceeaf6306 GIT binary patch literal 34 pcmWe(WKdRcNJ%YDF3Kz@$;{7FNGwgsEa6Ji&{U{au(DRD1puj{3IYHC literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-c b/fuzz/corpus/documentation/dispatch-c new file mode 100644 index 0000000000000000000000000000000000000000..4df0f42ba841cb5546c9990b6dcd3f1ee1a4b492 GIT binary patch literal 29 hcmd;PWYE{rN-RyuEYZ^ED$CDIQApDOQJMj01&_f3;+NC literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-cpp b/fuzz/corpus/documentation/dispatch-cpp new file mode 100644 index 0000000000000000000000000000000000000000..65e283dc5164011e4e29ac1fda37dcd24c17a31b GIT binary patch literal 25 gcmd;KWYE{rN-RyuEYZ^ED$CDIQApF!RH&{6084QOtN;K2 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-csharp b/fuzz/corpus/documentation/dispatch-csharp new file mode 100644 index 0000000000000000000000000000000000000000..81e98a9738beeb0dbe51b1416cfcd0238a99a502 GIT binary patch literal 41 pcmZQ&WYE{ww<#{o%}p$-v`Z{a$t>_>sICP7MDhld literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-irules b/fuzz/corpus/documentation/dispatch-irules new file mode 100644 index 0000000000000000000000000000000000000000..69c39c01b0d41185e179068cf0ba1074e199faca GIT binary patch literal 32 ncmWe*WKdQ}EKSKQ;VREa%~S9Q2?>Y~at#c14GvML=Bfn%jPVIL literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-java b/fuzz/corpus/documentation/dispatch-java new file mode 100644 index 0000000000000000000000000000000000000000..4220e6096aadd23f6a84539beb56a7d33ff412e9 GIT binary patch literal 22 dcmZQ#WYE{wPb^KzEa6JdNh~f_a8{_U1pqtW215V< literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-javascript b/fuzz/corpus/documentation/dispatch-javascript new file mode 100644 index 0000000000000000000000000000000000000000..b56e0301e81a4c8d1371a0afc27be3250e9d578e GIT binary patch literal 29 kcmZQ)WYE{rN-RyuEYZ^EN-NDvF3HT#Q%KX$RH&{60Bza`TL1t6 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-kotlin b/fuzz/corpus/documentation/dispatch-kotlin new file mode 100644 index 0000000000000000000000000000000000000000..4d25ac19d90f230c901859599e9b4332e57c7c8b GIT binary patch literal 24 fcmZQ(WYE{rN-RyuEYZ^EN-ND%NYl_%sICP7Lf!^C literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-lua b/fuzz/corpus/documentation/dispatch-lua new file mode 100644 index 0000000000000000000000000000000000000000..f6f0dfa0db82072968b3ef2848dd1507e54c8fdc GIT binary patch literal 40 vcmWe+WXR1=Da}dMP|8)($SB~_*V0l*EKSKQQP9%oN-NDvF3HT#Q%KX$RH&{60I!P*X8-^I literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/dispatch-preproc b/fuzz/corpus/documentation/dispatch-preproc new file mode 100644 index 0000000000000000000000000000000000000000..2e521da1fbde2423e4149a50423344d3d6abc1e4 GIT binary patch literal 15 Wcmb1OWKd2?P0P$nRfte9 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/go-directive-off b/fuzz/corpus/documentation/go-directive-off new file mode 100644 index 0000000000000000000000000000000000000000..557d1682d273ac71a0915fb85e35e2b5bd32993a GIT binary patch literal 31 mcmd;QWYE`7&$miX%}XsxEJ;-;$Do9MuPE1c#C;$MEuL=$T literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/go-directive-on b/fuzz/corpus/documentation/go-directive-on new file mode 100644 index 000000000..d3d832c9d --- /dev/null +++ b/fuzz/corpus/documentation/go-directive-on @@ -0,0 +1,2 @@ +@//go:generate tool +package p \ No newline at end of file diff --git a/fuzz/corpus/documentation/java-crlf-token-pieces b/fuzz/corpus/documentation/java-crlf-token-pieces new file mode 100644 index 0000000000000000000000000000000000000000..2ab1640a430f4c7184d97228599712e300fa1443 GIT binary patch literal 23 ecmZQ#Wzg5sO628A($eQj&PgmTR&Z9Rt_1)va0OWa literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/java-empty b/fuzz/corpus/documentation/java-empty new file mode 100644 index 0000000000000000000000000000000000000000..bf03b48133c98fbb871b8816bc5675cfec6bd65c GIT binary patch literal 29 icmZQ#WYE{rQpnFqQP9%o0y6cvl5-M^ixr#|s%rsJMFzG2 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/java-evidence b/fuzz/corpus/documentation/java-evidence new file mode 100644 index 000000000..ccfd52f5b --- /dev/null +++ b/fuzz/corpus/documentation/java-evidence @@ -0,0 +1,3 @@ + /** old */ +/**/ +class C {} \ No newline at end of file diff --git a/fuzz/corpus/documentation/java-scalar-pieces b/fuzz/corpus/documentation/java-scalar-pieces new file mode 100644 index 0000000000000000000000000000000000000000..47dd4320e00503de2f53c5f60d2c8845ac227e3c GIT binary patch literal 21 ccmZQ#Wzg5sI=oU#pDQ^hvA9^lS)sZX05;ME>i_@% literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/java-source-gap b/fuzz/corpus/documentation/java-source-gap new file mode 100644 index 0000000000000000000000000000000000000000..0095539a7b36735c69b6e657be0b2120b21cae22 GIT binary patch literal 22 dcmZQ#Wzg5sN@PgV(&tLfNh~f_a8{_U1pqD{1wsG- literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/kotlin-known-and-pending b/fuzz/corpus/documentation/kotlin-known-and-pending new file mode 100644 index 0000000000000000000000000000000000000000..fbd22d2ecbc2d6ab8feaef9773abda533456ee41 GIT binary patch literal 35 ncmZQ(X3*EtO3N%NF45BGN-ND%NYl_%0173Rrep$z6sl_hmuv}O literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/kotlin-pending-owner b/fuzz/corpus/documentation/kotlin-pending-owner new file mode 100644 index 0000000000000000000000000000000000000000..6ab4841400545fc564a27571ee95ab4eeda28c3d GIT binary patch literal 33 ocmZQ(WJu0QEG|}X*3j3|N-RyuEYZ?eC`-&ysIXG-%q!6Z0Ftl?LI3~& literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/php-documentor-deferred b/fuzz/corpus/documentation/php-documentor-deferred new file mode 100644 index 0000000000000000000000000000000000000000..cd39969ffd785301e9e36ae672709afc19666dda GIT binary patch literal 37 scmZQ$;IOeT$SB~_*V0l*EKSKQQP9%oN-NDvF3HT#Q%KX$RH&{60I+`wZU6uP literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/ruby-rdoc-deferred b/fuzz/corpus/documentation/ruby-rdoc-deferred new file mode 100644 index 0000000000000000000000000000000000000000..0198632881e25b7e43f960008b0bdafad1e5f81f GIT binary patch literal 20 bcmWe&;8RveEKSKQ;YvwOQ%K`V%}W6QFyjSz literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-active-scope b/fuzz/corpus/documentation/rust-active-scope new file mode 100644 index 0000000000000000000000000000000000000000..788dcb74519ed76e1acee6d3a8dfb888061483e7 GIT binary patch literal 21 ccmZSJVbIstPb^KzEa6JaQ%KX$RH&{605f0(egFUf literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-attribute b/fuzz/corpus/documentation/rust-attribute new file mode 100644 index 0000000000000000000000000000000000000000..c9a7fbf488f3a1d146e620a643db3d1db2bd72bf GIT binary patch literal 52 zcmZQzWYE{wS4hh&DlXwtj!wx>R(6qN! HsO16xYS|7( literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-cancelled-scope b/fuzz/corpus/documentation/rust-cancelled-scope new file mode 100644 index 0000000000000000000000000000000000000000..4d1dc3d863f0f2c4d459ea886688ace33c2355ad GIT binary patch literal 21 ccmZSJV9?jsPb^KzEa6JaQ%KX$RH&{605cE;dH?_b literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-crlf b/fuzz/corpus/documentation/rust-crlf new file mode 100644 index 0000000000000000000000000000000000000000..6a1129329573559070a04fcd5a6596dc21f7396c GIT binary patch literal 47 wcmZQzWYE{wSIAB+DB538Kq^WSGjn*k02O!(-T(jq literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-eof b/fuzz/corpus/documentation/rust-eof new file mode 100644 index 0000000000000000000000000000000000000000..9a97f8a1e62312c9f8a2b60186e2c221da1b35f8 GIT binary patch literal 31 mcmZQzWJt?XNYl_%s8%S?FUr=?w6|8M<S_Vg CqY+O4 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-valid-neighbor b/fuzz/corpus/documentation/rust-valid-neighbor new file mode 100644 index 0000000000000000000000000000000000000000..ca4b64b7ae11fafaa0c26cc2e965e868aacb3f92 GIT binary patch literal 58 zcmZQzWJt?XNGi(DPR-NMRH# { + pub language: LANG, + pub mode: Mode, + pub repeat: bool, + pub identity: bool, + pub options: DocumentationOptions, + pub source: &'a [u8], +} + +impl<'a> Input<'a> { + pub fn decode(bytes: &'a [u8]) -> Result { + let [tag, mode, flags, source @ ..] = bytes else { + return Err(Skip::ShortHeader); + }; + let language = *LANGUAGES + .get(usize::from(*tag)) + .ok_or(Skip::UnknownLanguage)?; + if mode & 0xf0 != 0 || flags & 0x80 != 0 { + return Err(Skip::ReservedBits); + } + let profile = *PROFILES + .get(usize::from(flags & 0x1f)) + .ok_or(Skip::UnknownProfile)?; + Ok(Self { + language, + mode: match (mode >> 2) & 3 { + 0 => Mode::Raw, + 1 => Mode::IncludedRanges, + 2 => Mode::CancelledScope, + _ => Mode::ActiveScope, + }, + repeat: mode & 1 != 0, + identity: mode & 2 != 0, + options: DocumentationOptions { + profile, + retain_unbound: flags & 0x20 != 0, + retain_directives: flags & 0x40 != 0, + }, + source, + }) + } +} + +pub(super) fn expected_profile( + language: LANG, + requested: Profile, +) -> Result { + let default = match language { + LANG::Rust => Profile::Rust, + LANG::Python => Profile::Python, + LANG::Java => Profile::Javadoc, + LANG::Kotlin => Profile::Kdoc, + LANG::Groovy => Profile::Groovydoc, + LANG::Csharp => Profile::CsharpXml, + LANG::Php => Profile::BcaPhpSource, + LANG::Javascript | LANG::Mozjs => Profile::Jsdoc, + LANG::Typescript | LANG::Tsx => Profile::BcaTypescriptSource, + LANG::C | LANG::Cpp | LANG::Mozcpp | LANG::Objc => Profile::Doxygen, + LANG::Go => Profile::GoDoc, + LANG::Ruby => Profile::Yard, + LANG::Lua => Profile::Ldoc, + LANG::Perl => Profile::Pod, + LANG::Elixir => Profile::Elixir, + LANG::Bash => Profile::Shdoc, + LANG::Tcl => Profile::Ruff, + LANG::Irules => Profile::Irules, + LANG::Ccomment | LANG::Preproc => Profile::Helper, + }; + let profile = if requested == Profile::Default { + default + } else { + requested + }; + let alternate = matches!( + (language, profile), + (LANG::Php, Profile::PhpDocumentor) | (LANG::Ruby, Profile::Rdoc) + ); + if profile != default && !alternate { + Err(CollectionError::UnsupportedProfile { language, profile }) + } else if alternate + || matches!( + language, + LANG::Python | LANG::Perl | LANG::Elixir | LANG::Bash | LANG::Tcl | LANG::Irules + ) + { + Err(CollectionError::AdapterUnavailable { language, profile }) + } else { + Ok(profile) + } +} diff --git a/fuzz/src/documentation/maps.rs b/fuzz/src/documentation/maps.rs new file mode 100644 index 000000000..05756d5ff --- /dev/null +++ b/fuzz/src/documentation/maps.rs @@ -0,0 +1,165 @@ +use big_code_analysis_ast::documentation::*; +use std::ops::Range; + +use super::{Check, MAX_QUERIES, require}; + +pub(super) struct Coverage<'s> { + source: &'s [u8], + excluded: Vec, +} + +impl<'s> Coverage<'s> { + pub fn new(tree: &tree_sitter::Tree, source: &'s [u8]) -> Self { + let ranges = tree.included_ranges(); + let mut at = 0; + let mut excluded = Vec::with_capacity(source.len() + 1); + excluded.push(0); + for byte in 0..source.len() { + while ranges.get(at).is_some_and(|range| range.end_byte <= byte) { + at += 1; + } + let included = ranges.get(at).is_some_and(|range| range.start_byte <= byte); + excluded.push(excluded[byte] + usize::from(!included)); + } + Self { source, excluded } + } + + pub fn piece(&self, piece: &SourcePiece<'_>) -> Check { + let range = piece.range(); + require( + range.start < range.end && range.end <= self.source.len(), + "piece bounds", + )?; + require( + self.source.get(range.clone()) == Some(piece.bytes()), + "piece bytes", + )?; + require( + self.excluded[range.start] == self.excluded[range.end], + "piece crosses excluded bytes", + ) + } + + pub fn pieces(&self, pieces: &[SourcePiece<'_>]) -> Check { + require(!pieces.is_empty(), "empty raw spelling")?; + let mut end = 0; + for piece in pieces { + self.piece(piece)?; + require(end <= piece.range().start, "piece source order")?; + end = piece.range().end; + } + Ok(()) + } +} + +pub(super) fn validate(complete: CompleteText<'_, '_>, coverage: &Coverage<'_>) -> Check { + let mut end = 0; + for mapping in complete.mappings() { + let range = mapping.output.range(); + require( + range.start == end && range.start < range.end && range.end <= complete.text().len(), + "map must partition output", + )?; + match &mapping.origin { + Origin::Copied(pieces) => { + coverage.pieces(pieces.pieces())?; + require( + pieces.pieces().len() == 1, + "copied map run must be contiguous", + )?; + require( + complete.text().as_bytes().get(range.clone()) + == Some(pieces.pieces()[0].bytes()), + "copied output differs from source", + )?; + } + Origin::Decoded(pieces) | Origin::Expanded(pieces) => { + coverage.pieces(pieces.pieces())? + } + Origin::Synthetic => {} + _ => return Err("unhandled origin variant"), + } + // Stored runs can divide a scalar when included source pieces divide it. + end = range.end; + } + require( + end == complete.text().len(), + "map does not cover complete text", + ) +} + +pub(super) fn queries(complete: CompleteText<'_, '_>, selector: u8) -> Check { + let text = complete.text(); + let len = text.len(); + let boundaries: Vec<_> = text.char_indices().map(|(at, _)| at).chain([len]).collect(); + let chosen = usize::from(selector) % boundaries.len(); + let start = boundaries[chosen]; + let end = boundaries.get(chosen + 1).copied().unwrap_or(len); + let late = boundaries[boundaries.len().saturating_sub(2)]; + let split = text + .char_indices() + .find(|(_, scalar)| scalar.len_utf8() > 1) + .map_or(len + 1, |(at, _)| at + 1); + let ranges: [Range; MAX_QUERIES] = [ + 0..len, + len..len, + Range { start: 1, end: 0 }, + 0..len + 1, + split..split, + start..end, + late..len, + 0..0, + ]; + for query in ranges { + let expected = if query.start > query.end || query.end > len { + Err(TextRangeError::Bounds) + } else if !text.is_char_boundary(query.start) || !text.is_char_boundary(query.end) { + Err(TextRangeError::ScalarBoundary) + } else { + Ok(()) + }; + match (expected, complete.origins(query.clone())) { + (Err(expected), Err(actual)) => { + require(expected == actual, "wrong map query rejection")? + } + (Ok(()), Ok(mut actual)) => { + if !query.is_empty() { + for mapping in complete.mappings() { + let range = mapping.output.range(); + let intersection = range.start.max(query.start)..range.end.min(query.end); + if intersection.start >= intersection.end { + continue; + } + let portion = actual.next().ok_or("missing map query portion")?; + require(portion.output == intersection, "map query clipping")?; + match (&mapping.origin, portion.origin) { + (Origin::Copied(pieces), OriginView::Copied(piece)) => { + let start = pieces.pieces()[0].range().start + intersection.start + - range.start; + require( + piece.range() == (start..start + intersection.len()), + "copied query source offset", + )?; + require( + piece.bytes() == &text.as_bytes()[intersection], + "copied query bytes", + )?; + } + (Origin::Decoded(pieces), OriginView::Decoded(actual)) + | (Origin::Expanded(pieces), OriginView::Expanded(actual)) => require( + pieces.pieces() == actual, + "transformed query lost token pieces", + )?, + (Origin::Synthetic, OriginView::Synthetic) => {} + _ => return Err("query changed origin kind"), + } + } + } + require(actual.next().is_none(), "extra map query portion")?; + require(actual.next().is_none(), "map iterator is not fused")?; + } + _ => return Err("map query acceptance mismatch"), + } + } + Ok(()) +} diff --git a/fuzz/src/documentation/mod.rs b/fuzz/src/documentation/mod.rs new file mode 100644 index 000000000..30c01e2bb --- /dev/null +++ b/fuzz/src/documentation/mod.rs @@ -0,0 +1,270 @@ +//! Bounded source-documentation properties shared by raw and tagged targets. + +mod header; +mod maps; +mod properties; +#[cfg(test)] +mod tests; + +use big_code_analysis::{Ast, LANG}; +use big_code_analysis_ast::{AnyParser, cancel::ParseCancel, documentation::*}; +use header::{Input, Mode, expected_profile}; + +/// Maximum exact source length inspected by the additional documentation operation. +pub const MAX_SOURCE: usize = 32 * 1024; +pub(super) const MAX_QUERIES: usize = 8; +pub(super) const MAX_STRUCTURE: usize = 256; + +/// A classified input that intentionally does not reach documentation collection. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Skip { + /// Fewer than three header bytes. + ShortHeader, + /// Language tag outside the version-one table. + UnknownLanguage, + /// Reserved operation or version bits are set. + ReservedBits, + /// Profile selector outside the version-one table. + UnknownProfile, + /// The exact source exceeds the harness budget. + Oversize, + /// Included-range input has no included bytes or too many ranges. + IncludedRangeLimit, +} + +/// What the checker actually executed, distinct from an empty extraction. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + /// Header or resource rejection before parsing. + Skipped(Skip), + /// A recognized unimplemented adapter or incompatible profile was rejected. + Rejected(CollectionError), + /// A helper grammar explicitly has no source declaration model. + Helper, + /// An implemented adapter completed all selected properties. + Checked, +} + +pub(super) type Check = Result<(), &'static str>; + +struct Parsed<'s> { + language: LANG, + tree: &'s tree_sitter::Tree, + source: &'s [u8], + typed: Option<&'s AnyParser>, +} + +impl<'s> Parsed<'s> { + fn collect( + &self, + options: &DocumentationOptions, + ) -> Result, CollectionError> { + let context = DocumentationContext::default(); + if let Some(parser) = self.typed { + parser.documentation(&context, options) + } else { + collect(self.language, self.tree, self.source, &context, options) + } + } +} + +fn require(condition: bool, message: &'static str) -> Check { + if condition { Ok(()) } else { Err(message) } +} + +/// Run the default check on the source actually held by an existing parse. +/// +/// # Errors +/// Returns the violated invariant; oversize input skips only this operation. +pub fn check_ast(ast: &Ast) -> Result { + if ast.source().len() > MAX_SOURCE { + return Ok(Outcome::Skipped(Skip::Oversize)); + } + check_parse( + &Parsed { + language: ast.language(), + tree: ast.as_tree_sitter(), + source: ast.source(), + typed: None, + }, + &DocumentationOptions::default(), + false, + false, + |_, _| Ok(()), + ) +} + +/// Decode the version-one header, parse its unchanged payload once, and check it. +/// +/// # Errors +/// Returns a property violation, including an unexpected collection failure. +pub fn exercise(bytes: &[u8]) -> Result { + exercise_with(bytes, |_, _| Ok(())) +} + +fn exercise_with( + bytes: &[u8], + inspect: impl FnOnce(Option<&DocumentationIndex<'_>>, &tree_sitter::Tree) -> Check, +) -> Result { + let input = match Input::decode(bytes) { + Ok(input) => input, + Err(skip) => return Ok(Outcome::Skipped(skip)), + }; + if input.source.len() > MAX_SOURCE { + return Ok(Outcome::Skipped(Skip::Oversize)); + } + if input.mode == Mode::IncludedRanges { + let Some(ranges) = included_ranges(input.source) else { + return Ok(Outcome::Skipped(Skip::IncludedRangeLimit)); + }; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language( + &input + .language + .tree_sitter_language() + .map_err(|_| "language unavailable")?, + ) + .map_err(|_| "grammar setup")?; + parser + .set_included_ranges(&ranges) + .map_err(|_| "range setup")?; + let tree = parser + .parse(input.source, None) + .ok_or("included parse aborted")?; + return check_parse( + &Parsed { + language: input.language, + tree: &tree, + source: input.source, + typed: None, + }, + &input.options, + input.repeat, + input.identity, + inspect, + ); + } + let parser = AnyParser::parse(input.language, input.source.to_vec(), None, None) + .map_err(|_| "primary parse failed")?; + require(parser.code() == input.source, "tag payload changed")?; + let context = DocumentationContext::default(); + if input.mode == Mode::CancelledScope { + let flag = ParseCancel::new(); + flag.cancel(); + require( + matches!( + flag.run(|| parser.documentation(&context, &input.options)), + Err(CollectionError::Cancelled) + ), + "active cancellation not propagated", + )?; + } + let check = || { + check_parse( + &Parsed { + language: input.language, + tree: parser.ts_tree(), + source: parser.code(), + typed: Some(&parser), + }, + &input.options, + input.repeat, + input.identity, + inspect, + ) + }; + if input.mode == Mode::ActiveScope { + ParseCancel::new().run(check) + } else { + check() + } +} + +fn check_parse( + parsed: &Parsed<'_>, + options: &DocumentationOptions, + repeat: bool, + identity: bool, + inspect: impl FnOnce(Option<&DocumentationIndex<'_>>, &tree_sitter::Tree) -> Check, +) -> Result { + let Parsed { + language, + tree, + source, + .. + } = *parsed; + let result = parsed.collect(options); + let profile = match expected_profile(language, options.profile) { + Ok(profile) => profile, + Err(expected) => { + require( + result.err() == Some(expected), + "wrong adapter/profile rejection", + )?; + inspect(None, tree)?; + return Ok(Outcome::Rejected(expected)); + } + }; + let index = result.map_err(|_| "unexpected collection failure")?; + require( + index.source() == source && index.profile() == profile, + "index source/profile mismatch", + )?; + properties::check(&index, tree, source)?; + if identity { + properties::negative_nodes(&index, tree)?; + } + if repeat { + let second = parsed + .collect(options) + .map_err(|_| "repeat collection failed")?; + properties::repeat(&index, &second)?; + } + inspect(Some(&index), tree)?; + if matches!(language, LANG::Ccomment | LANG::Preproc) { + require( + index.capability() == Capability::NoDeclarationModel, + "helper capability", + )?; + require( + index.documents().len() == 0 && index.associations().len() == 0, + "helper emitted documentation", + )?; + Ok(Outcome::Helper) + } else { + require( + index.capability() == Capability::Partial, + "adapter capability", + )?; + Ok(Outcome::Checked) + } +} + +// Every non-NUL byte is a separate included range, deliberately allowing adjacent +// ranges to divide a scalar. NUL bytes create gaps without changing coordinates. +fn included_ranges(source: &[u8]) -> Option> { + let mut ranges = Vec::new(); + let mut point = tree_sitter::Point::new(0, 0); + for (at, byte) in source.iter().copied().enumerate() { + let start_point = point; + if byte == b'\n' { + point.row += 1; + point.column = 0; + } else { + point.column += 1; + } + if byte != 0 { + ranges.push(tree_sitter::Range { + start_byte: at, + start_point, + end_byte: at + 1, + end_point: point, + }); + if ranges.len() > MAX_STRUCTURE { + return None; + } + } + } + (!ranges.is_empty()).then_some(ranges) +} diff --git a/fuzz/src/documentation/properties.rs b/fuzz/src/documentation/properties.rs new file mode 100644 index 000000000..27b2ae412 --- /dev/null +++ b/fuzz/src/documentation/properties.rs @@ -0,0 +1,700 @@ +use big_code_analysis_ast::documentation::*; +use std::collections::HashMap; + +use super::{Check, MAX_QUERIES, maps, require}; + +fn address(fact: FactRef<'_, T>) -> *const T { + std::ptr::from_ref(fact.get()) +} + +fn selected(length: usize, count: usize, selector: u8) -> Vec { + if length == 0 { + return Vec::new(); + } + let mut selected = vec![length - 1]; + for n in 0..count - 1 { + let at = (usize::from(selector) + n * length / count) % length; + if !selected.contains(&at) { + selected.push(at); + } + } + selected +} + +#[allow(clippy::too_many_lines)] // One bounded pass validates each retained fact family. +pub(super) fn check( + index: &DocumentationIndex<'_>, + tree: &tree_sitter::Tree, + source: &[u8], +) -> Check { + let coverage = maps::Coverage::new(tree, source); + for fragment in index.facts().fragments() { + coverage.pieces(fragment.get().source().pieces())?; + if let Some(node) = fragment.get().node() { + require( + node.node().into_raw().tree == tree.root_node().into_raw().tree, + "fragment evidence is foreign", + )?; + require( + node.node().end_byte() <= source.len(), + "fragment evidence bounds", + )?; + } + } + let mut last = None; + let mut mapped = None; + for document in index.documents() { + let key = index + .facts() + .document_order(document) + .map_err(|_| "document order key")?; + require( + last.is_none_or(|last| last <= key), + "documents out of source order", + )?; + last = Some(key); + require( + document.get().fragment_count() > 0, + "document has no fragments", + )?; + let mut fragment_end = 0; + for at in 0..document.get().fragment_count() { + let fragment = index + .facts() + .document_fragment(document, at) + .map_err(|_| "document fragment navigation")?; + let pieces = fragment.get().source().pieces(); + require( + pieces + .first() + .is_some_and(|piece| piece.range().start >= fragment_end), + "document fragment order", + )?; + fragment_end = pieces.last().ok_or("empty fragment")?.range().end; + } + require( + index + .facts() + .document_fragment(document, document.get().fragment_count()) + .err() + == Some(FactError::MissingRecord), + "missing fragment accepted", + )?; + let complete = index + .complete_text(document) + .map_err(|_| "same-index text handle rejected")?; + match (document.get().content(), complete) { + (Content::Complete { text, mappings, .. }, Some(complete)) => { + require( + complete.text() == text && complete.mappings() == mappings, + "retained text differs", + )?; + maps::validate(complete, &coverage)?; + mapped = Some(complete); + } + (Content::Complete { .. }, None) => return Err("complete text unavailable"), + (_, Some(_)) => return Err("noncomplete state flattened to text"), + (_, None) => {} + } + if let Some(cleaned) = index + .source_cleaned_text(document) + .map_err(|_| "cleaned text handle")? + { + maps::validate(cleaned, &coverage)?; + } + } + if let Some(complete) = mapped { + maps::queries(complete, source.last().copied().unwrap_or(0))?; + } + for owner in index.facts().owners() { + match owner.get() { + Owner::Slot(slot) => { + coverage.pieces(slot.source.pieces())?; + index + .facts() + .slot_enclosing(owner) + .map_err(|_| "slot enclosure")?; + } + Owner::Group(group) => { + for piece in &group.pieces { + coverage.pieces(piece.source.pieces())?; + } + } + Owner::Virtual(owner) => { + coverage.pieces(owner.name.pieces())?; + coverage.pieces(owner.declaration.pieces())?; + } + Owner::Node(_) | Owner::File(_) => {} + _ => return Err("unhandled owner variant"), + } + } + associations(index)?; + qualifications(index)?; + for assessment in index.assessments() { + require( + !assessment.get().reason.is_empty(), + "assessment reason absent", + )?; + index + .assessed_document(assessment) + .map_err(|_| "assessment document navigation")?; + } + for evidence in index.evidence() { + index + .evidence_fragment(evidence) + .map_err(|_| "candidate evidence navigation")?; + } + owner_queries(index, source.first().copied().unwrap_or(0))?; + node_queries(index, tree, source.last().copied().unwrap_or(0)) +} + +fn owner_anchor(owner: &Owner<'_>) -> (usize, usize) { + match owner { + Owner::Node(node) | Owner::File(node) => (node.node().start_byte(), 0), + Owner::Slot(slot) => (slot.source.pieces()[0].range().start, slot.ordinal), + Owner::Group(group) => (group.scope.node().start_byte(), 0), + Owner::Virtual(owner) => (owner.declaration.pieces()[0].range().start, 0), + _ => (0, 0), + } +} + +fn associations(index: &DocumentationIndex<'_>) -> Check { + let mut last = None; + for association in index.associations() { + let document = index + .facts() + .associated_document(association) + .map_err(|_| "association document navigation")?; + let key = index + .facts() + .document_order(document) + .map_err(|_| "association document order")?; + let anchor = if association.get().owner_count() == 0 { + (0, 0) + } else { + owner_anchor( + index + .facts() + .associated_owner(association, 0) + .map_err(|_| "association owner navigation")? + .get(), + ) + }; + require( + last.is_none_or(|last| last <= (key, anchor)), + "associations out of source order", + )?; + last = Some((key, anchor)); + for at in 0..association.get().owner_count() { + index + .facts() + .associated_owner(association, at) + .map_err(|_| "association owner navigation")?; + } + require( + index + .facts() + .associated_owner(association, association.get().owner_count()) + .err() + == Some(FactError::MissingRecord), + "missing owner accepted", + )?; + require( + association.get().convention.name() == index.profile().name(), + "association convention", + )?; + } + Ok(()) +} + +fn qualifications(index: &DocumentationIndex<'_>) -> Check { + let mut by_document: HashMap<_, Vec<_>> = HashMap::new(); + let mut last = None; + for qualification in index.qualifications() { + let fact = qualification.get(); + let document = index + .qualified_document(qualification) + .map_err(|_| "qualified document")?; + let owner = index + .qualified_owner(qualification) + .map_err(|_| "qualified owner")?; + require( + owner.is_some() == (fact.subject == QualificationSubject::Candidate), + "qualification subject identity", + )?; + let rank = match fact.reason { + UnresolvedReason::Conditional => 0, + UnresolvedReason::GrammarBoundary => 1, + _ => return Err("unknown qualification reason"), + }; + let key = ( + index + .facts() + .document_order(document) + .map_err(|_| "qualified document order")?, + fact.node.node().start_byte(), + fact.node.node().end_byte(), + rank, + ); + require( + last.is_none_or(|last| last <= key), + "qualifications out of source order", + )?; + last = Some(key); + by_document + .entry(address(document)) + .or_default() + .push(qualification); + } + for document in index.documents() { + let expected = by_document.remove(&address(document)).unwrap_or_default(); + require( + index + .document_qualifications(document) + .map_err(|_| "document qualification lookup")? + .eq(expected), + "document qualification adjacency", + )?; + } + require( + by_document.is_empty(), + "qualification refers to unenumerated document", + ) +} + +fn owner_queries(index: &DocumentationIndex<'_>, selector: u8) -> Check { + let owners: Vec<_> = index.facts().owners().collect(); + for at in selected(owners.len(), MAX_QUERIES / 2, selector) { + let owner = owners[at]; + let query = index + .owner_associations(owner) + .map_err(|_| "same-index owner rejected")?; + let mut expected = Vec::new(); + for association in index.associations() { + for position in 0..association.get().owner_count() { + if index + .facts() + .associated_owner(association, position) + .map_err(|_| "owner membership")? + == owner + { + expected.push(association); + } + } + } + require( + query.associations().eq(expected), + "owner association adjacency", + )?; + let mut expected = Vec::new(); + for qualification in index.qualifications() { + if index + .qualified_owner(qualification) + .map_err(|_| "qualification owner")? + == Some(owner) + { + expected.push(qualification); + } + } + require( + query.qualifications().eq(expected), + "owner qualification adjacency", + )?; + require( + !query.projection_pending(), + "concrete owner projection pending", + )?; + for assessment in query.assessments() { + index + .assessed_document(assessment) + .map_err(|_| "owner assessment foreign")?; + } + } + Ok(()) +} + +fn node_queries(index: &DocumentationIndex<'_>, tree: &tree_sitter::Tree, selector: u8) -> Check { + let mut nodes = Vec::new(); + let mut cursor = tree.walk(); + loop { + nodes.push(cursor.node()); + if cursor.goto_first_child() { + continue; + } + loop { + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return selected_nodes(index, &nodes, selector); + } + } + } +} + +fn selected_nodes( + index: &DocumentationIndex<'_>, + nodes: &[tree_sitter::Node<'_>], + selector: u8, +) -> Check { + for at in selected(nodes.len(), MAX_QUERIES / 2, selector) { + let node = nodes[at]; + match index.node_projection(node) { + Err(OwnerError::UnsupportedOwner) => { + require( + matches!( + index.node_associations(node), + Err(OwnerError::UnsupportedOwner) + ), + "unsupported projection query", + )?; + require( + matches!(index.node_owners(node), Err(OwnerError::UnsupportedOwner)), + "unsupported owners query", + )?; + } + Ok(projection) if projection.pending() => { + require( + projection.owners().len() == 0 && projection.assessments().next().is_some(), + "pending projection lost assessment", + )?; + require( + matches!(index.node_owners(node), Err(OwnerError::PendingOwner)), + "pending owners query", + )?; + let query = index + .node_associations(node) + .map_err(|_| "pending query must remain inspectable")?; + require( + query.projection_pending() && query.assessments().next().is_some(), + "pending query flattened to empty", + )?; + } + Ok(projection) => { + let owners: Vec<_> = projection.owners().collect(); + require( + index + .node_owners(node) + .map_err(|_| "known projection owners")? + .eq(owners.iter().copied()), + "projection owner enumeration", + )?; + match owners.len() { + 0 => require( + matches!( + index.node_associations(node), + Err(OwnerError::UnsupportedOwner) + ), + "empty projection query", + )?, + 1 => { + let query = index + .node_associations(node) + .map_err(|_| "known node query")?; + let expected = index + .owner_associations(owners[0]) + .map_err(|_| "known owner query")?; + require( + query.associations().eq(expected.associations()), + "node-owner association agreement", + )?; + require( + query.assessments().eq(expected.assessments()), + "node-owner pending agreement", + )?; + require( + query.qualifications().eq(expected.qualifications()), + "node-owner qualification agreement", + )?; + } + _ => require( + matches!( + index.node_associations(node), + Err(OwnerError::MultipleOwners) + ), + "multi-owner projection query", + )?, + } + } + _ => return Err("canonical cursor node rejected"), + } + } + Ok(()) +} + +pub(super) fn negative_nodes(index: &DocumentationIndex<'_>, tree: &tree_sitter::Tree) -> Check { + let cloned = tree.clone(); + require( + matches!( + index.node_projection(cloned.root_node()), + Err(OwnerError::Source(SourceError::ForeignTree)) + ), + "cloned tree accepted", + )?; + let shifted = tree.root_node_with_offset(1, tree_sitter::Point::new(0, 1)); + require( + matches!( + index.node_projection(shifted), + Err(OwnerError::Source(SourceError::NoncanonicalNode)) + ), + "shifted node accepted", + )?; + let mut edited = tree.root_node(); + edited.edit(&tree_sitter::InputEdit { + start_byte: 0, + old_end_byte: 0, + new_end_byte: 1, + start_position: tree_sitter::Point::new(0, 0), + old_end_position: tree_sitter::Point::new(0, 0), + new_end_position: tree_sitter::Point::new(0, 1), + }); + require( + matches!( + index.node_projection(edited), + Err(OwnerError::Source(SourceError::NoncanonicalNode)) + ), + "edited node accepted", + ) +} + +#[allow(clippy::too_many_lines)] // Compare each public record family in observed order. +pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationIndex<'s>) -> Check { + require( + first.documents().len() == second.documents().len() + && first.associations().len() == second.associations().len() + && first.facts().fragments().len() == second.facts().fragments().len() + && first.facts().owners().len() == second.facts().owners().len() + && first.assessments().len() == second.assessments().len() + && first.evidence().len() == second.evidence().len() + && first.qualifications().len() == second.qualifications().len(), + "nondeterministic record count", + )?; + for (left, right) in first.facts().fragments().zip(second.facts().fragments()) { + require( + left.get().source() == right.get().source() && left.get().form() == right.get().form(), + "nondeterministic retained fragments", + )?; + } + let first_owners: HashMap<_, _> = first + .facts() + .owners() + .enumerate() + .map(|(at, owner)| (address(owner), at)) + .collect(); + let second_owners: HashMap<_, _> = second + .facts() + .owners() + .enumerate() + .map(|(at, owner)| (address(owner), at)) + .collect(); + for (left, right) in first.facts().owners().zip(second.facts().owners()) { + require( + std::mem::discriminant(left.get()) == std::mem::discriminant(right.get()) + && owner_anchor(left.get()) == owner_anchor(right.get()), + "nondeterministic owners", + )?; + } + for (left, right) in first.documents().zip(second.documents()) { + require( + first + .facts() + .document_order(left) + .map_err(|_| "first document order")? + == second + .facts() + .document_order(right) + .map_err(|_| "second document order")?, + "nondeterministic document order", + )?; + require( + left.get().composition() == right.get().composition() + && left.get().fragment_count() == right.get().fragment_count(), + "nondeterministic composition", + )?; + for at in 0..left.get().fragment_count() { + let a = first + .facts() + .document_fragment(left, at) + .map_err(|_| "first fragment")?; + let b = second + .facts() + .document_fragment(right, at) + .map_err(|_| "second fragment")?; + require( + a.get().source() == b.get().source() && a.get().form() == b.get().form(), + "nondeterministic fragments", + )?; + } + match (left.get().content(), right.get().content()) { + ( + Content::Complete { + text: a, + mappings: am, + .. + }, + Content::Complete { + text: b, + mappings: bm, + .. + }, + ) => require(a == b && am == bm, "nondeterministic complete content")?, + (Content::Unavailable(a), Content::Unavailable(b)) => { + require(a == b, "nondeterministic unavailable reason")? + } + (a, b) => require( + std::mem::discriminant(a) == std::mem::discriminant(b), + "nondeterministic content state", + )?, + } + require( + second.complete_text(left).err() == Some(FactError::ForeignIndex), + "foreign document accepted", + )?; + } + for (left, right) in first.associations().zip(second.associations()) { + require( + left.get().resolution == right.get().resolution + && left.get().publication == right.get().publication + && left.get().owner_count() == right.get().owner_count(), + "nondeterministic association", + )?; + let a = first + .facts() + .associated_document(left) + .map_err(|_| "first associated document")?; + let b = second + .facts() + .associated_document(right) + .map_err(|_| "second associated document")?; + require( + first + .facts() + .document_order(a) + .map_err(|_| "first associated order")? + == second + .facts() + .document_order(b) + .map_err(|_| "second associated order")?, + "nondeterministic association document", + )?; + for position in 0..left.get().owner_count() { + let a = first + .facts() + .associated_owner(left, position) + .map_err(|_| "first associated owner")?; + let b = second + .facts() + .associated_owner(right, position) + .map_err(|_| "second associated owner")?; + require( + first_owners.get(&address(a)) == second_owners.get(&address(b)), + "nondeterministic association owner identity", + )?; + } + require( + second.facts().associated_document(left).err() == Some(FactError::ForeignIndex), + "foreign association accepted", + )?; + } + for (left, right) in first.qualifications().zip(second.qualifications()) { + let a = left.get(); + let b = right.get(); + require( + a.subject == b.subject && a.reason == b.reason && a.node.node() == b.node.node(), + "nondeterministic qualifications", + )?; + let a = first + .qualified_owner(left) + .map_err(|_| "first qualified owner")? + .map(|owner| first_owners[&address(owner)]); + let b = second + .qualified_owner(right) + .map_err(|_| "second qualified owner")? + .map(|owner| second_owners[&address(owner)]); + require(a == b, "nondeterministic qualification owner identity")?; + let a = first + .qualified_document(left) + .map_err(|_| "first qualified document")?; + let b = second + .qualified_document(right) + .map_err(|_| "second qualified document")?; + require( + first + .facts() + .document_order(a) + .map_err(|_| "first qualified order")? + == second + .facts() + .document_order(b) + .map_err(|_| "second qualified order")?, + "nondeterministic qualification document identity", + )?; + } + for (left, right) in first.assessments().zip(second.assessments()) { + let a = left.get(); + let b = right.get(); + require( + a.axis == b.axis + && a.reason == b.reason + && a.node.map(NodeEvidence::node) == b.node.map(NodeEvidence::node), + "nondeterministic assessments", + )?; + let a = first + .assessed_document(left) + .map_err(|_| "first assessed document")? + .map(|document| first.facts().document_order(document)) + .transpose() + .map_err(|_| "first assessed order")?; + let b = second + .assessed_document(right) + .map_err(|_| "second assessed document")? + .map(|document| second.facts().document_order(document)) + .transpose() + .map_err(|_| "second assessed order")?; + require(a == b, "nondeterministic assessment document identity")?; + } + for (left, right) in first.evidence().zip(second.evidence()) { + require( + left.get().disposition == right.get().disposition, + "nondeterministic evidence disposition", + )?; + let a = first + .evidence_fragment(left) + .map_err(|_| "first evidence fragment")?; + let b = second + .evidence_fragment(right) + .map_err(|_| "second evidence fragment")?; + require( + a.get().source() == b.get().source(), + "nondeterministic evidence source", + )?; + } + if let Some(owner) = first.facts().owners().next() { + require( + matches!( + second.owner_associations(owner), + Err(OwnerError::Fact(FactError::ForeignIndex)) + ), + "foreign owner accepted", + )?; + } + if let Some(assessment) = first.assessments().next() { + require( + second.assessed_document(assessment).err() == Some(FactError::ForeignIndex), + "foreign assessment accepted", + )?; + } + if let Some(qualification) = first.qualifications().next() { + require( + second.qualified_document(qualification).err() == Some(FactError::ForeignIndex), + "foreign qualification accepted", + )?; + } + if let Some(evidence) = first.evidence().next() { + require( + second.evidence_fragment(evidence).err() == Some(FactError::ForeignIndex), + "foreign candidate evidence accepted", + )?; + } + Ok(()) +} diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs new file mode 100644 index 000000000..1b45376e4 --- /dev/null +++ b/fuzz/src/documentation/tests.rs @@ -0,0 +1,527 @@ +use super::*; +use big_code_analysis_ast::parser::ParseCompletion; +use serde_json::Value; +use sha2::{Digest, Sha256}; +use std::{collections::BTreeSet, path::Path}; + +fn number(value: &Value) -> usize { + usize::try_from(value.as_u64().unwrap()).unwrap() +} +fn range(value: &Value) -> std::ops::Range { + number(&value[0])..number(&value[1]) +} + +fn nodes(tree: &tree_sitter::Tree) -> Vec> { + let mut nodes = Vec::new(); + let mut cursor = tree.walk(); + loop { + nodes.push(cursor.node()); + if cursor.goto_first_child() { + continue; + } + loop { + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return nodes; + } + } + } +} + +fn text<'i, 's>(index: &'i DocumentationIndex<'s>) -> CompleteText<'i, 's> { + index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap() +} + +fn positive(index: &DocumentationIndex<'_>, row: &Value) { + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let document = index.documents().next().unwrap(); + let fragment = index.facts().document_fragment(document, 0).unwrap(); + assert_eq!(document.get().fragment_count(), 1); + assert_eq!(fragment.get().source().pieces().len(), 1); + assert_eq!( + fragment.get().source().pieces()[0].range(), + range(&row["fragments"][0]) + ); + let complete = text(index); + assert_eq!(complete.text(), row["text"].as_str().unwrap()); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), 1); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("positive must have a real declaration") + }; + assert_eq!(node.node().byte_range(), range(&row["owner"])); + assert_eq!( + node.node().kind(), + row["selected_owner_kind"].as_str().unwrap() + ); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .len(), + 1 + ); + let portions: Vec<_> = complete + .origins(0..complete.text().len()) + .unwrap() + .collect(); + assert_eq!(portions.len(), 1); + let OriginView::Copied(piece) = &portions[0].origin else { + panic!("positive needs copied source mapping") + }; + assert_eq!(piece.bytes(), complete.text().as_bytes()); +} + +#[test] +#[allow(clippy::too_many_lines)] // Registration checks bytes, parse shape, and executed semantic oracles together. +fn registry_executes_every_dispatch_and_edge_assertion() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + let registry: Vec = + serde_json::from_str(include_str!("../../documentation-seeds.json")).unwrap(); + let inventory: Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/documentation/inventory.json" + )) + .unwrap(); + let mut names = BTreeSet::new(); + let mut dispatch = BTreeSet::new(); + let mut counts = [0; 3]; + for seed in ®istry { + let name = seed["name"].as_str().unwrap(); + assert!(names.insert(name.to_owned()), "duplicate seed {name}"); + let bytes = std::fs::read(root.join("corpus/documentation").join(name)).unwrap(); + let header: Vec<_> = seed["header"] + .as_array() + .unwrap() + .iter() + .map(|value| u8::try_from(number(value)).unwrap()) + .collect(); + assert_eq!(&bytes[..3], header); + assert_eq!( + format!("{:x}", Sha256::digest(&bytes[3..])), + seed["sha256"].as_str().unwrap() + ); + if let Some(fixture) = seed["fixture"].as_str() { + assert_eq!( + &bytes[3..], + std::fs::read( + root.join("../tests/fixtures/documentation/sources") + .join(fixture) + ) + .unwrap() + ); + } + let mut inspected = false; + let result = exercise_with(&bytes, |index, tree| { + inspected = true; + assert_eq!( + tree.root_node().has_error(), + seed["has_error"].as_bool().unwrap(), + "{name}" + ); + if let Some(language) = seed["inventory"].as_str() { + let row = &inventory[language]; + assert_eq!( + format!("{:?}", Input::decode(&bytes).unwrap().language).to_lowercase(), + language + ); + assert!(dispatch.insert(header[0])); + if let Some(kind) = row["selected_owner_kind"].as_str() { + assert!( + nodes(tree).iter().any(|node| node.kind() == kind), + "{name}: expected parsed declaration" + ); + } + match seed["class"].as_str().unwrap() { + "positive" => { + positive(index.unwrap(), row); + counts[0] += 1; + } + "deferred" => { + assert!(index.is_none()); + counts[1] += 1; + } + "helper" => { + assert_eq!(index.unwrap().capability(), Capability::NoDeclarationModel); + counts[2] += 1; + } + _ => panic!("unknown dispatch assertion"), + } + } else { + edge(seed["class"].as_str().unwrap(), index, tree); + } + Ok(()) + }); + assert!(result.is_ok(), "{name}: {result:?}"); + assert!(inspected, "{name}: registry seed skipped execution"); + match seed["class"].as_str().unwrap() { + "deferred" | "deferred-profile" => assert!(matches!( + result, + Ok(Outcome::Rejected( + CollectionError::AdapterUnavailable { .. } + )) + )), + "incompatible-profile" => assert!(matches!( + result, + Ok(Outcome::Rejected( + CollectionError::UnsupportedProfile { .. } + )) + )), + "helper" => assert_eq!(result, Ok(Outcome::Helper)), + _ => assert_eq!(result, Ok(Outcome::Checked)), + } + } + assert_eq!(counts, [17, 6, 2]); + assert_eq!(dispatch, (0..25).collect()); + let actual: BTreeSet<_> = std::fs::read_dir(root.join("corpus/documentation")) + .unwrap() + .map(|entry| entry.unwrap().file_name().into_string().unwrap()) + .collect(); + assert_eq!(actual, names); +} + +#[allow(clippy::too_many_lines)] // Independent expected outcomes for the finite registered edge families. +fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter::Tree) { + if matches!(class, "incompatible-profile" | "deferred-profile") { + assert!(index.is_none()); + return; + } + let index = index.unwrap(); + match class { + "eof" => { + assert!(!index.source().ends_with(b"\n")); + assert_eq!(index.documents().len(), 0); + } + "crlf" => { + assert!(index.source().windows(2).any(|bytes| bytes == b"\r\n")); + assert_eq!(text(index).text(), "kept"); + } + "pending-content" => { + assert_eq!(index.documents().len(), 1); + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::PendingAdapter + )); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Composition) + ); + } + "join" => { + assert_eq!(text(index).text(), "a\nb"); + assert_eq!(text(index).mappings().len(), 3); + assert!(matches!( + text(index).mappings()[1].origin, + Origin::Synthetic + )); + } + "shared" => { + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().next().unwrap().get().owner_count(), 2); + assert_eq!(text(index).text(), "audit"); + } + "gathered" => { + assert_eq!(index.documents().len(), 1); + assert_eq!(index.documents().next().unwrap().get().fragment_count(), 2); + assert_eq!(text(index).text(), "a\nb"); + } + "candidate-qualification" | "reference-qualification" => { + let candidate = class == "candidate-qualification"; + let expected = if candidate { + vec![ + UnresolvedReason::Conditional, + UnresolvedReason::GrammarBoundary, + ] + } else { + vec![UnresolvedReason::Conditional] + }; + assert_eq!( + index + .qualifications() + .map(|q| q.get().reason) + .collect::>(), + expected + ); + for qualification in index.qualifications() { + assert_eq!( + qualification.get().subject, + if candidate { + QualificationSubject::Candidate + } else { + QualificationSubject::Reference + } + ); + assert_eq!( + index.qualified_owner(qualification).unwrap().is_some(), + candidate + ); + } + } + "missing-name" => assert_eq!( + index.associations().next().unwrap().get().resolution, + Resolution::Unresolved(UnresolvedReason::MissingName) + ), + "pending-name" => { + assert_eq!(index.associations().len(), 0); + assert_eq!(index.documents().len(), 1); + assert!(index.assessments().next().is_some()); + } + "pending-owner" => { + let node = nodes(tree) + .into_iter() + .find(|node| node.kind() == "class_parameter") + .unwrap(); + assert!(index.node_projection(node).unwrap().pending()); + assert!(index.node_associations(node).unwrap().projection_pending()); + assert_eq!(text(index).text(), "audit"); + } + "known-and-pending" => { + assert_eq!(index.documents().len(), 2); + let node = nodes(tree) + .into_iter() + .find(|node| node.kind() == "function_declaration") + .unwrap(); + let query = index.node_associations(node).unwrap(); + assert_eq!(query.associations().len(), 1); + assert!( + query + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner) + ); + assert_eq!(text(index).text(), "first"); + assert_eq!( + index + .complete_text(index.documents().last().unwrap()) + .unwrap() + .unwrap() + .text(), + "audit" + ); + } + "invalid-encoding" => assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::InvalidEncoding) + )), + "partial" => assert!(tree.root_node().has_error()), + "scalar-pieces" => { + assert_eq!(text(index).text(), "é"); + assert!( + text(index) + .mappings() + .iter() + .any(|m| !text(index).text().is_char_boundary(m.output.range().end)) + ); + } + "decoded-pieces" => { + let complete = text(index); + assert_eq!(complete.text(), "a\nb"); + let mapping = complete + .mappings() + .iter() + .find(|mapping| matches!(mapping.origin, Origin::Decoded(_))) + .unwrap(); + let Origin::Decoded(pieces) = &mapping.origin else { + unreachable!() + }; + assert_eq!(pieces.pieces().len(), 2); + assert_eq!( + pieces + .pieces() + .iter() + .flat_map(|piece| piece.bytes().iter().copied()) + .collect::>(), + b"\r\n" + ); + let portion = complete.origins(1..2).unwrap().next().unwrap(); + assert_eq!(portion.origin, OriginView::Decoded(pieces.pieces())); + } + "source-gap" => { + assert!( + index + .facts() + .fragments() + .any(|fragment| fragment.get().source().has_excluded_gap()) + ); + assert!(index.documents().any(|document| matches!( + document.get().content(), + Content::Unavailable(UnavailableReason::ExcludedGap) + ))); + } + "empty" | "evidence" => { + assert_eq!(text(index).text(), ""); + assert_eq!(index.evidence().len(), usize::from(class == "evidence")); + } + "directive-off" | "directive-on" => { + assert_eq!(index.documents().len(), 0); + assert_eq!(index.evidence().len(), usize::from(class == "directive-on")); + for evidence in index.evidence() { + assert_eq!(evidence.get().disposition, CandidateDisposition::Directive); + } + } + "cancelled-scope" | "active-scope" => assert_eq!(text(index).text(), "audit"), + "neighbor" => { + assert_eq!(index.documents().len(), 1); + assert_eq!(text(index).text(), "neighbor"); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().resolution, Resolution::Resolved); + let Owner::Node(owner) = index + .facts() + .associated_owner(association, 0) + .unwrap() + .get() + else { + panic!("neighbor owner") + }; + assert_eq!( + &index.source()[owner.node().byte_range()], + b"fn neighbor() {}" + ); + } + _ => panic!("unknown edge assertion {class}"), + } +} + +#[test] +fn header_roster_skips_and_resource_boundaries_are_explicit() { + let actual: BTreeSet<_> = header::LANGUAGES.iter().map(|lang| lang.name()).collect(); + let expected: BTreeSet<_> = LANG::into_enum_iter().map(|lang| lang.name()).collect(); + assert_eq!(actual, expected); + assert_eq!(actual.len(), header::LANGUAGES.len()); + for (bytes, skip) in [ + (&[0, 0][..], Skip::ShortHeader), + (&[25, 0, 0], Skip::UnknownLanguage), + (&[255, 0, 0], Skip::UnknownLanguage), + (&[0, 16, 0], Skip::ReservedBits), + (&[0, 0, 128], Skip::ReservedBits), + (&[0, 0, 31], Skip::UnknownProfile), + ] { + assert_eq!(exercise(bytes), Ok(Outcome::Skipped(skip))); + } + let mut bytes = vec![0, 0, 0]; + bytes.extend(vec![b' '; MAX_SOURCE]); + assert_eq!(exercise(&bytes), Ok(Outcome::Checked)); + bytes.push(b' '); + assert_eq!(exercise(&bytes), Ok(Outcome::Skipped(Skip::Oversize))); + let ast = Ast::parse(big_code_analysis::Source::from_bytes( + LANG::Rust, + bytes[3..].to_vec(), + )) + .unwrap(); + assert_eq!(check_ast(&ast), Ok(Outcome::Skipped(Skip::Oversize))); + assert_eq!(ast.source().len(), MAX_SOURCE + 1); + assert!(included_ranges(&vec![b'a'; MAX_STRUCTURE]).is_some()); + assert!(included_ranges(&vec![b'a'; MAX_STRUCTURE + 1]).is_none()); + assert_eq!( + exercise(&[0, 4, 0, 0]), + Ok(Outcome::Skipped(Skip::IncludedRangeLimit)) + ); +} + +#[test] +fn typed_parse_cancellation_retains_actual_abort_after_scope_restoration() { + let flag = ParseCancel::new(); + flag.cancel(); + let parser = flag + .run(|| AnyParser::parse(LANG::Rust, b"fn f() {}\n".repeat(10_000), None, None).unwrap()); + assert_eq!(parser.parse_completion(), ParseCompletion::Cancelled); + assert!(matches!( + parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ), + Err(CollectionError::Cancelled) + )); + let next = AnyParser::parse(LANG::Rust, b"///audit\nfn f() {}".to_vec(), None, None).unwrap(); + assert_eq!(next.parse_completion(), ParseCompletion::Complete); + assert_eq!( + text( + &next + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default() + ) + .unwrap() + ) + .text(), + "audit" + ); +} + +#[test] +fn registry_oracles_reject_actual_wrong_payloads_and_foreign_nodes() { + let inventory: Value = serde_json::from_str(include_str!( + "../../../tests/fixtures/documentation/inventory.json" + )) + .unwrap(); + let bytes = b"\0\x01\0///other\nfn f() {}"; + let result = std::panic::catch_unwind(|| { + exercise_with(bytes, |index, _| { + positive(index.unwrap(), &inventory["rust"]); + Ok(()) + }) + }); + assert!( + result.is_err(), + "same-shaped wrong text must fail the real positive oracle" + ); + let bytes = b"\0\x01\0#[doc = \"audit\"]\nfn f() {}"; + let result = std::panic::catch_unwind(|| { + exercise_with(bytes, |index, tree| { + edge("active-scope", index, tree); + Ok(()) + }) + }); + assert!( + result.is_err(), + "pending text must not pass a complete-text assertion" + ); + let first = AnyParser::parse(LANG::Rust, b"fn f() {}".to_vec(), None, None).unwrap(); + let foreign = AnyParser::parse(LANG::Rust, b"fn f() {}".to_vec(), None, None).unwrap(); + let index = first + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert!(matches!( + index.node_projection(foreign.ts_tree().root_node()), + Err(OwnerError::Source(SourceError::ForeignTree)) + )); +} + +#[test] +fn ordinary_fanout_borrows_the_preprocessed_ast_buffer() { + use big_code_analysis::{PreprocResults, Source, preprocess}; + use std::sync::Arc; + let path = Path::new("fuzz_input.cpp"); + let bytes = b"#define API\n/**audit*/\nAPI void f() {}"; + let mut results = PreprocResults::default(); + preprocess(bytes.to_vec(), path, &mut results); + let ast = Ast::parse( + Source::from_bytes(LANG::Cpp, bytes.to_vec()) + .with_preproc_path(Some(path)) + .with_preproc(Some(Arc::new(results))), + ) + .unwrap(); + assert_ne!(ast.source(), bytes); + assert_eq!(check_ast(&ast), Ok(Outcome::Checked)); + let index = collect( + ast.language(), + ast.as_tree_sitter(), + ast.source(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.source(), ast.source()); + assert_eq!(text(&index).text(), "audit"); +} diff --git a/fuzz/src/lib.rs b/fuzz/src/lib.rs index 1271d70f9..20464eead 100644 --- a/fuzz/src/lib.rs +++ b/fuzz/src/lib.rs @@ -49,6 +49,7 @@ use std::sync::LazyLock; use big_code_analysis::{Ast, AstCfg, LANG, MetricsOptions, Source}; +pub mod documentation; pub mod nested; /// Node-kind filters handed to [`Ast::count`] and [`Ast::find`]. @@ -103,6 +104,8 @@ pub fn walk_all(lang: LANG, data: Vec) { /// [`Source`] — the preprocessor one has to — reuses the same fan-out /// rather than keeping a second copy of it in step. pub fn walk_parsed(ast: &Ast) { + let documentation = documentation::check_ast(ast); + assert!(documentation.is_ok(), "{documentation:?}"); // Each result is handed to `black_box` whole rather than reduced to // a bool or a length first: the reduction would let the optimizer // drop the value the walk produced while still looking like a From b13565dbb101b51cbe44ce781441eaf657a94da7 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:53:11 -0800 Subject: [PATCH 045/221] fix(fuzz): validate registered source outcomes and review guidance Fix digest formatting and clippy findings discovered in the first executable check. Qualify Tcl/iRules EOF recovery and the explicitly pending source-gap selection without changing seed bytes. Apply all six independent documentation-review corrections and add a finite mutation manifest. --- docs/development/fuzzing.md | 63 +++++++++++++++++++--------- fuzz/documentation-perturb.json | 33 +++++++++++++++ fuzz/documentation-seeds.json | 4 +- fuzz/generate_documentation_seeds.py | 2 +- fuzz/src/documentation/maps.rs | 8 ++-- fuzz/src/documentation/mod.rs | 23 ++++++---- fuzz/src/documentation/properties.rs | 7 +++- fuzz/src/documentation/tests.rs | 55 ++++++++++++++++++------ fuzz/src/lib.rs | 3 ++ 9 files changed, 151 insertions(+), 47 deletions(-) create mode 100644 fuzz/documentation-perturb.json diff --git a/docs/development/fuzzing.md b/docs/development/fuzzing.md index a737d730e..5aaea8f6c 100644 --- a/docs/development/fuzzing.md +++ b/docs/development/fuzzing.md @@ -27,7 +27,8 @@ You also need an [`llvm-symbolizer`](https://llvm.org/docs/CommandGuide/llvm-symbolizer.html) on `PATH` or under `/usr/lib/llvm-*/bin` (Debian/Ubuntu: `apt-get install llvm`; macOS: it -comes with Xcode's clang). `rustup component add llvm-tools` ships the +comes with Xcode's [Clang](https://clang.llvm.org/)). +[`rustup`](https://rust-lang.github.io/rustup/) component `llvm-tools` ships the rest of the LLVM binutils but **not** this one. It is a hard requirement, not a nicety: @@ -70,7 +71,7 @@ slowest *legitimate* input measured so far (`nested_depth`'s 5-byte seed decoding to 508 alternating `Block`/`Lambda` levels of JavaScript) takes **11 s** when run solo under [AddressSanitizer](https://clang.llvm.org/docs/AddressSanitizer.html) -(ASan) plus the harness's ten-walk fan-out, while the 4.8 KB JavaScript +(ASan) plus the harness's walk fan-out, while the 4.8 KB JavaScript file it generates costs 0.06 s through `bca metrics` in a plain release build. The default of 60 seconds is that measurement plus ~5x headroom (#1308; the previous @@ -142,6 +143,21 @@ Promoting a discovery to a committed seed is therefore a deliberate `cp`, which is the right bar: seeds are read by every future contributor and should each be explicable. +For `documentation`, register the seed's header, payload, provenance, and assertion +class in `fuzz/generate_documentation_seeds.py`. Add or reuse the matching assertions +in `fuzz/src/documentation/tests.rs`, then regenerate the corpus and registry: + +```bash +python3 -B fuzz/generate_documentation_seeds.py +cargo +nightly test --manifest-path fuzz/Cargo.toml --locked --lib documentation::tests +``` + +Copying a discovery into this corpus alone is insufficient: the generator rejects +unregistered files, and registration tests require every seed to execute its assertion class. +The Rust recovery seeds form a fixed valid/missing-expression pair. Both retain the same +documented neighboring function and assert its unchanged owner spelling and text. +That constructed oracle does not claim documentation parity under arbitrary source edits. + `bca` never analyses either directory: `.bcaignore` excludes them from the walk, because deliberately malformed source measures nothing and would put ERROR-node parses into `bca report`. @@ -167,13 +183,15 @@ run` / `tmin` directly. They carry the `CFLAGS_` / `CXXFLAGS_` settings described under [The targets](#the-targets), and [`cc`](https://docs.rs/cc) emits `cargo:rerun-if-env-changed` for those variables, so a bare invocation -rebuilds every tree-sitter grammar *without* ASan, which is precisely +rebuilds every [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammar +*without* ASan, which is precisely the instrumentation that found the C-scanner class in the first place. They also pass `--target ` explicitly, which matters more than it looks. cargo-fuzz defaults its target to the triple *it* was built for, not the host's: `cargo install cargo-fuzz` gives you the -host, while a binstall-backed install (what `taiki-e/install-action` +host, while a [cargo-binstall](https://github.com/cargo-bins/cargo-binstall)-backed +install (what [`taiki-e/install-action`](https://github.com/taiki-e/install-action) does in the workflow) hands you the prebuilt musl artifact, which then builds the targets for a statically-linked libc the sanitizer refuses. Pinning it also keeps the CFLAGS triple and the build triple the same @@ -200,9 +218,8 @@ drive a subprocess and assert it does not die by signal. ### Leak suppressions -Leak detection stays on. `fuzz/lsan-suppressions.txt` currently holds one -entry, and adding a second should feel expensive: every suppression is a -leak nothing will report again. Suppress by symbol rather than passing +Leak detection stays on. Every entry in `fuzz/lsan-suppressions.txt` needs a diagnosis +because it hides future leak reports matching that symbol. Suppress by symbol rather than passing `-detect_leaks=0`, so other leaks on the same path still fail. ## The targets {#the-targets} @@ -245,7 +262,7 @@ bounded by #1056, after nested input was found able to abort the process from `Serialize`. **The C grammars are instrumented too.** cargo-fuzz sanitizes the Rust -side; the [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars are C +side; the tree-sitter grammars are C compiled by build scripts and need separate instrumentation. `make fuzz-check` sets `CFLAGS_`. It has to be the triple-qualified spelling: `cc` resolves `_`, then `_`, @@ -255,6 +272,13 @@ than `TARGET_` for the build kind when it is not cross-compiling, so ### Documentation properties {#documentation-properties} +The [source-bound index](documentation_extraction.md#index) retains physical fragments, +logical documents, and associations with owners. An owner is the entity being documented; +a profile selects the documentation convention. Qualifications record known conditional +or recovery facts, while assessments record unfinished adapter work. Included ranges select +which original source bytes the parser reads. Source maps relate extracted text to those bytes; +a map run describes one contiguous output range. + The documentation target has a handwritten version-one three-byte header. The payload after byte 2 reaches the parser unchanged, including invalid encoding, NUL bytes, CRLF, and a missing final newline. Unknown tags, @@ -285,9 +309,10 @@ discriminants or iteration order: | 20–24 | Bash, Tcl, Irules, Ccomment, Preproc | Registration tests compare the table with the `LANG` roster and execute every -registered seed through the real target. Positive seeds assert exact fragment -and owner ranges, parsed declaration kinds, text, and copied mappings from -`tests/fixtures/documentation/inventory.json`. Deferred adapters require +registered seed through the real target. Positive seeds obtain exact fragment +and owner ranges, parsed declaration kinds, and text from +`tests/fixtures/documentation/inventory.json`. They separately require copied origins +whose bytes equal the extracted text. Deferred adapters require `AdapterUnavailable`; helper grammars require `NoDeclarationModel`. Recognized deferred profiles differ from `UnsupportedProfile`. These outcomes do not count as positive source extraction. Future adapters @@ -296,7 +321,7 @@ must add their own positive seeds when their source paths become available. The checker validates raw pieces against the exact source and included ranges. It checks observed document, association, and qualification ordering without sorting the results. Bounded owner and canonical-cursor queries compare -prepared adjacency with enumeration. Pending assessments remain inspectable +indexed results with the corresponding enumerated records. Pending assessments remain inspectable alongside known associations; candidate and reference qualifications retain their distinct identities and reasons. Cross-index handles and noncanonical nodes must return the documented identity errors. @@ -315,14 +340,16 @@ arms do not establish positive coverage of those forms. The resource limits are harness policy: -- Inspect source buffers up to 32 KiB. Larger inputs skip only the added - documentation operation in the ordinary walk fanout; no source is truncated. +- Inspect source buffers up to 32 KiB. The tagged target skips larger payloads before parsing. + Ordinary walk targets skip only documentation and continue their other checks. + Neither path truncates source. - Perform at most two ordinary collections over the same parse. - Select at most eight owner/node positions and eight map ranges per input, including late positions. - Limit structured included-range inputs to 256 ranges. Each non-NUL payload byte becomes one included range, so adjacent ranges can divide a scalar. - NUL bytes create excluded gaps. Parsing uses the original payload once. + NUL bytes create excluded gaps. Zero included bytes, including empty and all-NUL payloads, + or more than 256 ranges skip the input. Parsing uses the original payload once. The checker makes linear or output-proportional passes and uses expected constant-time hash indexing. Its included-byte prefix table costs linear @@ -352,9 +379,7 @@ Record the revision, nightly and cargo-fuzz versions, input timeout, registered seed inventory, and actual run counts. A printed tool-availability skip is a skipped stage. Preserve a failing input and stop investigation runs when a production crash appears; follow [crash triage](#triaging-a-crash) before -promoting it to a seed. Local recovery seeds use a constructed valid/error pair -with an independently documented neighbor. Arbitrary random inputs do not -imply equivalent documentation after an unspecified source edit. +promoting it to a seed. ### Fuzzing an order-dependent function @@ -400,7 +425,7 @@ The target set is deliberately narrow. Two pieces of evidence bound it. `clippy::indexing_slicing` on `big-code-analysis-ast/src/c_macro.rs`, and would have caught the five-byte input that panicked the library (#1051) at compile time. What a lint cannot check is the residue it -could not discharge: the nine per-function +could not discharge: the per-function `#[allow(clippy::indexing_slicing)]` sites in `big-code-analysis-ast/src/c_macro.rs`, each a computed index into attacker-controlled bytes whose bound is asserted by a human comment. That population is what diff --git a/fuzz/documentation-perturb.json b/fuzz/documentation-perturb.json new file mode 100644 index 000000000..8985c6f95 --- /dev/null +++ b/fuzz/documentation-perturb.json @@ -0,0 +1,33 @@ +{ + "command": ["cargo", "+nightly", "test", "--manifest-path", "fuzz/Cargo.toml", "--locked", "--lib", "--no-fail-fast"], + "cases": [ + { + "name": "swap-rust-python-tags", + "file": "fuzz/src/documentation/header.rs", + "old": " LANG::Rust,\n LANG::Python,", + "new": " LANG::Python,\n LANG::Rust,", + "expect": ["documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] + }, + { + "name": "skip-source-at-inclusive-cap", + "file": "fuzz/src/documentation/mod.rs", + "old": "if input.source.len() > MAX_SOURCE {", + "new": "if input.source.len() >= MAX_SOURCE {", + "expect": ["documentation::tests::header_roster_skips_and_resource_boundaries_are_explicit"] + }, + { + "name": "reject-stored-scalar-split", + "file": "fuzz/src/documentation/maps.rs", + "old": "range.start == end && range.start < range.end && range.end <= complete.text().len(),", + "new": "range.start == end && range.start < range.end && range.end <= complete.text().len() && complete.text().is_char_boundary(range.end),", + "expect": ["documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] + }, + { + "name": "lose-deferred-profile-distinction", + "file": "fuzz/src/documentation/header.rs", + "old": "Err(CollectionError::AdapterUnavailable { language, profile })", + "new": "Err(CollectionError::UnsupportedProfile { language, profile })", + "expect": ["documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] + } + ] +} diff --git a/fuzz/documentation-seeds.json b/fuzz/documentation-seeds.json index 18fd454c5..829faad9d 100644 --- a/fuzz/documentation-seeds.json +++ b/fuzz/documentation-seeds.json @@ -305,7 +305,7 @@ "provenance": "tests/fixtures/documentation/inventory.json", "inventory": "tcl", "fixture": "primary.tcl", - "has_error": false + "has_error": true }, { "name": "dispatch-irules", @@ -319,7 +319,7 @@ "provenance": "tests/fixtures/documentation/inventory.json", "inventory": "irules", "fixture": "primary.irule", - "has_error": false + "has_error": true }, { "name": "dispatch-ccomment", diff --git a/fuzz/generate_documentation_seeds.py b/fuzz/generate_documentation_seeds.py index 40c1b4473..c72364f3c 100644 --- a/fuzz/generate_documentation_seeds.py +++ b/fuzz/generate_documentation_seeds.py @@ -82,7 +82,7 @@ def add(name, header, payload, assertion, provenance, **expected): "tests/fixtures/documentation/inventory.json", inventory=language, fixture=row["path"], - has_error=False, + has_error=language in {"tcl", "irules"}, ) for name, fixture, assertion in [ diff --git a/fuzz/src/documentation/maps.rs b/fuzz/src/documentation/maps.rs index 05756d5ff..28a79ad91 100644 --- a/fuzz/src/documentation/maps.rs +++ b/fuzz/src/documentation/maps.rs @@ -1,4 +1,6 @@ -use big_code_analysis_ast::documentation::*; +use big_code_analysis_ast::documentation::{ + CompleteText, Origin, OriginView, SourcePiece, TextRangeError, +}; use std::ops::Range; use super::{Check, MAX_QUERIES, require}; @@ -74,7 +76,7 @@ pub(super) fn validate(complete: CompleteText<'_, '_>, coverage: &Coverage<'_>) )?; } Origin::Decoded(pieces) | Origin::Expanded(pieces) => { - coverage.pieces(pieces.pieces())? + coverage.pieces(pieces.pieces())?; } Origin::Synthetic => {} _ => return Err("unhandled origin variant"), @@ -120,7 +122,7 @@ pub(super) fn queries(complete: CompleteText<'_, '_>, selector: u8) -> Check { }; match (expected, complete.origins(query.clone())) { (Err(expected), Err(actual)) => { - require(expected == actual, "wrong map query rejection")? + require(expected == actual, "wrong map query rejection")?; } (Ok(()), Ok(mut actual)) => { if !query.is_empty() { diff --git a/fuzz/src/documentation/mod.rs b/fuzz/src/documentation/mod.rs index 30c01e2bb..3a49e841e 100644 --- a/fuzz/src/documentation/mod.rs +++ b/fuzz/src/documentation/mod.rs @@ -7,7 +7,14 @@ mod properties; mod tests; use big_code_analysis::{Ast, LANG}; -use big_code_analysis_ast::{AnyParser, cancel::ParseCancel, documentation::*}; +use big_code_analysis_ast::{ + AnyParser, + cancel::ParseCancel, + documentation::{ + Capability, CollectionError, DocumentationContext, DocumentationIndex, + DocumentationOptions, collect, + }, +}; use header::{Input, Mode, expected_profile}; /// Maximum exact source length inspected by the additional documentation operation. @@ -57,13 +64,13 @@ struct Parsed<'s> { impl<'s> Parsed<'s> { fn collect( &self, - options: &DocumentationOptions, + options: DocumentationOptions, ) -> Result, CollectionError> { let context = DocumentationContext::default(); if let Some(parser) = self.typed { - parser.documentation(&context, options) + parser.documentation(&context, &options) } else { - collect(self.language, self.tree, self.source, &context, options) + collect(self.language, self.tree, self.source, &context, &options) } } } @@ -87,7 +94,7 @@ pub fn check_ast(ast: &Ast) -> Result { source: ast.source(), typed: None, }, - &DocumentationOptions::default(), + DocumentationOptions::default(), false, false, |_, _| Ok(()), @@ -139,7 +146,7 @@ fn exercise_with( source: input.source, typed: None, }, - &input.options, + input.options, input.repeat, input.identity, inspect, @@ -168,7 +175,7 @@ fn exercise_with( source: parser.code(), typed: Some(&parser), }, - &input.options, + input.options, input.repeat, input.identity, inspect, @@ -183,7 +190,7 @@ fn exercise_with( fn check_parse( parsed: &Parsed<'_>, - options: &DocumentationOptions, + options: DocumentationOptions, repeat: bool, identity: bool, inspect: impl FnOnce(Option<&DocumentationIndex<'_>>, &tree_sitter::Tree) -> Check, diff --git a/fuzz/src/documentation/properties.rs b/fuzz/src/documentation/properties.rs index 27b2ae412..f0179e0b8 100644 --- a/fuzz/src/documentation/properties.rs +++ b/fuzz/src/documentation/properties.rs @@ -1,4 +1,7 @@ -use big_code_analysis_ast::documentation::*; +use big_code_analysis_ast::documentation::{ + Content, DocumentationIndex, FactError, FactRef, NodeEvidence, Owner, OwnerError, + QualificationSubject, SourceError, UnresolvedReason, +}; use std::collections::HashMap; use super::{Check, MAX_QUERIES, maps, require}; @@ -539,7 +542,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI }, ) => require(a == b && am == bm, "nondeterministic complete content")?, (Content::Unavailable(a), Content::Unavailable(b)) => { - require(a == b, "nondeterministic unavailable reason")? + require(a == b, "nondeterministic unavailable reason")?; } (a, b) => require( std::mem::discriminant(a) == std::mem::discriminant(b), diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index 1b45376e4..4c5d47ccb 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -1,7 +1,9 @@ use super::*; +use big_code_analysis_ast::documentation::*; use big_code_analysis_ast::parser::ParseCompletion; use serde_json::Value; use sha2::{Digest, Sha256}; +use std::fmt::Write; use std::{collections::BTreeSet, path::Path}; fn number(value: &Value) -> usize { @@ -106,7 +108,12 @@ fn registry_executes_every_dispatch_and_edge_assertion() { .collect(); assert_eq!(&bytes[..3], header); assert_eq!( - format!("{:x}", Sha256::digest(&bytes[3..])), + Sha256::digest(&bytes[3..]) + .iter() + .fold(String::new(), |mut hex, byte| { + write!(hex, "{byte:02x}").unwrap(); + hex + }), seed["sha256"].as_str().unwrap() ); if let Some(fixture) = seed["fixture"].as_str() { @@ -125,10 +132,18 @@ fn registry_executes_every_dispatch_and_edge_assertion() { assert_eq!( tree.root_node().has_error(), seed["has_error"].as_bool().unwrap(), - "{name}" + "{name}: {}", + tree.root_node().to_sexp() ); if let Some(language) = seed["inventory"].as_str() { let row = &inventory[language]; + if matches!(language, "tcl" | "irules") { + assert!( + nodes(tree) + .iter() + .any(|node| node.is_missing() && node.kind() == "\n") + ); + } assert_eq!( format!("{:?}", Input::decode(&bytes).unwrap().language).to_lowercase(), language @@ -345,16 +360,28 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: assert_eq!(portion.origin, OriginView::Decoded(pieces.pieces())); } "source-gap" => { - assert!( - index - .facts() - .fragments() - .any(|fragment| fragment.get().source().has_excluded_gap()) + assert_eq!(index.documents().len(), 0); + assert_eq!(index.assessments().len(), 1); + let assessment = index.assessments().next().unwrap(); + assert_eq!(assessment.get().axis, AssessmentAxis::Selection); + assert_eq!( + assessment.get().reason, + "Excluded bytes prevent complete native-carrier assessment" + ); + let node = assessment.get().node.unwrap().node(); + assert_eq!(node.byte_range(), 0..8); + let pieces = SourceContext::new(tree, index.source()) + .pieces(node.byte_range()) + .unwrap(); + assert!(pieces.has_excluded_gap()); + assert_eq!( + pieces + .pieces() + .iter() + .map(SourcePiece::range) + .collect::>(), + vec![0..1, 1..2, 2..3, 3..4, 5..6, 6..7, 7..8] ); - assert!(index.documents().any(|document| matches!( - document.get().content(), - Content::Unavailable(UnavailableReason::ExcludedGap) - ))); } "empty" | "evidence" => { assert_eq!(text(index).text(), ""); @@ -392,7 +419,7 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: #[test] fn header_roster_skips_and_resource_boundaries_are_explicit() { - let actual: BTreeSet<_> = header::LANGUAGES.iter().map(|lang| lang.name()).collect(); + let actual: BTreeSet<_> = header::LANGUAGES.iter().map(LANG::name).collect(); let expected: BTreeSet<_> = LANG::into_enum_iter().map(|lang| lang.name()).collect(); assert_eq!(actual, expected); assert_eq!(actual.len(), header::LANGUAGES.len()); @@ -424,6 +451,10 @@ fn header_roster_skips_and_resource_boundaries_are_explicit() { exercise(&[0, 4, 0, 0]), Ok(Outcome::Skipped(Skip::IncludedRangeLimit)) ); + assert_eq!( + exercise(&[0, 4, 0]), + Ok(Outcome::Skipped(Skip::IncludedRangeLimit)) + ); } #[test] diff --git a/fuzz/src/lib.rs b/fuzz/src/lib.rs index 20464eead..d20bb8fa7 100644 --- a/fuzz/src/lib.rs +++ b/fuzz/src/lib.rs @@ -103,6 +103,9 @@ pub fn walk_all(lang: LANG, data: Vec) { /// Split out from [`walk_all`] so a target that builds its own /// [`Source`] — the preprocessor one has to — reuses the same fan-out /// rather than keeping a second copy of it in step. +/// +/// # Panics +/// Panics when a documentation property fails, so libFuzzer preserves the input. pub fn walk_parsed(ast: &Ast) { let documentation = documentation::check_ast(ast); assert!(documentation.is_ok(), "{documentation:?}"); From f92e6636cb12c0477d0b27edac03bd4361443182 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:53:25 -0800 Subject: [PATCH 046/221] fix(fuzz): specify mutation runner working directory --- fuzz/documentation-perturb.json | 1 + 1 file changed, 1 insertion(+) diff --git a/fuzz/documentation-perturb.json b/fuzz/documentation-perturb.json index 8985c6f95..c2a9c2e95 100644 --- a/fuzz/documentation-perturb.json +++ b/fuzz/documentation-perturb.json @@ -1,4 +1,5 @@ { + "cwd": ".", "command": ["cargo", "+nightly", "test", "--manifest-path", "fuzz/Cargo.toml", "--locked", "--lib", "--no-fail-fast"], "cases": [ { From 7f54ec442cbbc063b55c80a88ad9393d8232a1e6 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:59:39 -0800 Subject: [PATCH 047/221] feat(bench): add source documentation performance infrastructure Share source fixtures across Criterion and a typed raw-batch scaling gate. Add the validated test-support fresh-render seam and finite source axes with semantic and counter guards. Source checkpoint only: formatting and Markdown lint checked. Cargo compilation, semantic tests, mutation evidence and full validation await the parent's exclusive heavy-check slot; remote qualification remains parent-owned. --- Makefile | 11 +- big-code-analysis-ast/src/documentation.rs | 17 + .../src/documentation/collector.rs | 2 +- .../documentation/collector/qualifications.rs | 4 + .../src/documentation/index.rs | 23 +- .../src/documentation/qualifications.rs | 15 +- .../src/documentation/render_probe.rs | 306 +++++++ big-code-analysis-bench/Cargo.toml | 4 +- .../benches/documentation.rs | 626 +------------- .../benches/documentation/validation.rs | 243 ------ big-code-analysis-bench/benches/scaling.rs | 195 ++--- big-code-analysis-bench/src/cli.rs | 64 +- .../src/documentation/combined.rs | 178 ++++ .../src/documentation/fixtures.rs | 556 ++++++++++++ .../src/documentation/mod.rs | 36 + .../src/documentation/operation.rs | 512 +++++++++++ .../src/documentation/runner.rs | 796 ++++++++++++++++++ .../src/documentation/tests.rs | 509 +++++++++++ .../src/documentation/validation.rs | 594 +++++++++++++ big-code-analysis-bench/src/lib.rs | 11 +- docs/development/benchmarking.md | 141 +++- 21 files changed, 3835 insertions(+), 1008 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/render_probe.rs delete mode 100644 big-code-analysis-bench/benches/documentation/validation.rs create mode 100644 big-code-analysis-bench/src/documentation/combined.rs create mode 100644 big-code-analysis-bench/src/documentation/fixtures.rs create mode 100644 big-code-analysis-bench/src/documentation/mod.rs create mode 100644 big-code-analysis-bench/src/documentation/operation.rs create mode 100644 big-code-analysis-bench/src/documentation/runner.rs create mode 100644 big-code-analysis-bench/src/documentation/tests.rs create mode 100644 big-code-analysis-bench/src/documentation/validation.rs diff --git a/Makefile b/Makefile index 88536194f..46a29b533 100644 --- a/Makefile +++ b/Makefile @@ -196,6 +196,8 @@ help: @echo " bench bench-scaling + bench-walk (out-of-band; never in ci)" @echo " bench-scaling Complexity-class gate for the metric walk" @echo " bench-walk Criterion metric-walk benchmarks over a corpus slice" + @echo " bench-documentation Criterion source-documentation benchmarks" + @echo " bench-source Source-only class gate" @echo " fuzz-check Lint, test + build the cargo-fuzz targets (out-of-band)" @echo " fuzz-smoke Short bounded fuzz run over the committed corpora" @echo " fuzz-replay Replay the committed seeds only (regression check)" @@ -1402,13 +1404,20 @@ BENCH_ARGS ?= bench: bench-scaling bench-walk bench-scaling: - @echo "Running the metric-walk complexity-class gate..." + @echo "Running the legacy and source complexity-class gates..." @cargo bench -p big-code-analysis-bench --bench scaling -- $(BENCH_ARGS) bench-walk: @echo "Running criterion metric-walk benchmarks..." @cargo bench -p big-code-analysis-bench --bench metric_walk -- $(BENCH_ARGS) +.PHONY: bench-documentation bench-source +bench-documentation: + @cargo bench -p big-code-analysis-bench --bench documentation -- $(BENCH_ARGS) + +bench-source: + @cargo bench -p big-code-analysis-bench --bench scaling -- --scope source $(BENCH_ARGS) + # --------------------------------------------------------------------------- # Fuzzing harness (#1154) # --------------------------------------------------------------------------- diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index 3f4119f94..4f4f03f33 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -39,6 +39,8 @@ mod ordering; mod owners; mod qualifications; pub(crate) mod recognition; +#[cfg(any(test, feature = "test-support"))] +pub mod render_probe; mod source; #[doc(hidden)] pub mod streaming; @@ -106,6 +108,16 @@ pub struct Observations { pub fold_slot_probes: usize, /// Recorded sibling positions compared. pub sibling_slot_probes: usize, + /// Association records consumed by prepared queries. + pub association_reads: usize, + /// Qualification records consumed by prepared queries. + pub qualification_reads: usize, + /// Qualification memberships indexed during collection. + pub qualification_memberships: usize, + /// Output-map binary-search comparisons. + pub map_searches: usize, + /// Output-map runs consumed by a query. + pub map_runs_visited: usize, } /// Read qualification counters without resetting other consumers' observations. @@ -138,6 +150,11 @@ pub fn observations() -> Observations { memo_probes: crate::node::memo_probes::observed(), fold_slot_probes: crate::node::fold_slot_probes::observed(), sibling_slot_probes: crate::node::sibling_slot_probes::observed(), + association_reads: index::association_reads::observed(), + qualification_reads: qualifications::qualification_reads::observed(), + qualification_memberships: collector::qualifications::memberships::observed(), + map_searches: content::map_searches::observed(), + map_runs_visited: content::map_runs_visited::observed(), } } diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index ed384e9ee..bf17ca2ee 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -9,7 +9,7 @@ use crate::{Ancestors, Checker, FoldCache, Node, SiblingCache}; mod assembly; mod projections; -mod qualifications; +pub(super) mod qualifications; enum Visit { Enter(NodeId, usize), diff --git a/big-code-analysis-ast/src/documentation/collector/qualifications.rs b/big-code-analysis-ast/src/documentation/collector/qualifications.rs index c374d5677..feb6ff980 100644 --- a/big-code-analysis-ast/src/documentation/collector/qualifications.rs +++ b/big-code-analysis-ast/src/documentation/collector/qualifications.rs @@ -3,6 +3,7 @@ use super::*; use crate::documentation::names::NamedOwner; use crate::documentation::qualifications::QualificationSet; +crate::observation::counter!(memberships, cfg(any(test, feature = "test-support"))); impl<'s> Builder<'s> { pub(super) fn candidate_qualifications( @@ -68,11 +69,14 @@ impl<'s> Builder<'s> { let qualification = &self.index.qualifications[ordinal]; self.index.qualifications_ordered.push(ordinal); self.index.qualifications_by_document[qualification.document.0].push(ordinal); + memberships::record(); if let Some(owner) = qualification.owner { self.index.qualifications_by_owner[owner.0].push(ordinal); + memberships::record(); self.index.canonical.nodes[self.index.owner_nodes[owner.0].0] .qualifications .push(ordinal); + memberships::record(); } } Ok(()) diff --git a/big-code-analysis-ast/src/documentation/index.rs b/big-code-analysis-ast/src/documentation/index.rs index 0d5b83412..d286cd2f0 100644 --- a/big-code-analysis-ast/src/documentation/index.rs +++ b/big-code-analysis-ast/src/documentation/index.rs @@ -152,6 +152,7 @@ crate::observation::counter!( assessment_scope_reads, cfg(any(test, feature = "test-support")) ); +crate::observation::counter!(association_reads, cfg(any(test, feature = "test-support"))); impl<'i, 's> OwnerAssociations<'i, 's> { /// Known conditional/recovery facts for this candidate, independently of @@ -169,10 +170,13 @@ impl<'i, 's> OwnerAssociations<'i, 's> { } /// Known association records, without scanning other owners. pub fn associations(&self) -> impl ExactSizeIterator>> + '_ { - self.associations.iter().map(|&ordinal| FactRef { - scope: &self.index.facts.scope, - ordinal, - fact: &self.index.facts.associations[ordinal], + self.associations.iter().map(|&ordinal| { + association_reads::record(); + FactRef { + scope: &self.index.facts.scope, + ordinal, + fact: &self.index.facts.associations[ordinal], + } }) } @@ -293,10 +297,13 @@ impl<'s> DocumentationIndex<'s> { /// Associations in document order, then owner anchor and slot order. pub fn associations(&self) -> impl ExactSizeIterator>> { - self.associations_ordered.iter().map(|&ordinal| FactRef { - scope: &self.facts.scope, - ordinal, - fact: &self.facts.associations[ordinal], + self.associations_ordered.iter().map(|&ordinal| { + association_reads::record(); + FactRef { + scope: &self.facts.scope, + ordinal, + fact: &self.facts.associations[ordinal], + } }) } diff --git a/big-code-analysis-ast/src/documentation/qualifications.rs b/big-code-analysis-ast/src/documentation/qualifications.rs index 457b83a1b..2ccce48e6 100644 --- a/big-code-analysis-ast/src/documentation/qualifications.rs +++ b/big-code-analysis-ast/src/documentation/qualifications.rs @@ -1,6 +1,10 @@ //! Known source qualifications, separate from unfinished adapter assessments. use super::*; +crate::observation::counter!( + qualification_reads, + cfg(any(test, feature = "test-support")) +); #[derive(Clone, Copy, Debug, Default)] pub(super) struct QualificationSet(u8); @@ -109,10 +113,13 @@ impl<'s> DocumentationIndex<'s> { &'i self, ids: &'i [usize], ) -> impl ExactSizeIterator>> { - ids.iter().map(|&ordinal| FactRef { - scope: &self.facts.scope, - ordinal, - fact: &self.qualifications[ordinal], + ids.iter().map(|&ordinal| { + qualification_reads::record(); + FactRef { + scope: &self.facts.scope, + ordinal, + fact: &self.qualifications[ordinal], + } }) } } diff --git a/big-code-analysis-ast/src/documentation/render_probe.rs b/big-code-analysis-ast/src/documentation/render_probe.rs new file mode 100644 index 000000000..609574537 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/render_probe.rs @@ -0,0 +1,306 @@ +//! Validated fresh comment rendering for benchmark and test callers. +//! +//! Preparation borrows an immutable index and its ordered fragments. Each call +//! renders new text and maps through the production renderer; dropping that output +//! belongs inside a construction benchmark. Retained `complete_text` is separate. + +use super::budget::{CollectionBudget, WorkBudget}; +use super::text::TextError; +use super::{Composition, Content, Document, DocumentationIndex, FactError, FactRef, Fragment}; +use super::{FragmentForm, SourceError, UnavailableReason}; + +/// Probe failures preserve identity, unsupported-form and source distinctions. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RenderError { + /// A handle came from a different index or a record is missing. + Fact(FactError), + /// The document has unsupported composition, fragments or content state. + Unsupported, + /// Source validation or active cancellation failed. + Source(SourceError), + /// The production renderer cannot provide complete output. + Unavailable(UnavailableReason), +} + +/// An index-borrowing prepared call to the production comment renderer. +#[derive(Debug)] +pub struct PreparedRender<'i, 's> { + index: &'i DocumentationIndex<'s>, + fragments: Vec<&'i Fragment<'s>>, +} + +impl<'i, 's> PreparedRender<'i, 's> { + /// Validate a real index document and retain references in composition order. + /// + /// # Errors + /// Rejects foreign handles, incomplete or non-comment documents, and invalid + /// retained source intersections. Preparation is outside the measured call. + pub fn new( + index: &'i DocumentationIndex<'s>, + document: FactRef<'_, Document<'s>>, + ) -> Result { + // bca: suppress(nexits, halstead) -- preparation validates identity, composition and every retained source intersection before trusting render input. + index + .facts + .check_scope(document) + .map_err(RenderError::Fact)?; + let document = &index.facts.documents[document.ordinal]; + if !matches!(document.content, Content::Complete { .. }) + || !matches!( + document.composition, + Composition::Single | Composition::CommentRun + ) + || document.fragments.is_empty() + { + return Err(RenderError::Unsupported); + } + let mut fragments = Vec::with_capacity(document.fragments.len()); + let mut previous_end = 0; + for id in &document.fragments { + let fragment = index + .facts + .fragments + .get(id.0) + .ok_or(RenderError::Fact(FactError::MissingRecord))?; + if fragment.form != FragmentForm::Comment || fragment.source.has_excluded_gap() { + return Err(RenderError::Unsupported); + } + let pieces = fragment.source.pieces(); + let first = pieces + .first() + .ok_or(RenderError::Source(SourceError::InvalidRange))?; + let last = pieces + .last() + .ok_or(RenderError::Source(SourceError::InvalidRange))?; + let range = first.range().start..last.range().end; + if range.start < previous_end { + return Err(RenderError::Source(SourceError::InvalidRange)); + } + let validated = index + .source + .pieces(range.clone()) + .map_err(RenderError::Source)?; + if validated != fragment.source { + return Err(RenderError::Source(SourceError::InvalidRange)); + } + previous_end = range.end; + fragments.push(fragment); + } + Ok(Self { index, fragments }) + } + + /// Build fresh content with a fresh work budget, including an entry poll. + /// + /// # Errors + /// Propagates active cancellation even for empty text, source failures and + /// unavailable production rendering. No retained output is reused. + pub fn render(&self) -> Result, RenderError> { + let budget = CollectionBudget::default(); + budget.checkpoint().map_err(RenderError::Source)?; + super::text::comments::render( + self.index.profile, + &self.index.source, + &self.fragments, + &budget, + ) + .map_err(|error| match error { + TextError::Source(error) => RenderError::Source(error), + TextError::Unavailable(reason) => RenderError::Unavailable(reason), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::documentation::{DocumentationContext, DocumentationOptions, observations}; + use crate::{AnyParser, LANG}; + + #[cfg(feature = "rust")] + #[test] + fn fresh_render_and_retained_access_have_distinct_work() { + let parser = + AnyParser::parse(LANG::Rust, b"///a\n///b\nfn f() {}".to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let document = index.documents().next().unwrap(); + let prepared = PreparedRender::new(&index, document).unwrap(); + let before = observations(); + for _ in 0..3 { + let Content::Complete { text, mappings } = prepared.render().unwrap() else { + panic!("complete") + }; + assert_eq!(text, "a\nb"); + assert_eq!( + mappings, + index.complete_text(document).unwrap().unwrap().mappings() + ); + } + let after = observations(); + assert_eq!(after.renders - before.renders, 3); + // Two copied characters and one synthetic separator per render. + assert_eq!(after.copy_chunks - before.copy_chunks, 9); + let retained = index.complete_text(document).unwrap().unwrap(); + for _ in 0..3 { + let next = index.complete_text(document).unwrap().unwrap(); + assert!(std::ptr::eq(retained.text(), next.text())); + assert!(std::ptr::eq(retained.mappings(), next.mappings())); + } + assert_eq!(observations().renders, after.renders); + assert_eq!(observations().copy_chunks, after.copy_chunks); + } + + #[cfg(feature = "rust")] + #[test] + fn tiny_and_empty_render_poll_cancellation_at_entry() { + for source in ["///\nfn f() {}", "///a\nfn f() {}"] { + let parser = + AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let prepared = PreparedRender::new(&index, index.documents().next().unwrap()).unwrap(); + let flag = crate::cancel::ParseCancel::new(); + flag.cancel(); + let before = observations(); + assert!(matches!( + flag.run(|| prepared.render()), + Err(RenderError::Source(SourceError::Cancelled)) + )); + assert_eq!(observations().renders, before.renders); + assert!(matches!(prepared.render(), Ok(Content::Complete { .. }))); + let active = crate::cancel::ParseCancel::new(); + assert!(matches!( + active.run(|| prepared.render()), + Ok(Content::Complete { .. }) + )); + } + } + + #[cfg(feature = "rust")] + #[test] + fn preparation_rejects_foreign_and_pending_documents() { + let parser = AnyParser::parse( + LANG::Rust, + b"#[doc(hidden)]\nfn f() {}".to_vec(), + None, + None, + ) + .unwrap(); + let first = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let second = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let document = first.documents().next().unwrap(); + assert!(matches!( + PreparedRender::new(&second, document), + Err(RenderError::Fact(_)) + )); + assert!(matches!( + PreparedRender::new(&first, document), + Err(RenderError::Unsupported) + )); + } + + #[cfg(feature = "rust")] + #[test] + fn preparation_rejects_unavailable_and_noncomment_forms() { + let parser = + AnyParser::parse(LANG::Rust, b"///audit\nfn f() {}".to_vec(), None, None).unwrap(); + let mut index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + index.facts.fragments[0].form = FragmentForm::Literal; + assert!(matches!( + PreparedRender::new(&index, index.documents().next().unwrap()), + Err(RenderError::Unsupported) + )); + index.facts.fragments[0].form = FragmentForm::Comment; + index.facts.documents[0].content = Content::Unavailable(UnavailableReason::ExcludedGap); + assert!(matches!( + PreparedRender::new(&index, index.documents().next().unwrap()), + Err(RenderError::Unsupported) + )); + } + + #[cfg(feature = "rust")] + #[test] + fn preparation_rejects_invalid_retained_source_order() { + let parser = + AnyParser::parse(LANG::Rust, b"///a\n///b\nfn f() {}".to_vec(), None, None).unwrap(); + let mut index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + index.facts.documents[0].fragments.swap(0, 1); + assert!(matches!( + PreparedRender::new(&index, index.documents().next().unwrap()), + Err(RenderError::Source(SourceError::InvalidRange)) + )); + } + + #[cfg(feature = "rust")] + #[test] + fn valid_preparation_borrows_adjacent_range_intersections() { + let source = b"///audit\nfn f() {}"; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser + .set_included_ranges(&[ + tree_sitter::Range { + start_byte: 0, + end_byte: 4, + start_point: tree_sitter::Point::new(0, 0), + end_point: tree_sitter::Point::new(0, 4), + }, + tree_sitter::Range { + start_byte: 4, + end_byte: source.len(), + start_point: tree_sitter::Point::new(0, 4), + end_point: tree_sitter::Point::new(1, 9), + }, + ]) + .unwrap(); + let tree = parser.parse(source, None).unwrap(); + let index = super::super::collect( + LANG::Rust, + &tree, + source, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let document = index.documents().next().unwrap(); + let prepared = PreparedRender::new(&index, document).unwrap(); + let Content::Complete { text, mappings } = prepared.render().unwrap() else { + panic!("complete") + }; + assert_eq!(text, "audit"); + assert_eq!( + mappings, + index.complete_text(document).unwrap().unwrap().mappings() + ); + } +} diff --git a/big-code-analysis-bench/Cargo.toml b/big-code-analysis-bench/Cargo.toml index b5cda3b80..11354390f 100644 --- a/big-code-analysis-bench/Cargo.toml +++ b/big-code-analysis-bench/Cargo.toml @@ -34,7 +34,9 @@ workspace = true # `vcs` is on so the harness can time `vcs::score::apply_percentile` # (#1267), the one hot path here that is not a walk over an AST. big-code-analysis = { path = "..", features = ["vcs"] } -big-code-analysis-ast = { path = "../big-code-analysis-ast", default-features = false } +# Ordinary dependency: prepared render state is used by the library runner. +# Workspace feature unification exposes readers; production recording is unconditional. +big-code-analysis-ast = { path = "../big-code-analysis-ast", default-features = false, features = ["test-support"] } # For the `verbatim-oracle` record lines (#1744); the root's own # serialisers are what the record carries. serde_json.workspace = true diff --git a/big-code-analysis-bench/benches/documentation.rs b/big-code-analysis-bench/benches/documentation.rs index c682b0fc4..cb97e5833 100644 --- a/big-code-analysis-bench/benches/documentation.rs +++ b/big-code-analysis-bench/benches/documentation.rs @@ -1,607 +1,37 @@ -//! Direct-AST source documentation workloads; parsing is outside timed regions. +//! Criterion measurements over the same registry as the source scaling gate. -use std::hint::black_box; - -use big_code_analysis_ast::documentation::{DocumentationContext, DocumentationOptions}; -use big_code_analysis_ast::{AnyParser, LANG}; +use big_code_analysis_bench::documentation::{Parsed, Prepared, REGISTRY}; use criterion::{BenchmarkId, Criterion}; -#[path = "documentation/validation.rs"] -mod validation; - fn main() { let mut criterion = Criterion::default().configure_from_args(); - let context = DocumentationContext::default(); - let options = DocumentationOptions::default(); - for size in [256, 512, 1024] { - cold(&mut criterion, size, &context, options); - secondary(&mut criterion, size, &context, options); - prepared(&mut criterion, size, &context, options); - late_owner(&mut criterion, size, &context, options); - included_ranges(&mut criterion, size, &context, options); - } - for size in [1024, 2048, 4096] { - remediation(&mut criterion, size, &context, options); - multiline_ranges(&mut criterion, size, &context, options); - } - criterion.final_summary(); -} - -fn included_ranges( - criterion: &mut Criterion, - size: usize, - context: &DocumentationContext, - options: DocumentationOptions, -) { - use big_code_analysis_ast::tree_sitter; - let source = "///audit\nfn f() {}\n".repeat(size).into_bytes(); - let mut parser = tree_sitter::Parser::new(); - parser - .set_language( - &LANG::Rust - .tree_sitter_language() - .unwrap_or_else(|error| panic!("grammar: {error}")), - ) - .unwrap_or_else(|error| panic!("grammar: {error}")); - let ranges: Vec<_> = (0..size) - .map(|at| tree_sitter::Range { - start_byte: at * 19, - end_byte: (at + 1) * 19, - start_point: tree_sitter::Point::new(at * 2, 0), - end_point: tree_sitter::Point::new((at + 1) * 2, 0), - }) - .collect(); - parser - .set_included_ranges(&ranges) - .unwrap_or_else(|error| panic!("ranges: {error}")); - let tree = parser - .parse(&source, None) - .unwrap_or_else(|| panic!("complete parse")); - assert_eq!(tree.included_ranges().len(), size); - let checked = big_code_analysis_ast::documentation::collect( - LANG::Rust, - &tree, - &source, - context, - &options, - ) - .unwrap_or_else(|error| panic!("collect: {error:?}")); - validation::documents(&checked, size, 1, 1, "audit"); - drop(checked); - let mut group = criterion.benchmark_group("documentation/ranges"); - group.bench_function(BenchmarkId::new("cold", size), |bencher| { - bencher.iter(|| { - black_box( - big_code_analysis_ast::documentation::collect( - LANG::Rust, - black_box(&tree), - black_box(&source), - black_box(context), - black_box(&options), - ) - .unwrap_or_else(|error| panic!("collect: {error:?}")), - ) - }); - }); - group.finish(); -} - -fn cold( - criterion: &mut Criterion, - size: usize, - context: &DocumentationContext, - options: DocumentationOptions, -) { - let workloads = [ - ( - "depth", - LANG::Rust, - format!( - "{}///audit\nfn leaf() {{}}{}", - "mod m {".repeat(size), - "}".repeat(size) - ), - ), - ("width", LANG::Rust, "///audit\nfn f() {}\n".repeat(size)), - ( - "fragments", - LANG::Go, - format!("package p\n{}func F() {{}}", "// audit\n".repeat(size)), - ), - ( - "single-line-lua", - LANG::Lua, - format!( - "module(\"m\")\n---{}\nfunction f() end", - "audit ".repeat(size) - ), - ), - ( - "single-line-jsdoc", - LANG::Javascript, - format!("/**{}*/\nfunction f() {{}}", "audit ".repeat(size)), - ), - ( - "c-slots", - LANG::C, - format!( - "/**audit*/\nint {};", - (0..size) - .map(|at| format!("v{at}")) - .collect::>() - .join(",") - ), - ), - ( - "wide-error", - LANG::C, - format!("/**audit*/\nstruct {{\n{}", "int x;\n".repeat(size)), - ), - ( - "missing", - LANG::Rust, - format!( - "fn f() {{ {}0{}; }}", - "(".repeat(size), - ")".repeat(size - 1) - ), - ), - ("names", LANG::Cpp, names_source(size)), - ]; - let mut group = criterion.benchmark_group("documentation/cold"); - for (name, language, source) in workloads { - let parser = AnyParser::parse(language, source.into_bytes(), None, None) - .unwrap_or_else(|error| panic!("{name}: {error}")); - validation::fixture(name, size, &parser, context, options); - group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { - bencher.iter(|| { - black_box( - black_box(parser) - .documentation(black_box(context), black_box(&options)) - .unwrap_or_else(|error| panic!("collection: {error:?}")), - ) - }); - }); - } - group.finish(); -} - -fn secondary( - criterion: &mut Criterion, - size: usize, - context: &DocumentationContext, - options: DocumentationOptions, -) { - let slots = (0..size) - .map(|at| format!("v{at}")) - .collect::>() - .join(","); - let workloads = [ - ( - "single-line-php", - LANG::Php, - format!(" String { - use std::fmt::Write; - let mut source = String::new(); - for at in 0..size { - let _ = writeln!(source, "/** @fn void f{at}() */\nvoid f{at}() {{}}"); - } - source -} - -fn prepared( - criterion: &mut Criterion, - size: usize, - context: &DocumentationContext, - options: DocumentationOptions, -) { - let parser = AnyParser::parse( - LANG::Rust, - "///a\n" - .repeat(size) - .into_bytes() - .into_iter() - .chain(b"fn f() {}".iter().copied()) - .collect(), - None, - None, - ) - .unwrap_or_else(|error| panic!("parse: {error}")); - let index = parser - .documentation(context, &options) - .unwrap_or_else(|error| panic!("collection: {error:?}")); - let document = index - .documents() - .next() - .unwrap_or_else(|| panic!("fixture has a document")); - let text = index - .complete_text(document) - .unwrap_or_else(|error| panic!("text: {error:?}")) - .unwrap_or_else(|| panic!("complete text")); - let owner = parser - .root_node() - .children() - .last() - .unwrap_or_else(|| panic!("fixture has a function")); - validation::documents( - &index, - 1, - size, - 1, - &std::iter::repeat_n("a", size) - .collect::>() - .join("\n"), - ); - assert_eq!(owner.kind(), "function_item"); - assert_eq!(owner.start_byte(), 5 * size); - assert_eq!(text.mappings().len(), size * 2 - 1); - let portions: Vec<_> = text - .origins(size * 2 - 2..size * 2 - 1) - .unwrap_or_else(|error| panic!("map: {error:?}")) - .collect(); - assert_eq!(portions.len(), 1); - let big_code_analysis_ast::documentation::OriginView::Copied(piece) = &portions[0].origin - else { - panic!("copied late origin") - }; - assert_eq!(piece.range(), (size - 1) * 5 + 3..(size - 1) * 5 + 4); - let mut group = criterion.benchmark_group("documentation/prepared"); - group.bench_function(BenchmarkId::new("owner", size), |bencher| { - bencher.iter(|| { - black_box( - black_box(&index) - .node_associations(black_box(owner.as_tree_sitter())) - .unwrap_or_else(|error| panic!("owner: {error:?}")) - .associations() - .count(), - ) - }); - }); - group.bench_function(BenchmarkId::new("late-map", size), |bencher| { - bencher.iter(|| { - for portion in black_box(text) - .origins(black_box(text.text().len() - 1..text.text().len())) - .unwrap_or_else(|error| panic!("map: {error:?}")) - { - black_box(portion); - } - }); - }); - group.bench_function(BenchmarkId::new("retained", size), |bencher| { - bencher.iter(|| { - black_box( - black_box(&index) - .complete_text(black_box(document)) - .unwrap_or_else(|error| panic!("text: {error:?}")), - ) - }); - }); - group.finish(); -} - -#[allow(clippy::too_many_lines)] // Each workload keeps its untimed semantic control next to its fixture. -fn remediation( - criterion: &mut Criterion, - size: usize, - context: &DocumentationContext, - options: DocumentationOptions, -) { - let depth = size / 16; - let workloads = [ - ( - "inline-spans", - LANG::Cpp, - format!("/**{}*/\nvoid f() {{}}", "`x` ".repeat(size)), - ), - ( - "gathered-disposition", - LANG::Cpp, - format!("{}/**{}@file*/", "/**a*/\n".repeat(size), "x ".repeat(size)), - ), - ( - "complex-signatures", - LANG::Cpp, - format!( - "{}void leaf();{}", - "void f(int x = [] { ".repeat(depth), - " return 1; }());".repeat(depth) - ), - ), - ( - "order-multiple-chunks", - LANG::Rust, - "///audit\nfn f() {}\n".repeat(size), - ), - ( - "text-budget-boundary", - LANG::Rust, - format!("///{}\nfn f() {{}}", "abcd".repeat(size * 2)), - ), - ( - "go-fold", - LANG::Go, - format!( - "package p\ntype S struct {{\n{}X int\n{} }}\n", - "X struct {\n".repeat(depth), - "}\n".repeat(depth) - ), - ), - ( - "ruby-fold", - LANG::Ruby, - format!( - "{}# audit\ndef f; end\n{}", - "class C\n".repeat(depth), - "end\n".repeat(depth) - ), - ), - ]; - let mut group = criterion.benchmark_group("documentation/remediation"); - for (name, language, source) in workloads { - let parser = AnyParser::parse(language, source.into_bytes(), None, None) - .unwrap_or_else(|error| panic!("{error}")); - assert!(!parser.root_node().has_error(), "{name}"); - let checked = parser - .documentation(context, &options) - .unwrap_or_else(|error| panic!("{error:?}")); - match name { - "inline-spans" => { - validation::documents(&checked, 1, 1, 1, &"`x` ".repeat(size)[..size * 4 - 1]); - } - "gathered-disposition" => { - assert_eq!(checked.documents().len(), 1); - assert_eq!( - checked - .documents() - .next() - .unwrap_or_else(|| panic!("doc")) - .get() - .fragment_count(), - size + 1 - ); + for probe in REGISTRY { + let Some((group_name, name)) = probe.id.rsplit_once('/') else { + eprintln!("invalid documentation benchmark ID: {}", probe.id); + std::process::exit(2); + }; + let mut group = criterion.benchmark_group(group_name); + for size in probe.sizes { + let result = (|| { + let parsed = Parsed::new(probe, size)?; + let index = parsed.collect(probe)?; + let prepared = Prepared::new(probe, size, &parsed, &index)?; + group.bench_function(BenchmarkId::new(name, size), |bencher| { + bencher.iter(|| { + if let Err(error) = prepared.execute() { + eprintln!("{} size {size}: {error}", probe.id); + std::process::exit(2); + } + }); + }); + Ok::<_, big_code_analysis_bench::documentation::HarnessError>(()) + })(); + if let Err(error) = result { + eprintln!("{} size {size}: {error}", probe.id); + std::process::exit(2); } - "complex-signatures" => { - assert_eq!(checked.documents().len(), 0); - assert_eq!( - parser - .root_node() - .preorder() - .filter(|node| node.kind() == "declaration") - .count(), - depth + 1 - ); - assert_eq!( - checked - .assessments() - .filter( - |a| a.get().reason == "Complex signature awaits exact named matching" - ) - .count(), - depth - ); - } - "go-fold" => { - assert_eq!(checked.documents().len(), 0); - assert_eq!( - parser - .root_node() - .preorder() - .filter(|node| node.kind() == "field_declaration") - .count(), - depth + 1 - ); - } - "order-multiple-chunks" => validation::documents(&checked, size, 1, 1, "audit"), - "text-budget-boundary" => { - validation::documents(&checked, 1, 1, 1, &"abcd".repeat(size * 2)); - } - "ruby-fold" => validation::documents(&checked, 1, 1, 1, "audit"), - _ => unreachable!(), } - drop(checked); - group.bench_with_input(BenchmarkId::new(name, size), &parser, |bencher, parser| { - bencher.iter(|| { - black_box( - black_box(parser) - .documentation(black_box(context), black_box(&options)) - .unwrap_or_else(|error| panic!("{error:?}")), - ) - }); - }); + group.finish(); } - group.finish(); -} - -fn multiline_ranges( - criterion: &mut Criterion, - size: usize, - context: &DocumentationContext, - options: DocumentationOptions, -) { - use big_code_analysis_ast::tree_sitter; - let source = format!("/**\n{}*/\nclass C {{}}", " * audit\n".repeat(size)); - let mut parser = tree_sitter::Parser::new(); - parser - .set_language( - &LANG::Java - .tree_sitter_language() - .unwrap_or_else(|error| panic!("{error}")), - ) - .unwrap_or_else(|error| panic!("{error}")); - let mut point = tree_sitter::Point::new(0, 0); - let ranges: Vec<_> = source - .bytes() - .enumerate() - .map(|(at, byte)| { - let start_point = point; - if byte == b'\n' { - point.row += 1; - point.column = 0; - } else { - point.column += 1; - } - tree_sitter::Range { - start_byte: at, - end_byte: at + 1, - start_point, - end_point: point, - } - }) - .collect(); - parser - .set_included_ranges(&ranges) - .unwrap_or_else(|error| panic!("{error}")); - let tree = parser - .parse(&source, None) - .unwrap_or_else(|| panic!("parse")); - assert!(!tree.root_node().has_error()); - let checked = big_code_analysis_ast::documentation::collect( - LANG::Java, - &tree, - source.as_bytes(), - context, - &options, - ) - .unwrap_or_else(|error| panic!("{error:?}")); - validation::documents( - &checked, - 1, - 1, - 1, - &std::iter::repeat_n("audit", size) - .collect::>() - .join("\n"), - ); - drop(checked); - let mut group = criterion.benchmark_group("documentation/remediation"); - group.bench_function( - BenchmarkId::new("multiline-adjacent-ranges", size), - |bencher| { - bencher.iter(|| { - black_box( - big_code_analysis_ast::documentation::collect( - LANG::Java, - black_box(&tree), - black_box(source.as_bytes()), - black_box(context), - black_box(&options), - ) - .unwrap_or_else(|error| panic!("{error:?}")), - ) - }); - }, - ); - group.finish(); + criterion.final_summary(); } diff --git a/big-code-analysis-bench/benches/documentation/validation.rs b/big-code-analysis-bench/benches/documentation/validation.rs deleted file mode 100644 index f3b435b19..000000000 --- a/big-code-analysis-bench/benches/documentation/validation.rs +++ /dev/null @@ -1,243 +0,0 @@ -//! Untimed semantic and grammar-shape checks for the documentation workloads. - -use big_code_analysis_ast::AnyParser; -use big_code_analysis_ast::documentation::{ - AssessmentAxis, Content, DocumentationContext, DocumentationIndex, DocumentationOptions, - OriginView, Owner, Resolution, UnresolvedReason, -}; - -pub(super) fn documents( - index: &DocumentationIndex<'_>, - count: usize, - fragments: usize, - owners: usize, - expected: &str, -) { - assert_eq!(index.documents().len(), count); - assert_eq!(index.associations().len(), count); - for association in index.associations() { - assert_eq!(association.get().resolution, Resolution::Resolved); - assert_eq!(association.get().owner_count(), owners); - let document = index - .facts() - .associated_document(association) - .unwrap_or_else(|error| panic!("document: {error:?}")); - assert_eq!(document.get().fragment_count(), fragments); - let text = index - .complete_text(document) - .unwrap_or_else(|error| panic!("text: {error:?}")) - .unwrap_or_else(|| panic!("complete text")); - assert_eq!(text.text(), expected); - let mut end = 0; - for portion in text - .origins(0..expected.len()) - .unwrap_or_else(|error| panic!("map: {error:?}")) - { - assert_eq!(portion.output.start, end); - end = portion.output.end; - if let OriginView::Copied(piece) = portion.origin { - assert_eq!(piece.bytes(), &expected.as_bytes()[portion.output]); - } - } - assert_eq!(end, expected.len()); - for position in 0..owners { - let owner = index - .facts() - .associated_owner(association, position) - .unwrap_or_else(|error| panic!("owner: {error:?}")); - let query = index - .owner_associations(owner) - .unwrap_or_else(|error| panic!("query: {error:?}")); - assert_eq!(query.associations().collect::>(), [association]); - } - } -} - -fn shape(name: &str, size: usize, parser: &AnyParser) { - let root = parser.root_node(); - assert_eq!( - root.has_error(), - matches!(name, "wide-error" | "missing"), - "{name}" - ); - let nodes: Vec<_> = root.preorder().collect(); - let count = |kind| nodes.iter().filter(|node| node.kind() == kind).count(); - let mut depth = 0; - let mut cursor = parser.ts_tree().walk(); - let mut maximum = 0; - loop { - maximum = maximum.max(depth); - if cursor.goto_first_child() { - depth += 1; - continue; - } - while !cursor.goto_next_sibling() { - if !cursor.goto_parent() { - break; - } - depth -= 1; - } - if depth == 0 { - break; - } - } - match name { - "depth" => { - assert_eq!(count("mod_item"), size); - assert!(maximum >= 2 * size); - } - "width" => assert_eq!(root.child_count(), size * 2), - "fragments" => assert_eq!(count("comment"), size), - "c-slots" | "fanout-fixed-text" => assert_eq!(count("identifier"), size), - "visible-declarator-depth" => { - assert_eq!(count("array_declarator"), size); - assert!(maximum >= size); - } - "ruby-modifiers" => { - assert_eq!(count("if_modifier"), size); - assert!(maximum >= size); - } - "java-undocumented" => { - assert_eq!(count("class_declaration"), size); - assert!(maximum >= 2 * size); - } - "pending-scope" => assert_eq!(count("function_item"), size), - "names" => assert_eq!(count("function_definition"), size), - "missing" => { - assert_eq!(nodes.iter().filter(|node| node.is_missing()).count(), 1); - assert!(maximum >= size); - } - "wide-error" => { - let error = nodes - .iter() - .find(|node| node.is_error()) - .unwrap_or_else(|| panic!("wide ERROR")); - assert!(error.child_count() >= size); - assert_eq!(count("field_declaration"), size); - } - _ => assert!(matches!( - name, - "single-line-lua" - | "single-line-jsdoc" - | "single-line-php" - | "single-line-ruby" - | "single-line-doxygen" - | "text-fixed-fanout" - )), - } -} - -#[allow(clippy::too_many_lines)] // One explicit expected outcome per benchmark workload. -pub(super) fn fixture( - name: &str, - size: usize, - parser: &AnyParser, - context: &DocumentationContext, - options: DocumentationOptions, -) { - shape(name, size, parser); - let index = parser - .documentation(context, &options) - .unwrap_or_else(|error| panic!("{name}: {error:?}")); - match name { - "depth" | "ruby-modifiers" | "visible-declarator-depth" => { - documents(&index, 1, 1, 1, "audit"); - } - "width" => documents(&index, size, 1, 1, "audit"), - "fragments" => documents( - &index, - 1, - size, - 1, - &std::iter::repeat_n("audit", size) - .collect::>() - .join("\n"), - ), - "c-slots" => documents(&index, 1, 1, size, "audit"), - "single-line-lua" | "single-line-ruby" => { - documents(&index, 1, 1, 1, &"audit ".repeat(size)); - } - "single-line-jsdoc" | "single-line-php" | "single-line-doxygen" => { - documents(&index, 1, 1, 1, &"audit ".repeat(size)[..size * 6 - 1]); - } - "text-fixed-fanout" => documents(&index, 1, 1, 2, &"audit ".repeat(size)[..size * 6 - 1]), - "fanout-fixed-text" => documents(&index, 1, 1, size, &"audit ".repeat(1024)[..6143]), - "java-undocumented" => { - assert_eq!(index.documents().len(), 0); - assert_eq!(index.facts().owners().len(), size + 2); - } - "missing" => { - assert_eq!(index.documents().len(), 0); - assert_eq!(index.associations().len(), 0); - } - "wide-error" => { - assert_eq!(index.documents().len(), 1); - let association = index - .associations() - .next() - .unwrap_or_else(|| panic!("recovery association")); - assert_eq!( - association.get().resolution, - Resolution::Unresolved(UnresolvedReason::GrammarBoundary) - ); - assert_eq!(association.get().owner_count(), 0); - } - "pending-scope" => { - assert_eq!(index.documents().len(), 1); - let document = index - .documents() - .next() - .unwrap_or_else(|| panic!("pending attribute")); - assert!(matches!(document.get().content(), Content::PendingAdapter)); - assert_eq!(index.assessments().len(), 3); - let last = parser - .root_node() - .children() - .last() - .unwrap_or_else(|| panic!("last function")); - let query = index - .node_associations(last.as_tree_sitter()) - .unwrap_or_else(|error| panic!("query: {error:?}")); - assert_eq!(query.associations().len(), 0); - assert_eq!( - query - .assessments() - .map(|assessment| assessment.get().axis) - .collect::>(), - [AssessmentAxis::Occurrence, AssessmentAxis::Publication] - ); - } - "names" => { - assert_eq!(index.documents().len(), size); - assert_eq!(index.associations().len(), size); - for (ordinal, association) in index.associations().enumerate() { - assert_eq!(association.get().resolution, Resolution::Resolved); - assert_eq!(association.get().owner_count(), 1); - let owner = index - .facts() - .associated_owner(association, 0) - .unwrap_or_else(|error| panic!("owner: {error:?}")); - let Owner::Node(node) = owner.get() else { - panic!("function definition") - }; - assert_eq!( - &parser.code()[node.node().byte_range()], - format!("void f{ordinal}() {{}}").as_bytes() - ); - let document = index - .facts() - .associated_document(association) - .unwrap_or_else(|error| panic!("document: {error:?}")); - assert_eq!( - index - .complete_text(document) - .unwrap_or_else(|error| panic!("text: {error:?}")) - .unwrap_or_else(|| panic!("complete text")) - .text(), - format!("@fn void f{ordinal}()") - ); - } - } - _ => panic!("unvalidated workload {name}"), - } -} diff --git a/big-code-analysis-bench/benches/scaling.rs b/big-code-analysis-bench/benches/scaling.rs index 48795fc10..061e21e7d 100644 --- a/big-code-analysis-bench/benches/scaling.rs +++ b/big-code-analysis-bench/benches/scaling.rs @@ -1,49 +1,14 @@ -//! Complexity-class gate for the metric walk (#1068). -//! -//! Measures every probe in `shapes::PROBES` at three doubling sizes, -//! fits `time ~ size^k`, and fails when a probe's `k` exceeds the -//! bound it declared. This is where the wall-clock assertions that used -//! to live in `cognitive_deep_nesting_is_tractable` and -//! `tokens_deep_nesting_is_tractable` went: the unit suite keeps the -//! value assertions, which are host-independent, and the timing half -//! moved here, where it runs under the bench profile on a host the -//! operator chose. -//! -//! ```text -//! cargo bench -p big-code-analysis-bench --bench scaling -//! cargo bench -p big-code-analysis-bench --bench scaling -- --rounds 11 -//! ``` -//! -//! Argument handling lives in `big_code_analysis_bench::cli`, where it -//! is covered by tests that actually run: a `harness = false` bench -//! target executes `main` instead of libtest, so a `#[cfg(test)]` -//! module in this file would compile and never be exercised. -//! -//! See `docs/development/benchmarking.md`. +//! Combined legacy and source class gate. Arguments and reductions are library-tested. use std::process::ExitCode; -use big_code_analysis_bench::cli::{Action, Mode, USAGE, parse_args}; -use big_code_analysis_bench::scaling; -use big_code_analysis_bench::shapes::{PROBES, Probe}; -use big_code_analysis_bench::vcs::{self, VCS_PROBES, VcsProbe}; - -/// Exit code for "a probe left its complexity class". -/// -/// Distinct from [`HARNESS_ERROR`] because -/// `.github/workflows/benchmark.yml` reacts to the two differently: a -/// regression is re-measured and then filed as an issue, while a -/// harness that could not run is an infrastructure failure and must -/// not open one. Collapsing both onto a bare failure meant any error -/// that reproduced on the retry filed an issue claiming a complexity -/// regression. -const GATE_FAILURE: u8 = 1; - -/// Exit code for "the harness could not produce a measurement". -/// -/// Bad arguments, or a `MetricsError` from a language that is not -/// compiled into this build. -const HARNESS_ERROR: u8 = 2; +use big_code_analysis_bench::cli::{Action, Mode, Scope, USAGE, parse_args}; +use big_code_analysis_bench::documentation::{REGISTRY, combined::CombinedReport, runner}; +use big_code_analysis_bench::{ + scaling, + shapes::PROBES, + vcs::{self, VCS_PROBES}, +}; fn main() -> ExitCode { let args = match parse_args(std::env::args().skip(1)) { @@ -52,90 +17,78 @@ fn main() -> ExitCode { print!("{USAGE}"); return ExitCode::SUCCESS; } - Err(message) => { - eprintln!("{message}\n\n{USAGE}"); - return ExitCode::from(HARNESS_ERROR); + Err(error) => { + eprintln!("{error}\n{USAGE}"); + return ExitCode::from(2); } }; - - // An unoptimised build measures the walk through overflow checks - // and unelided bounds checks, which perturbs the constant factor - // enough that the exponent is not worth a verdict. let optimized = !cfg!(debug_assertions); - if !optimized { - eprintln!( - "note: built with debug assertions, so nothing here is gated. \ - Use `cargo bench` for a measurement worth quoting." - ); - } - - let smoke_set; - let smoke_ranking; - let (probes, ranking): (&[Probe], &[VcsProbe]) = if args.mode == Mode::Smoke { - eprintln!( - "note: smoke run at small sizes. Use `cargo bench -p \ - big-code-analysis-bench --bench scaling` for the real gate." - ); - smoke_set = scaling::smoke_probes(PROBES); - smoke_ranking = vcs::smoke_probes(VCS_PROBES); - (&smoke_set, &smoke_ranking) - } else { - (PROBES, VCS_PROBES) - }; - - let mut report = match scaling::run(probes, args.rounds) { - Ok(report) => report, + let mode = if optimized { args.mode } else { Mode::Smoke }; + eprintln!( + "scope {:?}, mode {:?}; legacy {} workloads, source {} workloads", + args.scope, + mode, + if args.scope == Scope::Source { + 0 + } else { + PROBES.len() + VCS_PROBES.len() + }, + if args.scope == Scope::Legacy { + 0 + } else { + REGISTRY.len() + } + ); + let result = (|| { + let legacy = if args.scope == Scope::Source { + None + } else { + let probes = if mode == Mode::Smoke { + scaling::smoke_probes(PROBES) + } else { + PROBES.to_vec() + }; + let ranking = if mode == Mode::Smoke { + vcs::smoke_probes(VCS_PROBES) + } else { + VCS_PROBES.to_vec() + }; + let mut report = scaling::run(&probes, args.rounds).map_err(|e| e.to_string())?; + report.probes.extend(vcs::run(&ranking, args.rounds).probes); + print!("{report}"); + Some(report) + }; + let source = if args.scope == Scope::Legacy { + None + } else { + let report = runner::run(REGISTRY, args.rounds, mode).map_err(|e| e.to_string())?; + print!("{report}"); + Some(report) + }; + let report = CombinedReport { legacy, source }; + let legacy_ids: Vec<_> = PROBES + .iter() + .map(|p| p.name) + .chain(VCS_PROBES.iter().map(|p| p.name)) + .collect(); + let source_ids: Vec<_> = REGISTRY.iter().map(|p| p.id).collect(); + report + .validate(args.scope, &legacy_ids, &source_ids) + .map_err(|e| e.to_string())?; + Ok::<_, String>(report) + })(); + match result { Err(error) => { eprintln!("scaling harness could not run: {error}"); - return ExitCode::from(HARNESS_ERROR); + ExitCode::from(2) } - }; - // The ranking probes grow a `Vec` rather than a tree, so - // they are measured by their own runner and joined here, where one - // report carries the whole gate. - report.probes.extend(vcs::run(ranking, args.rounds).probes); - print!("{report}"); - - if args.mode != Mode::Gate || !optimized { - return ExitCode::SUCCESS; - } - - let failures = report.failures(); - if failures.is_empty() { - println!( - "\nall {} probes within their complexity bound", - report.probes.len() - ); - return ExitCode::SUCCESS; - } - eprintln!("\n{} probe(s) failed:", failures.len()); - for probe in failures { - // An abandoned probe is reported by the budget it blew, not by - // its exponent: it was fitted over the cells that finished, so - // that number is flattering and quoting it reads as a harness - // bug rather than as the worst regression the gate can see. - if let Some((size, elapsed)) = probe.over_budget { - eprintln!( - " {name}: one walk at size {size} took {elapsed:?}, over the \ - {budget:?} per-walk budget\n {rationale}", - name = probe.name, - budget = scaling::MAX_CELL_WALK, - rationale = probe.rationale, - ); - } else { - eprintln!( - " {name}: fitted exponent {exp:.2} > {bound:.2}\n {rationale}", - name = probe.name, - exp = probe.exponent, - bound = probe.max_exponent, - rationale = probe.rationale, - ); + Ok(report) => { + if mode == Mode::Gate { + println!("combined gate: {} performance failures", report.failures()); + } else { + println!("{mode:?}: no performance verdict"); + } + ExitCode::from(report.exit_code(mode, optimized)) } } - eprintln!( - "\nRe-run on an idle host before treating this as a regression; a wide \ - min-max spread in the table above means the measurement, not the code, \ - is what changed." - ); - ExitCode::from(GATE_FAILURE) } diff --git a/big-code-analysis-bench/src/cli.rs b/big-code-analysis-bench/src/cli.rs index ba455205d..bfb2181e4 100644 --- a/big-code-analysis-bench/src/cli.rs +++ b/big-code-analysis-bench/src/cli.rs @@ -12,9 +12,10 @@ use crate::scaling::DEFAULT_ROUNDS; pub const USAGE: &str = "\ usage: cargo bench -p big-code-analysis-bench --bench scaling -- [options] - --rounds N measurement rounds per cell (default 7, must be odd) - --no-gate measure at full size, report the exponents, never fail + --rounds N measurement rounds per cell (default 7, odd in 1..=1023) + --no-gate full-size report, no performance verdict; harness failures still fail --smoke small sizes, no verdict (the `cargo test` path) + --scope S all (default), legacy, or source --help this message "; @@ -24,7 +25,7 @@ pub enum Mode { /// Measure at the probes' declared sizes and fail on a probe that /// left its complexity class. Gate, - /// Measure at the probes' declared sizes, report, never fail. + /// Full-size measurements without a performance verdict; harness errors still fail. ReportOnly, /// Small sizes, no verdict: enough to prove the harness still /// runs, not enough to mean anything. @@ -38,6 +39,19 @@ pub struct Args { pub rounds: usize, /// What the run is for. pub mode: Mode, + /// Explicit registry selection; no positional filter is silently ignored. + pub scope: Scope, +} + +/// Which registered workloads the combined entry point runs. +#[derive(PartialEq, Eq, Clone, Copy, Debug)] +pub enum Scope { + /// All legacy and source workloads. + All, + /// The unchanged metric-walk and VCS ladders. + Legacy, + /// Source-documentation ladders only. + Source, } /// What the caller should do with a parsed command line. @@ -62,19 +76,18 @@ pub enum Action { /// of order, because cargo appends `--bench` itself and the caller /// does not control where it lands. /// -/// A bare positional is criterion's benchmark filter, which arrives -/// here too when `cargo bench` runs every target in the package. It -/// selects nothing in this harness and is ignored. +/// Positional filters are rejected: ignoring one would measure the wrong set. /// /// # Errors /// /// Returns a message suitable for printing above [`USAGE`] when an /// option is unknown, or when `--rounds` is missing its value or given -/// something that is not a positive odd integer. +/// something outside the odd integers in 1..=1023. pub fn parse_args(argv: impl IntoIterator) -> Result { let mut rounds = DEFAULT_ROUNDS; let mut cargo_bench = false; let mut requested: Option = None; + let mut scope = Scope::All; let mut argv = argv.into_iter(); while let Some(arg) = argv.next() { @@ -85,13 +98,25 @@ pub fn parse_args(argv: impl IntoIterator) -> Result requested = Some(Mode::Smoke), "--no-gate" => requested = Some(Mode::ReportOnly), + "--scope" => { + scope = match argv.next().as_deref() { + Some("all") => Scope::All, + Some("legacy") => Scope::Legacy, + Some("source") => Scope::Source, + other => { + return Err(format!( + "--scope requires all, legacy, or source; got {other:?}" + )); + } + }; + } "--rounds" => { let value = argv.next().ok_or("--rounds needs a value")?; rounds = value .parse() .map_err(|_| format!("--rounds: not a positive integer: {value}"))?; - if rounds == 0 { - return Err("--rounds must be at least 1".to_owned()); + if rounds == 0 || rounds > 1023 { + return Err("--rounds must be in 1..=1023".to_owned()); } // Same invariant the `DEFAULT_ROUNDS` const assert // holds: an even count makes every median the average @@ -109,7 +134,7 @@ pub fn parse_args(argv: impl IntoIterator) -> Result { return Err(format!("unknown option: {other}")); } - _ => {} + _ => return Err(format!("unsupported positional filter: {arg}; use --scope")), } } @@ -117,12 +142,13 @@ pub fn parse_args(argv: impl IntoIterator) -> Result Args { match parse_args(args.iter().map(|a| (*a).to_owned())) { @@ -155,11 +181,18 @@ mod tests { assert_eq!(parse(&["--smoke", "--bench"]).mode, Mode::Smoke); } - /// A positional is criterion's filter, forwarded to every bench - /// target in the package. It must not be mistaken for an error. #[test] - fn positional_filter_is_ignored() { - assert_eq!(parse(&["--bench", "cognitive"]).mode, Mode::Gate); + fn scope_is_explicit_and_unknown_filters_fail_closed() { + assert_eq!(parse(&[]).scope, Scope::All); + assert_eq!(parse(&["--scope", "source"]).scope, Scope::Source); + assert_eq!(parse(&["--scope", "legacy"]).scope, Scope::Legacy); + for argv in [ + vec!["cognitive"], + vec!["--scope"], + vec!["--scope", "soruce"], + ] { + assert!(parse_args(argv.into_iter().map(str::to_owned)).is_err()); + } } #[test] @@ -180,6 +213,7 @@ mod tests { // which `USAGE` forbids and `DEFAULT_ROUNDS` asserts. vec!["--rounds", "10"], vec!["--rounds", "many"], + vec!["--rounds", "1025"], vec!["--unknown"], ] { assert!( diff --git a/big-code-analysis-bench/src/documentation/combined.rs b/big-code-analysis-bench/src/documentation/combined.rs new file mode 100644 index 000000000..715f54c35 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/combined.rs @@ -0,0 +1,178 @@ +//! Combined membership and exit semantics without changing legacy report types. + +use super::runner::SourceReport; +use super::{HarnessError, require}; +use crate::cli::{Mode, Scope}; +use crate::scaling; + +/// Independent result collections from the two scaling methods. +pub struct CombinedReport { + /// Legacy exponents, preserving their library contract. + pub legacy: Option, + /// Typed source statistics. + pub source: Option, +} + +impl CombinedReport { + /// Validate selected registry membership and count both kinds of failures. + /// + /// # Errors + /// Rejects absent, extra, duplicated or reordered results in either selected set. + pub fn validate( + &self, + scope: Scope, + legacy_ids: &[&str], + source_ids: &[&str], + ) -> Result<(), HarnessError> { + require( + self.legacy.is_some() == (scope != Scope::Source), + "legacy report scope mismatch", + )?; + require( + self.source.is_some() == (scope != Scope::Legacy), + "source report scope mismatch", + )?; + if let Some(report) = &self.legacy { + require( + legacy_ids + .iter() + .copied() + .collect::>() + .len() + == legacy_ids.len(), + "duplicate expected legacy ID", + )?; + require( + !report.probes.is_empty() + && report + .probes + .iter() + .map(|p| p.name) + .eq(legacy_ids.iter().copied()), + "legacy result membership mismatch", + )?; + } + if let Some(report) = &self.source { + require( + source_ids + .iter() + .copied() + .collect::>() + .len() + == source_ids.len(), + "duplicate expected source ID", + )?; + report.validate_data()?; + require( + !report.results.is_empty() + && report + .results + .iter() + .map(|p| p.id) + .eq(source_ids.iter().copied()), + "source result membership mismatch", + )?; + } + Ok(()) + } + + /// Total performance failures across separate report collections. + #[must_use] + pub fn failures(&self) -> usize { + self.legacy.as_ref().map_or(0, |r| r.failures().len()) + + self.source.as_ref().map_or(0, |r| r.failures().len()) + } + + /// Exit 1 for a performance failure in gate mode, otherwise 0. Harness errors + /// are represented by failed construction/validation and use exit 2 upstream. + #[must_use] + pub fn exit_code(&self, mode: Mode, optimized: bool) -> u8 { + u8::from(mode == Mode::Gate && optimized && self.failures() > 0) + } +} + +#[cfg(test)] +mod tests { + use super::super::runner::{Batch, SourceCell, SourceResult, Statistic}; + use super::*; + + #[test] + fn combined_membership_and_source_failure_cannot_hide_behind_legacy_pass() { + let legacy = scaling::Report { + rounds: 3, + probes: vec![scaling::ProbeReport { + name: "legacy", + cells: vec![], + exponent: 1.0, + max_exponent: 1.5, + rationale: "", + over_budget: None, + }], + }; + let source = SourceReport { + rounds: 3, + mode: Mode::Gate, + results: vec![SourceResult { + id: "source", + cells: [256, 512, 1024] + .into_iter() + .zip([200_000, 200_000, 400_000]) + .map(|(size, ns)| { + let elapsed = std::time::Duration::from_nanos(ns); + SourceCell { + counts: super::super::SourceCounts::default(), + size, + bytes: size, + segments: 1, + iterations: 1, + batches: (0..3).map(|round| Batch { round, elapsed }).collect(), + batch_min: elapsed, + batch_median: elapsed, + batch_max: elapsed, + ns_per_operation: elapsed.as_secs_f64() * 1e9, + } + }) + .collect(), + statistic: Statistic::FixedOutputRatio(2.0), + bound: 1.5, + dimensions: "", + timing: "", + policy: "", + }], + }; + let mut report = CombinedReport { + legacy: Some(legacy), + source: Some(source), + }; + assert!( + report + .validate(Scope::All, &["legacy"], &["source"]) + .is_ok() + ); + assert_eq!(report.failures(), 1); + assert_eq!(report.exit_code(Mode::Gate, true), 1); + assert_eq!(report.exit_code(Mode::ReportOnly, true), 0); + assert_eq!(report.exit_code(Mode::Smoke, true), 0); + report.legacy.as_mut().unwrap().probes[0].over_budget = + Some((256, std::time::Duration::from_secs(21))); + assert_eq!(report.failures(), 2); + assert_eq!(report.exit_code(Mode::Gate, true), 1); + assert!( + report + .validate(Scope::All, &["legacy"], &["different"]) + .is_err() + ); + assert!(report.validate(Scope::Legacy, &["legacy"], &[]).is_err()); + report.source.as_mut().unwrap().results[0].cells.clear(); + assert!( + report + .validate(Scope::All, &["legacy"], &["source"]) + .is_err() + ); + let missing = CombinedReport { + legacy: None, + source: None, + }; + assert!(missing.validate(Scope::All, &[], &[]).is_err()); + } +} diff --git a/big-code-analysis-bench/src/documentation/fixtures.rs b/big-code-analysis-bench/src/documentation/fixtures.rs new file mode 100644 index 000000000..7c5dd0746 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/fixtures.rs @@ -0,0 +1,556 @@ +//! Stable workload identities and source generators; shared by both timing methods. + +use big_code_analysis_ast::LANG; +use big_code_analysis_ast::documentation::{DocumentationOptions, Profile}; + +use super::{HarnessError, require}; + +/// Statistic implied by the operation's declared input/output growth. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum StatisticClass { + /// Construction with linear or linearithmic legitimate work/output. + Exponent, + /// Indexed query with a fixed number of returned records. + FixedOutputRatio, + /// Fixed-output map query, normalized by log2(mapping segments + 1). + LogMapRatio, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Operation { + Collect, + Owner, + Pending, + OwnerQualifications, + DocumentQualifications, + Map, + Retained, + Render, + EvidencePair, +} + +/// One source workload, including the declared timing and growth policy. +#[derive(Clone, Copy, Debug)] +pub struct SourceProbe { + /// Stable full Criterion/gate identifier. + pub id: &'static str, + /// Source grammar; the default profile is used unless explicitly overridden. + pub language: LANG, + /// Actual measured size ladder. + pub sizes: [usize; 3], + /// Class-specific statistic, never an untyped exponent/ratio field. + pub class: StatisticClass, + /// Frozen bound, from the approved documentation infrastructure policy. + pub bound: f64, + /// Varied dimensions and held-fixed dimensions. + pub dimensions: &'static str, + /// Timed work, preparation and destruction boundary. + pub timing: &'static str, + /// Policy provenance, independent of observed timings. + pub policy: &'static str, + pub(super) operation: Operation, + pub(super) key: &'static str, + pub(super) evidence: bool, +} + +const fn probe( + id: &'static str, + key: &'static str, + language: LANG, + large: bool, + operation: Operation, + dimensions: &'static str, +) -> SourceProbe { + SourceProbe { + id, + key, + language, + sizes: if large { + [1024, 2048, 4096] + } else { + [256, 512, 1024] + }, + class: match operation { + Operation::Collect | Operation::Render | Operation::EvidencePair => { + StatisticClass::Exponent + } + Operation::Map => StatisticClass::LogMapRatio, + _ => StatisticClass::FixedOutputRatio, + }, + bound: 1.50, + dimensions, + timing: match operation { + Operation::Collect => "parse excluded; collect eager text/maps and drop index included", + Operation::EvidencePair => { + "parse excluded; off collection/drop then on collection/drop included; both outputs validated separately" + } + Operation::Render => { + "parse/index/validated fragment preparation excluded; fresh render and content drop included" + } + _ => { + "parse/index/query handles excluded; lookup and lazy record consumption included; borrowed result drop included" + } + }, + policy: "docs/development/benchmarking.md#source-documentation: premeasurement median/exponent/fixed-K policy, bound 1.50", + operation, + evidence: false, + } +} + +/// The original 31 workloads followed by fifteen finite missing-axis ladders. +/// Original generators, options and all 93 full-size cells are preserved. +pub const REGISTRY: &[SourceProbe] = &[ + probe( + "documentation/cold/depth", + "depth", + LANG::Rust, + false, + Operation::Collect, + "grow lexical depth/nodes/bytes; F=E=1, text=5, K fixed", + ), + probe( + "documentation/cold/width", + "width", + LANG::Rust, + false, + Operation::Collect, + "grow siblings/docs/F/E/text/maps; lexical depth fixed", + ), + probe( + "documentation/cold/fragments", + "fragments", + LANG::Go, + false, + Operation::Collect, + "grow fragments/text/maps/bytes; D=E=1, depth fixed", + ), + probe( + "documentation/cold/single-line-lua", + "single-line-lua", + LANG::Lua, + false, + Operation::Collect, + "grow comment bytes/text; D=F=E=1, nodes fixed", + ), + probe( + "documentation/cold/single-line-jsdoc", + "single-line-jsdoc", + LANG::Javascript, + false, + Operation::Collect, + "grow comment bytes/text; D=F=E=1, nodes fixed", + ), + probe( + "documentation/cold/c-slots", + "c-slots", + LANG::C, + false, + Operation::Collect, + "grow slots/edges/name bytes; D=F=1, text=5", + ), + probe( + "documentation/cold/wide-error", + "wide-error", + LANG::C, + false, + Operation::Collect, + "grow recovery siblings; one unresolved document, E=0", + ), + probe( + "documentation/cold/missing", + "missing", + LANG::Rust, + false, + Operation::Collect, + "grow visible parentheses; one missing token, D=E=0", + ), + probe( + "documentation/cold/names", + "names", + LANG::Cpp, + false, + Operation::Collect, + "grow names/references/docs/edges; distinct buckets, variable-width legacy names", + ), + probe( + "documentation/secondary/single-line-php", + "single-line-php", + LANG::Php, + false, + Operation::Collect, + "grow comment bytes/text; D=F=E=1", + ), + probe( + "documentation/secondary/single-line-ruby", + "single-line-ruby", + LANG::Ruby, + false, + Operation::Collect, + "grow comment bytes/text; D=F=E=1", + ), + probe( + "documentation/secondary/single-line-doxygen", + "single-line-doxygen", + LANG::Cpp, + false, + Operation::Collect, + "grow comment bytes/text; D=F=E=1", + ), + probe( + "documentation/secondary/text-fixed-fanout", + "text-fixed-fanout", + LANG::C, + false, + Operation::Collect, + "grow text bytes; D=F=1, E=2, map segments=1", + ), + probe( + "documentation/secondary/fanout-fixed-text", + "fanout-fixed-text", + LANG::C, + false, + Operation::Collect, + "grow slots/edges; D=F=1, text=6143, map segments=1", + ), + probe( + "documentation/secondary/visible-declarator-depth", + "visible-declarator-depth", + LANG::C, + false, + Operation::Collect, + "grow visible array-declarator depth; D=F=E=1; not hidden-only FFI cost", + ), + probe( + "documentation/secondary/ruby-modifiers", + "ruby-modifiers", + LANG::Ruby, + false, + Operation::Collect, + "grow visible modifier depth and field requests; D=F=E=1", + ), + probe( + "documentation/secondary/java-undocumented", + "java-undocumented", + LANG::Java, + false, + Operation::Collect, + "grow lexical depth/owners; D=F=E=0", + ), + probe( + "documentation/secondary/pending-scope", + "pending-scope", + LANG::Rust, + false, + Operation::Collect, + "grow unrelated owners; one pending doc, three assessments", + ), + probe( + "documentation/prepared/owner", + "prepared", + LANG::Rust, + false, + Operation::Owner, + "grow F/text/maps; one owner, query K=1", + ), + probe( + "documentation/prepared/late-map", + "prepared", + LANG::Rust, + false, + Operation::Map, + "grow S=2n-1; one last-byte origin, K=1; normalize log2(S+1)", + ), + probe( + "documentation/prepared/retained", + "prepared", + LANG::Rust, + false, + Operation::Retained, + "grow F/text/maps; one borrowed complete-text view, K=1", + ), + probe( + "documentation/prepared/late-owner", + "width", + LANG::Rust, + false, + Operation::Owner, + "grow unrelated owners/docs; last owner K=1", + ), + probe( + "documentation/ranges/cold", + "ranges", + LANG::Rust, + false, + Operation::Collect, + "grow R/D/F/E equally; one intersection per fragment, depth fixed", + ), + probe( + "documentation/remediation/inline-spans", + "inline-spans", + LANG::Cpp, + true, + Operation::Collect, + "grow inline spans/bytes/text; D=F=E=1", + ), + probe( + "documentation/remediation/gathered-disposition", + "gathered-disposition", + LANG::Cpp, + true, + Operation::Collect, + "grow gathered fragments and final block bytes; one file document", + ), + probe( + "documentation/remediation/complex-signatures", + "complex-signatures", + LANG::Cpp, + true, + Operation::Collect, + "grow declaration depth=n/16; pending signatures, D=0", + ), + probe( + "documentation/remediation/order-multiple-chunks", + "width", + LANG::Rust, + true, + Operation::Collect, + "grow docs/F/E/text/maps through ordering chunk boundary", + ), + probe( + "documentation/remediation/text-budget-boundary", + "text-budget-boundary", + LANG::Rust, + true, + Operation::Collect, + "grow text bytes=8n through copy-budget boundary; D=F=E=1", + ), + probe( + "documentation/remediation/go-fold", + "go-fold", + LANG::Go, + true, + Operation::Collect, + "grow field depth=n/16; undocumented", + ), + probe( + "documentation/remediation/ruby-fold", + "ruby-fold", + LANG::Ruby, + true, + Operation::Collect, + "grow class depth=n/16; one inner documented function", + ), + probe( + "documentation/remediation/multiline-adjacent-ranges", + "multiline-adjacent-ranges", + LANG::Java, + true, + Operation::Collect, + "grow rows/R/intersections/text/maps; D=F=E=1", + ), + probe( + "documentation/qualifications/candidates", + "qualified-candidates", + LANG::Cpp, + false, + Operation::Collect, + "grow C with D=1: E=Q=C; no D*C diagonal", + ), + probe( + "documentation/qualifications/references", + "qualified-references", + LANG::Cpp, + false, + Operation::Collect, + "grow D with C=2: E=2D,Q=2D; fixed candidate factor", + ), + probe( + "documentation/qualifications/late-owner", + "qualified-unrelated", + LANG::Cpp, + false, + Operation::OwnerQualifications, + "grow unrelated Q/docs/owners; last owner qualification K=1", + ), + probe( + "documentation/qualifications/late-document", + "qualified-unrelated", + LANG::Cpp, + false, + Operation::DocumentQualifications, + "grow unrelated Q/docs/owners; last document qualification K=1", + ), + SourceProbe { + class: StatisticClass::Exponent, + ..probe( + "documentation/pending/ancestry", + "pending-ancestry", + LANG::Rust, + false, + Operation::Pending, + "grow nonempty pending ancestry; K=2n, linear-output query", + ) + }, + probe( + "documentation/pending/late", + "pending-late", + LANG::Rust, + false, + Operation::Pending, + "grow unrelated owners and empty scopes; fixed pending K=2", + ), + probe( + "documentation/structure/wide-depth", + "wide-depth", + LANG::Rust, + false, + Operation::Collect, + "grow lexical depth; innermost width=32 documented siblings fixed", + ), + probe( + "documentation/structure/recovery-depth", + "recovery-depth", + LANG::C, + false, + Operation::Collect, + "grow enclosing struct depth; innermost recovery sibling width=32 fixed; parse/error shape validated at every rung", + ), + probe( + "documentation/structure/comment-run-depth", + "comment-run-depth", + LANG::Rust, + false, + Operation::Collect, + "grow depth and innermost F=n; one doc, bytes/text/maps linear", + ), + probe( + "documentation/structure/conditional-depth", + "conditional-depth", + LANG::Cpp, + false, + Operation::Collect, + "one conditional per struct depth; nodes/bytes grow, one leaf document", + ), + probe( + "documentation/names/missing", + "missing-name", + LANG::Cpp, + false, + Operation::Collect, + "grow unrelated declarations with fixed-width names; one valid unresolved reference", + ), + SourceProbe { + evidence: true, + ..probe( + "documentation/evidence/rejected", + "rejected", + LANG::Java, + false, + Operation::EvidencePair, + "grow rejected blocks, evidence=n-1; timed off/on pair, one selected doc in both", + ) + }, + SourceProbe { + evidence: true, + ..probe( + "documentation/evidence/directives", + "directives", + LANG::Go, + false, + Operation::EvidencePair, + "grow directive-only comments, evidence=n; timed off/on pair, no selected docs", + ) + }, + SourceProbe { + sizes: [4096, 8192, 16384], + ..probe( + "documentation/render/bytes", + "text-fixed-fanout", + LANG::C, + false, + Operation::Render, + "grow text bytes; D=F=1,E=2,S=1; fresh output, not retained access", + ) + }, + probe( + "documentation/render/fragments", + "prepared", + LANG::Rust, + false, + Operation::Render, + "grow F=n,S=2n-1,text=2n-1; one document/owner", + ), +]; + +impl SourceProbe { + /// The explicit options used by both runners. + #[must_use] + pub fn options(&self) -> DocumentationOptions { + DocumentationOptions { + profile: Profile::Default, + retain_unbound: self.evidence && self.key != "directives", + retain_directives: self.evidence && self.key == "directives", + } + } + + /// Generate the exact source for a positive size, without newline normalization. + /// + /// # Errors + /// Rejects sizes outside 1..=2^20 or unregistered fixture keys. + pub fn source(&self, size: usize) -> Result, HarnessError> { + require( + size > 0 && size <= 1 << 20, + "source fixture size must be in 1..=2^20", + )?; + let depth = size / 16; + let source = match self.key { + "depth" => format!("{}///audit\nfn leaf() {{}}{}", "mod m {".repeat(size), "}".repeat(size)), + "width" | "ranges" => "///audit\nfn f() {}\n".repeat(size), + "fragments" => format!("package p\n{}func F() {{}}", "// audit\n".repeat(size)), + "single-line-lua" => format!("module(\"m\")\n---{}\nfunction f() end", "audit ".repeat(size)), + "single-line-jsdoc" => format!("/**{}*/\nfunction f() {{}}", "audit ".repeat(size)), + "c-slots" => format!("/**audit*/\nint {};", slots(size)), + "wide-error" => format!("/**audit*/\nstruct {{\n{}", "int x;\n".repeat(size)), + "missing" => format!("fn f() {{ {}0{}; }}", "(".repeat(size), ")".repeat(size - 1)), + "names" => (0..size).map(|at| format!("/** @fn void f{at}() */\nvoid f{at}() {{}}\n")).collect(), + "single-line-php" => format!(" format!("# {}\ndef f\nend", "audit ".repeat(size)), + "single-line-doxygen" => format!("/**{}*/\nvoid f() {{}}", "audit ".repeat(size)), + "text-fixed-fanout" => format!("/**{}*/\nint a,b;", "audit ".repeat(size)), + "fanout-fixed-text" => format!("/**{}*/\nint {};", "audit ".repeat(1024), slots(size)), + "visible-declarator-depth" => format!("/**audit*/\nint a{};", "[1]".repeat(size)), + "ruby-modifiers" => format!("# audit\ndef f; end{}", " if true".repeat(size)), + "java-undocumented" => format!("{}void f() {{}}{}", "class C {".repeat(size), "}".repeat(size)), + "pending-scope" => format!("#![doc(hidden)]\n{}", "fn f() {}\n".repeat(size)), + "prepared" => format!("{}fn f() {{}}", "///a\n".repeat(size)), + "inline-spans" => format!("/**{}*/\nvoid f() {{}}", "`x` ".repeat(size)), + "gathered-disposition" => format!("{}/**{}@file*/", "/**a*/\n".repeat(size), "x ".repeat(size)), + "complex-signatures" => format!("{}void leaf();{}", "void f(int x = [] { ".repeat(depth), " return 1; }());".repeat(depth)), + "text-budget-boundary" => format!("///{}\nfn f() {{}}", "abcd".repeat(size * 2)), + "go-fold" => format!("package p\ntype S struct {{\n{}X int\n{} }}\n", "X struct {\n".repeat(depth), "}\n".repeat(depth)), + "ruby-fold" => format!("{}# audit\ndef f; end\n{}", "class C\n".repeat(depth), "end\n".repeat(depth)), + "multiline-adjacent-ranges" => format!("/**\n{}*/\nclass C {{}}", " * audit\n".repeat(size)), + "qualified-candidates" => format!("#if FLAG\n{}#endif\n/**@fn f*/", "void f(void);\n".repeat(size)), + "qualified-references" => format!("#if FLAG\nvoid f(void);\nvoid f(void);\n#endif\n{}", "/**@fn f*/\nint separator;\n".repeat(size)), + "qualified-unrelated" => (0..size).map(|at| format!("#if FLAG\nvoid f{at:08}(void);\n#endif\n/**@fn f{at:08}*/\nint separator;\n")).collect(), + "pending-ancestry" => format!("{}fn leaf() {{}}{}", "mod m {\n#![doc(hidden)]\n".repeat(size), "}\n".repeat(size)), + "pending-late" => format!("#![doc(hidden)]\n{}{}fn leaf() {{}}{}", "fn f() {}\n".repeat(size), "mod m {".repeat(size), "}".repeat(size)), + "wide-depth" => format!("{}{}{}", "mod m {".repeat(size), "///audit\nfn f() {}\n".repeat(32), "}".repeat(size)), + "recovery-depth" => format!("{}struct {{\n{}{}", "struct S {\n".repeat(size), "/**audit*/\nint x;\n".repeat(32), "};\n".repeat(size)), + "comment-run-depth" => format!("{}{}fn f() {{}}{}", "mod m {".repeat(size), "///a\n".repeat(size), "}".repeat(size)), + "conditional-depth" => format!("{}/**audit*/\nvoid f();\n{}", "struct S {\n#if FLAG\n".repeat(size), "#endif\n};\n".repeat(size)), + "missing-name" => format!("{}/**@fn absent*/", (0..size).map(|at| format!("void f{at:08}(void);\n")).collect::()), + "rejected" => format!("{}class C {{}}", "/**audit*/\n".repeat(size)), + "directives" => format!("package p\n{}func F() {{}}", "//go:generate command\n".repeat(size)), + _ => return Err(HarnessError(format!("unregistered source fixture {}", self.key))), + }; + Ok(source.into_bytes()) + } +} + +fn slots(size: usize) -> String { + (0..size) + .map(|at| format!("v{at}")) + .collect::>() + .join(",") +} diff --git a/big-code-analysis-bench/src/documentation/mod.rs b/big-code-analysis-bench/src/documentation/mod.rs new file mode 100644 index 000000000..bba14b66f --- /dev/null +++ b/big-code-analysis-bench/src/documentation/mod.rs @@ -0,0 +1,36 @@ +//! Shared source-documentation registry, operations and class-specific gate. + +pub mod combined; +mod fixtures; +mod operation; +pub mod runner; +#[cfg(test)] +mod tests; +mod validation; + +pub use fixtures::{REGISTRY, SourceProbe, StatisticClass}; +pub use operation::{Parsed, Prepared, SourceCounts}; + +/// Benchmark setup, operation or measurement failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HarnessError(pub String); + +impl std::fmt::Display for HarnessError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for HarnessError {} + +pub(super) fn failure(error: impl std::fmt::Debug) -> HarnessError { + HarnessError(format!("{error:?}")) +} + +pub(super) fn require(condition: bool, message: impl Into) -> Result<(), HarnessError> { + if condition { + Ok(()) + } else { + Err(HarnessError(message.into())) + } +} diff --git a/big-code-analysis-bench/src/documentation/operation.rs b/big-code-analysis-bench/src/documentation/operation.rs new file mode 100644 index 000000000..9c336109f --- /dev/null +++ b/big-code-analysis-bench/src/documentation/operation.rs @@ -0,0 +1,512 @@ +//! Separate owned parse, borrowed index and prepared query lifetimes. + +use std::hint::black_box; + +use big_code_analysis::{Ast, Source}; +use big_code_analysis_ast::documentation::render_probe::PreparedRender; +use big_code_analysis_ast::documentation::{ + CompleteText, Content, Document, DocumentationContext, DocumentationIndex, + DocumentationOptions, FactRef, Owner, collect, +}; +use big_code_analysis_ast::{LANG, tree_sitter}; + +use super::fixtures::Operation; +use super::{HarnessError, SourceProbe, failure, require}; + +/// Owned parse storage. Restricted cells retain their exact tree and source. +pub enum Parsed { + /// Ordinary inputs are parsed once through the root facade. + Ordinary(Ast), + /// Deliberately restricted parse; never cloned, adopted or reparsed. + Restricted { + /// Exact parse buffer. + source: Vec, + /// Tree carrying the explicit included ranges. + tree: tree_sitter::Tree, + /// Selected grammar. + language: LANG, + }, +} + +impl Parsed { + /// Parse a registry fixture once, outside measurement. + /// + /// # Errors + /// Rejects invalid fixture generation, grammar setup and incomplete parses. + pub fn new(probe: &SourceProbe, size: usize) -> Result { + let source = probe.source(size)?; + if !matches!(probe.key, "ranges" | "multiline-adjacent-ranges") { + return Ast::parse(Source::new(probe.language, &source)) + .map(Self::Ordinary) + .map_err(failure); + } + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&probe.language.tree_sitter_language().map_err(failure)?) + .map_err(failure)?; + let ranges = included_ranges(&source, probe.key == "ranges"); + parser.set_included_ranges(&ranges).map_err(failure)?; + let tree = parser + .parse(&source, None) + .ok_or_else(|| HarnessError("incomplete restricted parse".into()))?; + require( + tree.included_ranges() == ranges, + "restricted range membership changed", + )?; + Ok(Self::Restricted { + source, + tree, + language: probe.language, + }) + } + + pub(super) fn language(&self) -> LANG { + match self { + Self::Ordinary(ast) => ast.language(), + Self::Restricted { language, .. } => *language, + } + } + + /// The actual held parse buffer, including any facade preprocessing. + #[must_use] + pub fn source(&self) -> &[u8] { + match self { + Self::Ordinary(ast) => ast.source(), + Self::Restricted { source, .. } => source, + } + } + + pub(super) fn tree(&self) -> &tree_sitter::Tree { + match self { + Self::Ordinary(ast) => ast.as_tree_sitter(), + Self::Restricted { tree, .. } => tree, + } + } + + pub(super) fn nodes(&self) -> Vec<(tree_sitter::Node<'_>, usize)> { + let mut nodes = Vec::new(); + let mut cursor = self.tree().walk(); + let mut depth = 0; + loop { + nodes.push((cursor.node(), depth)); + if cursor.goto_first_child() { + depth += 1; + continue; + } + while !cursor.goto_next_sibling() { + if !cursor.goto_parent() { + return nodes; + } + depth -= 1; + } + } + } + + /// Collect from exact borrowed language/tree/source accessors. + /// + /// # Errors + /// Propagates every collection failure as a harness error. + pub fn collect(&self, probe: &SourceProbe) -> Result, HarnessError> { + self.collect_with(&DocumentationContext::default(), &probe.options()) + } + + fn collect_with( + &self, + context: &DocumentationContext, + options: &DocumentationOptions, + ) -> Result, HarnessError> { + collect( + black_box(self.language()), + black_box(self.tree()), + black_box(self.source()), + black_box(context), + black_box(options), + ) + .map_err(failure) + } +} + +fn included_ranges(source: &[u8], rows: bool) -> Vec { + let mut point = tree_sitter::Point::new(0, 0); + let mut start_point = point; + let mut start_byte = 0; + let mut ranges = Vec::new(); + for (at, byte) in source.iter().enumerate() { + if *byte == b'\n' { + point.row += 1; + point.column = 0; + } else { + point.column += 1; + } + if !rows || (at + 1).is_multiple_of(19) { + ranges.push(tree_sitter::Range { + start_byte, + end_byte: at + 1, + start_point, + end_point: point, + }); + start_byte = at + 1; + start_point = point; + } + } + ranges +} + +/// Borrowed state constructed only after the owned parses and indexes are stable. +pub struct Prepared<'i, 's> { + probe: &'i SourceProbe, + parsed: &'s Parsed, + index: &'i DocumentationIndex<'s>, + document: Option>>, + node: Option>, + owner: Option>>, + text: Option>, + render: Option>, + counts: SourceCounts, + context: DocumentationContext, + options: DocumentationOptions, + off_options: DocumentationOptions, +} + +/// Untimed input/output dimensions reported independently from elapsed time. +#[derive(Clone, Copy, Debug, Default)] +pub struct SourceCounts { + /// Visible parse nodes. + pub nodes: usize, + /// Maximum visible tree depth, root at zero. + pub depth: usize, + /// Maximum direct child count of a visible node. + pub width: usize, + /// Physical retained fragments. + pub fragments: usize, + /// Logical documents. + pub documents: usize, + /// Association-owner edges, including legitimate fanout. + pub edges: usize, + /// Candidate/reference qualification records. + pub qualifications: usize, + /// Complete text bytes stored once per document. + pub rendered_bytes: usize, + /// Complete map segments stored once per document. + pub map_segments: usize, + /// Retained included ranges. + pub ranges: usize, + /// Retained fragment/source intersections. + pub intersections: usize, + /// Records consumed by one selected query; zero for construction. + pub query_output: usize, +} + +impl SourceCounts { + fn new(parsed: &Parsed, index: &DocumentationIndex<'_>) -> Result { + let nodes = parsed.nodes(); + let mut counts = Self { + nodes: nodes.len(), + depth: nodes.iter().map(|(_, depth)| *depth).max().unwrap_or(0), + width: nodes + .iter() + .map(|(node, _)| node.child_count()) + .max() + .unwrap_or(0), + fragments: index.facts().fragments().len(), + documents: index.documents().len(), + edges: index.associations().map(|a| a.get().owner_count()).sum(), + qualifications: index.qualifications().len(), + ranges: parsed.tree().included_ranges().len(), + intersections: index + .facts() + .fragments() + .map(|f| f.get().source().pieces().len()) + .sum(), + ..Self::default() + }; + for doc in index.documents() { + if let Some(text) = index.complete_text(doc).map_err(failure)? { + counts.rendered_bytes += text.text().len(); + counts.map_segments += text.mappings().len(); + } + } + Ok(counts) + } +} + +impl<'i, 's> Prepared<'i, 's> { + /// Validate every actual rung, then prepare the selected query/render handles. + /// + /// # Errors + /// Rejects shape/output drift or an operation with unavailable prepared state. + pub fn new( + probe: &'i SourceProbe, + size: usize, + parsed: &'s Parsed, + index: &'i DocumentationIndex<'s>, + ) -> Result { + super::validation::fixture(probe, size, parsed, index)?; + let document = index.documents().last(); + let node = parsed + .nodes() + .into_iter() + .rev() + .map(|(node, _)| node) + .find(|node| node.kind() == "function_item"); + let owner = if probe.operation == Operation::OwnerQualifications { + let association = index + .associations() + .last() + .ok_or_else(|| HarnessError("qualification association absent".into()))?; + Some( + index + .facts() + .associated_owner(association, 0) + .map_err(failure)?, + ) + } else { + None + }; + let text = document + .map(|doc| index.complete_text(doc)) + .transpose() + .map_err(failure)? + .flatten(); + let render = if probe.operation == Operation::Render { + Some( + PreparedRender::new( + index, + document.ok_or_else(|| HarnessError("render document absent".into()))?, + ) + .map_err(failure)?, + ) + } else { + None + }; + let mut prepared = Self { + probe, + parsed, + index, + document, + node, + owner, + text, + render, + counts: SourceCounts::new(parsed, index)?, + context: DocumentationContext::default(), + options: probe.options(), + off_options: DocumentationOptions::default(), + }; + prepared.validate_operation(size)?; + prepared.counts.query_output = match probe.operation { + Operation::Owner + | Operation::Retained + | Operation::Map + | Operation::OwnerQualifications + | Operation::DocumentQualifications => 1, + Operation::Pending => { + if probe.key == "pending-ancestry" { + size * 2 + } else { + 2 + } + } + _ => 0, + }; + Ok(prepared) + } + + #[allow(clippy::too_many_lines)] // Each operation has an independent untimed output control. + fn validate_operation(&self, size: usize) -> Result<(), HarnessError> { + match self.probe.operation { + Operation::Collect | Operation::EvidencePair => {} + Operation::Owner => { + let node = self + .node + .ok_or_else(|| HarnessError("owner node absent".into()))?; + let expected = if self.probe.key == "width" { + (size - 1) * 19 + 9 + } else { + 5 * size + }; + require( + node.start_byte() == expected, + "prepared owner source anchor", + )?; + require( + self.index + .node_associations(node) + .map_err(failure)? + .associations() + .count() + == 1, + "prepared owner K=1", + )?; + } + Operation::Render => { + let rendered = self + .render + .as_ref() + .ok_or_else(|| HarnessError("render not prepared".into()))? + .render() + .map_err(failure)?; + let Content::Complete { text, mappings, .. } = rendered else { + return Err(HarnessError("fresh render incomplete".into())); + }; + let retained = self + .text + .ok_or_else(|| HarnessError("retained render control missing".into()))?; + require( + text == retained.text() && mappings == retained.mappings(), + "fresh render text/map mismatch", + )?; + } + Operation::Pending => { + let node = self + .node + .ok_or_else(|| HarnessError("pending node absent".into()))?; + let query = self.index.node_associations(node).map_err(failure)?; + let expected = if self.probe.key == "pending-ancestry" { + size * 2 + } else { + 2 + }; + require(query.assessments().count() == expected, "pending query K")?; + } + Operation::OwnerQualifications => { + let owner = self + .owner + .ok_or_else(|| HarnessError("qualification owner absent".into()))?; + require( + self.index + .owner_associations(owner) + .map_err(failure)? + .qualifications() + .count() + == 1, + "owner qualification K=1", + )?; + } + Operation::DocumentQualifications => { + let document = self + .document + .ok_or_else(|| HarnessError("qualification document absent".into()))?; + require( + self.index + .document_qualifications(document) + .map_err(failure)? + .count() + == 1, + "document qualification K=1", + )?; + } + Operation::Map | Operation::Retained => { + require(self.text.is_some(), "complete prepared text absent")?; + self.execute()?; + } + } + Ok(()) + } + + /// Run exactly one operation, consuming lazy results and dropping owned output. + /// + /// # Errors + /// Returns missing-state, collection, query and rendering failures. + pub fn execute(&self) -> Result<(), HarnessError> { + match self.probe.operation { + Operation::EvidencePair => { + drop(black_box( + self.parsed.collect_with(&self.context, &self.off_options)?, + )); + drop(black_box( + self.parsed.collect_with(&self.context, &self.options)?, + )); + } + Operation::Collect => { + drop(black_box( + self.parsed.collect_with(&self.context, &self.options)?, + )); + } + Operation::Render => { + drop(black_box( + black_box( + self.render + .as_ref() + .ok_or_else(|| HarnessError("render not prepared".into()))?, + ) + .render() + .map_err(failure)?, + )); + } + Operation::Owner | Operation::Pending => { + let node = self + .node + .ok_or_else(|| HarnessError("query node absent".into()))?; + let query = black_box(self.index) + .node_associations(black_box(node)) + .map_err(failure)?; + if self.probe.operation == Operation::Pending { + for assessment in query.assessments() { + black_box(assessment.get()); + } + } else { + for association in query.associations() { + black_box(association.get()); + } + } + } + Operation::OwnerQualifications => { + let owner = self + .owner + .ok_or_else(|| HarnessError("qualification owner absent".into()))?; + let query = black_box(self.index) + .owner_associations(black_box(owner)) + .map_err(failure)?; + for qualification in query.qualifications() { + black_box(qualification.get()); + } + } + Operation::DocumentQualifications => { + let doc = self + .document + .ok_or_else(|| HarnessError("qualification document absent".into()))?; + for qualification in black_box(self.index) + .document_qualifications(black_box(doc)) + .map_err(failure)? + { + black_box(qualification.get()); + } + } + Operation::Map => { + let text = black_box( + self.text + .ok_or_else(|| HarnessError("map text absent".into()))?, + ); + let end = text.text().len(); + require(end > 0, "late map query has no text")?; + for portion in text.origins(black_box(end - 1..end)).map_err(failure)? { + black_box(portion); + } + } + Operation::Retained => { + let doc = self + .document + .ok_or_else(|| HarnessError("retained document absent".into()))?; + black_box( + black_box(self.index) + .complete_text(black_box(doc)) + .map_err(failure)?, + ); + } + } + Ok(()) + } + + /// Number of retained output-map segments, for the declared logarithmic axis. + #[must_use] + pub fn segments(&self) -> usize { + self.text.map_or(0, |text| text.mappings().len()) + } + + /// Independently observed input/output dimensions, collected before timing. + #[must_use] + pub fn counts(&self) -> SourceCounts { + self.counts + } +} diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs new file mode 100644 index 000000000..29c59ff94 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -0,0 +1,796 @@ +//! Source-specific raw-batch calibration, validation and typed statistics. +#![allow(clippy::cast_precision_loss)] + +use std::collections::HashSet; +use std::fmt; +use std::time::{Duration, Instant}; + +use super::{HarnessError, Parsed, Prepared, SourceCounts, SourceProbe, StatisticClass, require}; +use crate::cli::Mode; +use crate::scaling::{MAX_CELL_WALK, SMOKE_SIZES, WARMUP_ROUNDS, schedule}; + +/// Target elapsed duration for source-only calibration; legacy calibration is unchanged. +pub const SOURCE_TARGET_SAMPLE: Duration = Duration::from_millis(2); +/// Maximum source repetitions in one batch. +pub const SOURCE_MAX_ITERATIONS: u32 = 1 << 20; +/// A full-size cell with a shorter measured median is unresolved, never a pass. +pub const MIN_SOURCE_SAMPLE: Duration = Duration::from_micros(200); + +/// Source calibration, frozen before warmup/measurement. A zero calibration +/// observation saturates the cap; measured zero batches still fail validation. +#[must_use] +pub fn iterations_for(single: Duration) -> u32 { + let needed = SOURCE_TARGET_SAMPLE + .as_nanos() + .div_ceil(single.as_nanos().max(1)); + u32::try_from(needed) + .unwrap_or(SOURCE_MAX_ITERATIONS) + .clamp(1, SOURCE_MAX_ITERATIONS) +} + +/// One actual scheduled batch, retained before any per-operation division. +#[derive(Clone, Debug)] +pub struct Batch { + /// Measured-round ordinal, excluding warmup. + pub round: usize, + /// Actual elapsed duration of all repetitions. + pub elapsed: Duration, +} + +/// A complete validated cell with raw batches and fractional ns/operation. +#[derive(Clone, Debug)] +pub struct SourceCell { + /// Input/output dimensions observed outside measurement. + pub counts: SourceCounts, + /// Declared size rung. + pub size: usize, + /// Actual held source bytes. + pub bytes: usize, + /// Map segments used by logarithmic normalization, zero when unavailable. + pub segments: usize, + /// Frozen repetitions for every warmup/measured round. + pub iterations: u32, + /// Complete samples in scheduled-round order. + pub batches: Vec, + /// Shortest actual batch. + pub batch_min: Duration, + /// Median actual batch. + pub batch_median: Duration, + /// Longest actual batch. + pub batch_max: Duration, + /// Median batch divided in floating point, without a Duration floor. + pub ns_per_operation: f64, +} + +/// Class-specific result. A ratio is never stored in a legacy exponent field. +#[derive(Clone, Copy, Debug)] +pub enum Statistic { + /// Least-squares log-size slope. + Exponent(f64), + /// Largest/smallest per-rung median. + FixedOutputRatio(f64), + /// Largest/smallest median after division by log2(S+1). + LogMapRatio(f64), +} + +impl Statistic { + /// Numeric value interpreted according to this statistic's variant. + #[must_use] + pub fn value(self) -> f64 { + match self { + Self::Exponent(x) | Self::FixedOutputRatio(x) | Self::LogMapRatio(x) => x, + } + } +} + +impl fmt::Display for Statistic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Self::Exponent(_) => "exponent", + Self::FixedOutputRatio(_) => "fixed-K ratio", + Self::LogMapRatio(_) => "log-map ratio", + }; + write!(f, "{name} {:.4}", self.value()) + } +} + +/// A source ladder with a class-correct statistic and complete membership. +#[derive(Clone, Debug)] +pub struct SourceResult { + /// Registry identity. + pub id: &'static str, + /// All declared rungs in declaration order. + pub cells: Vec, + /// Statistic derived from raw batches. + pub statistic: Statistic, + /// Predeclared bound. + pub bound: f64, + /// Varied and fixed dimensions. + pub dimensions: &'static str, + /// Declared operation, preparation and destruction boundary. + pub timing: &'static str, + /// Source of the predeclared class/bound policy. + pub policy: &'static str, +} + +/// Validated source report, kept separate from the legacy result collection. +#[derive(Clone, Debug)] +pub struct SourceReport { + /// Measured rounds per cell. + pub rounds: usize, + /// Run purpose. Smoke/report-only never carry a performance pass. + pub mode: Mode, + /// Complete registry membership. + pub results: Vec, +} + +impl SourceReport { + pub(super) fn validate_data(&self) -> Result<(), HarnessError> { + require(!self.results.is_empty(), "empty source report")?; + validate_rounds(self.rounds)?; + let mut ids = HashSet::new(); + for result in &self.results { + require(ids.insert(result.id), "duplicate source result")?; + require( + result.cells.len() == 3 && result.bound.is_finite() && result.bound > 0.0, + "invalid source result", + )?; + require( + result.cells[0].size > 0 + && result + .cells + .windows(2) + .all(|pair| pair[0].size.checked_mul(2) == Some(pair[1].size)), + "invalid source result ladder", + )?; + for cell in &result.cells { + let verified = reduce_cell( + RawCell { + counts: cell.counts, + id: result.id, + size: cell.size, + bytes: cell.bytes, + segments: cell.segments, + iterations: cell.iterations, + batches: cell.batches.clone(), + }, + self.rounds, + self.mode, + )?; + require( + verified.batch_min == cell.batch_min + && verified.batch_median == cell.batch_median + && verified.batch_max == cell.batch_max + && verified.ns_per_operation.to_bits() == cell.ns_per_operation.to_bits(), + "source cell summary differs from raw batches", + )?; + } + let class = match result.statistic { + Statistic::Exponent(_) => StatisticClass::Exponent, + Statistic::FixedOutputRatio(_) => StatisticClass::FixedOutputRatio, + Statistic::LogMapRatio(_) => StatisticClass::LogMapRatio, + }; + require( + statistic(class, &result.cells)?.value().to_bits() + == result.statistic.value().to_bits(), + "source statistic differs from validated cells", + )?; + } + Ok(()) + } + + /// Bound failures only; harness errors prevent report construction entirely. + #[must_use] + pub fn failures(&self) -> Vec<&SourceResult> { + self.results + .iter() + .filter(|r| { + !r.bound.is_finite() + || !r.statistic.value().is_finite() + || r.statistic.value() > r.bound + }) + .collect() + } +} + +impl fmt::Display for SourceReport { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + writeln!( + f, + "source documentation: {} workloads, {} cells, {} median-of-scheduled rounds; {:?}", + self.results.len(), + self.results.iter().map(|r| r.cells.len()).sum::(), + self.rounds, + self.mode + )?; + for result in &self.results { + if self.mode == Mode::Smoke { + writeln!( + f, + "{}: structural smoke; no timing-resolution or performance claim", + result.id + )?; + } else { + writeln!( + f, + "{}: {} (bound {:.2}){}", + result.id, + result.statistic, + result.bound, + if self.mode == Mode::ReportOnly { + " report-only; no performance verdict" + } else if result.statistic.value() <= result.bound { + " ok" + } else { + " OVER BOUND" + } + )?; + } + writeln!(f, " {}", result.dimensions)?; + writeln!(f, " timing: {}", result.timing)?; + writeln!(f, " policy: {}", result.policy)?; + writeln!( + f, + " size bytes segments iterations batch-min-us batch-median-us batch-max-us ns/operation" + )?; + for cell in &result.cells { + writeln!( + f, + " {} {} {} {} {:.3} {:.3} {:.3} {:.6}", + cell.size, + cell.bytes, + cell.segments, + cell.iterations, + cell.batch_min.as_secs_f64() * 1e6, + cell.batch_median.as_secs_f64() * 1e6, + cell.batch_max.as_secs_f64() * 1e6, + cell.ns_per_operation + )?; + write!(f, " raw-batches-ns:")?; + for batch in &cell.batches { + write!(f, " {}:{}", batch.round, batch.elapsed.as_nanos())?; + } + writeln!(f)?; + writeln!(f, " dimensions: {:?}", cell.counts)?; + } + } + Ok(()) + } +} + +#[derive(Clone, Debug)] +struct RawCell { + counts: SourceCounts, + id: &'static str, + size: usize, + bytes: usize, + segments: usize, + iterations: u32, + batches: Vec, +} + +/// Run the complete supplied source registry with source-specific calibration. +/// +/// # Errors +/// Rejects invalid registry/rounds, shape/operation failures, over-budget work, +/// malformed samples and under-resolved full-size cells. There is no retry. +pub fn run( + probes: &[SourceProbe], + rounds: usize, + mode: Mode, +) -> Result { + run_with_budget(probes, rounds, mode, MAX_CELL_WALK) +} + +/// Run with an explicit post-operation budget, primarily to test abandonment. +/// This cannot interrupt the first operation; an external campaign deadline is separate. +/// +/// # Errors +/// As [`run`], including every abandoned cell as a harness failure. +#[allow(clippy::too_many_lines)] // Parse, index and prepared borrows must remain in separate ordered lifetime layers. +pub fn run_with_budget( + probes: &[SourceProbe], + rounds: usize, + mode: Mode, + budget: Duration, +) -> Result { + validate_registry(probes, rounds)?; + let probes: Vec<_> = probes + .iter() + .map(|probe| { + if mode == Mode::Smoke { + SourceProbe { + sizes: SMOKE_SIZES, + ..*probe + } + } else { + *probe + } + }) + .collect(); + let mut parsed = Vec::new(); + for probe in &probes { + for size in probe.sizes { + parsed.push(Parsed::new(probe, size).map_err(|e| context(probe.id, size, e))?); + } + } + let mut indexes = Vec::new(); + for (at, parse) in parsed.iter().enumerate() { + let started = Instant::now(); + indexes.push( + parse + .collect(&probes[at / 3]) + .map_err(|e| context(probes[at / 3].id, probes[at / 3].sizes[at % 3], e))?, + ); + check_budget( + probes[at / 3].id, + probes[at / 3].sizes[at % 3], + started.elapsed(), + 1, + budget, + )?; + } + let mut prepared = Vec::new(); + for (at, (parse, index)) in parsed.iter().zip(&indexes).enumerate() { + let probe = &probes[at / 3]; + prepared.push( + Prepared::new(probe, probe.sizes[at % 3], parse, index) + .map_err(|e| context(probe.id, probe.sizes[at % 3], e))?, + ); + } + let mut raw = Vec::new(); + for (at, operation) in prepared.iter().enumerate() { + let probe = &probes[at / 3]; + let size = probe.sizes[at % 3]; + let single = batch(operation, 1).map_err(|e| context(probe.id, size, e))?; + check_budget(probe.id, size, single, 1, budget)?; + raw.push(RawCell { + counts: operation.counts(), + id: probe.id, + size, + bytes: parsed[at].source().len(), + segments: operation.segments(), + iterations: if mode == Mode::Smoke { + 1 + } else { + iterations_for(single) + }, + batches: Vec::with_capacity(rounds), + }); + } + for (round, at) in schedule(raw.len(), rounds) { + let cell = &raw[at]; + let elapsed = batch(&prepared[at], cell.iterations) + .and_then(|elapsed| { + check_budget(cell.id, cell.size, elapsed, cell.iterations, budget)?; + require( + !elapsed.is_zero(), + format!( + "{} size {}: zero batch in round {round}", + cell.id, cell.size + ), + )?; + Ok(elapsed) + }) + .map_err(|error| { + HarnessError(format!( + "{}\nretained source batches: {raw:#?}", + context(cell.id, cell.size, error) + )) + })?; + if round >= WARMUP_ROUNDS { + raw[at].batches.push(Batch { + round: round - WARMUP_ROUNDS, + elapsed, + }); + } + } + reduce(&probes, rounds, mode, raw.clone()) + .map_err(|error| HarnessError(format!("{error}\nretained source batches: {raw:#?}"))) +} + +fn batch(operation: &Prepared<'_, '_>, iterations: u32) -> Result { + let start = Instant::now(); + for _ in 0..iterations { + operation.execute()?; + } + Ok(start.elapsed()) +} + +fn context(id: &str, size: usize, error: HarnessError) -> HarnessError { + HarnessError(format!("{id} size {size}: {error}")) +} + +fn check_budget( + id: &str, + size: usize, + elapsed: Duration, + iterations: u32, + budget: Duration, +) -> Result<(), HarnessError> { + require( + elapsed.as_secs_f64() / f64::from(iterations) <= budget.as_secs_f64(), + format!( + "AbandonedCell: {id} size {size}, {iterations} iterations, batch {elapsed:?}, per-operation budget {budget:?}" + ), + ) +} + +fn validate_registry(probes: &[SourceProbe], rounds: usize) -> Result<(), HarnessError> { + validate_rounds(rounds)?; + require(!probes.is_empty(), "empty source registry")?; + let mut ids = HashSet::new(); + for probe in probes { + require(!probe.id.is_empty(), "empty source identifier")?; + require( + ids.insert(probe.id), + format!("duplicate source ID {}", probe.id), + )?; + require( + probe.sizes[0] > 0 + && probe.sizes[2] <= 1 << 20 + && probe + .sizes + .windows(2) + .all(|s| s[0].checked_mul(2) == Some(s[1])), + format!("{}: invalid size ladder", probe.id), + )?; + require( + probe.bound.is_finite() && probe.bound > 0.0, + format!("{}: invalid bound", probe.id), + )?; + } + Ok(()) +} + +fn validate_rounds(rounds: usize) -> Result<(), HarnessError> { + require( + rounds > 0 && rounds % 2 == 1 && rounds <= 1023, + "source rounds must be odd in 1..=1023", + ) +} + +fn reduce( + probes: &[SourceProbe], + rounds: usize, + mode: Mode, + raw: Vec, +) -> Result { + validate_registry(probes, rounds)?; + require(raw.len() == probes.len() * 3, "missing/extra source cells")?; + let mut results = Vec::new(); + let mut raw = raw.into_iter(); + for probe in probes { + let mut cells = Vec::new(); + for size in probe.sizes { + let cell = raw + .next() + .ok_or_else(|| HarnessError("missing source cell".into()))?; + require( + cell.id == probe.id && cell.size == size, + format!( + "wrong source cell membership: expected {} size {size}, got {} size {}", + probe.id, cell.id, cell.size + ), + )?; + cells.push(reduce_cell(cell, rounds, mode)?); + } + let statistic = statistic(probe.class, &cells)?; + results.push(SourceResult { + id: probe.id, + cells, + statistic, + bound: probe.bound, + dimensions: probe.dimensions, + timing: probe.timing, + policy: probe.policy, + }); + } + Ok(SourceReport { + rounds, + mode, + results, + }) +} + +fn reduce_cell(raw: RawCell, rounds: usize, mode: Mode) -> Result { + validate_rounds(rounds)?; + require( + raw.bytes > 0 && raw.iterations > 0 && raw.iterations <= SOURCE_MAX_ITERATIONS, + format!("{}: invalid cell work/count", raw.id), + )?; + require( + raw.batches.len() == rounds, + format!("{} size {}: missing samples", raw.id, raw.size), + )?; + let mut times = Vec::new(); + for (round, batch) in raw.batches.iter().enumerate() { + require( + batch.round == round + && !batch.elapsed.is_zero() + && batch.elapsed.as_secs_f64().is_finite(), + format!("{} size {}: invalid batch round {round}", raw.id, raw.size), + )?; + times.push(batch.elapsed); + } + times.sort_unstable(); + let median = times[rounds / 2]; + if mode != Mode::Smoke && median < MIN_SOURCE_SAMPLE { + return Err(HarnessError(format!( + "UnresolvedCell: {} size {}, iterations {}, actual median batch {median:?} < {MIN_SOURCE_SAMPLE:?}", + raw.id, raw.size, raw.iterations + ))); + } + let ns = median.as_secs_f64() * 1e9 / f64::from(raw.iterations); + require( + ns.is_finite() && ns > 0.0, + format!("{}: invalid per-operation median", raw.id), + )?; + Ok(SourceCell { + counts: raw.counts, + size: raw.size, + bytes: raw.bytes, + segments: raw.segments, + iterations: raw.iterations, + batches: raw.batches, + batch_min: times[0], + batch_median: median, + batch_max: times[rounds - 1], + ns_per_operation: ns, + }) +} + +fn statistic(class: StatisticClass, cells: &[SourceCell]) -> Result { + require( + cells.len() == 3 + && cells + .iter() + .all(|c| c.ns_per_operation > 0.0 && c.ns_per_operation.is_finite()), + "invalid source statistic inputs", + )?; + require( + cells[0].size > 0 && cells.windows(2).all(|pair| pair[0].size < pair[1].size), + "degenerate source statistic ladder", + )?; + let mut values = Vec::new(); + for cell in cells { + let divisor = if class == StatisticClass::LogMapRatio { + require(cell.segments > 0, "map query has no segments")?; + (cell.segments as f64 + 1.0).log2() + } else { + 1.0 + }; + values.push(cell.ns_per_operation / divisor); + } + let value = if class == StatisticClass::Exponent { + // The source fit intentionally has no legacy minimum-time floor. + let x: Vec<_> = cells.iter().map(|c| (c.size as f64).ln()).collect(); + let y: Vec<_> = values.iter().map(|v| v.ln()).collect(); + let mx = x.iter().sum::() / 3.0; + let my = y.iter().sum::() / 3.0; + x.iter() + .zip(&y) + .map(|(x, y)| (x - mx) * (y - my)) + .sum::() + / x.iter().map(|x| (x - mx).powi(2)).sum::() + } else { + values.iter().copied().fold(f64::NEG_INFINITY, f64::max) + / values.iter().copied().fold(f64::INFINITY, f64::min) + }; + require(value.is_finite(), "nonfinite source statistic")?; + Ok(match class { + StatisticClass::Exponent => Statistic::Exponent(value), + StatisticClass::FixedOutputRatio => Statistic::FixedOutputRatio(value), + StatisticClass::LogMapRatio => Statistic::LogMapRatio(value), + }) +} + +#[cfg(test)] +mod tests { + use super::super::REGISTRY; + use super::*; + + fn raw(probe: &SourceProbe, ns: [u64; 3]) -> Vec { + probe + .sizes + .into_iter() + .zip(ns) + .map(|(size, ns)| RawCell { + counts: SourceCounts::default(), + id: probe.id, + size, + bytes: size, + segments: size, + iterations: 1, + batches: (0..3) + .map(|round| Batch { + round, + elapsed: Duration::from_nanos(ns), + }) + .collect(), + }) + .collect() + } + + #[test] + fn calibration_caps_zero_and_preserves_ceiling() { + assert_eq!(iterations_for(Duration::ZERO), 1 << 20); + assert_eq!(iterations_for(Duration::from_nanos(3)), 666_667); + assert_eq!(iterations_for(Duration::from_millis(3)), 1); + assert_eq!(iterations_for(Duration::from_micros(1)), 2000); + } + + #[test] + fn actual_batches_control_resolution_even_at_iteration_cap() { + let probe = REGISTRY[18]; + let mut cells = raw(&probe, [199_999; 3]); + for cell in &mut cells { + cell.iterations = SOURCE_MAX_ITERATIONS; + } + let error = reduce(&[probe], 3, Mode::Gate, cells).unwrap_err(); + assert!(error.0.contains("UnresolvedCell")); + assert!(error.0.contains("1048576")); + assert!(reduce(&[probe], 3, Mode::ReportOnly, raw(&probe, [199_999; 3])).is_err()); + assert!(reduce(&[probe], 3, Mode::Smoke, raw(&probe, [1; 3])).is_ok()); + } + + #[test] + fn malformed_membership_and_samples_fail_in_every_mode() { + let probe = REGISTRY[18]; + for mode in [Mode::Gate, Mode::ReportOnly, Mode::Smoke] { + assert!(reduce(&[], 3, mode, vec![]).is_err()); + assert!(reduce(&[probe, probe], 3, mode, vec![]).is_err()); + assert!(reduce(&[probe], 3, mode, vec![]).is_err()); + for mutation in 0..9 { + let mut cells = raw(&probe, [200_000; 3]); + match mutation { + 0 => cells[0].id = "unknown", + 1 => cells[0].size *= 2, + 2 => { + cells[0].batches.pop(); + } + 3 => cells[0].batches[1].round = 0, + 4 => cells[0].batches[1].elapsed = Duration::ZERO, + 5 => cells[0].iterations = 0, + 6 => cells[0].iterations = SOURCE_MAX_ITERATIONS + 1, + 7 => { + cells.push(cells[0].clone()); + } + _ => cells.swap(0, 1), + } + assert!( + reduce(&[probe], 3, mode, cells).is_err(), + "mutation {mutation}, {mode:?}" + ); + } + } + } + + #[test] + fn ratios_keep_subnanosecond_values_and_report_performance_failure() { + let probe = REGISTRY[18]; + let mut cells = raw(&probe, [200_000, 400_000, 800_000]); + for cell in &mut cells { + cell.iterations = SOURCE_MAX_ITERATIONS; + } + let report = reduce(&[probe], 3, Mode::Gate, cells).unwrap(); + assert!((report.results[0].statistic.value() - 4.0).abs() < 1e-12); + assert_eq!(report.failures().len(), 1); + assert!(report.results[0].cells[0].ns_per_operation < 1.0); + assert_eq!( + report.results[0].cells[0].batch_median, + Duration::from_micros(200) + ); + assert!(report.to_string().contains("fixed-K ratio")); + } + + #[test] + fn typed_statistics_reject_invalid_values_and_distinguish_growth() { + let probe = REGISTRY[0]; + let report = reduce( + &[probe], + 3, + Mode::Gate, + raw(&probe, [200_000, 400_000, 800_000]), + ) + .unwrap(); + assert!((report.results[0].statistic.value() - 1.0).abs() < 1e-12); + for bad in [f64::NAN, f64::INFINITY, 0.0, -1.0] { + let mut cells = report.results[0].cells.clone(); + cells[0].ns_per_operation = bad; + assert!(statistic(StatisticClass::FixedOutputRatio, &cells).is_err()); + } + let mut cells = report.results[0].cells.clone(); + for cell in &mut cells { + cell.ns_per_operation = (cell.segments as f64 + 1.0).log2() * 0.125; + } + assert!( + (statistic(StatisticClass::LogMapRatio, &cells) + .unwrap() + .value() + - 1.0) + .abs() + < 1e-12 + ); + assert!(check_budget("probe", 32, Duration::from_nanos(1), 1, Duration::ZERO).is_err()); + } + + #[test] + fn abandoned_source_operation_is_a_harness_error_in_all_modes() { + let probe = SourceProbe { + sizes: SMOKE_SIZES, + ..REGISTRY[0] + }; + for mode in [Mode::Gate, Mode::ReportOnly, Mode::Smoke] { + let error = run_with_budget(&[probe], 1, mode, Duration::ZERO).unwrap_err(); + assert!(error.0.contains("AbandonedCell"), "{mode:?}: {error}"); + } + } + + #[test] + fn report_revalidates_batches_counts_and_statistic() { + let probe = REGISTRY[18]; + let report = reduce(&[probe], 3, Mode::Gate, raw(&probe, [200_000; 3])).unwrap(); + assert!(report.validate_data().is_ok()); + for mutation in 0..5 { + let mut invalid = report.clone(); + match mutation { + 0 => invalid.results[0].cells[0].ns_per_operation = f64::NAN, + 1 => invalid.results[0].statistic = Statistic::FixedOutputRatio(f64::INFINITY), + 2 => invalid.results[0].bound = f64::NAN, + 3 => invalid.results[0].cells[0].batches.clear(), + _ => invalid.results[0].cells[0].iterations = SOURCE_MAX_ITERATIONS + 1, + } + assert!(invalid.validate_data().is_err(), "mutation {mutation}"); + } + } + + #[test] + fn source_round_and_size_configuration_is_bounded_before_work() { + for rounds in [0, 2, 1025, usize::MAX] { + assert!(validate_registry(®ISTRY[..1], rounds).is_err()); + } + assert!(REGISTRY[0].source(0).is_err()); + assert!(REGISTRY[0].source(usize::MAX).is_err()); + let duplicate = [REGISTRY[0], REGISTRY[0]]; + assert!(validate_registry(&duplicate, 3).is_err()); + let wrong_sizes = SourceProbe { + sizes: [1, 1, 1], + ..REGISTRY[0] + }; + assert!(run(&[wrong_sizes], 1, Mode::Smoke).is_err()); + } + + #[test] + fn median_uses_complete_scheduled_batches_without_rounding() { + let probe = REGISTRY[18]; + let mut cells = raw(&probe, [200_001; 3]); + for cell in &mut cells { + cell.iterations = 3; + cell.batches[0].elapsed = Duration::from_nanos(900_001); + cell.batches[1].elapsed = Duration::from_nanos(200_002); + } + let report = reduce(&[probe], 3, Mode::Gate, cells).unwrap(); + let cell = &report.results[0].cells[0]; + assert_eq!(cell.batch_min, Duration::from_nanos(200_001)); + assert_eq!(cell.batch_median, Duration::from_nanos(200_002)); + assert_eq!(cell.batch_max, Duration::from_nanos(900_001)); + assert!((cell.ns_per_operation - 200_002.0 / 3.0).abs() < 1e-9); + assert_eq!(cell.batches[0].elapsed, Duration::from_nanos(900_001)); + assert_eq!( + cell.batches.iter().map(|b| b.round).collect::>(), + [0, 1, 2] + ); + } + + #[test] + fn source_smoke_exercises_every_registered_cell() { + let report = run(super::super::REGISTRY, 1, Mode::Smoke).unwrap(); + assert_eq!(report.results.len(), 46); + assert_eq!( + report.results.iter().map(|r| r.cells.len()).sum::(), + 138 + ); + assert!(!report.to_string().contains(" ok")); + } +} diff --git a/big-code-analysis-bench/src/documentation/tests.rs b/big-code-analysis-bench/src/documentation/tests.rs new file mode 100644 index 000000000..efdf47e11 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/tests.rs @@ -0,0 +1,509 @@ +use super::*; +use big_code_analysis_ast::LANG; +use big_code_analysis_ast::documentation::*; + +#[test] +fn original_registry_ids_sizes_and_options_are_preserved() { + assert_eq!( + crate::shapes::PROBES.len() + crate::vcs::VCS_PROBES.len(), + 140 + ); + let expected = [ + "documentation/cold/depth", + "documentation/cold/width", + "documentation/cold/fragments", + "documentation/cold/single-line-lua", + "documentation/cold/single-line-jsdoc", + "documentation/cold/c-slots", + "documentation/cold/wide-error", + "documentation/cold/missing", + "documentation/cold/names", + "documentation/secondary/single-line-php", + "documentation/secondary/single-line-ruby", + "documentation/secondary/single-line-doxygen", + "documentation/secondary/text-fixed-fanout", + "documentation/secondary/fanout-fixed-text", + "documentation/secondary/visible-declarator-depth", + "documentation/secondary/ruby-modifiers", + "documentation/secondary/java-undocumented", + "documentation/secondary/pending-scope", + "documentation/prepared/owner", + "documentation/prepared/late-map", + "documentation/prepared/retained", + "documentation/prepared/late-owner", + "documentation/ranges/cold", + "documentation/remediation/inline-spans", + "documentation/remediation/gathered-disposition", + "documentation/remediation/complex-signatures", + "documentation/remediation/order-multiple-chunks", + "documentation/remediation/text-budget-boundary", + "documentation/remediation/go-fold", + "documentation/remediation/ruby-fold", + "documentation/remediation/multiline-adjacent-ranges", + ]; + assert_eq!( + REGISTRY[..31].iter().map(|p| p.id).collect::>(), + expected + ); + for (at, probe) in REGISTRY[..31].iter().enumerate() { + assert_eq!( + probe.sizes, + if at < 23 { + [256, 512, 1024] + } else { + [1024, 2048, 4096] + } + ); + let options = probe.options(); + assert_eq!(options.profile, Profile::Default); + assert!(!options.retain_unbound && !options.retain_directives); + } + assert_eq!(REGISTRY.len() - 31, 15); +} + +#[test] +fn declared_growth_axes_match_full_size_input_and_output_counts() { + for probe in REGISTRY { + let counts: Vec<_> = probe + .sizes + .into_iter() + .map(|size| { + let parsed = Parsed::new(probe, size).unwrap(); + let index = parsed.collect(probe).unwrap(); + Prepared::new(probe, size, &parsed, &index) + .unwrap_or_else(|e| panic!("{} size {size}: {e}", probe.id)) + .counts() + }) + .collect(); + for (pair, sizes) in counts.windows(2).zip(probe.sizes.windows(2)) { + if probe.class == StatisticClass::FixedOutputRatio + || probe.class == StatisticClass::LogMapRatio + { + assert!(pair[0].query_output > 0, "{}", probe.id); + assert_eq!(pair[0].query_output, pair[1].query_output, "{}", probe.id); + } + if matches!( + probe.key, + "width" | "qualified-unrelated" | "qualified-candidates" | "qualified-references" + ) { + assert_eq!( + pair[0].depth, pair[1].depth, + "{}: fixed lexical depth", + probe.id + ); + } + if matches!( + probe.key, + "wide-depth" + | "pending-ancestry" + | "pending-late" + | "conditional-depth" + | "recovery-depth" + ) { + assert!( + pair[1].depth >= pair[0].depth + sizes[0], + "{}: growing lexical depth", + probe.id + ); + } + match probe.key { + "qualified-candidates" | "qualified-unrelated" => { + assert_eq!(pair[1].qualifications, pair[0].qualifications * 2); + assert_eq!(pair[1].edges, pair[0].edges * 2); + } + "qualified-references" => { + assert_eq!(pair[1].qualifications, pair[1].documents * 2); + assert_eq!(pair[1].edges, pair[1].documents * 2); + } + "wide-depth" => { + assert_eq!(pair[0].width, pair[1].width); + assert_eq!(pair[0].documents, 32); + assert_eq!(pair[1].documents, 32); + } + _ => {} + } + } + } +} + +#[test] +fn prepared_query_counters_charge_only_declared_output() { + use fixtures::Operation; + for size in [32, 64, 128] { + for probe in REGISTRY.iter().filter(|p| { + !matches!( + p.operation, + Operation::Collect | Operation::Render | Operation::EvidencePair + ) + }) { + let parsed = Parsed::new(probe, size).unwrap(); + let index = parsed.collect(probe).unwrap(); + let prepared = Prepared::new(probe, size, &parsed, &index).unwrap(); + let before = observations(); + prepared.execute().unwrap(); + let after = observations(); + assert_eq!(after.renders - before.renders, 0, "{}", probe.id); + assert_eq!(after.copy_chunks - before.copy_chunks, 0, "{}", probe.id); + assert_eq!(after.visits - before.visits, 0, "{}", probe.id); + assert_eq!(after.memo_probes - before.memo_probes, 0, "{}", probe.id); + assert_eq!( + after.fold_slot_probes - before.fold_slot_probes, + 0, + "{}", + probe.id + ); + assert_eq!( + after.sibling_slot_probes - before.sibling_slot_probes, + 0, + "{}", + probe.id + ); + match probe.operation { + Operation::Owner => { + assert_eq!(after.association_reads - before.association_reads, 1); + assert_eq!(after.identity_probes - before.identity_probes, 1); + } + Operation::OwnerQualifications | Operation::DocumentQualifications => { + assert_eq!( + after.qualification_reads - before.qualification_reads, + 1, + "{}", + probe.id + ); + assert_eq!(after.association_reads - before.association_reads, 0); + } + Operation::Pending => { + // Two records plus one exhausted-scope read per populated + // ancestor, and the final None read; the query starts at leaf. + let expected = if probe.key == "pending-ancestry" { + 3 * size + 1 + } else { + 4 + }; + assert_eq!( + after.assessment_scope_reads - before.assessment_scope_reads, + expected, + "{}", + probe.id + ); + } + Operation::Map => { + assert_eq!(after.map_runs_visited - before.map_runs_visited, 1); + // Rust's slice partition_point uses floor(log2(S)) + 2 + // comparisons for this non-power-of-two S=2n-1 ladder. + assert_eq!( + after.map_searches - before.map_searches, + (2 * size - 1).ilog2() as usize + 2 + ); + } + Operation::Retained => { + assert_eq!(after.association_reads - before.association_reads, 0); + assert_eq!(after.map_runs_visited - before.map_runs_visited, 0); + } + _ => unreachable!(), + } + } + } +} + +#[test] +fn added_collection_axes_charge_actual_visits_and_qualification_memberships() { + for size in [32, 64, 128] { + for probe in ®ISTRY[31..] { + let parsed = Parsed::new(probe, size).unwrap(); + let nodes = parsed.nodes().len(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + let after = observations(); + assert_eq!(after.visits - before.visits, nodes, "{}", probe.id); + assert_eq!( + after.child_batches - before.child_batches, + nodes, + "{}", + probe.id + ); + assert_eq!( + after.target_classifications - before.target_classifications, + nodes - 1, + "{}", + probe.id + ); + assert_eq!( + after.target_computations - before.target_computations, + nodes - 1, + "{}", + probe.id + ); + if probe.key.starts_with("qualified-") { + let q = if probe.key == "qualified-references" { + 2 * size + } else { + size + }; + // Each candidate fact is indexed by document, owner and node. + assert_eq!( + after.qualification_memberships - before.qualification_memberships, + 3 * q + ); + assert_eq!(index.qualifications().len(), q); + if probe.key == "qualified-candidates" { + // Per candidate: name key 3, two signature scans 24, + // signature hash/copy 30. Repeated keys compare 16 bytes; + // the single `f` reference scans/hashes/compares 5 bytes. + assert_eq!(after.name_bytes - before.name_bytes, 73 * size - 11); + assert_eq!(after.key_bytes_stored - before.key_bytes_stored, 16); + assert_eq!(after.name_candidates - before.name_candidates, 2 * size - 1); + } + } + } + } +} + +#[test] +fn preserved_scope_folds_and_field_axes_charge_search_work() { + for size in [32, 64, 128] { + for (key, slots) in [ + ("go-fold", 4 * (size / 16) + 5), + ("ruby-fold", 4 * (size / 16) - 1), + ] { + let probe = REGISTRY.iter().find(|p| p.key == key).unwrap(); + let parsed = Parsed::new(probe, size).unwrap(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + assert_eq!( + observations().fold_slot_probes - before.fold_slot_probes, + slots, + "{key}" + ); + assert_eq!(index.documents().len(), usize::from(key == "ruby-fold")); + } + let probe = REGISTRY + .iter() + .find(|p| p.key == "java-undocumented") + .unwrap(); + let parsed = Parsed::new(probe, size).unwrap(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + assert_eq!( + observations().memo_probes - before.memo_probes, + parsed.nodes().len() - 1 + ); + assert_eq!(observations().field_lookups - before.field_lookups, 0); + assert_eq!(index.facts().owners().len(), size + 2); + let probe = REGISTRY + .iter() + .find(|p| p.key == "visible-declarator-depth") + .unwrap(); + let parsed = Parsed::new(probe, size).unwrap(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + // Four children per visible array declarator, three on the declaration. + assert_eq!( + observations().field_requests - before.field_requests, + 4 * size + 3 + ); + assert_eq!(index.documents().len(), 1); + } +} + +#[test] +fn documented_wide_batch_slot_search_is_independent_of_lexical_depth() { + let probe = REGISTRY.iter().find(|p| p.key == "wide-depth").unwrap(); + let mut expected = None; + for depth in [32, 64, 128] { + let parsed = Parsed::new(probe, depth).unwrap(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + let reads = observations().sibling_slot_probes - before.sibling_slot_probes; + assert_eq!(index.documents().len(), 32); + assert!( + reads > 0, + "wide documented parent must exercise recorded sibling slots" + ); + if let Some(expected) = expected { + assert_eq!(reads, expected); + } else { + expected = Some(reads); + } + } +} + +#[test] +fn fresh_render_axes_build_once_and_fanout_keeps_one_text() { + for size in [32, 64, 128] { + for probe in REGISTRY + .iter() + .filter(|p| p.operation == fixtures::Operation::Render) + { + let parsed = Parsed::new(probe, size).unwrap(); + let index = parsed.collect(probe).unwrap(); + let prepared = Prepared::new(probe, size, &parsed, &index).unwrap(); + let before = observations(); + prepared.execute().unwrap(); + let after = observations(); + assert_eq!(after.renders - before.renders, 1); + assert_eq!( + after.copy_chunks - before.copy_chunks, + if probe.key == "prepared" { + 2 * size - 1 + } else { + 1 + } + ); + assert_eq!( + after.intersection_searches - before.intersection_searches, + 0 + ); + assert_eq!(after.visits - before.visits, 0); + assert_eq!(index.documents().len(), 1); + assert_eq!( + index.associations().next().unwrap().get().owner_count(), + if probe.language == LANG::C { 2 } else { 1 } + ); + } + } +} + +#[test] +fn large_fresh_render_preserves_bounded_copy_work() { + let probe = REGISTRY + .iter() + .find(|p| p.id == "documentation/render/bytes") + .unwrap(); + for size in probe.sizes { + let parsed = Parsed::new(probe, size).unwrap(); + let index = parsed.collect(probe).unwrap(); + let prepared = Prepared::new(probe, size, &parsed, &index).unwrap(); + let before = observations(); + prepared.execute().unwrap(); + let after = observations(); + assert_eq!(after.renders - before.renders, 1); + assert_eq!( + after.copy_chunks - before.copy_chunks, + (6 * size - 1).div_ceil(16 * 1024) + ); + assert_eq!(prepared.counts().rendered_bytes, 6 * size - 1); + assert_eq!(prepared.counts().map_segments, 1); + assert_eq!(prepared.counts().edges, 2); + } +} + +#[test] +fn evidence_pair_executes_both_off_and_on_collections() { + for probe in REGISTRY + .iter() + .filter(|p| p.operation == fixtures::Operation::EvidencePair) + { + let parsed = Parsed::new(probe, 32).unwrap(); + let index = parsed.collect(probe).unwrap(); + let prepared = Prepared::new(probe, 32, &parsed, &index).unwrap(); + let before = observations(); + prepared.execute().unwrap(); + let after = observations(); + assert_eq!(after.visits - before.visits, 2 * parsed.nodes().len()); + assert_eq!( + after.child_batches - before.child_batches, + 2 * parsed.nodes().len() + ); + assert_eq!( + after.renders - before.renders, + if probe.key == "rejected" { 2 } else { 0 } + ); + } +} + +#[test] +fn new_generated_names_keep_affine_bytes() { + for key in ["qualified-unrelated", "missing-name"] { + let probe = REGISTRY.iter().find(|p| p.key == key).unwrap(); + let [a, b, c] = probe.sizes.map(|size| probe.source(size).unwrap().len()); + assert_eq!(c - b, 2 * (b - a), "{key}"); + } +} + +#[test] +fn candidate_reference_overlap_and_unknown_signature_controls_are_distinct() { + for (source, subject, reasons) in [ + ( + "#if FLAG\nvoid f(int x = );\n#endif\nvoid f(void);\n/**@fn f*/", + QualificationSubject::Candidate, + vec![ + UnresolvedReason::Conditional, + UnresolvedReason::GrammarBoundary, + ], + ), + ( + "void f(void);\n#if FLAG\n/**@fn f*/\n#endif", + QualificationSubject::Reference, + vec![UnresolvedReason::Conditional], + ), + ] { + let ast = big_code_analysis::Ast::parse(big_code_analysis::Source::new( + LANG::Cpp, + source.as_bytes(), + )) + .unwrap(); + let index = collect( + ast.language(), + ast.as_tree_sitter(), + ast.source(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let qualifications: Vec<_> = index.qualifications().collect(); + assert_eq!( + qualifications + .iter() + .map(|q| q.get().reason) + .collect::>(), + reasons + ); + for q in qualifications { + assert_eq!(q.get().subject, subject); + assert_eq!( + index.qualified_owner(q).unwrap().is_some(), + subject == QualificationSubject::Candidate + ); + assert_eq!( + index.qualified_document(q).unwrap(), + index.documents().next().unwrap() + ); + } + } + let ast = big_code_analysis::Ast::parse(big_code_analysis::Source::new( + LANG::Cpp, + b"void f(int x[2]);\n/**@fn void absent(int x[2])*/", + )) + .unwrap(); + let index = collect( + ast.language(), + ast.as_tree_sitter(), + ast.source(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 0); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner) + ); +} + +#[test] +fn semantic_validation_rejects_a_fixture_with_its_measured_axis_removed() { + let probe = REGISTRY.iter().find(|p| p.key == "width").unwrap(); + let parsed = Parsed::new(probe, 32).unwrap(); + let index = parsed.collect(probe).unwrap(); + assert!(Prepared::new(probe, 64, &parsed, &index).is_err()); + let probe = REGISTRY + .iter() + .find(|p| p.key == "qualified-candidates") + .unwrap(); + let parsed = Parsed::new(probe, 32).unwrap(); + let index = parsed.collect(probe).unwrap(); + assert!(Prepared::new(probe, 64, &parsed, &index).is_err()); +} diff --git a/big-code-analysis-bench/src/documentation/validation.rs b/big-code-analysis-bench/src/documentation/validation.rs new file mode 100644 index 000000000..dd2950a05 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/validation.rs @@ -0,0 +1,594 @@ +//! Untimed semantic and grammar-shape checks for the documentation workloads. + +use super::{HarnessError, Parsed, SourceProbe, failure, require}; +use big_code_analysis_ast::documentation::{ + AssessmentAxis, Content, DocumentationIndex, OriginView, Owner, Resolution, UnresolvedReason, +}; + +pub(super) fn documents( + index: &DocumentationIndex<'_>, + count: usize, + fragments: usize, + owners: usize, + expected: &str, +) -> Result<(), HarnessError> { + require(index.documents().len() == count, "document count")?; + require(index.associations().len() == count, "association count")?; + for association in index.associations() { + require( + association.get().resolution == Resolution::Resolved, + "resolved association", + )?; + require( + association.get().owner_count() == owners, + "owner edge count", + )?; + let document = index + .facts() + .associated_document(association) + .map_err(failure)?; + require( + document.get().fragment_count() == fragments, + "fragment count", + )?; + let text = index + .complete_text(document) + .map_err(failure)? + .ok_or_else(|| HarnessError("complete text absent".into()))?; + require(text.text() == expected, "complete text mismatch")?; + let mut end = 0; + for portion in text.origins(0..expected.len()).map_err(failure)? { + require(portion.output.start == end, "map coverage start")?; + end = portion.output.end; + if let OriginView::Copied(piece) = portion.origin { + require( + piece.bytes() == &expected.as_bytes()[portion.output], + "copied origin bytes", + )?; + } + } + require(end == expected.len(), "map coverage end")?; + for position in 0..owners { + let owner = index + .facts() + .associated_owner(association, position) + .map_err(failure)?; + let query = index.owner_associations(owner).map_err(failure)?; + require( + query.associations().collect::>() == [association], + "owner association adjacency", + )?; + } + } + Ok(()) +} + +pub(super) fn fixture( + probe: &SourceProbe, + size: usize, + parsed: &Parsed, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + if matches!( + probe.key, + "depth" + | "width" + | "fragments" + | "single-line-lua" + | "single-line-jsdoc" + | "c-slots" + | "wide-error" + | "missing" + | "names" + | "single-line-php" + | "single-line-ruby" + | "single-line-doxygen" + | "text-fixed-fanout" + | "fanout-fixed-text" + | "visible-declarator-depth" + | "ruby-modifiers" + | "java-undocumented" + | "pending-scope" + ) { + original_fixture(probe.key, size, parsed, index)?; + } else { + additional_fixture(probe, size, parsed, index)?; + } + Ok(()) +} + +#[allow(clippy::too_many_lines)] // Explicit independent expected outcomes for the finite fixture inventory. +fn additional_fixture( + probe: &SourceProbe, + size: usize, + parsed: &Parsed, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + let nodes = parsed.nodes(); + let count = |kind| nodes.iter().filter(|(node, _)| node.kind() == kind).count(); + require( + parsed.tree().root_node().has_error() == (probe.key == "recovery-depth"), + format!("{}: parse shape", probe.id), + )?; + match probe.key { + "ranges" => documents(index, size, 1, 1, "audit")?, + "prepared" => { + documents( + index, + 1, + size, + 1, + &std::iter::repeat_n("a", size) + .collect::>() + .join("\n"), + )?; + let doc = index + .documents() + .next() + .ok_or_else(|| HarnessError("document absent".into()))?; + let text = index + .complete_text(doc) + .map_err(failure)? + .ok_or_else(|| HarnessError("text absent".into()))?; + require(text.mappings().len() == size * 2 - 1, "prepared map count")?; + let portions: Vec<_> = text + .origins(size * 2 - 2..size * 2 - 1) + .map_err(failure)? + .collect(); + require(portions.len() == 1, "late map K")?; + let OriginView::Copied(piece) = &portions[0].origin else { + return Err(HarnessError("late map not copied".into())); + }; + require( + piece.range() == ((size - 1) * 5 + 3..(size - 1) * 5 + 4), + "late map source range", + )?; + require( + nodes.iter().any(|(node, _)| { + node.kind() == "function_item" && node.start_byte() == 5 * size + }), + "prepared function anchor", + )?; + } + "inline-spans" => documents(index, 1, 1, 1, &"`x` ".repeat(size)[..size * 4 - 1])?, + "gathered-disposition" => { + require(index.documents().len() == 1, "gathered document count")?; + require( + index + .documents() + .next() + .is_some_and(|d| d.get().fragment_count() == size + 1), + "gathered fragment count", + )?; + } + "complex-signatures" => { + require( + index.documents().len() == 0 && count("declaration") == size / 16 + 1, + "complex declaration shape", + )?; + require( + index + .assessments() + .filter(|a| a.get().reason == "Complex signature awaits exact named matching") + .count() + == size / 16, + "complex signature pending count", + )?; + } + "go-fold" => require( + index.documents().len() == 0 && count("field_declaration") == size / 16 + 1, + "go fold shape", + )?, + "text-budget-boundary" => documents(index, 1, 1, 1, &"abcd".repeat(size * 2))?, + "ruby-fold" => documents(index, 1, 1, 1, "audit")?, + "multiline-adjacent-ranges" => documents( + index, + 1, + 1, + 1, + &std::iter::repeat_n("audit", size) + .collect::>() + .join("\n"), + )?, + "qualified-candidates" | "qualified-references" | "qualified-unrelated" => { + qualifications(probe, size, index)? + } + "pending-ancestry" | "pending-late" => { + let leaf = nodes + .iter() + .rev() + .find(|(node, _)| node.kind() == "function_item") + .ok_or_else(|| HarnessError("pending query leaf absent".into()))? + .0; + let query = index.node_associations(leaf).map_err(failure)?; + let expected = if probe.key == "pending-ancestry" { + 2 * size + } else { + 2 + }; + require(query.assessments().count() == expected, "pending output K")?; + require(count("mod_item") == size, "pending lexical depth")?; + require( + index.assessments().len() + == if probe.key == "pending-ancestry" { + 3 * size + } else { + 3 + }, + "pending retained count", + )?; + } + "wide-depth" => { + documents(index, 32, 1, 1, "audit")?; + require( + count("mod_item") == size && count("function_item") == 32, + "wide-depth shape", + )?; + } + "comment-run-depth" => { + documents( + index, + 1, + size, + 1, + &std::iter::repeat_n("a", size) + .collect::>() + .join("\n"), + )?; + require(count("mod_item") == size, "comment-run depth")?; + } + "recovery-depth" => { + require(count("field_declaration") == 32, "recovery sibling width")?; + require( + nodes.iter().any(|(node, depth)| { + node.is_error() && node.child_count() >= 32 && *depth >= size + }), + "deep wide recovery parent absent", + )?; + require(index.documents().len() == 32, "recovery document count")?; + } + "conditional-depth" => { + require( + count("struct_specifier") == size && count("preproc_if") == size, + "conditional structure depth", + )?; + require(index.documents().len() == 1, "conditional document count")?; + } + "missing-name" => { + require(count("declaration") == size, "unrelated named declarations")?; + require( + index.associations().len() == 1, + "missing-name association count", + )?; + require( + index.associations().next().is_some_and(|a| { + a.get().resolution == Resolution::Unresolved(UnresolvedReason::MissingName) + && a.get().owner_count() == 0 + }), + "valid MissingName outcome", + )?; + } + "rejected" | "directives" => evidence(probe, size, parsed, index)?, + _ => return Err(HarnessError(format!("unvalidated workload {}", probe.id))), + } + Ok(()) +} + +fn qualifications( + probe: &SourceProbe, + size: usize, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + use big_code_analysis_ast::documentation::QualificationSubject; + let (documents, owners, total) = match probe.key { + "qualified-candidates" => (1, size, size), + "qualified-references" => (size, 2, 2 * size), + _ => (size, 1, size), + }; + require( + index.documents().len() == documents && index.associations().len() == documents, + "qualification D/A counts", + )?; + require( + index.qualifications().len() == total, + "qualification output Q", + )?; + for association in index.associations() { + require( + association.get().owner_count() == owners, + "qualification edge count", + )?; + let doc = index + .facts() + .associated_document(association) + .map_err(failure)?; + require( + index.document_qualifications(doc).map_err(failure)?.len() == owners, + "document qualification adjacency", + )?; + let expected_resolution = if owners > 1 { + UnresolvedReason::Ambiguous + } else { + UnresolvedReason::Conditional + }; + require( + association.get().resolution == Resolution::Unresolved(expected_resolution), + "qualified association resolution", + )?; + let ordinal = index + .document_qualifications(doc) + .map_err(failure)? + .next() + .ok_or_else(|| HarnessError("document has no qualification".into()))?; + require( + index.qualified_document(ordinal).map_err(failure)? == doc, + "qualification document identity", + )?; + } + for q in index.qualifications() { + require( + q.get().subject == QualificationSubject::Candidate + && q.get().reason == UnresolvedReason::Conditional, + "candidate qualification kind", + )?; + require( + index.qualified_owner(q).map_err(failure)?.is_some(), + "candidate qualification owner identity", + )?; + } + Ok(()) +} + +fn evidence( + probe: &SourceProbe, + size: usize, + parsed: &Parsed, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + use big_code_analysis_ast::documentation::CandidateDisposition; + let mut off = *probe; + off.evidence = false; + let control = parsed.collect(&off)?; + require( + control.evidence().len() == 0, + "off control materialized evidence", + )?; + let expected = if probe.key == "rejected" { + size - 1 + } else { + size + }; + require( + index.evidence().len() == expected, + "retained evidence count", + )?; + require( + index.documents().len() == if probe.key == "rejected" { 1 } else { 0 }, + "evidence document count", + )?; + if probe.key == "directives" { + require( + index + .evidence() + .all(|e| e.get().disposition == CandidateDisposition::Directive), + "directive disposition", + )?; + } else { + require( + index + .evidence() + .all(|e| e.get().disposition == CandidateDisposition::Superseded), + "rejected disposition", + )?; + documents(&control, 1, 1, 1, "audit")?; + } + require( + control.documents().len() == index.documents().len(), + "retention changed selected documents", + )?; + Ok(()) +} + +fn shape(name: &str, size: usize, parser: &Parsed) -> Result<(), HarnessError> { + let root = parser.tree().root_node(); + require( + root.has_error() == matches!(name, "wide-error" | "missing"), + format!("{name}: parse error shape"), + )?; + let walk = parser.nodes(); + let maximum = walk.iter().map(|(_, depth)| *depth).max().unwrap_or(0); + let nodes: Vec<_> = walk.into_iter().map(|(node, _)| node).collect(); + let count = |kind| nodes.iter().filter(|node| node.kind() == kind).count(); + match name { + "depth" => { + require( + count("mod_item") == size && maximum >= 2 * size, + "module depth", + )?; + } + "width" => require(root.child_count() == size * 2, "sibling width")?, + "fragments" => require(count("comment") == size, "comment fragments")?, + "c-slots" | "fanout-fixed-text" => { + require(count("identifier") == size, "declaration slots")? + } + "visible-declarator-depth" => { + require( + count("array_declarator") == size && maximum >= size, + "array depth", + )?; + } + "ruby-modifiers" => { + require( + count("if_modifier") == size && maximum >= size, + "modifier depth", + )?; + } + "java-undocumented" => { + require( + count("class_declaration") == size && maximum >= 2 * size, + "class depth", + )?; + } + "pending-scope" => require(count("function_item") == size, "pending scope functions")?, + "names" => require(count("function_definition") == size, "named functions")?, + "missing" => { + require( + nodes.iter().filter(|node| node.is_missing()).count() == 1 && maximum >= size, + "missing token depth", + )?; + } + "wide-error" => { + let error = nodes + .iter() + .find(|node| node.is_error()) + .ok_or_else(|| HarnessError("wide ERROR absent".into()))?; + require( + error.child_count() >= size && count("field_declaration") == size, + "wide recovery fields", + )?; + } + _ => require( + matches!( + name, + "single-line-lua" + | "single-line-jsdoc" + | "single-line-php" + | "single-line-ruby" + | "single-line-doxygen" + | "text-fixed-fanout" + ), + "unregistered shape", + )?, + } + Ok(()) +} + +#[allow(clippy::too_many_lines)] // One explicit expected outcome per benchmark workload. +fn original_fixture( + name: &str, + size: usize, + parser: &Parsed, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + shape(name, size, parser)?; + match name { + "depth" | "ruby-modifiers" | "visible-declarator-depth" => { + documents(index, 1, 1, 1, "audit")?; + } + "width" => documents(index, size, 1, 1, "audit")?, + "fragments" => documents( + index, + 1, + size, + 1, + &std::iter::repeat_n("audit", size) + .collect::>() + .join("\n"), + )?, + "c-slots" => documents(index, 1, 1, size, "audit")?, + "single-line-lua" | "single-line-ruby" => { + documents(index, 1, 1, 1, &"audit ".repeat(size))?; + } + "single-line-jsdoc" | "single-line-php" | "single-line-doxygen" => { + documents(index, 1, 1, 1, &"audit ".repeat(size)[..size * 6 - 1])?; + } + "text-fixed-fanout" => documents(index, 1, 1, 2, &"audit ".repeat(size)[..size * 6 - 1])?, + "fanout-fixed-text" => documents(index, 1, 1, size, &"audit ".repeat(1024)[..6143])?, + "java-undocumented" => { + require( + index.documents().len() == 0 && index.facts().owners().len() == size + 2, + "undocumented owner count", + )?; + } + "missing" => { + require( + index.documents().len() == 0 && index.associations().len() == 0, + "missing token output", + )?; + } + "wide-error" => { + require(index.documents().len() == 1, "recovery document count")?; + let association = index + .associations() + .next() + .ok_or_else(|| HarnessError("recovery association absent".into()))?; + require( + association.get().resolution + == Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + && association.get().owner_count() == 0, + "recovery association state", + )?; + } + "pending-scope" => { + require(index.documents().len() == 1, "pending document count")?; + let document = index + .documents() + .next() + .ok_or_else(|| HarnessError("pending attribute absent".into()))?; + require( + matches!(document.get().content(), Content::PendingAdapter) + && index.assessments().len() == 3, + "pending state", + )?; + let last = parser + .nodes() + .into_iter() + .map(|(node, _)| node) + .rfind(|node| node.kind() == "function_item") + .ok_or_else(|| HarnessError("last function absent".into()))?; + let query = index.node_associations(last).map_err(failure)?; + require( + query.associations().len() == 0, + "pending owner associations", + )?; + require( + query + .assessments() + .map(|assessment| assessment.get().axis) + .collect::>() + == [AssessmentAxis::Occurrence, AssessmentAxis::Publication], + "pending assessment axes", + )?; + } + "names" => { + require( + index.documents().len() == size && index.associations().len() == size, + "named D/A counts", + )?; + for (ordinal, association) in index.associations().enumerate() { + require( + association.get().resolution == Resolution::Resolved + && association.get().owner_count() == 1, + "named resolution", + )?; + let owner = index + .facts() + .associated_owner(association, 0) + .map_err(failure)?; + let Owner::Node(node) = owner.get() else { + return Err(HarnessError("named owner is not a node".into())); + }; + require( + &parser.source()[node.node().byte_range()] + == format!("void f{ordinal}() {{}}").as_bytes(), + "named owner spelling", + )?; + let document = index + .facts() + .associated_document(association) + .map_err(failure)?; + require( + index + .complete_text(document) + .map_err(failure)? + .ok_or_else(|| HarnessError("named text absent".into()))? + .text() + == format!("@fn void f{ordinal}()"), + "named reference spelling", + )?; + } + } + _ => return Err(HarnessError(format!("unvalidated workload {name}"))), + } + Ok(()) +} diff --git a/big-code-analysis-bench/src/lib.rs b/big-code-analysis-bench/src/lib.rs index 75f1db758..f9446f247 100644 --- a/big-code-analysis-bench/src/lib.rs +++ b/big-code-analysis-bench/src/lib.rs @@ -1,6 +1,6 @@ //! Benchmark harness for the `big-code-analysis` metric walk (#1068). //! -//! The crate is split three ways: +//! The crate contains these benchmark and validation modules: //! //! - [`shapes`] generates the synthetic scaling inputs — nesting on //! one axis, sibling count on the other — and pairs each with the @@ -13,14 +13,16 @@ //! - [`vcs`] grows a ranked population instead of a tree, for the one //! hot path that is not a walk: the change-history percentile pass //! (#1267). It fits the same exponent and joins the same gate. +//! - [`documentation`] shares source fixtures and untimed validation between +//! Criterion and the class-specific raw-batch source gate. //! - [`verbatim`] is not a benchmark at all: the `verbatim-oracle` //! binary behind `utils/drift-oracle.py` (#1744), housed here because //! this is the one dev-only crate that depends on the root with every //! grammar and never ships. //! -//! Two bench targets drive them: `benches/scaling.rs` (the -//! complexity-class gate) and `benches/metric_walk.rs` (criterion -//! measurements over the corpus slice, per metric). [`cli`] holds the +//! The targets are `benches/scaling.rs` (the combined class gate), +//! `benches/metric_walk.rs` (Criterion over the corpus slice, per metric), and +//! `benches/documentation.rs` (Criterion over the source registry). [`cli`] holds the //! former's argument handling, which lives here rather than in the //! bench target so it is covered by tests that actually run. //! @@ -34,6 +36,7 @@ pub mod cli; pub mod corpus; +pub mod documentation; pub mod scaling; pub mod shapes; pub mod vcs; diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index dbbaa512b..35e62ccba 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -1,26 +1,27 @@ -# Benchmarking the metric walk +# Benchmarking analysis operations -`big-code-analysis-bench` is the benchmark harness for the metric -walk. It is for contributors changing AST traversal, a `Checker` or -`Getter` predicate, or a metric's `compute`. It exists so that a -performance claim about this project can be reproduced by someone who -did not make it, and so that a change in *complexity class* fails -loudly instead of quietly making deeply nested files unanalysable. +`big-code-analysis-bench` measures metric walks and source-documentation +operations. It is for contributors changing AST traversal, a `Checker` or +`Getter` predicate, a metric's `compute`, or documentation collection and queries. +The harness makes performance claims reproducible and detects changes in complexity class. It has two halves, and they answer different questions. - **The complexity-class gate** (`benches/scaling.rs`) answers "does doubling the input (its nesting depth, or one parent's child count) roughly double the cost?" It fails the process when a probe's - measured exponent exceeds the bound that probe declares. + class-specific statistic exceeds the bound that probe declares. - **The criterion benchmarks** (`benches/metric_walk.rs`) answer "how fast is this, and did my change help?" They use [criterion][criterion], which reports a confidence interval rather than a point estimate and can compare two builds against a saved baseline. +The combined gate also runs the [source-documentation registry](#source-documentation). +Source construction uses a fitted exponent; fixed-output queries use ratios. + Neither runs in per-PR CI. See [Why not in CI](#why-not-in-ci). The -first two sections cover running the gate and reading its output. The +opening sections cover running the gates and reading their output. The per-probe histories after them record why each probe exists and what it was measured catching; read those when a probe fails or when adding one. @@ -46,11 +47,11 @@ cargo bench -p big-code-analysis-bench --bench metric_walk The crate is a workspace member but not a default member, so a bare `cargo build` at the repo root does not build it or pull in criterion. -`cargo test --benches` also executes both targets, because a +`cargo test --benches` also executes the benchmark targets, because a `harness = false` bench target runs its `main`. The gate detects that (cargo passes `--bench` only under `cargo bench`) and downgrades to a -shallow smoke run with no verdict, so an unoptimised build never -produces a number or a failure. +shallow smoke run with no performance verdict. Source smoke can fail for invalid +fixtures, operations or samples. It makes no timing-resolution or performance claim. The criterion benchmarks read a slice of the corpus submodules under `tests/repositories/`. Without them the corpus group is skipped with a @@ -60,6 +61,122 @@ message and the synthetic shapes still run: git submodule update --init --recursive ``` +## Source-documentation measurements {#source-documentation} + +Use these commands when changing documentation collection, rendering or prepared queries: + +```bash +make bench-source +make bench-documentation +cargo bench -p big-code-analysis-bench --bench scaling -- --scope source --rounds 7 +cargo bench -p big-code-analysis-bench --bench scaling -- --scope legacy --rounds 7 +cargo bench -p big-code-analysis-bench --bench scaling -- --scope source --no-gate +cargo bench -p big-code-analysis-bench --bench scaling -- --scope source --smoke +``` + +The default scope is `all`. The entry point prints the selected membership. +Unknown scopes and positional filters fail instead of silently selecting another set. +Exit 0 means a successful gate, or a successful non-gating run when that mode is printed. +Exit 1 means a performance bound failed. Exit 2 means invalid configuration, missing or invalid +measurements, abandoned work, or an operation/fixture failure. Report-only suppresses performance +failure; it still rejects harness errors. + +### Registry and timed boundaries + +`big-code-analysis-bench/src/documentation/` supplies one registry to the source gate and +`benches/documentation.rs`. Each entry declares its language, options, size ladder, operation, +varied and fixed dimensions, bound and policy provenance. Full-size fixture validation runs +outside the timers at every rung. The original Criterion identities and source bytes stay in +this registry, alongside a finite set of additional qualification, pending-query, combined +structure, rejection, evidence and rendering axes. + +Ordinary fixtures parse once through `Ast` and call the borrowed collector with +`Ast::language`, `Ast::as_tree_sitter` and `Ast::source`. Deliberate included-range fixtures +retain their exact tree and byte buffer. Storage has three lifetime layers: owned parses, +indexes borrowing those parses, then prepared query/render state borrowing the indexes. +The runner drops those layers in reverse order after measurement. + +| Operation | Prepared outside timing | Work inside timing | +| --- | --- | --- | +| Cold collection | Parsed tree and exact source | Collection, eager text/maps, index destruction | +| Evidence off/on pair | Parsed tree and exact source | Collection and destruction with retention off, then on; one pair per iteration | +| Fresh rendering | Immutable index, validated document and ordered fragment references | Production comment rendering with a fresh budget, new content destruction | +| Owner or pending lookup | Index and canonical query node | Lookup and consumption of each declared association or assessment | +| Qualification lookup | Index and index-qualified owner/document handle | Lookup and consumption of each qualification | +| Late map query | Complete text and mappings | Last-byte lookup and consumption of every returned portion | +| Retained text access | Index and document handle | Borrowed complete-text access; no rendering or output copy | + +The `test-support`-gated `documentation::render_probe::PreparedRender` accepts only a document +from a real immutable index. Preparation rejects foreign handles, unsupported composition, +non-comment fragments and unavailable content. It validates retained source intersections before +timing. Each measured call uses the production renderer and checks active cancellation at entry, +including empty text. Cancellation, source errors and unsupported preparation remain distinct. +Counter controls distinguish a fresh render from retained access and shared text from per-owner +copies. + +The benchmark library enables `test-support` on its ordinary AST dependency. +[Cargo feature unification](https://doc.rust-lang.org/cargo/reference/features.html#feature-unification) +therefore also enables it for other workspace consumers in the same build. Production +counter recording remains unconditional; only readers and the prepared seam are feature-gated. +Match and record the actual feature sets for base/candidate legacy comparisons. + +### Source statistics and timing resolution + +The source gate uses the median of scheduled rounds after the same rotating warmup schedule as +the legacy runner. It keeps separate typed results: + +| Declared work | Statistic | Bound | +| --- | --- | --- | +| Collection or fresh rendering with linear/linearithmic output | Fitted slope of log time against log size | 1.50 | +| Fixed-output owner, qualification, pending or retained query | Largest/smallest per-rung median | 1.50 | +| Fixed-output late map query with S segments | Largest/smallest median after division by log2(S+1) | 1.50 | +| Pending ancestry returning growing K records | Linear-output fitted exponent | 1.50 | + +K is the number of records consumed by a query. Qualification construction holds references or +candidates fixed while varying the other factor. It reports the legitimate association-edge and +qualification growth separately; a references-times-candidates product is output work, not proof +of excessive overhead. + +Each cell calibrates once before warmup. Its repetition count is +`ceil(2 ms / max(single-operation time, 1 ns))`, clamped to `1..=2^20`. The runner freezes this +count for all warmup and measured rounds. It stores actual batch durations and derives fractional +nanoseconds per operation only during reduction. It never reconstructs a batch from rounded +per-operation durations or applies the legacy fit's timing floor to a ratio. + +Full-size gate and report modes require a measured median batch of at least 200 microseconds. +A shorter batch produces `UnresolvedCell` and exit 2, with its ID, size, iterations and actual +duration. A cold calibration call can overestimate later cost, so even an ordinary workload can +fail this resolution check. The runner does not retry or increase repetitions after observing a +short batch. Preserve the failed run for analysis. + +Reports include raw scheduled batches, iteration counts, batch minimum/median/maximum and +floating-point nanoseconds per operation. Untimed counts report nodes, depth, width, fragments, +documents, owner edges, qualifications, rendered bytes, map segments, included ranges, +intersections and query output. Missing cells or rounds, duplicate identities, zero +durations, wrong membership and nonfinite statistics are harness errors. Smoke uses small +inputs and bounded repetitions, skips the resolution requirement and prints no performance +verdict. Structural and malformed-data checks still apply. + +The per-operation budget detects excessive time after an operation or batch finishes. It cannot +interrupt the first execution or a dependency call. An external deadline can bound the whole +campaign; it does not provide per-operation cancellation. + +### Controlled comparisons and coverage limits + +Run the maintained source gate and Criterion on one frozen revision and matching features on +the same controlled host. Record the revision, toolchain, CPU assignment, commands, membership, +raw batches and Criterion results. Keep the old Criterion mean/95% confidence-interval evidence +separate from the new median statistic. Do not change bounds after observing a run. New +optimization guards also need discriminating counter tests and controlled regressed/fixed pairs +where a timing claim requires them. + +The visible array-declarator ladder measures visible nesting and field requests. It does not +establish a bound on work inside a dependency's hidden-rule field lookup. Investigation is +limited to the collector's implemented `fields_needed` parents: C-family declarations and +declarators, JavaScript-family exports, and Ruby modifiers. No hidden-only growing source path +has been established by this registry. A later adapter must add a positive probe for any new +reachable path; deferred Tcl support cannot serve as a successful empty control. + ## The complexity-class gate {#complexity-gate} Each probe pairs a generated source shape with the workload that From bcf3359d635d71ba2a74404c9930bccdef2caace Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:08:36 -0800 Subject: [PATCH 048/221] docs(bench): clarify source gate qualification and benchmark coverage Apply independent benchmark-guide review: distinguish legacy/source exits and Criterion scopes, define source dimensions and per-operation ratios, document extension and under-resolution policy, and correct field-query reachability and legacy-only claims. Verified with rumdl check --no-cache docs/development/benchmarking.md, git diff --check, and local link/anchor checks. Heavy hooks skipped while #1663 owns validation; no Cargo build, test, mutation, gate or benchmark ran. Source checkpoint remains uncompiled. --- docs/development/benchmarking.md | 232 ++++++++++++++++++++----------- 1 file changed, 152 insertions(+), 80 deletions(-) diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 35e62ccba..2c5ceb074 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -5,55 +5,61 @@ operations. It is for contributors changing AST traversal, a `Checker` or `Getter` predicate, a metric's `compute`, or documentation collection and queries. The harness makes performance claims reproducible and detects changes in complexity class. -It has two halves, and they answer different questions. +The gate and timing benchmarks answer different questions. -- **The complexity-class gate** (`benches/scaling.rs`) answers "does - doubling the input (its nesting depth, or one parent's child count) - roughly double the cost?" It fails the process when a probe's +- **The complexity-class gate** (`benches/scaling.rs`) answers "does cost + stay within the growth bound declared for this workload's input and output?" + It fails the process when a probe's class-specific statistic exceeds the bound that probe declares. -- **The criterion benchmarks** (`benches/metric_walk.rs`) answer "how - fast is this, and did my change help?" They use - [criterion][criterion], which reports a confidence interval rather - than a point estimate and can compare two builds against a saved - baseline. +- **The [Criterion][criterion] benchmarks** answer "how fast is this, + and did my change help?" `benches/metric_walk.rs` measures metric walks; + `benches/documentation.rs` measures source-documentation operations. + Criterion reports confidence intervals and compares builds against saved baselines. The combined gate also runs the [source-documentation registry](#source-documentation). Source construction uses a fitted exponent; fixed-output queries use ratios. -Neither runs in per-PR CI. See [Why not in CI](#why-not-in-ci). The -opening sections cover running the gates and reading their output. The -per-probe histories after them record why each probe exists and what -it was measured catching; read those when a probe fails or when adding -one. +Neither runs in per-PR CI. See [Why not in CI](#why-not-in-ci). +Start with [source-documentation measurements](#source-documentation) or +[legacy probes](#complexity-gate) for gate results. For cross-build timings, read +[comparing two builds](#comparing-two-builds), +[interleaving on a busy host](#interleaved-ab), and +[measurement traps](#measurement-traps). The later probe histories explain why +each legacy probe exists and which regression it detects. [criterion]: https://bheisler.github.io/criterion.rs/book/index.html ## Running it ```bash -make bench-scaling # complexity-class gate -make bench-walk # criterion measurements -make bench # both +make bench-scaling # combined legacy and source class gate +make bench-walk # metric-walk Criterion measurements +make bench-documentation # source-documentation Criterion measurements +make bench # combined gate + metric-walk Criterion ``` -Or directly, which is what you want when passing criterion flags: +`make bench` runs the combined scaling gate and metric-walk Criterion target. +Run `make bench-documentation` separately for documentation Criterion measurements. + +Or directly, when passing Criterion flags: ```bash cargo bench -p big-code-analysis-bench --bench scaling cargo bench -p big-code-analysis-bench --bench scaling -- --rounds 11 cargo bench -p big-code-analysis-bench --bench metric_walk +cargo bench -p big-code-analysis-bench --bench documentation ``` The crate is a workspace member but not a default member, so a bare -`cargo build` at the repo root does not build it or pull in criterion. +`cargo build` at the repo root does not build it or pull in Criterion. -`cargo test --benches` also executes the benchmark targets, because a +`cargo test -p big-code-analysis-bench --benches` also executes the benchmark targets, because a `harness = false` bench target runs its `main`. The gate detects that (cargo passes `--bench` only under `cargo bench`) and downgrades to a shallow smoke run with no performance verdict. Source smoke can fail for invalid fixtures, operations or samples. It makes no timing-resolution or performance claim. -The criterion benchmarks read a slice of the corpus submodules under +Metric-walk Criterion benchmarks read a slice of the corpus submodules under `tests/repositories/`. Without them the corpus group is skipped with a message and the synthetic shapes still run: @@ -66,20 +72,27 @@ git submodule update --init --recursive Use these commands when changing documentation collection, rendering or prepared queries: ```bash -make bench-source -make bench-documentation +make bench-source # source class gate +make bench-documentation # source Criterion measurements cargo bench -p big-code-analysis-bench --bench scaling -- --scope source --rounds 7 cargo bench -p big-code-analysis-bench --bench scaling -- --scope legacy --rounds 7 cargo bench -p big-code-analysis-bench --bench scaling -- --scope source --no-gate cargo bench -p big-code-analysis-bench --bench scaling -- --scope source --smoke ``` -The default scope is `all`. The entry point prints the selected membership. -Unknown scopes and positional filters fail instead of silently selecting another set. -Exit 0 means a successful gate, or a successful non-gating run when that mode is printed. -Exit 1 means a performance bound failed. Exit 2 means invalid configuration, missing or invalid -measurements, abandoned work, or an operation/fixture failure. Report-only suppresses performance -failure; it still rejects harness errors. +The scaling executable accepts `--scope source` for source-documentation workloads, +`--scope legacy` for metric-walk and VCS ranking probes, and `--scope all` for both sets. +The default is `all`. It prints the selected membership and rejects unknown scopes and +positional filters. These scope options do not apply to the Criterion targets. + +The scaling executable uses these exit codes: + +- Exit 0 means a successful gate, or a successful non-gating run when that mode is printed. +- Exit 1 means a declared bound failed or a legacy walk exceeded its budget. +- Exit 2 means configuration, source measurement, operation, fixture or report validation failed. + Source `AbandonedCell` and `UnresolvedCell` failures use this code. + +Report-only suppresses exit 1 but still rejects harness errors. ### Registry and timed boundaries @@ -90,6 +103,35 @@ outside the timers at every rung. The original Criterion identities and source b this registry, alongside a finite set of additional qualification, pending-query, combined structure, rejection, evidence and rendering axes. +The [extraction traversal contract](documentation_extraction.md#traversal) defines the +implementation cost boundaries. The registry uses `n` for a ladder's size parameter and these +dimension labels: + +| Label | Meaning in the source benchmark registry | +| --- | --- | +| D | Logical documents | +| F | Physical retained fragments | +| E | Association-owner memberships (edges), including multiple owners of one document | +| Q | Candidate/reference qualification records | +| C | Named declaration candidates | +| S | Complete output-map segments | +| K | Query results consumed by one operation, including a retained text view | +| R | Included source ranges | +| `text` | Complete rendered bytes stored once per document | + +The report also emits visible node count, maximum depth and sibling width, actual source bytes, +and retained fragment/source intersections. E counts owner memberships here; the extraction +contract's general bound uses E for associations. Keep both owner fanout and qualification +memberships explicit rather than treating them as source-byte size. + +Representative ladders separate input growth from output growth: + +- Grow text at fixed owner fanout, then grow owner fanout at fixed text size. +- Grow candidates for one reference, then grow references with a fixed candidate count. +- Grow lexical depth with fixed sibling width, or with a growing innermost comment run. +- Grow pending ancestry whose query returns more records, then query fixed output near the end + of unrelated owners and empty scopes. + Ordinary fixtures parse once through `Ast` and call the borrowed collector with `Ast::language`, `Ast::as_tree_sitter` and `Ast::source`. Deliberate included-range fixtures retain their exact tree and byte buffer. Storage has three lifetime layers: owned parses, @@ -120,6 +162,13 @@ therefore also enables it for other workspace consumers in the same build. Produ counter recording remains unconditional; only readers and the prepared seam are feature-gated. Match and record the actual feature sets for base/candidate legacy comparisons. +To add a source workload, register it in +`big-code-analysis-bench/src/documentation/fixtures.rs`. Declare the operation, size ladder, +fixed and varied dimensions, statistic and policy before timing. Add independent expected +shape/output validation in `validation.rs` and discriminating counter controls in `tests.rs` +in the same directory. Both source timing runners consume this registry. The +[legacy probe recipe](#adding-a-probe) uses `shapes.rs` instead. + ### Source statistics and timing resolution The source gate uses the median of scheduled rounds after the same rotating warmup schedule as @@ -128,13 +177,14 @@ the legacy runner. It keeps separate typed results: | Declared work | Statistic | Bound | | --- | --- | --- | | Collection or fresh rendering with linear/linearithmic output | Fitted slope of log time against log size | 1.50 | -| Fixed-output owner, qualification, pending or retained query | Largest/smallest per-rung median | 1.50 | -| Fixed-output late map query with S segments | Largest/smallest median after division by log2(S+1) | 1.50 | +| Fixed-output owner, qualification, pending or retained query | Largest/smallest median nanoseconds per operation across rungs | 1.50 | +| Fixed-output late map query with S segments | Largest/smallest median nanoseconds per operation after dividing each by log2(S+1) | 1.50 | | Pending ancestry returning growing K records | Linear-output fitted exponent | 1.50 | -K is the number of records consumed by a query. Qualification construction holds references or -candidates fixed while varying the other factor. It reports the legitimate association-edge and -qualification growth separately; a references-times-candidates product is output work, not proof +Each ratio compares per-operation medians. Raw batch durations cannot be compared directly when +repetition counts differ. Qualification construction holds references or candidates fixed while +varying the other factor. It reports legitimate association-edge and qualification growth +separately; a references-times-candidates product is output work, not proof of excessive overhead. Each cell calibrates once before warmup. Its repetition count is @@ -149,6 +199,13 @@ duration. A cold calibration call can overestimate later cost, so even an ordina fail this resolution check. The runner does not retry or increase repetitions after observing a short batch. Preserve the failed run for analysis. +Inspect the cell's frozen repetition count and retained batches. Calibration may have +overestimated steady-state cost or reached the repetition cap. More rounds do not directly +change that count, and report-only still enforces source resolution. A new calibration or +workload policy requires review before another qualification campaign; retain the failed run +with the proposal. Do not repeat an unchanged campaign until it passes or adjust thresholds +based on observed results. + Reports include raw scheduled batches, iteration counts, batch minimum/median/maximum and floating-point nanoseconds per operation. Untimed counts report nodes, depth, width, fragments, documents, owner edges, qualifications, rendered bytes, map segments, included ranges, @@ -163,21 +220,29 @@ campaign; it does not provide per-operation cancellation. ### Controlled comparisons and coverage limits -Run the maintained source gate and Criterion on one frozen revision and matching features on -the same controlled host. Record the revision, toolchain, CPU assignment, commands, membership, -raw batches and Criterion results. Keep the old Criterion mean/95% confidence-interval evidence -separate from the new median statistic. Do not change bounds after observing a run. New -optimization guards also need discriminating counter tests and controlled regressed/fixed pairs -where a timing claim requires them. +For each evaluated revision, run the maintained source gate and documentation Criterion on the +same controlled host with matching features. Record the revision, toolchain, CPU assignment, +exact commands, membership, raw batches and Criterion results. Earlier Criterion mean/95% +confidence-interval evidence does not qualify the maintained median gate, even when fixture +IDs and source bytes are preserved. The gate needs its own runner results under the predeclared +policy. Do not change bounds after observing a run. New optimization guards also need +discriminating counter tests and controlled regressed/fixed pairs where a timing claim requires +them. Record both revisions explicitly for each regressed/fixed comparison. + +The visible array-declarator ladder measures visible nesting and requests to +`TreeCursor::field_name`. It does not bound hidden-rule work inside each dependency call. +Investigation is limited to the collector's implemented `fields_needed` parent kinds: -The visible array-declarator ladder measures visible nesting and field requests. It does not -establish a bound on work inside a dependency's hidden-rule field lookup. Investigation is -limited to the collector's implemented `fields_needed` parents: C-family declarations and -declarators, JavaScript-family exports, and Ruby modifiers. No hidden-only growing source path -has been established by this registry. A later adapter must add a positive probe for any new -reachable path; deferred Tcl support cannot serve as a successful empty control. +- [Doxygen](https://www.doxygen.nl/): `declaration`, `field_declaration`, `function_definition`, and kinds ending in + `declarator`. +- JavaScript-family profiles: `export_statement`. +- [YARD](https://yardoc.org/): `if_modifier` and `unless_modifier`. -## The complexity-class gate {#complexity-gate} +No hidden-only growing source path has been established by this registry. A later adapter must +add a positive probe for any new reachable path; deferred Tcl support cannot serve as a +successful empty control. + +## Legacy complexity-class probes {#complexity-gate} Each probe pairs a generated source shape with the workload that exercises one hot path: a metric selection through `Ast::metrics`, @@ -234,7 +299,7 @@ Read it as follows. - `median ms` is what the fit uses. `min` and `max` bracket the rounds. A wide spread means the host was busy and the run should be repeated, not interpreted. -- `bytes` grows linearly with `size` for every shape, by +- `bytes` grows linearly with `size` for every legacy shape, by construction. If it did not, a walk that is linear in input size would read as superlinear in its size parameter. - `ns/byte` drifts up with size on a depth shape even for a linear @@ -325,8 +390,8 @@ Read it as follows. | `loc/python-block-comments-paren-strings` | Python | width | the same question where each asker's own statement answers and the block above it is a long scan: the levels above the nearest answer are never read (#1863) | linear | | `loc/go-nested-doc-fields` | Go | depth | Go's package-level scope test over nested struct fields (#1597) | linear | | `loc/ruby-nested-doc-constants` | Ruby | depth | YARD's namespace scope test through nested `if`s (#1597) | linear | -| `loc/lua-tagless-blocks` | Lua | width | LDoc's first-block test, scanning back to the previous block (#1597) | linear | -| `loc/perl-data-pod` | Perl | width | the one-pass POD scan of the data section after `__END__` (#1608) | linear | +| `loc/lua-tagless-blocks` | Lua | width | [LDoc](https://lunarmodules.github.io/ldoc/)'s first-block test, scanning back to the previous block (#1597) | linear | +| `loc/perl-data-pod` | Perl | width | the one-pass [POD](https://perldoc.perl.org/perlpod) scan of the data section after `__END__` (#1608) | linear | | `loc/bash-nested-continued-fn` | Bash | depth | the bare-`\`-row gap scan (`credit_bare_continuation_rows`), each padding byte read by one node however deep the spaces nest (#1445) | linear | | `loc/tcl-wide-continued-comment` | Tcl | width | the comment lookup for a bare row continuing a comment, from the child before the row's gap (#1445) | linear | | `loc/tcl-unclosed-continued-comments` | Tcl | width | the same lookup when an unclosed opener per unit leaves every unit a direct child of one flat `ERROR` (#1445) | linear | @@ -452,7 +517,7 @@ The control probes are what make the other readings mean something. source under a metric that does not ask for a parent, is the metric control that stands in for one. -### Adding a probe {#adding-a-probe} +### Adding a legacy probe {#adding-a-probe} Add a `Probe` to `PROBES` in `big-code-analysis-bench/src/shapes.rs`. The unit tests in that module enforce what a probe has to satisfy: @@ -527,7 +592,7 @@ questions sort a climb before any timing: [The climbs #1868 audited](#climb-audit-1868) are listed with what bounds each. -### Why each probe exists +### Why each probe exists {#why-each-probe-exists} Each probe below is paired with the issue that added it and the measurement that showed it failing. Four of the probes in the table @@ -1471,11 +1536,11 @@ alone. ### The ranking pass {#ranking-pass} -`vcs::score::apply_percentile` re-ranks every file's ten signals to a +`vcs::score::apply_percentile` re-ranks every file's signals to a mid-rank percentile within the analyzed set. Until [#1267][ranking-pass] -it took both tie counts — how many files sit strictly below a value, -how many within the tie tolerance of it — by scanning the whole -population per file, per signal: `O(signals × n²)`, re-paid on every +it took both tie counts (files strictly below a value and files within +its tie tolerance) by scanning the whole population per file, per signal: +`O(signals × n²)`, re-paid on every cache hit and on every `bca vcs trend` point. Measured on the three `vcs/*` shapes before the fix: exponents **2.00 / 1.98 / 1.98**, with the 8 000-file cell at ~100 ms in release. The pass now sorts once per @@ -1491,18 +1556,18 @@ on `all-equal` and quadratic on `spread`. All three on the ladder is what pins the class rather than one shape's constant. The reading is the number of distinct `risk_score` values the pass -produced, taken once per cell outside the timed repetitions — it -sorts, and inside the loop it would fold a second `O(n log n)` term into -every sample. A reading of 1 on `spread` would mean the pass collapsed +produces. The harness counts these once per cell outside the timed repetitions. +Counting requires sorting, which would add `O(n log n)` to the measured work. +A reading of 1 on `spread` would mean the pass collapsed every file to one score; `readings_follow_the_tie_structure` in `big-code-analysis-bench/src/vcs.rs` asserts the three readings grow with the shape. [ranking-pass]: https://github.com/dekobon/big-code-analysis/issues/1267 -## Criterion measurements +## Metric-walk Criterion measurements {#criterion-measurements} -Three groups: +The `metric_walk` target has these groups: - `corpus/parse` is `tree_sitter` parse cost over the corpus slice, the baseline the walk sits on top of. @@ -1535,11 +1600,11 @@ measurement from the #1052 / #1062 work described its input as "2862 Python files" when the tree it walked was 78% C/C++, and nobody could check it because the input was never reported. -Not every supported language appears. The three corpus submodules +Not every supported language appears. The selected corpus submodules carry no Elixir, Lua, PHP, Ruby, or Tcl, so those languages are covered by the synthetic shapes only. -### Comparing two builds +### Comparing two builds {#comparing-two-builds} ```bash git switch main @@ -1569,7 +1634,9 @@ Interleave instead. Keep a binary per side. A paired series is usually compared across sessions, and the base binary is slow to rebuild, so the copy goes under `/var/tmp/bca//` rather than `/tmp` (see -[`AGENTS.md`](../../AGENTS.md), "Temporary files"): +[`AGENTS.md`](../../AGENTS.md), "Temporary files"). + +Use [jq](https://jqlang.org/manual/) to extract the executable path from Cargo's JSON output: ```bash mkdir -p /var/tmp/bca/ @@ -1593,7 +1660,9 @@ tool call. Then alternate them round by round, flipping which side goes first so a one-way drift does not always land on the same arm, and narrow each -run to the benchmarks under test: +run to the benchmarks under test. +[taskset](https://www.kernel.org/pub/linux/utils/util-linux/man/taskset.1.html) +pins each command to the selected CPU: ```bash taskset -c 3 "$bin_dir/metric_walk_before" --bench --discard-baseline --noplot \ @@ -1613,26 +1682,28 @@ interleaving that removes the load. [interleave]: https://github.com/dekobon/big-code-analysis/issues/1069 -## Measurement traps +## Measurement traps {#measurement-traps} -Every one of these produced a misleading measurement in this -repository. The first four predate the harness, which defends against -the first three structurally. The fourth is on you, and so is most of -the fifth. +These cases produced misleading measurements in this repository. Legacy fixture +checks and interleaved sampling address some causes. Controls and reachability +checks still require deliberate experiments. 1. **An indented generator makes the input grow quadratically.** A Python nested-`def` generator produced 32 MB at depth 4000, so time-per-byte was flat while the headline number looked - superlinear. Two separate measurements were invalidated. Every - shape here emits a constant number of bytes per level, and - `byte_growth_is_affine` fails if one stops doing so. + superlinear. Two separate measurements were invalidated. Legacy + shapes in `shapes.rs` emit a constant number of bytes per size unit; + `byte_growth_is_affine` guards that property. Source ladders report + their declared dimensions and actual bytes. Variable-width generated + names can cross digit boundaries, so byte growth is not universally affine. 2. **`fd -e py | wc -l` is not the corpus.** Report what was analysed, which `CorpusSlice::summary` does for you. 3. **A ratio between two sizes is host-independent but not load-independent.** The two measurements are sequential, so a load spike between them skews the ratio by itself; best-of-three sheds - bursty contention but not sustained overhead. The gate interleaves - cells across rounds and fits three points instead of comparing two. + bursty contention but not sustained overhead. The runners rotate + cells across rounds. Legacy probes fit exponents; source probes use + the statistic declared for their input/output growth. 4. **Use a control.** Without one, a cross-build code-layout shift reads as a real effect. An independent replication of a #1062 measurement saw the control move 1.02% on its own. @@ -1682,7 +1753,7 @@ environments: | `test (windows-latest)` in CI | 10.9 s | absolute 8 s budget | | local `make pre-commit` | 5.6x | ratio, single measurement | | local, heavy parallel load | 3.9x | ratio, single measurement | -| `cargo llvm-cov` | 3.5x | ratio, best-of-three | +| [`cargo llvm-cov`](https://github.com/taiki-e/cargo-llvm-cov) | 3.5x | ratio, best-of-three | The last one is the decisive one: the `coverage` job runs in CI, so instrumentation overhead alone redded the build. @@ -1698,9 +1769,10 @@ traversal, `Checker`, `Getter`, or a metric's `compute`. `.github/workflows/benchmark.yml` runs the gate quarterly and on `workflow_dispatch`, mirroring [mutation testing](mutation_testing.md). It files an issue on a -sustained failure. The gate is ratio-based and therefore portable, but -a runner is still a runner: confirm any failure on an idle host before -treating it as a regression. +sustained performance failure. The growth statistics reduce sensitivity to host speed, +but load still affects them. Confirm a performance-bound failure on an idle host before +treating it as a regression. For source harness errors, follow the +[resolution and validation guidance](#source-documentation) before another campaign. ## Related @@ -1710,7 +1782,7 @@ treating it as a regression. per-probe rationale. - `big-code-analysis-bench/src/scaling.rs`: the measurement and fit, with the reasoning behind interleaving and three-point fitting. -- `big-code-analysis-bench/src/verbatim.rs`: not a benchmark — the +- `big-code-analysis-bench/src/verbatim.rs`: the `verbatim-oracle` binary (`cargo build -p big-code-analysis-bench --bin verbatim-oracle`) that `utils/drift-oracle.py` and `utils/recovery-oracle.py` drive for the library-level zero-drift From 099df858523ea318cb8175f02828dfbb66b405b3 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:00:57 -0800 Subject: [PATCH 049/221] test(fuzz): anchor qualification and pending document identity Pin the qualified candidate and reference spelling independently of prepared lookup agreement. Add a same-reasons wrong-candidate control and tie Kotlin pending ownership to its local document. Preserve the four existing perturbations and add intended-test cases for these assertions. Source-only ordered audit checkpoint. Rustfmt, diff checks, seed byte/hash checks and mutation-anchor checks passed. Cargo tests, behavioral perturbations, full gates and fuzz execution remain pending the parent-assigned heavy-check slot. --- fuzz/documentation-perturb.json | 14 +++++++ fuzz/src/documentation/tests.rs | 72 ++++++++++++++++++++++++++++----- 2 files changed, 77 insertions(+), 9 deletions(-) diff --git a/fuzz/documentation-perturb.json b/fuzz/documentation-perturb.json index c2a9c2e95..8dbcd2163 100644 --- a/fuzz/documentation-perturb.json +++ b/fuzz/documentation-perturb.json @@ -29,6 +29,20 @@ "old": "Err(CollectionError::AdapterUnavailable { language, profile })", "new": "Err(CollectionError::UnsupportedProfile { language, profile })", "expect": ["documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] + }, + { + "name": "lose-qualified-candidate-identity", + "file": "fuzz/src/documentation/tests.rs", + "old": " assert_eq!(index.qualified_owner(qualification).unwrap(), Some(owner));", + "new": " let _ = owner;\n assert!(index.qualified_owner(qualification).unwrap().is_some());", + "expect": ["documentation::tests::qualification_oracle_rejects_same_reasons_on_the_wrong_candidate"] + }, + { + "name": "attribute-local-pending-to-leading-document", + "file": "fuzz/src/documentation/tests.rs", + "old": "&& index.assessed_document(a).unwrap() == Some(local))", + "new": "&& index.assessed_document(a).unwrap() == index.documents().next())", + "expect": ["documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] } ] } diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index 4c5d47ccb..60bb56ead 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -251,6 +251,14 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: } "candidate-qualification" | "reference-qualification" => { let candidate = class == "candidate-qualification"; + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().owner_count(), + if candidate { 2 } else { 1 } + ); + let document = index.facts().associated_document(association).unwrap(); let expected = if candidate { vec![ UnresolvedReason::Conditional, @@ -279,6 +287,15 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: index.qualified_owner(qualification).unwrap().is_some(), candidate ); + assert_eq!(index.qualified_document(qualification).unwrap(), document); + let node = qualification.get().node.node(); + if candidate { + let owner = index.facts().associated_owner(association, 0).unwrap(); + assert_eq!(index.qualified_owner(qualification).unwrap(), Some(owner)); + assert_eq!(&index.source()[node.byte_range()], b"void f(int x = );"); + } else { + assert_eq!(&index.source()[node.byte_range()], b"/**@fn f*/"); + } } } "missing-name" => assert_eq!( @@ -307,20 +324,15 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: .unwrap(); let query = index.node_associations(node).unwrap(); assert_eq!(query.associations().len(), 1); + let local = index.documents().last().unwrap(); assert!( query .assessments() - .any(|a| a.get().axis == AssessmentAxis::Owner) + .any(|a| a.get().axis == AssessmentAxis::Owner + && index.assessed_document(a).unwrap() == Some(local)) ); assert_eq!(text(index).text(), "first"); - assert_eq!( - index - .complete_text(index.documents().last().unwrap()) - .unwrap() - .unwrap() - .text(), - "audit" - ); + assert_eq!(index.complete_text(local).unwrap().unwrap().text(), "audit"); } "invalid-encoding" => assert!(matches!( index.documents().next().unwrap().get().content(), @@ -556,3 +568,45 @@ fn ordinary_fanout_borrows_the_preprocessed_ast_buffer() { assert_eq!(index.source(), ast.source()); assert_eq!(text(&index).text(), "audit"); } + +#[test] +fn qualification_oracle_rejects_same_reasons_on_the_wrong_candidate() { + let bytes = b"\x0c\x01\0void f(void);\n#if FLAG\nvoid f(int x = );\n#endif\n/**@fn f*/"; + let result = exercise_with(bytes, |index, tree| { + let index = index.unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().owner_count(), 2); + let document = index.facts().associated_document(association).unwrap(); + let owner = index.facts().associated_owner(association, 1).unwrap(); + assert_eq!( + index + .qualifications() + .map(|q| q.get().reason) + .collect::>(), + [ + UnresolvedReason::Conditional, + UnresolvedReason::GrammarBoundary + ] + ); + for qualification in index.qualifications() { + assert_eq!(qualification.get().subject, QualificationSubject::Candidate); + assert_eq!(index.qualified_document(qualification).unwrap(), document); + assert_eq!(index.qualified_owner(qualification).unwrap(), Some(owner)); + assert_eq!( + &index.source()[qualification.get().node.node().byte_range()], + b"void f(int x = );" + ); + } + let rejected = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + edge("candidate-qualification", Some(index), tree); + })); + assert!( + rejected.is_err(), + "qualification identity oracle accepted the other candidate" + ); + Ok(()) + }); + assert_eq!(result, Ok(Outcome::Checked)); +} From 017bad527c9a7c3dfc3b506735088a506d7a2458 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:01:58 -0800 Subject: [PATCH 050/221] fix(bench): validate localized recovery shape and render profiles Use a recovered deepest field-list with fixed documented width; the original incomplete struct recovered at the root. Preserve all registry IDs and ladders. Check split-scalar included ranges and C/Go/Java render profiles; fix focused Clippy findings. Focused benchmark and AST documentation tests, isolated feature checks, combined smoke, role gates and self-scan pass. Freeze before mutation sweep and full gate; hooks deferred to the scheduled validation run. --- .../src/documentation/render_probe.rs | 40 ++++- .../src/documentation/fixtures.rs | 140 +++++++++++++++--- .../src/documentation/operation.rs | 1 + .../src/documentation/runner.rs | 1 + .../src/documentation/validation.rs | 19 ++- 5 files changed, 169 insertions(+), 32 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/render_probe.rs b/big-code-analysis-ast/src/documentation/render_probe.rs index 609574537..6f3d9af9b 100644 --- a/big-code-analysis-ast/src/documentation/render_probe.rs +++ b/big-code-analysis-ast/src/documentation/render_probe.rs @@ -262,7 +262,7 @@ mod tests { #[cfg(feature = "rust")] #[test] fn valid_preparation_borrows_adjacent_range_intersections() { - let source = b"///audit\nfn f() {}"; + let source = "///é\nfn f() {}".as_bytes(); let mut parser = tree_sitter::Parser::new(); parser .set_language(&LANG::Rust.tree_sitter_language().unwrap()) @@ -297,10 +297,46 @@ mod tests { let Content::Complete { text, mappings } = prepared.render().unwrap() else { panic!("complete") }; - assert_eq!(text, "audit"); + assert_eq!(text, "é"); assert_eq!( mappings, index.complete_text(document).unwrap().unwrap().mappings() ); } + + #[cfg(all(feature = "c", feature = "go", feature = "java"))] + #[test] + fn production_comment_profiles_share_the_prepared_render_seam() { + for (language, source, expected) in [ + (LANG::C, "/**audit*/\nint a, b;", "audit"), + ( + LANG::Go, + "package p\n// first\n// second\nfunc F() {}", + "first\nsecond", + ), + (LANG::Java, "/**\n * audit\n */\nclass C {}", "audit"), + ] { + let parser = + AnyParser::parse(language, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + let prepared = PreparedRender::new(&index, document).unwrap(); + let before = observations(); + let Content::Complete { text, mappings } = prepared.render().unwrap() else { + panic!("complete") + }; + assert_eq!(text, expected); + assert_eq!( + mappings, + index.complete_text(document).unwrap().unwrap().mappings() + ); + assert_eq!(observations().renders - before.renders, 1); + } + } } diff --git a/big-code-analysis-bench/src/documentation/fixtures.rs b/big-code-analysis-bench/src/documentation/fixtures.rs index 7c5dd0746..3660419c0 100644 --- a/big-code-analysis-bench/src/documentation/fixtures.rs +++ b/big-code-analysis-bench/src/documentation/fixtures.rs @@ -2,6 +2,7 @@ use big_code_analysis_ast::LANG; use big_code_analysis_ast::documentation::{DocumentationOptions, Profile}; +use std::fmt::Write; use super::{HarnessError, require}; @@ -413,7 +414,7 @@ pub const REGISTRY: &[SourceProbe] = &[ LANG::C, false, Operation::Collect, - "grow enclosing struct depth; innermost recovery sibling width=32 fixed; parse/error shape validated at every rung", + "grow enclosing struct depth; innermost recovered field-list has 32 documented siblings and one invalid token", ), probe( "documentation/structure/comment-run-depth", @@ -497,6 +498,7 @@ impl SourceProbe { /// /// # Errors /// Rejects sizes outside 1..=2^20 or unregistered fixture keys. + #[allow(clippy::too_many_lines)] // One explicit spelling per registered fixture keeps byte preservation reviewable. pub fn source(&self, size: usize) -> Result, HarnessError> { require( size > 0 && size <= 1 << 20, @@ -504,45 +506,135 @@ impl SourceProbe { )?; let depth = size / 16; let source = match self.key { - "depth" => format!("{}///audit\nfn leaf() {{}}{}", "mod m {".repeat(size), "}".repeat(size)), + "depth" => format!( + "{}///audit\nfn leaf() {{}}{}", + "mod m {".repeat(size), + "}".repeat(size) + ), "width" | "ranges" => "///audit\nfn f() {}\n".repeat(size), "fragments" => format!("package p\n{}func F() {{}}", "// audit\n".repeat(size)), - "single-line-lua" => format!("module(\"m\")\n---{}\nfunction f() end", "audit ".repeat(size)), + "single-line-lua" => format!( + "module(\"m\")\n---{}\nfunction f() end", + "audit ".repeat(size) + ), "single-line-jsdoc" => format!("/**{}*/\nfunction f() {{}}", "audit ".repeat(size)), "c-slots" => format!("/**audit*/\nint {};", slots(size)), "wide-error" => format!("/**audit*/\nstruct {{\n{}", "int x;\n".repeat(size)), - "missing" => format!("fn f() {{ {}0{}; }}", "(".repeat(size), ")".repeat(size - 1)), - "names" => (0..size).map(|at| format!("/** @fn void f{at}() */\nvoid f{at}() {{}}\n")).collect(), - "single-line-php" => format!(" format!( + "fn f() {{ {}0{}; }}", + "(".repeat(size), + ")".repeat(size - 1) + ), + "names" => (0..size).fold(String::new(), |mut source, at| { + let _ = writeln!(source, "/** @fn void f{at}() */\nvoid f{at}() {{}}"); + source + }), + "single-line-php" => { + format!(" format!("# {}\ndef f\nend", "audit ".repeat(size)), "single-line-doxygen" => format!("/**{}*/\nvoid f() {{}}", "audit ".repeat(size)), "text-fixed-fanout" => format!("/**{}*/\nint a,b;", "audit ".repeat(size)), "fanout-fixed-text" => format!("/**{}*/\nint {};", "audit ".repeat(1024), slots(size)), "visible-declarator-depth" => format!("/**audit*/\nint a{};", "[1]".repeat(size)), "ruby-modifiers" => format!("# audit\ndef f; end{}", " if true".repeat(size)), - "java-undocumented" => format!("{}void f() {{}}{}", "class C {".repeat(size), "}".repeat(size)), + "java-undocumented" => format!( + "{}void f() {{}}{}", + "class C {".repeat(size), + "}".repeat(size) + ), "pending-scope" => format!("#![doc(hidden)]\n{}", "fn f() {}\n".repeat(size)), "prepared" => format!("{}fn f() {{}}", "///a\n".repeat(size)), "inline-spans" => format!("/**{}*/\nvoid f() {{}}", "`x` ".repeat(size)), - "gathered-disposition" => format!("{}/**{}@file*/", "/**a*/\n".repeat(size), "x ".repeat(size)), - "complex-signatures" => format!("{}void leaf();{}", "void f(int x = [] { ".repeat(depth), " return 1; }());".repeat(depth)), + "gathered-disposition" => { + format!("{}/**{}@file*/", "/**a*/\n".repeat(size), "x ".repeat(size)) + } + "complex-signatures" => format!( + "{}void leaf();{}", + "void f(int x = [] { ".repeat(depth), + " return 1; }());".repeat(depth) + ), "text-budget-boundary" => format!("///{}\nfn f() {{}}", "abcd".repeat(size * 2)), - "go-fold" => format!("package p\ntype S struct {{\n{}X int\n{} }}\n", "X struct {\n".repeat(depth), "}\n".repeat(depth)), - "ruby-fold" => format!("{}# audit\ndef f; end\n{}", "class C\n".repeat(depth), "end\n".repeat(depth)), - "multiline-adjacent-ranges" => format!("/**\n{}*/\nclass C {{}}", " * audit\n".repeat(size)), - "qualified-candidates" => format!("#if FLAG\n{}#endif\n/**@fn f*/", "void f(void);\n".repeat(size)), - "qualified-references" => format!("#if FLAG\nvoid f(void);\nvoid f(void);\n#endif\n{}", "/**@fn f*/\nint separator;\n".repeat(size)), - "qualified-unrelated" => (0..size).map(|at| format!("#if FLAG\nvoid f{at:08}(void);\n#endif\n/**@fn f{at:08}*/\nint separator;\n")).collect(), - "pending-ancestry" => format!("{}fn leaf() {{}}{}", "mod m {\n#![doc(hidden)]\n".repeat(size), "}\n".repeat(size)), - "pending-late" => format!("#![doc(hidden)]\n{}{}fn leaf() {{}}{}", "fn f() {}\n".repeat(size), "mod m {".repeat(size), "}".repeat(size)), - "wide-depth" => format!("{}{}{}", "mod m {".repeat(size), "///audit\nfn f() {}\n".repeat(32), "}".repeat(size)), - "recovery-depth" => format!("{}struct {{\n{}{}", "struct S {\n".repeat(size), "/**audit*/\nint x;\n".repeat(32), "};\n".repeat(size)), - "comment-run-depth" => format!("{}{}fn f() {{}}{}", "mod m {".repeat(size), "///a\n".repeat(size), "}".repeat(size)), - "conditional-depth" => format!("{}/**audit*/\nvoid f();\n{}", "struct S {\n#if FLAG\n".repeat(size), "#endif\n};\n".repeat(size)), - "missing-name" => format!("{}/**@fn absent*/", (0..size).map(|at| format!("void f{at:08}(void);\n")).collect::()), + "go-fold" => format!( + "package p\ntype S struct {{\n{}X int\n{} }}\n", + "X struct {\n".repeat(depth), + "}\n".repeat(depth) + ), + "ruby-fold" => format!( + "{}# audit\ndef f; end\n{}", + "class C\n".repeat(depth), + "end\n".repeat(depth) + ), + "multiline-adjacent-ranges" => { + format!("/**\n{}*/\nclass C {{}}", " * audit\n".repeat(size)) + } + "qualified-candidates" => format!( + "#if FLAG\n{}#endif\n/**@fn f*/", + "void f(void);\n".repeat(size) + ), + "qualified-references" => format!( + "#if FLAG\nvoid f(void);\nvoid f(void);\n#endif\n{}", + "/**@fn f*/\nint separator;\n".repeat(size) + ), + "qualified-unrelated" => (0..size).fold(String::new(), |mut source, at| { + let _ = writeln!( + source, + "#if FLAG\nvoid f{at:08}(void);\n#endif\n/**@fn f{at:08}*/\nint separator;" + ); + source + }), + "pending-ancestry" => format!( + "{}fn leaf() {{}}{}", + "mod m {\n#![doc(hidden)]\n".repeat(size), + "}\n".repeat(size) + ), + "pending-late" => format!( + "#![doc(hidden)]\n{}{}fn leaf() {{}}{}", + "fn f() {}\n".repeat(size), + "mod m {".repeat(size), + "}".repeat(size) + ), + "wide-depth" => format!( + "{}{}{}", + "mod m {".repeat(size), + "///audit\nfn f() {}\n".repeat(32), + "}".repeat(size) + ), + "recovery-depth" => format!( + "{}@ {}{}", + "struct S {\n".repeat(size), + "/**audit*/\nint x;\n".repeat(32), + "};\n".repeat(size) + ), + "comment-run-depth" => format!( + "{}{}fn f() {{}}{}", + "mod m {".repeat(size), + "///a\n".repeat(size), + "}".repeat(size) + ), + "conditional-depth" => format!( + "{}/**audit*/\nvoid f();\n{}", + "struct S {\n#if FLAG\n".repeat(size), + "#endif\n};\n".repeat(size) + ), + "missing-name" => format!( + "{}/**@fn absent*/", + (0..size).fold(String::new(), |mut source, at| { + let _ = writeln!(source, "void f{at:08}(void);"); + source + }) + ), "rejected" => format!("{}class C {{}}", "/**audit*/\n".repeat(size)), - "directives" => format!("package p\n{}func F() {{}}", "//go:generate command\n".repeat(size)), - _ => return Err(HarnessError(format!("unregistered source fixture {}", self.key))), + "directives" => format!( + "package p\n{}func F() {{}}", + "//go:generate command\n".repeat(size) + ), + _ => { + return Err(HarnessError(format!( + "unregistered source fixture {}", + self.key + ))); + } }; Ok(source.into_bytes()) } diff --git a/big-code-analysis-bench/src/documentation/operation.rs b/big-code-analysis-bench/src/documentation/operation.rs index 9c336109f..aa1dec42d 100644 --- a/big-code-analysis-bench/src/documentation/operation.rs +++ b/big-code-analysis-bench/src/documentation/operation.rs @@ -110,6 +110,7 @@ impl Parsed { self.collect_with(&DocumentationContext::default(), &probe.options()) } + #[allow(clippy::trivially_copy_pass_by_ref)] // Preserve the borrowed production options boundary inside timing. fn collect_with( &self, context: &DocumentationContext, diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index 29c59ff94..9de00c8e1 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -397,6 +397,7 @@ fn batch(operation: &Prepared<'_, '_>, iterations: u32) -> Result HarnessError { HarnessError(format!("{id} size {size}: {error}")) } diff --git a/big-code-analysis-bench/src/documentation/validation.rs b/big-code-analysis-bench/src/documentation/validation.rs index dd2950a05..d8e27b16f 100644 --- a/big-code-analysis-bench/src/documentation/validation.rs +++ b/big-code-analysis-bench/src/documentation/validation.rs @@ -191,7 +191,7 @@ fn additional_fixture( .join("\n"), )?, "qualified-candidates" | "qualified-references" | "qualified-unrelated" => { - qualifications(probe, size, index)? + qualifications(probe, size, index)?; } "pending-ancestry" | "pending-late" => { let leaf = nodes @@ -238,12 +238,19 @@ fn additional_fixture( require(count("mod_item") == size, "comment-run depth")?; } "recovery-depth" => { - require(count("field_declaration") == 32, "recovery sibling width")?; + require( + count("field_declaration") == size + 31, + "nested struct fields plus recovery sibling width", + )?; + require(count("struct_specifier") == size, "recovery struct depth")?; require( nodes.iter().any(|(node, depth)| { - node.is_error() && node.child_count() >= 32 && *depth >= size + node.kind() == "field_declaration_list" + && node.has_error() + && node.child_count() >= 64 + && *depth >= size }), - "deep wide recovery parent absent", + "deep recovered sibling parent absent", )?; require(index.documents().len() == 32, "recovery document count")?; } @@ -363,7 +370,7 @@ fn evidence( "retained evidence count", )?; require( - index.documents().len() == if probe.key == "rejected" { 1 } else { 0 }, + index.documents().len() == usize::from(probe.key == "rejected"), "evidence document count", )?; if probe.key == "directives" { @@ -409,7 +416,7 @@ fn shape(name: &str, size: usize, parser: &Parsed) -> Result<(), HarnessError> { "width" => require(root.child_count() == size * 2, "sibling width")?, "fragments" => require(count("comment") == size, "comment fragments")?, "c-slots" | "fanout-fixed-text" => { - require(count("identifier") == size, "declaration slots")? + require(count("identifier") == size, "declaration slots")?; } "visible-declarator-depth" => { require( From a4397339f872647d672e44e056a043502e13527f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:02:57 -0800 Subject: [PATCH 051/221] test(bench): count every scheduled source operation Pin initial collection, calibration, both warmups and the measured round with render counters so a skipped operation cannot leave a green structural smoke. Freeze this test before the mutation sweep. --- .../src/documentation/runner.rs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index 9de00c8e1..fcf0505f7 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -794,4 +794,28 @@ mod tests { ); assert!(!report.to_string().contains(" ok")); } + + #[test] + fn source_schedule_executes_calibration_warmup_and_measured_work() { + let probe = REGISTRY + .iter() + .find(|p| p.id == "documentation/cold/width") + .unwrap(); + let before = big_code_analysis_ast::documentation::observations(); + let report = run(&[*probe], 1, Mode::Smoke).unwrap(); + let after = big_code_analysis_ast::documentation::observations(); + // Per rung: one initial index, one calibration, two warmups and one + // measured collection. Each collection renders one document per sibling. + assert_eq!( + after.renders - before.renders, + 5 * SMOKE_SIZES.iter().sum::() + ); + assert_eq!(report.results[0].cells.len(), 3); + assert!( + report.results[0] + .cells + .iter() + .all(|c| c.batches.len() == 1 && c.iterations == 1) + ); + } } From e0b375e35dfe4c83038425652dd3e53cf350cc39 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:19:19 -0800 Subject: [PATCH 052/221] test(bench): strengthen documentation timing guards Preserve the original 15 exact mutation cases and archived behavioral outcomes in maintained benchmark artifacts. Add pending mutations for off/off, on/on and missing iteration normalization, with specific expected tests. Ordered source audit: simplify-rust, rust-optimize, audit-tests. Direct rustfmt and artifact integrity checks pass. Parent holds the heavy validation slot: Cargo, tests, mutations, benchmarks and pre-commit hooks were deliberately not run after these edits. This is a source checkpoint, not runtime qualification. --- .../perturbations/documentation-audit.json | 36 ++++ .../documentation-results-a4397339.json | 155 ++++++++++++++++++ .../perturbations/documentation.json | 121 ++++++++++++++ .../src/documentation/runner.rs | 19 +++ .../src/documentation/tests.rs | 14 ++ 5 files changed, 345 insertions(+) create mode 100644 big-code-analysis-bench/perturbations/documentation-audit.json create mode 100644 big-code-analysis-bench/perturbations/documentation-results-a4397339.json create mode 100644 big-code-analysis-bench/perturbations/documentation.json diff --git a/big-code-analysis-bench/perturbations/documentation-audit.json b/big-code-analysis-bench/perturbations/documentation-audit.json new file mode 100644 index 000000000..7460e16af --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-audit.json @@ -0,0 +1,36 @@ +{ + "cwd": ".", + "provenance": { + "starting_checkpoint": "a4397339f872647d672e44e056a043502e13527f", + "status": "Pending execution after ordered source audit; requires the added test assertions.", + "usage": "Run from the repository root: python3 -B utils/perturb.py big-code-analysis-bench/perturbations/documentation-audit.json", + "discrimination": "The two evidence substitutions must leave the prior visits/render assertions unchanged and fail the new materialization assertions. Ignoring iteration division must fail the unequal-iteration ratio test. Build failures do not count." + }, + "command": [ + "cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", + "--all-features", "--lib", "documentation", "--no-fail-fast" + ], + "cases": [ + { + "name": "evidence pair repeats retention off", + "file": "big-code-analysis-bench/src/documentation/operation.rs", + "old": "self.parsed.collect_with(&self.context, &self.off_options)?,\n ));\n drop(black_box(\n self.parsed.collect_with(&self.context, &self.options)?,", + "new": "self.parsed.collect_with(&self.context, &self.off_options)?,\n ));\n drop(black_box(\n self.parsed.collect_with(&self.context, &self.off_options)?,", + "expect": ["documentation::tests::evidence_pair_executes_both_off_and_on_collections"] + }, + { + "name": "evidence pair repeats retention on", + "file": "big-code-analysis-bench/src/documentation/operation.rs", + "old": "self.parsed.collect_with(&self.context, &self.off_options)?,", + "new": "self.parsed.collect_with(&self.context, &self.options)?,", + "expect": ["documentation::tests::evidence_pair_executes_both_off_and_on_collections"] + }, + { + "name": "compare raw batch medians instead of per-operation times", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "let ns = median.as_secs_f64() * 1e9 / f64::from(raw.iterations);", + "new": "let ns = median.as_secs_f64() * 1e9;", + "expect": ["documentation::runner::tests::ratios_compare_per_operation_times_when_iterations_differ"] + } + ] +} diff --git a/big-code-analysis-bench/perturbations/documentation-results-a4397339.json b/big-code-analysis-bench/perturbations/documentation-results-a4397339.json new file mode 100644 index 000000000..731716b0a --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-results-a4397339.json @@ -0,0 +1,155 @@ +{ + "checkpoint": "a4397339f872647d672e44e056a043502e13527f", + "issue_base": "9abf9720cd5d1506455cb94fed5b0009f4fc1a15", + "manifest": "documentation.json", + "command": [ + "cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", + "--all-features", "--lib", "documentation", "--no-fail-fast" + ], + "provenance": { + "rustc": "1.99.0 (b940084d7)", + "cargo": "1.99.0 (5f94df478)", + "python": "3.14.8", + "source_manifests": [ + "/tmp/opencode/bca-performance-mutations.h1m_p9p1.json", + "/tmp/opencode/bca-performance-scan-mutations.s9zc2491.json" + ], + "source_results": [ + "/tmp/bca-perturb-backup.g905bukb/perturb-results.json", + "/tmp/bca-perturb-backup.pm4ta8uy/perturb-results.json" + ], + "scope": "Archived writer-reported local behavioral mutation results, preserved during source audit. These are not a new run or wall-clock qualification. The added documentation-audit.json cases remain unexecuted." + }, + "results": [ + { + "name": "skip registered cell execution", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::tests::source_schedule_executes_calibration_warmup_and_measured_work", + "documentation::runner::tests::source_smoke_exercises_every_registered_cell" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "ignore wrong cell membership", + "verdict": "caught", + "detail": "", + "failed": ["documentation::runner::tests::malformed_membership_and_samples_fail_in_every_mode"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "ignore missing samples", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::tests::malformed_membership_and_samples_fail_in_every_mode", + "documentation::runner::tests::report_revalidates_batches_counts_and_statistic" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "disable measured batch resolution", + "verdict": "caught", + "detail": "", + "failed": ["documentation::runner::tests::actual_batches_control_resolution_even_at_iteration_cap"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "floor fractional ns", + "verdict": "caught", + "detail": "", + "failed": ["documentation::runner::tests::ratios_keep_subnanosecond_values_and_report_performance_failure"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "legacy cheap iteration cap", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::tests::actual_batches_control_resolution_even_at_iteration_cap", + "documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling", + "documentation::runner::tests::ratios_keep_subnanosecond_values_and_report_performance_failure" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "omit source failures", + "verdict": "caught", + "detail": "", + "failed": ["documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "ignore gate exit failure", + "verdict": "caught", + "detail": "", + "failed": ["documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "skip association consumption", + "verdict": "caught", + "detail": "", + "failed": ["documentation::tests::prepared_query_counters_charge_only_declared_output"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "skip qualification consumption", + "verdict": "caught", + "detail": "", + "failed": ["documentation::tests::prepared_query_counters_charge_only_declared_output"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "drop included scalar intersections", + "verdict": "caught", + "detail": "", + "failed": ["documentation::render_probe::tests::valid_preparation_borrows_adjacent_range_intersections"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "skip tiny render entry cancellation", + "verdict": "caught", + "detail": "", + "failed": ["documentation::render_probe::tests::tiny_and_empty_render_poll_cancellation_at_entry"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "skip render identity validation", + "verdict": "caught", + "detail": "", + "failed": ["documentation::render_probe::tests::preparation_rejects_foreign_and_pending_documents"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "scan all associations", + "verdict": "caught", + "detail": "", + "failed": ["documentation::tests::prepared_query_counters_charge_only_declared_output"], + "missing_expected": [], + "rc": 101 + }, + { + "name": "scan all qualifications", + "verdict": "caught", + "detail": "", + "failed": ["documentation::tests::prepared_query_counters_charge_only_declared_output"], + "missing_expected": [], + "rc": 101 + } + ] +} diff --git a/big-code-analysis-bench/perturbations/documentation.json b/big-code-analysis-bench/perturbations/documentation.json new file mode 100644 index 000000000..0adba02d9 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation.json @@ -0,0 +1,121 @@ +{ + "cwd": ".", + "provenance": { + "checkpoint": "a4397339f872647d672e44e056a043502e13527f", + "issue_base": "9abf9720cd5d1506455cb94fed5b0009f4fc1a15", + "usage": "Run from the repository root: python3 -B utils/perturb.py big-code-analysis-bench/perturbations/documentation.json", + "preservation": "Combines the original 13-case performance and 2-case scan manifests. Command, substitutions and expected test targets are unchanged; cwd is relative for replay in another checkout.", + "results": "documentation-results-a4397339.json" + }, + "command": [ + "cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", + "--all-features", "--lib", "documentation", "--no-fail-fast" + ], + "cases": [ + { + "name": "skip registered cell execution", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "operation.execute()?;", + "new": "std::hint::black_box(operation);", + "expect": ["documentation::runner::tests::source_schedule_executes_calibration_warmup_and_measured_work"] + }, + { + "name": "ignore wrong cell membership", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "cell.id == probe.id && cell.size == size,", + "new": "true,", + "expect": ["documentation::runner::tests::malformed_membership_and_samples_fail_in_every_mode"] + }, + { + "name": "ignore missing samples", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "raw.batches.len() == rounds,", + "new": "raw.batches.len() <= rounds,", + "expect": ["documentation::runner::tests::malformed_membership_and_samples_fail_in_every_mode"] + }, + { + "name": "disable measured batch resolution", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "if mode != Mode::Smoke && median < MIN_SOURCE_SAMPLE {", + "new": "if false && mode != Mode::Smoke && median < MIN_SOURCE_SAMPLE {", + "expect": ["documentation::runner::tests::actual_batches_control_resolution_even_at_iteration_cap"] + }, + { + "name": "floor fractional ns", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "let ns = median.as_secs_f64() * 1e9 / f64::from(raw.iterations);", + "new": "let ns = (median.as_secs_f64() * 1e9 / f64::from(raw.iterations)).max(1.0);", + "expect": ["documentation::runner::tests::ratios_keep_subnanosecond_values_and_report_performance_failure"] + }, + { + "name": "legacy cheap iteration cap", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "pub const SOURCE_MAX_ITERATIONS: u32 = 1 << 20;", + "new": "pub const SOURCE_MAX_ITERATIONS: u32 = 64;", + "expect": ["documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling"] + }, + { + "name": "omit source failures", + "file": "big-code-analysis-bench/src/documentation/combined.rs", + "old": "+ self.source.as_ref().map_or(0, |r| r.failures().len())", + "new": "+ self.source.as_ref().map_or(0, |_r| 0)", + "expect": ["documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass"] + }, + { + "name": "ignore gate exit failure", + "file": "big-code-analysis-bench/src/documentation/combined.rs", + "old": "u8::from(mode == Mode::Gate && optimized && self.failures() > 0)", + "new": "u8::from(mode == Mode::Gate && optimized && self.failures() > usize::MAX)", + "expect": ["documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass"] + }, + { + "name": "skip association consumption", + "file": "big-code-analysis-bench/src/documentation/operation.rs", + "old": "for association in query.associations() {", + "new": "for association in query.associations().take(0) {", + "expect": ["documentation::tests::prepared_query_counters_charge_only_declared_output"] + }, + { + "name": "skip qualification consumption", + "file": "big-code-analysis-bench/src/documentation/operation.rs", + "old": "for qualification in query.qualifications() {", + "new": "for qualification in query.qualifications().take(0) {", + "expect": ["documentation::tests::prepared_query_counters_charge_only_declared_output"] + }, + { + "name": "drop included scalar intersections", + "file": "big-code-analysis-ast/src/documentation/render_probe.rs", + "old": "if validated != fragment.source {", + "new": "if validated != fragment.source || pieces.len() > 1 {", + "expect": ["documentation::render_probe::tests::valid_preparation_borrows_adjacent_range_intersections"] + }, + { + "name": "skip tiny render entry cancellation", + "file": "big-code-analysis-ast/src/documentation/render_probe.rs", + "old": "budget.checkpoint().map_err(RenderError::Source)?;", + "new": "budget.step().map_err(RenderError::Source)?;", + "expect": ["documentation::render_probe::tests::tiny_and_empty_render_poll_cancellation_at_entry"] + }, + { + "name": "skip render identity validation", + "file": "big-code-analysis-ast/src/documentation/render_probe.rs", + "old": " index\n .facts\n .check_scope(document)\n .map_err(RenderError::Fact)?;", + "new": " let _ = document;", + "expect": ["documentation::render_probe::tests::preparation_rejects_foreign_and_pending_documents"] + }, + { + "name": "scan all associations", + "file": "big-code-analysis-ast/src/documentation/index.rs", + "old": " self.associations.iter().map(|&ordinal| {", + "new": " for association in self.index.associations() { std::hint::black_box(association); }\n self.associations.iter().map(|&ordinal| {", + "expect": ["documentation::tests::prepared_query_counters_charge_only_declared_output"] + }, + { + "name": "scan all qualifications", + "file": "big-code-analysis-ast/src/documentation/index.rs", + "old": " self.index.qualification_refs(self.qualifications)", + "new": " for qualification in self.index.qualifications() { std::hint::black_box(qualification); }\n self.index.qualification_refs(self.qualifications)", + "expect": ["documentation::tests::prepared_query_counters_charge_only_declared_output"] + } + ] +} diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index fcf0505f7..a2389f40a 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -685,6 +685,25 @@ mod tests { assert!(report.to_string().contains("fixed-K ratio")); } + #[test] + fn ratios_compare_per_operation_times_when_iterations_differ() { + let probe = REGISTRY[18]; + for (batches, expected_ratio) in [([200_000, 400_000, 800_000], 1.0), ([200_000; 3], 4.0)] { + let mut cells = raw(&probe, batches); + for (cell, iterations) in cells.iter_mut().zip([1, 2, 4]) { + cell.iterations = iterations; + } + let report = reduce(&[probe], 3, Mode::Gate, cells).unwrap(); + // Doubling both batch time and work keeps cost fixed; holding + // batch time fixed while quadrupling work gives a fourfold ratio. + assert!((report.results[0].statistic.value() - expected_ratio).abs() < 1e-12); + assert_eq!(report.failures().len(), usize::from(expected_ratio > 1.5)); + for (cell, iterations) in report.results[0].cells.iter().zip([1, 2, 4]) { + assert_eq!(cell.iterations, iterations); + } + } + } + #[test] fn typed_statistics_reject_invalid_values_and_distinguish_growth() { let probe = REGISTRY[0]; diff --git a/big-code-analysis-bench/src/documentation/tests.rs b/big-code-analysis-bench/src/documentation/tests.rs index efdf47e11..580d47955 100644 --- a/big-code-analysis-bench/src/documentation/tests.rs +++ b/big-code-analysis-bench/src/documentation/tests.rs @@ -390,6 +390,8 @@ fn large_fresh_render_preserves_bounded_copy_work() { #[test] fn evidence_pair_executes_both_off_and_on_collections() { + use big_code_analysis_ast::documentation::streaming::{markers, positional}; + for probe in REGISTRY .iter() .filter(|p| p.operation == fixtures::Operation::EvidencePair) @@ -398,6 +400,8 @@ fn evidence_pair_executes_both_off_and_on_collections() { let index = parsed.collect(probe).unwrap(); let prepared = Prepared::new(probe, 32, &parsed, &index).unwrap(); let before = observations(); + let marker_evidence = markers::evidence_built::observed(); + let positional_evidence = positional::evidence_built::observed(); prepared.execute().unwrap(); let after = observations(); assert_eq!(after.visits - before.visits, 2 * parsed.nodes().len()); @@ -409,6 +413,16 @@ fn evidence_pair_executes_both_off_and_on_collections() { after.renders - before.renders, if probe.key == "rejected" { 2 } else { 0 } ); + // Off/on materializes one selected Java member plus all 32 members, + // or zero Go directives plus all 32 directives. + assert_eq!( + markers::evidence_built::observed() - marker_evidence, + if probe.key == "rejected" { 33 } else { 0 } + ); + assert_eq!( + positional::evidence_built::observed() - positional_evidence, + if probe.key == "directives" { 32 } else { 0 } + ); } } From 15dcd6ddf8222dade0555866b97a37bb639322ce Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:01:40 -0800 Subject: [PATCH 053/221] fix(bench): guard source qualification execution and reporting Scope the inherited scheduled retry to legacy probes and restore compact typed failure summaries. Add deterministic multi-repetition and shared-scheduler guards, private failed-name lookup cost tests, and exact recovery/conditional attachment oracles with negative controls. Preserve all 18 earlier mutation cases and add nine remediation cases. Source-only checkpoint under the parent's heavy-slot hold: rustfmt, diff checks, manifest integrity and uncached Markdown lint pass; Cargo, behavioral tests, mutations, actionlint and full gate pending. Heavy commit hooks skipped. --- .github/workflows/benchmark.yml | 6 +- .../src/documentation/names.rs | 2 + .../src/documentation/names/miss_tests.rs | 81 ++++++ big-code-analysis-bench/benches/scaling.rs | 6 +- .../documentation-remediation.json | 75 ++++++ .../documentation/attachment_validation.rs | 206 ++++++++++++++++ .../src/documentation/combined.rs | 232 ++++++++++++++++++ .../src/documentation/mod.rs | 3 + .../src/documentation/runner.rs | 85 ++++++- .../src/documentation/tests.rs | 77 ++++++ .../src/documentation/validation.rs | 2 + .../src/documentation/workflow_tests.rs | 149 +++++++++++ docs/development/benchmarking.md | 16 +- 13 files changed, 928 insertions(+), 12 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/names/miss_tests.rs create mode 100644 big-code-analysis-bench/perturbations/documentation-remediation.json create mode 100644 big-code-analysis-bench/src/documentation/attachment_validation.rs create mode 100644 big-code-analysis-bench/src/documentation/workflow_tests.rs diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 3e358fc87..78d0a720d 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -74,7 +74,7 @@ jobs: # the exit code is captured with `|| status=$?` instead. # `pipefail` makes that cargo's code rather than tee's. status=0 - cargo bench -p big-code-analysis-bench --bench scaling -- --rounds 11 \ + cargo bench -p big-code-analysis-bench --bench scaling -- --scope legacy --rounds 11 \ 2>&1 | tee target/bench/scaling.log || status=$? if [ "$status" = "0" ]; then exit 0 @@ -87,7 +87,7 @@ jobs: echo "A probe exceeded its bound; re-measuring with more rounds" echo "before reporting, in case the runner was contended." status=0 - cargo bench -p big-code-analysis-bench --bench scaling -- --rounds 21 \ + cargo bench -p big-code-analysis-bench --bench scaling -- --scope legacy --rounds 21 \ 2>&1 | tee target/bench/scaling-confirm.log || status=$? if [ "$status" = "0" ]; then echo "The second run passed. Treating the first as measurement noise." @@ -133,7 +133,7 @@ jobs: echo echo "- Run: ${RUN_URL}" echo - echo "Reproduce locally with \`make bench-scaling\`. See" + echo "Reproduce locally with \`make bench-scaling BENCH_ARGS='--scope legacy --rounds 21'\`. See" echo "\`docs/development/benchmarking.md\` for how to read the table" echo "and what each probe covers." echo diff --git a/big-code-analysis-ast/src/documentation/names.rs b/big-code-analysis-ast/src/documentation/names.rs index cadd39247..2acfa6bd3 100644 --- a/big-code-analysis-ast/src/documentation/names.rs +++ b/big-code-analysis-ast/src/documentation/names.rs @@ -12,6 +12,8 @@ use super::{OwnerId, SourceError, UnresolvedReason}; #[cfg(test)] mod budget_tests; mod grammar; +#[cfg(test)] +mod miss_tests; mod tokens; #[derive(Default)] diff --git a/big-code-analysis-ast/src/documentation/names/miss_tests.rs b/big-code-analysis-ast/src/documentation/names/miss_tests.rs new file mode 100644 index 000000000..a0b1e3d10 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/names/miss_tests.rs @@ -0,0 +1,81 @@ +use super::*; +use crate::documentation::budget::NoBudget; + +fn miss_index(unrelated: usize, collision: bool) -> Names { + let mut names = Names::default(); + let (hash, _) = key(b"absent", &names.hasher, &NoBudget).unwrap(); + for at in 0..unrelated { + // Different scopes deterministically keep these buckets out of the query, + // even when RandomState happens to assign equal hash values. + let owner = CandidateId(names.candidates.len()); + names.candidates.push(NamedOwner { + owner: OwnerId(at), + qualification: QualificationSet::default(), + }); + names.identifiers.insert( + (NodeId(at + 1), hash), + vec![NameEntry { + spelling: b"absent".to_vec(), + owners: vec![owner], + complex: vec![], + }], + ); + } + if collision { + let first = CandidateId(names.candidates.len()); + let second = CandidateId(names.candidates.len() + 1); + for ordinal in [unrelated, unrelated + 1] { + names.candidates.push(NamedOwner { + owner: OwnerId(ordinal), + qualification: QualificationSet::default(), + }); + } + names.identifiers.insert( + (NodeId(0), hash), + vec![ + NameEntry { + spelling: b"absorb".to_vec(), + owners: vec![first], + complex: vec![], + }, + NameEntry { + spelling: b"absentx".to_vec(), + owners: vec![second], + complex: vec![], + }, + ], + ); + } + names +} + +#[test] +fn absent_bucket_miss_never_compares_unrelated_names() { + for unrelated in [0, 8, 64, 256] { + let names = miss_index(unrelated, false); + let before_bytes = name_bytes::observed(); + let before_comparisons = name_candidates::observed(); + let result = names.resolve_in(b"absent", NodeId(0), &NoBudget).unwrap(); + assert_eq!(result.reason, Some(UnresolvedReason::MissingName)); + assert!(result.owners.is_empty() && !result.pending); + // Two six-byte token scans plus six bytes hashed and copied: 24. + assert_eq!(name_bytes::observed() - before_bytes, 24); + assert_eq!(name_candidates::observed() - before_comparisons, 0); + } +} + +#[test] +fn collision_bucket_miss_compares_only_its_nonmatching_spellings() { + for unrelated in [0, 8, 64, 256] { + let names = miss_index(unrelated, true); + let before_bytes = name_bytes::observed(); + let before_comparisons = name_candidates::observed(); + let result = names.resolve_in(b"absent", NodeId(0), &NoBudget).unwrap(); + assert_eq!(result.reason, Some(UnresolvedReason::MissingName)); + assert!(result.owners.is_empty() && !result.pending); + // Key processing is 24 bytes; `absorb` compares four bytes through + // the differing fourth byte, and `absentx` fails on length alone. + assert_eq!(name_bytes::observed() - before_bytes, 28); + assert_eq!(name_candidates::observed() - before_comparisons, 2); + } +} diff --git a/big-code-analysis-bench/benches/scaling.rs b/big-code-analysis-bench/benches/scaling.rs index 061e21e7d..cffec8a22 100644 --- a/big-code-analysis-bench/benches/scaling.rs +++ b/big-code-analysis-bench/benches/scaling.rs @@ -83,11 +83,7 @@ fn main() -> ExitCode { ExitCode::from(2) } Ok(report) => { - if mode == Mode::Gate { - println!("combined gate: {} performance failures", report.failures()); - } else { - println!("{mode:?}: no performance verdict"); - } + print!("{}", report.final_summary(mode)); ExitCode::from(report.exit_code(mode, optimized)) } } diff --git a/big-code-analysis-bench/perturbations/documentation-remediation.json b/big-code-analysis-bench/perturbations/documentation-remediation.json new file mode 100644 index 000000000..396d620a9 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-remediation.json @@ -0,0 +1,75 @@ +{ + "cwd": ".", + "provenance": { + "starting_checkpoint": "e0b375e35dfe4c83038425652dd3e53cf350cc39", + "status": "Source-only remediation guards; execution pending assigned validation slot.", + "usage": "python3 -B utils/perturb.py big-code-analysis-bench/perturbations/documentation-remediation.json", + "preservation": "The original documentation.json and documentation-audit.json retain all 18 cases and expected tests. The batch and miss-only scan mutations below preserve the exact parent-confirmed surviving behaviors." + }, + "command": ["cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation", "--no-fail-fast"], + "cases": [ + { + "name": "truncate measured repetitions to one", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "for _ in 0..iterations {\n operation.execute()?;\n }", + "new": "for _ in 0..iterations.min(1) {\n operation.execute()?;\n }", + "expect": ["documentation::runner::tests::batch_executes_every_requested_repetition", "documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts"] + }, + { + "name": "scheduler ignores frozen count metadata", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "let elapsed = batch(&prepared[at], cell.iterations)", + "new": "let elapsed = batch(&prepared[at], 1)", + "expect": ["documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts"] + }, + { + "name": "scan all name entries only after an indexed miss", + "file": "big-code-analysis-ast/src/documentation/names.rs", + "old": " let reason = match owners.len() {", + "new": " if owners.is_empty() {\n for bucket in index.values() {\n for entry in bucket {\n budget.step().map_err(Into::into)?;\n std::hint::black_box(same_spelling(&entry.spelling, &key, budget)?);\n }\n }\n }\n let reason = match owners.len() {", + "expect": ["documentation::names::miss_tests::absent_bucket_miss_never_compares_unrelated_names", "documentation::names::miss_tests::collision_bucket_miss_compares_only_its_nonmatching_spellings"] + }, + { + "name": "initial workflow run implicitly selects all", + "file": ".github/workflows/benchmark.yml", + "old": "--scope legacy --rounds 11", + "new": "--rounds 11", + "expect": ["documentation::workflow_tests::inherited_workflow_retries_only_legacy_and_preserves_harness_errors"] + }, + { + "name": "workflow confirmation implicitly selects all", + "file": ".github/workflows/benchmark.yml", + "old": "--scope legacy --rounds 21 \\", + "new": "--rounds 21 \\", + "expect": ["documentation::workflow_tests::inherited_workflow_retries_only_legacy_and_preserves_harness_errors"] + }, + { + "name": "suppress typed trailing failure rows", + "file": "big-code-analysis-bench/src/documentation/combined.rs", + "old": "if mode != Mode::Gate {", + "new": "if mode == Mode::Gate {", + "expect": ["documentation::combined::tests::final_failure_tail_identifies_early_failures_and_each_statistic", "documentation::combined::tests::final_summary_distinguishes_all_pass_and_non_gating_output"] + }, + { + "name": "bypass new exact structural attachment validation", + "file": "big-code-analysis-bench/src/documentation/attachment_validation.rs", + "old": "let recovery = key == \"recovery-depth\";", + "new": "if !key.is_empty() { return Ok(()); }\n let recovery = key == \"recovery-depth\";", + "expect": ["documentation::tests::recovery_and_conditional_semantics_reject_shape_preserving_substitutions"] + }, + { + "name": "workflow reproduction implicitly selects all", + "file": ".github/workflows/benchmark.yml", + "old": "BENCH_ARGS='--scope legacy --rounds 21'", + "new": "BENCH_ARGS='--rounds 21'", + "expect": ["documentation::workflow_tests::workflow_reproduction_command_selects_the_confirmation_scope"] + }, + { + "name": "suppress source trailing failure detail", + "file": "big-code-analysis-bench/src/documentation/combined.rs", + "old": "for result in report.failures() {\n let _ = writeln!(", + "new": "for result in report.failures().into_iter().take(0) {\n let _ = writeln!(", + "expect": ["documentation::combined::tests::final_failure_tail_identifies_early_failures_and_each_statistic"] + } + ] +} diff --git a/big-code-analysis-bench/src/documentation/attachment_validation.rs b/big-code-analysis-bench/src/documentation/attachment_validation.rs new file mode 100644 index 000000000..6af494d59 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/attachment_validation.rs @@ -0,0 +1,206 @@ +//! Exact source-derived attachment oracles for combined structural ladders. + +use super::{HarnessError, Parsed, failure, require}; +use big_code_analysis_ast::documentation::{ + Document, DocumentationIndex, FactRef, FragmentForm, Origin, Owner, Resolution, SlotRole, + SourcePieces, UnresolvedReason, +}; +use big_code_analysis_ast::tree_sitter::Node; +use std::collections::HashMap; +use std::ops::Range; + +fn node_at<'s>( + nodes: &HashMap<(usize, usize), Node<'s>>, + range: Range, + kind: &str, +) -> Result, HarnessError> { + nodes + .get(&(range.start, range.end)) + .copied() + .filter(|n| n.kind() == kind) + .ok_or_else(|| HarnessError(format!("expected {kind} at {range:?}"))) +} + +fn exact_piece( + pieces: &SourcePieces<'_>, + range: Range, + bytes: &[u8], +) -> Result<(), HarnessError> { + require( + !pieces.has_excluded_gap() && pieces.pieces().len() == 1, + "exact source piece count", + )?; + let piece = &pieces.pieces()[0]; + require( + piece.range() == range && piece.bytes() == bytes, + "exact source piece range/bytes", + ) +} + +fn comment_text<'s>( + index: &DocumentationIndex<'s>, + doc: FactRef<'_, Document<'s>>, + start: usize, +) -> Result<(), HarnessError> { + require( + doc.get().fragment_count() == 1, + "combined fixture fragment count", + )?; + let fragment = index.facts().document_fragment(doc, 0).map_err(failure)?; + require( + fragment.get().form() == FragmentForm::Comment, + "combined fixture comment form", + )?; + exact_piece(fragment.get().source(), start..start + 10, b"/**audit*/")?; + require( + fragment.get().node().is_some_and(|n| { + n.node().byte_range() == (start..start + 10) && n.node().kind() == "comment" + }), + "combined fixture comment node", + )?; + let text = index + .complete_text(doc) + .map_err(failure)? + .ok_or_else(|| HarnessError("combined fixture complete text absent".into()))?; + require( + text.text() == "audit" && text.mappings().len() == 1, + "combined fixture audit text/map count", + )?; + let mapping = &text.mappings()[0]; + require( + mapping.output.range() == (0..5), + "combined fixture map output", + )?; + let Origin::Copied(pieces) = &mapping.origin else { + return Err(HarnessError( + "combined fixture origin must be copied".into(), + )); + }; + exact_piece(pieces, start + 3..start + 8, b"audit") +} + +#[allow(clippy::too_many_lines)] // Shared fixture oracle keeps source ranges and the corresponding owner identities together. +pub(super) fn validate( + key: &str, + size: usize, + parsed: &Parsed, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + let recovery = key == "recovery-depth"; + let count = if recovery { 32 } else { 1 }; + require( + index.documents().len() == count && index.associations().len() == count, + "combined fixture D/A count", + )?; + require( + index.qualifications().len() == 0, + "direct attachment must have Q=0", + )?; + let resolution = if recovery { + Resolution::Resolved + } else { + Resolution::Unresolved(UnresolvedReason::Conditional) + }; + require( + index + .associations() + .all(|a| a.get().owner_count() == 1 && a.get().resolution == resolution), + "combined fixture resolution/owner count", + )?; + // A single canonical traversal supplies identity without per-output parent walks. + let nodes: HashMap<_, _> = parsed + .nodes() + .into_iter() + .filter(|(n, _)| { + matches!( + n.kind(), + "field_declaration" | "field_declaration_list" | "preproc_if" + ) + }) + .map(|(n, _)| ((n.start_byte(), n.end_byte()), n)) + .collect(); + let base = if recovery { 11 * size + 2 } else { 20 * size }; + let scope_range = if recovery { + // The final opener's brace is two bytes before the 11n prefix end; + // 32 leaf units and the first closing brace end this field list. + 11 * size - 2..base + 32 * 18 + 1 + } else { + // #if FLAG\n is nine bytes; the leaf unit is 21 and #endif is six. + base - 9..base + 21 + 6 + }; + let scope = node_at( + &nodes, + scope_range, + if recovery { + "field_declaration_list" + } else { + "preproc_if" + }, + )?; + for (ordinal, (doc, association)) in index.documents().zip(index.associations()).enumerate() { + let start = base + ordinal * 18; + let declaration = node_at( + &nodes, + start + 11..start + if recovery { 17 } else { 20 }, + "field_declaration", + )?; + require( + &parsed.source()[declaration.byte_range()] + == if recovery { + b"int x;".as_slice() + } else { + b"void f();".as_slice() + }, + "combined fixture leaf declaration spelling", + )?; + require( + index + .facts() + .associated_document(association) + .map_err(failure)? + == doc, + "combined fixture document association identity", + )?; + let fact = association.get(); + require( + fact.binding.is_some_and(|n| n.node() == declaration) + && fact.lexical_scope.node() == scope, + "combined fixture binding/scope identity", + )?; + let owner = index + .facts() + .associated_owner(association, 0) + .map_err(failure)?; + if recovery { + let Owner::Slot(slot) = owner.get() else { + return Err(HarnessError("recovery owner must be field slot".into())); + }; + require( + slot.role == SlotRole::Field && slot.ordinal == 0, + "recovery field slot role/ordinal", + )?; + exact_piece(&slot.source, start + 15..start + 16, b"x")?; + let enclosing = index.facts().slot_enclosing(owner).map_err(failure)?; + require( + matches!(enclosing.get(), Owner::Node(n) if n.node() == declaration), + "recovery slot enclosure identity", + )?; + } else { + require( + matches!(owner.get(), Owner::Node(n) if n.node() == declaration), + "conditional leaf owner identity", + )?; + } + require( + index + .owner_associations(owner) + .map_err(failure)? + .associations() + .collect::>() + == [association], + "combined fixture owner adjacency", + )?; + comment_text(index, doc, start)?; + } + Ok(()) +} diff --git a/big-code-analysis-bench/src/documentation/combined.rs b/big-code-analysis-bench/src/documentation/combined.rs index 715f54c35..1219a60c9 100644 --- a/big-code-analysis-bench/src/documentation/combined.rs +++ b/big-code-analysis-bench/src/documentation/combined.rs @@ -4,6 +4,7 @@ use super::runner::SourceReport; use super::{HarnessError, require}; use crate::cli::{Mode, Scope}; use crate::scaling; +use std::fmt::Write; /// Independent result collections from the two scaling methods. pub struct CombinedReport { @@ -89,6 +90,53 @@ impl CombinedReport { pub fn exit_code(&self, mode: Mode, optimized: bool) -> u8 { u8::from(mode == Mode::Gate && optimized && self.failures() > 0) } + + /// Compact trailing diagnosis after both full tables. All failure rows are + /// retained; tail-only excerpts can omit earlier rows and name the full log. + #[must_use] + pub fn final_summary(&self, mode: Mode) -> String { + if mode != Mode::Gate { + return format!("{mode:?}: no performance verdict\n"); + } + let mut output = String::new(); + if let Some(report) = &self.legacy { + for result in report.failures() { + if let Some((size, elapsed)) = result.over_budget { + let _ = writeln!( + output, + "FAIL legacy {}: abandoned size {size}, duration {elapsed:?} > budget {:?}; {}", + result.name, + scaling::MAX_CELL_WALK, + result.rationale + ); + } else { + let _ = writeln!( + output, + "FAIL legacy {}: exponent {:.4} > bound {:.2}; {}", + result.name, result.exponent, result.max_exponent, result.rationale + ); + } + } + } + if let Some(report) = &self.source { + for result in report.failures() { + let _ = writeln!( + output, + "FAIL source {}: {} > bound {:.2}; policy: {}", + result.id, result.statistic, result.bound, result.policy + ); + } + } + let count = self.failures(); + if count > 0 { + let _ = writeln!( + output, + "Tail excerpts are truncated if fewer than {count} FAIL rows appear; full logs: metric-walk-benchmarks artifact, target/bench/scaling*.log." + ); + } + let _ = writeln!(output, "combined gate: {count} performance failures"); + output + } } #[cfg(test)] @@ -96,6 +144,190 @@ mod tests { use super::super::runner::{Batch, SourceCell, SourceResult, Statistic}; use super::*; + #[cfg(unix)] + fn legacy_failure(name: &'static str) -> scaling::ProbeReport { + scaling::ProbeReport { + name, + exponent: 2.0, + max_exponent: 1.5, + rationale: "walk growth", + over_budget: None, + cells: [256, 512, 1024] + .into_iter() + .zip([200, 800, 3200]) + .map(|(size, micros)| { + let elapsed = std::time::Duration::from_micros(micros); + scaling::Cell { + size, + bytes: size, + reading: 1, + iterations: 1, + min: elapsed, + median: elapsed, + max: elapsed, + } + }) + .collect(), + } + } + + fn source_reports(failing: bool) -> SourceReport { + let results = super::super::REGISTRY + .iter() + .enumerate() + .map(|(at, probe)| { + let times = if failing && matches!(at, 0 | 18 | 19) { + [200_000, 800_000, 3_200_000] + } else { + [200_000; 3] + }; + let cells: Vec<_> = [256, 512, 1024] + .into_iter() + .zip(times) + .map(|(size, ns)| { + let elapsed = std::time::Duration::from_nanos(ns); + SourceCell { + counts: super::super::SourceCounts::default(), + size, + bytes: size, + segments: 1, + iterations: 1, + batches: (0..3).map(|round| Batch { round, elapsed }).collect(), + batch_min: elapsed, + batch_median: elapsed, + batch_max: elapsed, + ns_per_operation: elapsed.as_secs_f64() * 1e9, + } + }) + .collect(); + SourceResult { + id: probe.id, + bound: 1.5, + dimensions: probe.dimensions, + timing: probe.timing, + policy: probe.policy, + statistic: super::super::runner::statistic(probe.class, &cells).unwrap(), + cells, + } + }) + .collect(); + SourceReport { + rounds: 3, + mode: Mode::Gate, + results, + } + } + + #[cfg(unix)] + #[test] + #[allow(clippy::too_many_lines)] // One rendered log exercises mixed typed failures and the workflow's actual tail size. + fn final_failure_tail_identifies_early_failures_and_each_statistic() { + let source = source_reports(true); + source.validate_data().unwrap(); + let legacy = scaling::Report { + rounds: 3, + probes: vec![ + legacy_failure("early-legacy"), + scaling::ProbeReport { + name: "abandoned-legacy", + cells: vec![], + exponent: 0.0, + max_exponent: 1.5, + rationale: "walk budget", + over_budget: Some((256, std::time::Duration::from_secs(21))), + }, + ], + }; + let report = CombinedReport { + legacy: Some(legacy), + source: Some(source), + }; + let full = format!( + "{}{}{}", + report.legacy.as_ref().unwrap(), + report.source.as_ref().unwrap(), + report.final_summary(Mode::Gate) + ); + let lines: Vec<_> = full.lines().collect(); + let excerpt = lines[lines + .len() + .saturating_sub(super::super::workflow_tests::issue_tail_lines())..] + .join("\n"); + for needle in [ + "FAIL legacy early-legacy: exponent 2.0000 > bound 1.50; walk growth", + "FAIL legacy abandoned-legacy: abandoned size 256, duration 21s > budget 20s", + "documentation/cold/depth: exponent 2.0000", + "documentation/prepared/owner: fixed-K ratio 16.0000", + "documentation/prepared/late-map: log-map ratio 16.0000", + "policy:", + "combined gate: 5 performance failures", + ] { + assert!(excerpt.contains(needle), "missing {needle}: {excerpt}"); + } + assert_eq!( + full.lines() + .filter(|line| line.starts_with("FAIL ")) + .count(), + 5 + ); + assert!(excerpt.contains("metric-walk-benchmarks artifact")); + assert!(excerpt.ends_with("combined gate: 5 performance failures")); + } + + #[test] + fn final_summary_distinguishes_all_pass_and_non_gating_output() { + let source = source_reports(false); + source.validate_data().unwrap(); + let report = CombinedReport { + legacy: None, + source: Some(source), + }; + assert_eq!( + report.final_summary(Mode::Gate), + "combined gate: 0 performance failures\n" + ); + for mode in [Mode::Smoke, Mode::ReportOnly] { + let text = report.final_summary(mode); + assert!(text.contains("no performance verdict")); + assert!(!text.contains("combined gate")); + } + } + + #[cfg(unix)] + #[test] + fn failure_tail_reports_when_the_excerpt_omits_rows() { + let limit = super::super::workflow_tests::issue_tail_lines(); + let count = limit + 3; + let legacy = scaling::Report { + rounds: 3, + probes: crate::shapes::PROBES + .iter() + .take(count) + .map(|probe| legacy_failure(probe.name)) + .collect(), + }; + assert_eq!( + legacy.probes.len(), + count, + "fixture needs more unique legacy IDs than the workflow tail" + ); + let report = CombinedReport { + legacy: Some(legacy), + source: None, + }; + let full = report.final_summary(Mode::Gate); + assert_eq!( + full.lines().filter(|l| l.starts_with("FAIL ")).count(), + count + ); + let lines: Vec<_> = full.lines().collect(); + let tail = lines[lines.len() - limit..].join("\n"); + assert!(tail.contains(&format!("truncated if fewer than {count} FAIL rows appear"))); + assert!(tail.contains("target/bench/scaling*.log")); + assert!(tail.ends_with(&format!("combined gate: {count} performance failures"))); + assert!(tail.lines().filter(|l| l.starts_with("FAIL ")).count() < count); + } + #[test] fn combined_membership_and_source_failure_cannot_hide_behind_legacy_pass() { let legacy = scaling::Report { diff --git a/big-code-analysis-bench/src/documentation/mod.rs b/big-code-analysis-bench/src/documentation/mod.rs index bba14b66f..8c799bb0c 100644 --- a/big-code-analysis-bench/src/documentation/mod.rs +++ b/big-code-analysis-bench/src/documentation/mod.rs @@ -1,5 +1,6 @@ //! Shared source-documentation registry, operations and class-specific gate. +mod attachment_validation; pub mod combined; mod fixtures; mod operation; @@ -7,6 +8,8 @@ pub mod runner; #[cfg(test)] mod tests; mod validation; +#[cfg(all(test, unix))] +mod workflow_tests; pub use fixtures::{REGISTRY, SourceProbe, StatisticClass}; pub use operation::{Parsed, Prepared, SourceCounts}; diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index a2389f40a..40c88e939 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -358,6 +358,21 @@ pub fn run_with_budget( batches: Vec::with_capacity(rounds), }); } + measure_schedule(&prepared, &mut raw, rounds, budget)?; + reduce(&probes, rounds, mode, raw.clone()) + .map_err(|error| HarnessError(format!("{error}\nretained source batches: {raw:#?}"))) +} + +fn measure_schedule( + prepared: &[Prepared<'_, '_>], + raw: &mut [RawCell], + rounds: usize, + budget: Duration, +) -> Result<(), HarnessError> { + require( + prepared.len() == raw.len() && !raw.is_empty(), + "invalid scheduled cell membership", + )?; for (round, at) in schedule(raw.len(), rounds) { let cell = &raw[at]; let elapsed = batch(&prepared[at], cell.iterations) @@ -385,8 +400,7 @@ pub fn run_with_budget( }); } } - reduce(&probes, rounds, mode, raw.clone()) - .map_err(|error| HarnessError(format!("{error}\nretained source batches: {raw:#?}"))) + Ok(()) } fn batch(operation: &Prepared<'_, '_>, iterations: u32) -> Result { @@ -541,7 +555,10 @@ fn reduce_cell(raw: RawCell, rounds: usize, mode: Mode) -> Result Result { +pub(super) fn statistic( + class: StatisticClass, + cells: &[SourceCell], +) -> Result { require( cells.len() == 3 && cells @@ -837,4 +854,66 @@ mod tests { .all(|c| c.batches.len() == 1 && c.iterations == 1) ); } + + #[test] + fn batch_executes_every_requested_repetition() { + let probe = ®ISTRY[1]; + let parsed = Parsed::new(probe, 4).unwrap(); + let index = parsed.collect(probe).unwrap(); + let prepared = Prepared::new(probe, 4, &parsed, &index).unwrap(); + for iterations in [1, 3, 5] { + let before = big_code_analysis_ast::documentation::observations(); + let _elapsed = batch(&prepared, iterations).unwrap(); + let after = big_code_analysis_ast::documentation::observations(); + assert_eq!(after.renders - before.renders, 4 * iterations as usize); + assert_eq!( + after.visits - before.visits, + parsed.nodes().len() * iterations as usize + ); + } + } + + #[test] + fn scheduler_executes_and_records_unequal_frozen_counts() { + let probe = ®ISTRY[1]; + let sizes = [2, 4, 8]; + let counts = [1, 2, 4]; + let parsed: Vec<_> = sizes + .into_iter() + .map(|size| Parsed::new(probe, size).unwrap()) + .collect(); + let indexes: Vec<_> = parsed.iter().map(|p| p.collect(probe).unwrap()).collect(); + let prepared: Vec<_> = parsed + .iter() + .zip(&indexes) + .zip(sizes) + .map(|((p, i), size)| Prepared::new(probe, size, p, i).unwrap()) + .collect(); + let before = big_code_analysis_ast::documentation::observations(); + let mut raw = Vec::new(); + for ((operation, size), iterations) in prepared.iter().zip(sizes).zip(counts) { + let _calibration = batch(operation, 1).unwrap(); + raw.push(RawCell { + counts: operation.counts(), + id: probe.id, + size, + bytes: size, + segments: 1, + iterations, + batches: vec![], + }); + } + measure_schedule(&prepared, &mut raw, 3, MAX_CELL_WALK).unwrap(); + let after = big_code_analysis_ast::documentation::observations(); + // Calibration renders 2+4+8 documents. Each scheduled round renders + // 2*1+4*2+8*4; two warmups plus three measured rounds gives 224 total. + assert_eq!(after.renders - before.renders, 224); + for (cell, count) in raw.iter().zip(counts) { + assert_eq!(cell.iterations, count); + assert_eq!( + cell.batches.iter().map(|b| b.round).collect::>(), + [0, 1, 2] + ); + } + } } diff --git a/big-code-analysis-bench/src/documentation/tests.rs b/big-code-analysis-bench/src/documentation/tests.rs index 580d47955..12016a490 100644 --- a/big-code-analysis-bench/src/documentation/tests.rs +++ b/big-code-analysis-bench/src/documentation/tests.rs @@ -2,6 +2,62 @@ use super::*; use big_code_analysis_ast::LANG; use big_code_analysis_ast::documentation::*; +#[test] +fn recovery_and_conditional_semantics_reject_shape_preserving_substitutions() { + for key in ["recovery-depth", "conditional-depth"] { + let probe = REGISTRY.iter().find(|p| p.key == key).unwrap(); + for size in [4, 32] { + let source = String::from_utf8(probe.source(size).unwrap()).unwrap(); + for replacement in ["wrong", "@file", "@fn absent"] { + let changed = source.replace("audit", replacement); + let parsed = Parsed::Ordinary( + big_code_analysis::Ast::parse(big_code_analysis::Source::new( + probe.language, + changed.as_bytes(), + )) + .unwrap(), + ); + let index = parsed.collect(probe).unwrap(); + let nodes = parsed.nodes(); + let count = |kind| nodes.iter().filter(|(n, _)| n.kind() == kind).count(); + // Pin the original weaker conditions before requiring the new + // text/attachment oracle to reject each counterexample. + assert_eq!( + parsed.tree().root_node().has_error(), + key == "recovery-depth" + ); + assert_eq!(count("struct_specifier"), size); + if key == "recovery-depth" { + assert_eq!(count("field_declaration"), size + 31); + assert!( + nodes + .iter() + .any(|(n, depth)| n.kind() == "field_declaration_list" + && n.has_error() + && n.child_count() >= 64 + && *depth >= size) + ); + assert_eq!(index.documents().len(), 32); + } else { + assert_eq!(count("preproc_if"), size); + assert_eq!(index.documents().len(), 1); + } + let Err(error) = Prepared::new(probe, size, &parsed, &index) else { + panic!("accepted {key}/{size}/{replacement}") + }; + let expected = match replacement { + "wrong" => "exact source piece range/bytes", + "@file" if key == "recovery-depth" => "combined fixture binding/scope identity", + "@file" => "combined fixture resolution/owner count", + "@fn absent" if key == "conditional-depth" => "direct attachment must have Q=0", + _ => "combined fixture resolution/owner count", + }; + assert_eq!(error.0, expected, "{key}/{size}/{replacement}"); + } + } + } +} + #[test] fn original_registry_ids_sizes_and_options_are_preserved() { assert_eq!( @@ -435,6 +491,27 @@ fn new_generated_names_keep_affine_bytes() { } } +#[test] +fn missing_name_source_retains_distinct_keys_without_owner_edges() { + let probe = REGISTRY.iter().find(|p| p.key == "missing-name").unwrap(); + for size in [32, 64, 128] { + let parsed = Parsed::new(probe, size).unwrap(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + let after = observations(); + // Each fixed-width f00000000 name stores nine bytes; its normalized + // void\0f00000000\0(\0void\0) signature stores 23, regardless of bucket collisions. + assert_eq!(after.key_bytes_stored - before.key_bytes_stored, 32 * size); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::MissingName) + ); + assert_eq!(association.get().owner_count(), 0); + } +} + #[test] fn candidate_reference_overlap_and_unknown_signature_controls_are_distinct() { for (source, subject, reasons) in [ diff --git a/big-code-analysis-bench/src/documentation/validation.rs b/big-code-analysis-bench/src/documentation/validation.rs index d8e27b16f..c709f74e4 100644 --- a/big-code-analysis-bench/src/documentation/validation.rs +++ b/big-code-analysis-bench/src/documentation/validation.rs @@ -253,6 +253,7 @@ fn additional_fixture( "deep recovered sibling parent absent", )?; require(index.documents().len() == 32, "recovery document count")?; + super::attachment_validation::validate(probe.key, size, parsed, index)?; } "conditional-depth" => { require( @@ -260,6 +261,7 @@ fn additional_fixture( "conditional structure depth", )?; require(index.documents().len() == 1, "conditional document count")?; + super::attachment_validation::validate(probe.key, size, parsed, index)?; } "missing-name" => { require(count("declaration") == size, "unrelated named declarations")?; diff --git a/big-code-analysis-bench/src/documentation/workflow_tests.rs b/big-code-analysis-bench/src/documentation/workflow_tests.rs new file mode 100644 index 000000000..eff12d191 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/workflow_tests.rs @@ -0,0 +1,149 @@ +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::Command; + +use crate::cli::{Action, Mode, Scope, parse_args}; + +fn workflow() -> String { + fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")).join("../.github/workflows/benchmark.yml"), + ) + .unwrap() +} + +fn gate_script(yaml: &str) -> String { + let after = yaml + .split_once(" - name: Complexity-class gate\n") + .unwrap() + .1; + let body = after.split_once(" run: |\n").unwrap().1; + body.lines() + .take_while(|line| line.is_empty() || line.starts_with(" ")) + .map(|line| line.strip_prefix(" ").unwrap_or(line)) + .collect::>() + .join("\n") +} + +pub(super) fn issue_tail_lines() -> usize { + let yaml = workflow(); + let command = yaml + .lines() + .find(|line| line.trim_start().starts_with("tail -n ")) + .unwrap(); + command.split_whitespace().nth(2).unwrap().parse().unwrap() +} + +#[test] +fn workflow_reproduction_command_selects_the_confirmation_scope() { + let yaml = workflow(); + let echo = yaml + .lines() + .find(|line| line.contains("Reproduce locally with")) + .unwrap() + .trim(); + let output = Command::new("bash").args(["-c", echo]).output().unwrap(); + assert!(output.status.success()); + let prose = String::from_utf8(output.stdout).unwrap(); + let command = prose.split('`').nth(1).unwrap(); + let dir = tempfile::tempdir().unwrap(); + let stub = dir.path().join("make"); + fs::write(&stub, "#!/bin/bash\nset -eu\nprintf '%s\\n' \"$@\"\n").unwrap(); + fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap(); + let path = std::env::join_paths( + std::iter::once(dir.path().to_path_buf()) + .chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())), + ) + .unwrap(); + let invocation = Command::new("bash") + .args(["-c", command]) + .env("PATH", path) + .current_dir(dir.path()) + .output() + .unwrap(); + assert!(invocation.status.success()); + let arguments = String::from_utf8(invocation.stdout).unwrap(); + let mut lines = arguments.lines(); + assert_eq!(lines.next(), Some("bench-scaling")); + let flags = lines.next().unwrap().strip_prefix("BENCH_ARGS=").unwrap(); + assert_eq!(lines.next(), None); + let Action::Run(args) = parse_args( + std::iter::once("--bench") + .chain(flags.split_whitespace()) + .map(str::to_owned), + ) + .unwrap() else { + panic!("run") + }; + assert_eq!(args.scope, Scope::Legacy); + assert_eq!(args.rounds, 21); +} + +#[test] +fn inherited_workflow_retries_only_legacy_and_preserves_harness_errors() { + let script = gate_script(&workflow()); + for (exits, expected_exit, expected_rounds, confirmation) in [ + ("0", 0, vec![11], false), + ("1 0", 0, vec![11, 21], true), + ("1 1", 1, vec![11, 21], true), + ("2", 2, vec![11], false), + ("1 2", 2, vec![11, 21], false), + ] { + let dir = tempfile::tempdir().unwrap(); + let stub = dir.path().join("cargo"); + fs::write(&stub, "#!/bin/bash\nset -eu\nprintf '%s\\n' \"$*\" >> \"$CALLS\"\nread -r -a codes <<< \"$CODES\"\nn=$(wc -l < \"$CALLS\")\necho simulated-scaling\nexit \"${codes[n-1]}\"\n").unwrap(); + fs::set_permissions(&stub, fs::Permissions::from_mode(0o755)).unwrap(); + let calls = dir.path().join("calls"); + let path = std::env::join_paths( + std::iter::once(dir.path().to_path_buf()) + .chain(std::env::split_paths(&std::env::var_os("PATH").unwrap())), + ) + .unwrap(); + let output = Command::new("bash") + .args(["-c", &script]) + .current_dir(dir.path()) + .env("PATH", path) + .env("CALLS", &calls) + .env("CODES", exits) + .output() + .unwrap(); + assert_eq!( + output.status.code(), + Some(expected_exit), + "{exits}: {} {}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let calls = fs::read_to_string(calls).unwrap(); + let parsed: Vec<_> = calls + .lines() + .map(|call| { + let argv: Vec<_> = call.split_whitespace().collect(); + let separator = argv.iter().position(|arg| *arg == "--").unwrap(); + assert_eq!( + &argv[..separator], + [ + "bench", + "-p", + "big-code-analysis-bench", + "--bench", + "scaling" + ] + ); + let args = std::iter::once("--bench".to_owned()) + .chain(argv[separator + 1..].iter().map(|s| (*s).to_owned())); + let Action::Run(args) = parse_args(args).unwrap() else { + panic!("run") + }; + assert_eq!(args.scope, Scope::Legacy); + assert_eq!(args.mode, Mode::Gate); + args.rounds + }) + .collect(); + assert_eq!(parsed, expected_rounds); + assert_eq!( + dir.path().join("target/bench/scaling-confirm.log").exists(), + confirmation + ); + } +} diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 2c5ceb074..a56d0fcdc 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -94,6 +94,12 @@ The scaling executable uses these exit codes: Report-only suppresses exit 1 but still rejects harness errors. +After both full tables, a compact footer lists each failure's ID and cause. Legacy failures +name the exponent and bound or the abandoned walk's size, duration and budget. Source failures +name their statistic class, value, bound and policy. The final line gives the total failure +count. A tail excerpt can omit earlier failure rows; compare its visible count with that total +and consult the full `target/bench/scaling*.log` files in the `metric-walk-benchmarks` artifact. + ### Registry and timed boundaries `big-code-analysis-bench/src/documentation/` supplies one registry to the source gate and @@ -229,6 +235,12 @@ policy. Do not change bounds after observing a run. New optimization guards also discriminating counter tests and controlled regressed/fixed pairs where a timing claim requires them. Record both revisions explicitly for each regressed/fixed comparison. +The source gate retains all parsed inputs and indexes across its schedule; documentation +Criterion prepares state per cell. Record this working-set difference, actual compiled features +and production counter overhead in the comparison. Counter guards cover their recorded paths; +raw storage scans can bypass public iterator counters. The private failed-name lookup tests +guard unrelated spelling comparisons after an indexed miss, not every possible name-index cost. + The visible array-declarator ladder measures visible nesting and requests to `TreeCursor::field_name`. It does not bound hidden-rule work inside each dependency call. Investigation is limited to the collector's implemented `fields_needed` parent kinds: @@ -1767,7 +1779,9 @@ rather than red. Run `make bench-scaling` around any change to AST traversal, `Checker`, `Getter`, or a metric's `compute`. `.github/workflows/benchmark.yml` runs the gate quarterly and on -`workflow_dispatch`, mirroring +`workflow_dispatch`, explicitly selecting `--scope legacy` for both its initial and confirmation +runs. Its retry policy applies only to legacy probes. Source qualification uses the +[separate predeclared policy](#source-documentation). The schedule mirrors [mutation testing](mutation_testing.md). It files an issue on a sustained performance failure. The growth statistics reduce sensitivity to host speed, but load still affects them. Confirm a performance-bound failure on an idle host before From 50de79254d073e7eebc48b5a577864b092461703 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:04:57 -0800 Subject: [PATCH 054/221] test(bench): resolve remediation guard lint findings Rename workflow tokens and remove a duplicate expected-error match arm. Focused tests and actionlint pass; freeze before maintained mutation sweeps and final gate. --- big-code-analysis-bench/src/documentation/tests.rs | 1 - .../src/documentation/workflow_tests.rs | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/big-code-analysis-bench/src/documentation/tests.rs b/big-code-analysis-bench/src/documentation/tests.rs index 12016a490..5b723d9b6 100644 --- a/big-code-analysis-bench/src/documentation/tests.rs +++ b/big-code-analysis-bench/src/documentation/tests.rs @@ -48,7 +48,6 @@ fn recovery_and_conditional_semantics_reject_shape_preserving_substitutions() { let expected = match replacement { "wrong" => "exact source piece range/bytes", "@file" if key == "recovery-depth" => "combined fixture binding/scope identity", - "@file" => "combined fixture resolution/owner count", "@fn absent" if key == "conditional-depth" => "direct attachment must have Q=0", _ => "combined fixture resolution/owner count", }; diff --git a/big-code-analysis-bench/src/documentation/workflow_tests.rs b/big-code-analysis-bench/src/documentation/workflow_tests.rs index eff12d191..e4586c53a 100644 --- a/big-code-analysis-bench/src/documentation/workflow_tests.rs +++ b/big-code-analysis-bench/src/documentation/workflow_tests.rs @@ -118,10 +118,10 @@ fn inherited_workflow_retries_only_legacy_and_preserves_harness_errors() { let parsed: Vec<_> = calls .lines() .map(|call| { - let argv: Vec<_> = call.split_whitespace().collect(); - let separator = argv.iter().position(|arg| *arg == "--").unwrap(); + let words: Vec<_> = call.split_whitespace().collect(); + let separator = words.iter().position(|arg| *arg == "--").unwrap(); assert_eq!( - &argv[..separator], + &words[..separator], [ "bench", "-p", @@ -131,7 +131,7 @@ fn inherited_workflow_retries_only_legacy_and_preserves_harness_errors() { ] ); let args = std::iter::once("--bench".to_owned()) - .chain(argv[separator + 1..].iter().map(|s| (*s).to_owned())); + .chain(words[separator + 1..].iter().map(|s| (*s).to_owned())); let Action::Run(args) = parse_args(args).unwrap() else { panic!("run") }; From 2eb9b8103477d1d02e76620c4475b47b0a37a5d2 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:10:24 -0800 Subject: [PATCH 055/221] test(bench): archive remediation mutation evidence Record all 27 behavioral catches at 50de7925 with exact command, toolchain and expected-failure results; preserve historical a4397339 evidence. Data-only checkpoint before all-files hooks and final gate. --- .../documentation-results-50de7925.json | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 big-code-analysis-bench/perturbations/documentation-results-50de7925.json diff --git a/big-code-analysis-bench/perturbations/documentation-results-50de7925.json b/big-code-analysis-bench/perturbations/documentation-results-50de7925.json new file mode 100644 index 000000000..cf9bf18f5 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-results-50de7925.json @@ -0,0 +1,58 @@ +{ + "checkpoint": "50de79254d073e7eebc48b5a577864b092461703", + "issue_base": "9abf9720cd5d1506455cb94fed5b0009f4fc1a15", + "command": ["cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation", "--no-fail-fast"], + "provenance": { + "rustc": "1.99.0 (b940084d7 2026-09-28)", + "cargo": "1.99.0 (5f94df478 2026-08-27)", + "python": "3.14.3", + "driver": "python3 -B utils/perturb.py big-code-analysis-bench/perturbations/", + "scope": "Sequential local behavioral sweeps on a clean frozen revision. Every case compiled and failed its intended tests; sources restored. These results are not performance qualification.", + "first_validation_failure": "Clippy similar_names in workflow tests (two diagnostics) and match_same_arms in fixture rejection test; corrected in checkpoint 50de7925 without changing assertions. Compilation and focused tests passed on the initial candidate.", + "source_results": ["/tmp/bca-perturb-backup.olk2rhjb/perturb-results.json", "/tmp/bca-perturb-backup.dbepu19h/perturb-results.json", "/tmp/bca-perturb-backup.4i0kwroi/perturb-results.json"] + }, + "sweeps": [ + { + "manifest": "documentation.json", + "results": [ + {"name":"skip registered cell execution","verdict":"caught","detail":"","failed":["documentation::runner::tests::batch_executes_every_requested_repetition","documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts","documentation::runner::tests::source_schedule_executes_calibration_warmup_and_measured_work","documentation::runner::tests::source_smoke_exercises_every_registered_cell"],"missing_expected":[],"rc":101}, + {"name":"ignore wrong cell membership","verdict":"caught","detail":"","failed":["documentation::runner::tests::malformed_membership_and_samples_fail_in_every_mode"],"missing_expected":[],"rc":101}, + {"name":"ignore missing samples","verdict":"caught","detail":"","failed":["documentation::runner::tests::malformed_membership_and_samples_fail_in_every_mode","documentation::runner::tests::report_revalidates_batches_counts_and_statistic"],"missing_expected":[],"rc":101}, + {"name":"disable measured batch resolution","verdict":"caught","detail":"","failed":["documentation::runner::tests::actual_batches_control_resolution_even_at_iteration_cap"],"missing_expected":[],"rc":101}, + {"name":"floor fractional ns","verdict":"caught","detail":"","failed":["documentation::runner::tests::ratios_keep_subnanosecond_values_and_report_performance_failure"],"missing_expected":[],"rc":101}, + {"name":"legacy cheap iteration cap","verdict":"caught","detail":"","failed":["documentation::runner::tests::actual_batches_control_resolution_even_at_iteration_cap","documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling","documentation::runner::tests::ratios_keep_subnanosecond_values_and_report_performance_failure"],"missing_expected":[],"rc":101}, + {"name":"omit source failures","verdict":"caught","detail":"","failed":["documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass","documentation::combined::tests::final_failure_tail_identifies_early_failures_and_each_statistic"],"missing_expected":[],"rc":101}, + {"name":"ignore gate exit failure","verdict":"caught","detail":"","failed":["documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass"],"missing_expected":[],"rc":101}, + {"name":"skip association consumption","verdict":"caught","detail":"","failed":["documentation::tests::prepared_query_counters_charge_only_declared_output"],"missing_expected":[],"rc":101}, + {"name":"skip qualification consumption","verdict":"caught","detail":"","failed":["documentation::tests::prepared_query_counters_charge_only_declared_output"],"missing_expected":[],"rc":101}, + {"name":"drop included scalar intersections","verdict":"caught","detail":"","failed":["documentation::render_probe::tests::valid_preparation_borrows_adjacent_range_intersections"],"missing_expected":[],"rc":101}, + {"name":"skip tiny render entry cancellation","verdict":"caught","detail":"","failed":["documentation::render_probe::tests::tiny_and_empty_render_poll_cancellation_at_entry"],"missing_expected":[],"rc":101}, + {"name":"skip render identity validation","verdict":"caught","detail":"","failed":["documentation::render_probe::tests::preparation_rejects_foreign_and_pending_documents"],"missing_expected":[],"rc":101}, + {"name":"scan all associations","verdict":"caught","detail":"","failed":["documentation::tests::prepared_query_counters_charge_only_declared_output"],"missing_expected":[],"rc":101}, + {"name":"scan all qualifications","verdict":"caught","detail":"","failed":["documentation::tests::prepared_query_counters_charge_only_declared_output"],"missing_expected":[],"rc":101} + ] + }, + { + "manifest": "documentation-audit.json", + "results": [ + {"name":"evidence pair repeats retention off","verdict":"caught","detail":"","failed":["documentation::tests::evidence_pair_executes_both_off_and_on_collections"],"missing_expected":[],"rc":101}, + {"name":"evidence pair repeats retention on","verdict":"caught","detail":"","failed":["documentation::tests::evidence_pair_executes_both_off_and_on_collections"],"missing_expected":[],"rc":101}, + {"name":"compare raw batch medians instead of per-operation times","verdict":"caught","detail":"","failed":["documentation::runner::tests::median_uses_complete_scheduled_batches_without_rounding","documentation::runner::tests::ratios_compare_per_operation_times_when_iterations_differ","documentation::runner::tests::ratios_keep_subnanosecond_values_and_report_performance_failure"],"missing_expected":[],"rc":101} + ] + }, + { + "manifest": "documentation-remediation.json", + "results": [ + {"name":"truncate measured repetitions to one","verdict":"caught","detail":"","failed":["documentation::runner::tests::batch_executes_every_requested_repetition","documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts"],"missing_expected":[],"rc":101}, + {"name":"scheduler ignores frozen count metadata","verdict":"caught","detail":"","failed":["documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts"],"missing_expected":[],"rc":101}, + {"name":"scan all name entries only after an indexed miss","verdict":"caught","detail":"","failed":["documentation::names::miss_tests::absent_bucket_miss_never_compares_unrelated_names","documentation::names::miss_tests::collision_bucket_miss_compares_only_its_nonmatching_spellings"],"missing_expected":[],"rc":101}, + {"name":"initial workflow run implicitly selects all","verdict":"caught","detail":"","failed":["documentation::workflow_tests::inherited_workflow_retries_only_legacy_and_preserves_harness_errors"],"missing_expected":[],"rc":101}, + {"name":"workflow confirmation implicitly selects all","verdict":"caught","detail":"","failed":["documentation::workflow_tests::inherited_workflow_retries_only_legacy_and_preserves_harness_errors"],"missing_expected":[],"rc":101}, + {"name":"suppress typed trailing failure rows","verdict":"caught","detail":"","failed":["documentation::combined::tests::failure_tail_reports_when_the_excerpt_omits_rows","documentation::combined::tests::final_failure_tail_identifies_early_failures_and_each_statistic","documentation::combined::tests::final_summary_distinguishes_all_pass_and_non_gating_output"],"missing_expected":[],"rc":101}, + {"name":"bypass new exact structural attachment validation","verdict":"caught","detail":"","failed":["documentation::tests::recovery_and_conditional_semantics_reject_shape_preserving_substitutions"],"missing_expected":[],"rc":101}, + {"name":"workflow reproduction implicitly selects all","verdict":"caught","detail":"","failed":["documentation::workflow_tests::workflow_reproduction_command_selects_the_confirmation_scope"],"missing_expected":[],"rc":101}, + {"name":"suppress source trailing failure detail","verdict":"caught","detail":"","failed":["documentation::combined::tests::final_failure_tail_identifies_early_failures_and_each_statistic"],"missing_expected":[],"rc":101} + ] + } + ] +} From 2c98909c79678260d12691fe8901e794c5eef255 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:57:27 -0800 Subject: [PATCH 056/221] fix(fuzz): discriminate documentation identity modes and repeat fields --- docs/development/fuzzing.md | 30 +- fuzz/check_documentation_producers.py | 177 +++++++ fuzz/documentation-perturb.json | 56 +++ fuzz/src/documentation/identity.rs | 56 +++ fuzz/src/documentation/mod.rs | 38 +- fuzz/src/documentation/observation.rs | 107 +++++ fuzz/src/documentation/properties.rs | 126 +++-- fuzz/src/documentation/repeat.rs | 93 ++++ fuzz/src/documentation/tests.rs | 38 +- fuzz/src/documentation/tests/remediation.rs | 490 ++++++++++++++++++++ 10 files changed, 1156 insertions(+), 55 deletions(-) create mode 100644 fuzz/check_documentation_producers.py create mode 100644 fuzz/src/documentation/identity.rs create mode 100644 fuzz/src/documentation/observation.rs create mode 100644 fuzz/src/documentation/repeat.rs create mode 100644 fuzz/src/documentation/tests/remediation.rs diff --git a/docs/development/fuzzing.md b/docs/development/fuzzing.md index 5aaea8f6c..230bdcd4b 100644 --- a/docs/development/fuzzing.md +++ b/docs/development/fuzzing.md @@ -326,6 +326,20 @@ alongside known associations; candidate and reference qualifications retain their distinct identities and reasons. Cross-index handles and noncanonical nodes must return the documented identity errors. +Candidate qualifications linked to Node/File owners validate the owner's full +`NodeEvidence`. Reference qualifications use document identity and `node.id()` to find +fragment evidence, then validate the full node context. The checker never hashes a +tree-sitter node or scans every fragment for each qualification. Building this index +costs expected linear work in document-fragment memberships and qualifications, plus +the actual comparisons within buckets whose node IDs coincide. Slot, Group, and Virtual +owners retain link/source checks; their exact candidate-node relationship is not yet +established by the supported adapters. + +Repeat checking compares borrowed public fields and linked record identities, including +optional node evidence, slot roles and enclosure, association binding/scope, source-cleaned +maps, context, and options. These are API-consistency checks. The registered seeds separately +assert independent semantic outcomes, including ambiguous/conditional resolutions and field slots. + Every complete document gets one map validation. Runs must cover its output; copied origins match source bytes, transformed queries retain all responsible token pieces, and synthetic output has no source. Stored runs may divide a @@ -344,12 +358,16 @@ The resource limits are harness policy: Ordinary walk targets skip only documentation and continue their other checks. Neither path truncates source. - Perform at most two ordinary collections over the same parse. -- Select at most eight owner/node positions and eight map ranges per input, - including late positions. +- Select at most eight owner/node subjects and eight map ranges per input, including late + positions. Cross-checking the selected subjects uses up to 20 ordinary owner/node API calls. + Explicit identity modes add three rejection queries; cross-index handle checks are separate. - Limit structured included-range inputs to 256 ranges. Each non-NUL payload byte becomes one included range, so adjacent ranges can divide a scalar. NUL bytes create excluded gaps. Zero included bytes, including empty and all-NUL payloads, or more than 256 ranges skip the input. Parsing uses the original payload once. +- Retain the existing `nested_depth` generator's 512-construct limit. The documentation + operation accepts its generated source when it fits the 32 KiB cap; the 256 limit applies + to newly constructed included ranges, not inherited nesting. The checker makes linear or output-proportional passes and uses expected constant-time hash indexing. Its included-byte prefix table costs linear @@ -366,6 +384,14 @@ restoration, and an uncancelled flag. A tiny empty root is never evidence that the parse callback aborted. Large phase-budget cancellation tests remain in the AST crate; the fuzz target does not expose private phase hooks. +Tests pin every low mode-byte combination independently and record actual parse, collection, +repeat, identity, and query operations in a bounded thread-local recorder. The active-scope +test first finishes normal collection, then cancels the same installed flag and requires raw +collection to return `Cancelled` at entry. This test-only witness creates no additional +successful index and performs no extra call in a fuzz campaign. Recorder scopes restore on +success, rejection, and unwind. Removing scope installation must fail the witness's result +assertion, not just an operation count. + Run the finite documentation validation sequence one heavy operation at a time: ```bash diff --git a/fuzz/check_documentation_producers.py b/fuzz/check_documentation_producers.py new file mode 100644 index 000000000..971833ebb --- /dev/null +++ b/fuzz/check_documentation_producers.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Verify bounded documentation producer perturbations and restore exact source. + +Run from the repository root with --out pointing to an owned evidence directory. +The AST substitutions are temporary verification inputs, never shipped changes. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import subprocess + + +def cases(): + """Return unique producer anchors and independently expected rejection sites.""" + qualification = ( + "big-code-analysis-ast/src/documentation/collector/qualifications.rs" + ) + collector = "big-code-analysis-ast/src/documentation/collector.rs" + root = "self.index.canonical.nodes[0].evidence" + yield ( + "candidate-root", + qualification, + "let node = self.index.canonical.nodes[self.index.owner_nodes[candidate.owner.0].0].evidence;", + f"let node = {root};", + "qualification candidate evidence differs from owner", + ) + yield ( + "reference-root", + qualification, + " subject: QualificationSubject::Reference,\n reason,\n node,", + f" subject: QualificationSubject::Reference,\n reason,\n node: {root},", + "qualification reference evidence is not a document fragment", + ) + for name, reason in [ + ("candidate-resolution", "Ambiguous"), + ("reference-resolution", "Conditional"), + ]: + yield ( + name, + collector, + " Ok(builder.index)\n}", + " for association in &mut builder.index.facts.associations {\n" + f" if association.resolution == Resolution::Unresolved(UnresolvedReason::{reason}) {{\n" + " association.resolution = Resolution::Resolved;\n }\n }\n Ok(builder.index)\n}", + "seed association resolution", + ) + changes = { + "repeat-slot": "for owner in &mut builder.index.facts.owners { if let Owner::Slot(slot) = owner { slot.role = SlotRole::Binding; } }", + "repeat-binding": "for association in &mut builder.index.facts.associations { association.binding = Some(builder.index.canonical.nodes[0].evidence); }", + "repeat-scope": "for association in &mut builder.index.facts.associations { let mut node = association.lexical_scope.node(); node.edit(&tree_sitter::InputEdit { start_byte: 0, old_end_byte: 0, new_end_byte: 1, start_position: tree_sitter::Point::new(0, 0), old_end_position: tree_sitter::Point::new(0, 0), new_end_position: tree_sitter::Point::new(0, 1) }); association.lexical_scope = builder.index.source.node(node)?; }", + } + for name, change in changes.items(): + replacement = ( + " thread_local! { static CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; }\n" + " let second = CALLS.with(|calls| { let n = calls.get() + 1; calls.set(n); n == 2 });\n" + f" if second {{ {change} }}\n Ok(builder.index)\n}}" + ) + yield ( + name, + collector, + " Ok(builder.index)\n}", + replacement, + "nondeterministic slot fields" + if name == "repeat-slot" + else "nondeterministic node evidence", + ) + + +def run(out, name, test, mutation): + """Rebuild and run one exact guard; retain complete output and return status.""" + command = [ + "cargo", + "+nightly", + "test", + "--manifest-path", + "fuzz/Cargo.toml", + "--locked", + "--lib", + test, + "--", + "--exact", + "--nocapture", + ] + env = os.environ.copy() + env.pop("BCA_FUZZ_PRODUCER_CASE", None) + if mutation: + env["BCA_FUZZ_PRODUCER_CASE"] = mutation + result = subprocess.run( + command, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + output = result.stdout.decode(errors="replace") + (out / f"{name}.log").write_bytes(result.stdout) + if "error[E" in output or "could not compile" in output: + raise RuntimeError(f"{name}: compilation failure is not a catch") + return { + "command": command, + "mutation_env": mutation, + "exit": result.returncode, + }, output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + out = args.out.resolve() + out.mkdir(parents=True, exist_ok=True) + if subprocess.check_output(["git", "status", "--porcelain"]): + raise SystemExit("producer verification requires a clean tracked checkpoint") + head = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip() + prefix = "documentation::tests::remediation::" + records = [] + for name, filename, old, new, message in cases(): + path = Path(filename) + subprocess.run( + ["git", "ls-files", "--error-unmatch", filename], + check=True, + stdout=subprocess.DEVNULL, + ) + original = path.read_bytes() + assert old != new and original.count(old.encode()) == 1, name + (out / f"{name}.original").write_bytes(original) + test = prefix + ( + "producer_second_collection_repeat_control" + if name.startswith("repeat-") + else "producer_qualification_runtime_and_registry_controls" + ) + baseline, text = run(out, name + "-setup", test, None) + assert baseline["exit"] == 0 and "1 passed" in text, (name, "invalid setup") + try: + path.write_bytes(original.replace(old.encode(), new.encode())) + controlled, text = run(out, name + "-controlled", test, name) + assert controlled["exit"] == 0 and "1 passed" in text, ( + name, + "wrong controlled outcome", + ) + ordinary_test = ( + test + if name.startswith("repeat-") + else "documentation::tests::registry_executes_every_dispatch_and_edge_assertion" + ) + ordinary, text = run(out, name + "-ordinary", ordinary_test, None) + assert ( + ordinary["exit"] == 101 + and message in text + and f"{ordinary_test} ... FAILED" in text + ), (name, "wrong ordinary failure") + records.append( + { + "name": name, + "revision": head, + "baseline": baseline, + "controlled": controlled, + "ordinary": ordinary, + "rejection": message, + "original_sha256": hashlib.sha256(original).hexdigest(), + } + ) + finally: + path.write_bytes(original) + assert path.read_bytes() == original + (out / "results.json").write_text(json.dumps(records, indent=2) + "\n") + print( + f"{name}: controlled rejection verified; ordinary guard failed at {message}", + flush=True, + ) + assert not subprocess.check_output(["git", "status", "--porcelain"]) + assert ( + subprocess.check_output(["git", "rev-parse", "HEAD"]).decode().strip() == head + ) + + +if __name__ == "__main__": + main() diff --git a/fuzz/documentation-perturb.json b/fuzz/documentation-perturb.json index 8dbcd2163..c02edf0ce 100644 --- a/fuzz/documentation-perturb.json +++ b/fuzz/documentation-perturb.json @@ -43,6 +43,62 @@ "old": "&& index.assessed_document(a).unwrap() == Some(local))", "new": "&& index.assessed_document(a).unwrap() == index.documents().next())", "expect": ["documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] + }, + { + "name": "decode-without-repeat", + "file": "fuzz/src/documentation/header.rs", + "old": "repeat: mode & 1 != 0,", + "new": "repeat: false,", + "expect": ["documentation::tests::remediation::decoder_mode_table_is_independent", "documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "decode-without-identity", + "file": "fuzz/src/documentation/header.rs", + "old": "identity: mode & 2 != 0,", + "new": "identity: false,", + "expect": ["documentation::tests::remediation::decoder_mode_table_is_independent", "documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "decode-cancel-as-raw", + "file": "fuzz/src/documentation/header.rs", + "old": "2 => Mode::CancelledScope,", + "new": "2 => Mode::Raw,", + "expect": ["documentation::tests::remediation::decoder_mode_table_is_independent", "documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "decode-active-as-raw", + "file": "fuzz/src/documentation/header.rs", + "old": "_ => Mode::ActiveScope,", + "new": "_ => Mode::Raw,", + "expect": ["documentation::tests::remediation::decoder_mode_table_is_independent", "documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "bypass-repeat-operation", + "file": "fuzz/src/documentation/mod.rs", + "old": "if repeat {", + "new": "if repeat && false {", + "expect": ["documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "bypass-identity-operation", + "file": "fuzz/src/documentation/mod.rs", + "old": "if identity {", + "new": "if identity && false {", + "expect": ["documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "bypass-cancel-operation", + "file": "fuzz/src/documentation/mod.rs", + "old": "if input.mode == Mode::CancelledScope {", + "new": "if input.mode == Mode::CancelledScope && false {", + "expect": ["documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "remove-active-scope-installation", + "file": "fuzz/src/documentation/mod.rs", + "old": "flag.run(|| {\n let outcome = check()?;\n #[cfg(test)]\n observation::active_witness(&flag, &parsed, input.options)?;\n Ok(outcome)\n })", + "new": "{\n let outcome = check()?;\n #[cfg(test)]\n observation::active_witness(&flag, &parsed, input.options)?;\n Ok(outcome)\n }", + "expect": ["documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] } ] } diff --git a/fuzz/src/documentation/identity.rs b/fuzz/src/documentation/identity.rs new file mode 100644 index 000000000..4ac62d5e1 --- /dev/null +++ b/fuzz/src/documentation/identity.rs @@ -0,0 +1,56 @@ +use std::collections::HashMap; + +use big_code_analysis_ast::documentation::{Document, FactRef, NodeEvidence, Owner}; + +use super::{Check, require}; + +pub(super) fn address(fact: FactRef<'_, T>) -> *const T { + std::ptr::from_ref(fact.get()) +} + +pub(super) fn evidence(left: Option>, right: Option>) -> Check { + match (left, right) { + (Some(left), Some(right)) => left + .validate(right.node()) + .map_err(|_| "nondeterministic node evidence"), + (None, None) => Ok(()), + _ => Err("nondeterministic optional evidence"), + } +} + +#[derive(Default)] +pub(super) struct References<'s> { + candidates: HashMap<(*const Document<'s>, usize), Vec>>, +} + +impl<'s> References<'s> { + pub fn insert(&mut self, document: FactRef<'_, Document<'s>>, node: NodeEvidence<'s>) { + self.candidates + .entry((address(document), node.node().id())) + .or_default() + .push(node); + } + + pub fn validate(&self, document: FactRef<'_, Document<'s>>, node: NodeEvidence<'_>) -> Check { + require( + self.candidates + .get(&(address(document), node.node().id())) + .is_some_and(|candidates| { + candidates + .iter() + .any(|candidate| candidate.validate(node.node()).is_ok()) + }), + "qualification reference evidence is not a document fragment", + ) + } +} + +pub(super) fn candidate(owner: &Owner<'_>, node: NodeEvidence<'_>) -> Check { + match owner { + Owner::Node(owner) | Owner::File(owner) => owner + .validate(node.node()) + .map_err(|_| "qualification candidate evidence differs from owner"), + Owner::Slot(_) | Owner::Group(_) | Owner::Virtual(_) => Ok(()), + _ => Err("unhandled candidate owner variant"), + } +} diff --git a/fuzz/src/documentation/mod.rs b/fuzz/src/documentation/mod.rs index 3a49e841e..2e56952d0 100644 --- a/fuzz/src/documentation/mod.rs +++ b/fuzz/src/documentation/mod.rs @@ -1,8 +1,11 @@ //! Bounded source-documentation properties shared by raw and tagged targets. mod header; +mod identity; mod maps; +mod observation; mod properties; +mod repeat; #[cfg(test)] mod tests; @@ -16,6 +19,7 @@ use big_code_analysis_ast::{ }, }; use header::{Input, Mode, expected_profile}; +use observation::Event; /// Maximum exact source length inspected by the additional documentation operation. pub const MAX_SOURCE: usize = 32 * 1024; @@ -67,11 +71,15 @@ impl<'s> Parsed<'s> { options: DocumentationOptions, ) -> Result, CollectionError> { let context = DocumentationContext::default(); - if let Some(parser) = self.typed { + let result = if let Some(parser) = self.typed { parser.documentation(&context, &options) } else { collect(self.language, self.tree, self.source, &context, &options) - } + }; + observation::record(Event::Collection( + result.as_ref().map(|_| ()).map_err(|error| *error), + )); + result } } @@ -139,6 +147,7 @@ fn exercise_with( let tree = parser .parse(input.source, None) .ok_or("included parse aborted")?; + observation::record(Event::IncludedParse(tree.included_ranges().len())); return check_parse( &Parsed { language: input.language, @@ -154,14 +163,20 @@ fn exercise_with( } let parser = AnyParser::parse(input.language, input.source.to_vec(), None, None) .map_err(|_| "primary parse failed")?; + observation::record(Event::Parse); require(parser.code() == input.source, "tag payload changed")?; - let context = DocumentationContext::default(); + let parsed = Parsed { + language: input.language, + tree: parser.ts_tree(), + source: parser.code(), + typed: Some(&parser), + }; if input.mode == Mode::CancelledScope { let flag = ParseCancel::new(); flag.cancel(); require( matches!( - flag.run(|| parser.documentation(&context, &input.options)), + flag.run(|| parsed.collect(input.options)), Err(CollectionError::Cancelled) ), "active cancellation not propagated", @@ -169,12 +184,7 @@ fn exercise_with( } let check = || { check_parse( - &Parsed { - language: input.language, - tree: parser.ts_tree(), - source: parser.code(), - typed: Some(&parser), - }, + &parsed, input.options, input.repeat, input.identity, @@ -182,7 +192,13 @@ fn exercise_with( ) }; if input.mode == Mode::ActiveScope { - ParseCancel::new().run(check) + let flag = ParseCancel::new(); + flag.run(|| { + let outcome = check()?; + #[cfg(test)] + observation::active_witness(&flag, &parsed, input.options)?; + Ok(outcome) + }) } else { check() } diff --git a/fuzz/src/documentation/observation.rs b/fuzz/src/documentation/observation.rs new file mode 100644 index 000000000..5141d03be --- /dev/null +++ b/fuzz/src/documentation/observation.rs @@ -0,0 +1,107 @@ +#[cfg(test)] +use super::{Check, Parsed}; +use big_code_analysis_ast::documentation::CollectionError; +#[cfg(test)] +use big_code_analysis_ast::{ + cancel::ParseCancel, + documentation::{DocumentationContext, DocumentationOptions, collect}, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Event { + Parse, + IncludedParse(usize), + Collection(Result<(), CollectionError>), + Repeat, + CloneRejected, + ShiftRejected, + EditRejected, + #[cfg(test)] + ActiveWitness, + OwnerQuery, + NodeProjection, + NodeOwners, + NodeAssociations, +} + +#[cfg(test)] +thread_local! { + static RECORDING: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +#[cfg(test)] +struct Recording { + events: [Option; 64], + length: usize, +} + +pub(super) fn record(event: Event) { + #[cfg(test)] + RECORDING.with_borrow_mut(|recording| { + if let Some(recording) = recording { + assert!( + recording.length < recording.events.len(), + "bounded operation recorder overflow" + ); + recording.events[recording.length] = Some(event); + recording.length += 1; + } + }); + #[cfg(not(test))] + let _ = event; +} + +pub(super) fn observed(event: Event, result: T) -> T { + record(event); + result +} + +#[cfg(test)] +pub(super) fn active_witness( + flag: &ParseCancel, + parsed: &Parsed<'_>, + options: DocumentationOptions, +) -> Check { + if RECORDING.with_borrow(Option::is_some) { + flag.cancel(); + let result = collect( + parsed.language, + parsed.tree, + parsed.source, + &DocumentationContext::default(), + &options, + ); + super::require( + result.err() == Some(CollectionError::Cancelled), + "active scope installation witness", + )?; + record(Event::ActiveWitness); + } + Ok(()) +} + +#[cfg(test)] +pub(super) fn capture(action: impl FnOnce() -> T) -> (T, Vec) { + struct Restore(Option); + impl Drop for Restore { + fn drop(&mut self) { + RECORDING.with_borrow_mut(|current| *current = self.0.take()); + } + } + let previous = RECORDING.with_borrow_mut(|current| { + current.replace(Recording { + events: [None; 64], + length: 0, + }) + }); + let _restore = Restore(previous); + let result = action(); + let events = RECORDING.with_borrow(|current| { + let current = current.as_ref().unwrap(); + current.events[..current.length] + .iter() + .map(|event| event.unwrap()) + .collect() + }); + (result, events) +} diff --git a/fuzz/src/documentation/properties.rs b/fuzz/src/documentation/properties.rs index f0179e0b8..e9b02a73e 100644 --- a/fuzz/src/documentation/properties.rs +++ b/fuzz/src/documentation/properties.rs @@ -1,14 +1,15 @@ use big_code_analysis_ast::documentation::{ - Content, DocumentationIndex, FactError, FactRef, NodeEvidence, Owner, OwnerError, - QualificationSubject, SourceError, UnresolvedReason, + Content, DocumentationIndex, FactError, Owner, OwnerError, QualificationSubject, SourceError, + UnresolvedReason, }; use std::collections::HashMap; -use super::{Check, MAX_QUERIES, maps, require}; - -fn address(fact: FactRef<'_, T>) -> *const T { - std::ptr::from_ref(fact.get()) -} +use super::observation::{self, Event, observed}; +use super::{ + Check, MAX_QUERIES, + identity::{self, References, address}, + maps, repeat as comparison, require, +}; fn selected(length: usize, count: usize, selector: u8) -> Vec { if length == 0 { @@ -46,6 +47,7 @@ pub(super) fn check( } let mut last = None; let mut mapped = None; + let mut references = References::default(); for document in index.documents() { let key = index .facts() @@ -67,6 +69,9 @@ pub(super) fn check( .document_fragment(document, at) .map_err(|_| "document fragment navigation")?; let pieces = fragment.get().source().pieces(); + if let Some(node) = fragment.get().node() { + references.insert(document, node); + } require( pieces .first() @@ -132,7 +137,7 @@ pub(super) fn check( } } associations(index)?; - qualifications(index)?; + qualifications(index, &references)?; for assessment in index.assessments() { require( !assessment.get().reason.is_empty(), @@ -210,7 +215,7 @@ fn associations(index: &DocumentationIndex<'_>) -> Check { Ok(()) } -fn qualifications(index: &DocumentationIndex<'_>) -> Check { +fn qualifications<'s>(index: &DocumentationIndex<'s>, references: &References<'s>) -> Check { let mut by_document: HashMap<_, Vec<_>> = HashMap::new(); let mut last = None; for qualification in index.qualifications() { @@ -225,6 +230,11 @@ fn qualifications(index: &DocumentationIndex<'_>) -> Check { owner.is_some() == (fact.subject == QualificationSubject::Candidate), "qualification subject identity", )?; + if let Some(owner) = owner { + identity::candidate(owner.get(), fact.node)?; + } else { + references.validate(document, fact.node)?; + } let rank = match fact.reason { UnresolvedReason::Conditional => 0, UnresolvedReason::GrammarBoundary => 1, @@ -269,8 +279,7 @@ fn owner_queries(index: &DocumentationIndex<'_>, selector: u8) -> Check { let owners: Vec<_> = index.facts().owners().collect(); for at in selected(owners.len(), MAX_QUERIES / 2, selector) { let owner = owners[at]; - let query = index - .owner_associations(owner) + let query = observed(Event::OwnerQuery, index.owner_associations(owner)) .map_err(|_| "same-index owner rejected")?; let mut expected = Vec::new(); for association in index.associations() { @@ -342,17 +351,20 @@ fn selected_nodes( ) -> Check { for at in selected(nodes.len(), MAX_QUERIES / 2, selector) { let node = nodes[at]; - match index.node_projection(node) { + match observed(Event::NodeProjection, index.node_projection(node)) { Err(OwnerError::UnsupportedOwner) => { require( matches!( - index.node_associations(node), + observed(Event::NodeAssociations, index.node_associations(node)), Err(OwnerError::UnsupportedOwner) ), "unsupported projection query", )?; require( - matches!(index.node_owners(node), Err(OwnerError::UnsupportedOwner)), + matches!( + observed(Event::NodeOwners, index.node_owners(node)), + Err(OwnerError::UnsupportedOwner) + ), "unsupported owners query", )?; } @@ -362,11 +374,13 @@ fn selected_nodes( "pending projection lost assessment", )?; require( - matches!(index.node_owners(node), Err(OwnerError::PendingOwner)), + matches!( + observed(Event::NodeOwners, index.node_owners(node)), + Err(OwnerError::PendingOwner) + ), "pending owners query", )?; - let query = index - .node_associations(node) + let query = observed(Event::NodeAssociations, index.node_associations(node)) .map_err(|_| "pending query must remain inspectable")?; require( query.projection_pending() && query.assessments().next().is_some(), @@ -376,8 +390,7 @@ fn selected_nodes( Ok(projection) => { let owners: Vec<_> = projection.owners().collect(); require( - index - .node_owners(node) + observed(Event::NodeOwners, index.node_owners(node)) .map_err(|_| "known projection owners")? .eq(owners.iter().copied()), "projection owner enumeration", @@ -385,18 +398,18 @@ fn selected_nodes( match owners.len() { 0 => require( matches!( - index.node_associations(node), + observed(Event::NodeAssociations, index.node_associations(node)), Err(OwnerError::UnsupportedOwner) ), "empty projection query", )?, 1 => { - let query = index - .node_associations(node) - .map_err(|_| "known node query")?; - let expected = index - .owner_associations(owners[0]) - .map_err(|_| "known owner query")?; + let query = + observed(Event::NodeAssociations, index.node_associations(node)) + .map_err(|_| "known node query")?; + let expected = + observed(Event::OwnerQuery, index.owner_associations(owners[0])) + .map_err(|_| "known owner query")?; require( query.associations().eq(expected.associations()), "node-owner association agreement", @@ -412,7 +425,7 @@ fn selected_nodes( } _ => require( matches!( - index.node_associations(node), + observed(Event::NodeAssociations, index.node_associations(node)), Err(OwnerError::MultipleOwners) ), "multi-owner projection query", @@ -434,6 +447,7 @@ pub(super) fn negative_nodes(index: &DocumentationIndex<'_>, tree: &tree_sitter: ), "cloned tree accepted", )?; + observation::record(Event::CloneRejected); let shifted = tree.root_node_with_offset(1, tree_sitter::Point::new(0, 1)); require( matches!( @@ -442,6 +456,7 @@ pub(super) fn negative_nodes(index: &DocumentationIndex<'_>, tree: &tree_sitter: ), "shifted node accepted", )?; + observation::record(Event::ShiftRejected); let mut edited = tree.root_node(); edited.edit(&tree_sitter::InputEdit { start_byte: 0, @@ -457,11 +472,25 @@ pub(super) fn negative_nodes(index: &DocumentationIndex<'_>, tree: &tree_sitter: Err(OwnerError::Source(SourceError::NoncanonicalNode)) ), "edited node accepted", - ) + )?; + observation::record(Event::EditRejected); + Ok(()) } #[allow(clippy::too_many_lines)] // Compare each public record family in observed order. pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationIndex<'s>) -> Check { + let a = first.options(); + let b = second.options(); + require( + first.source() == second.source() + && first.profile() == second.profile() + && first.capability() == second.capability() + && first.context().logical_filename == second.context().logical_filename + && a.profile == b.profile + && a.retain_unbound == b.retain_unbound + && a.retain_directives == b.retain_directives, + "nondeterministic index context/options", + )?; require( first.documents().len() == second.documents().len() && first.associations().len() == second.associations().len() @@ -473,6 +502,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI "nondeterministic record count", )?; for (left, right) in first.facts().fragments().zip(second.facts().fragments()) { + identity::evidence(left.get().node(), right.get().node())?; require( left.get().source() == right.get().source() && left.get().form() == right.get().form(), "nondeterministic retained fragments", @@ -490,13 +520,11 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI .enumerate() .map(|(at, owner)| (address(owner), at)) .collect(); - for (left, right) in first.facts().owners().zip(second.facts().owners()) { - require( - std::mem::discriminant(left.get()) == std::mem::discriminant(right.get()) - && owner_anchor(left.get()) == owner_anchor(right.get()), - "nondeterministic owners", - )?; - } + comparison::owners(first, second, &first_owners, &second_owners)?; + let first_documents = comparison::ordinals(first.documents()); + let second_documents = comparison::ordinals(second.documents()); + let first_fragments = comparison::ordinals(first.facts().fragments()); + let second_fragments = comparison::ordinals(second.facts().fragments()); for (left, right) in first.documents().zip(second.documents()) { require( first @@ -511,6 +539,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI )?; require( left.get().composition() == right.get().composition() + && left.get().role() == right.get().role() && left.get().fragment_count() == right.get().fragment_count(), "nondeterministic composition", )?; @@ -523,6 +552,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI .facts() .document_fragment(right, at) .map_err(|_| "second fragment")?; + comparison::corresponding(a, b, &first_fragments, &second_fragments)?; require( a.get().source() == b.get().source() && a.get().form() == b.get().form(), "nondeterministic fragments", @@ -549,14 +579,28 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI "nondeterministic content state", )?, } + comparison::complete( + first + .source_cleaned_text(left) + .map_err(|_| "first cleaned text")?, + second + .source_cleaned_text(right) + .map_err(|_| "second cleaned text")?, + )?; require( second.complete_text(left).err() == Some(FactError::ForeignIndex), "foreign document accepted", )?; } for (left, right) in first.associations().zip(second.associations()) { + identity::evidence(left.get().binding, right.get().binding)?; + identity::evidence( + Some(left.get().lexical_scope), + Some(right.get().lexical_scope), + )?; require( left.get().resolution == right.get().resolution + && left.get().convention == right.get().convention && left.get().publication == right.get().publication && left.get().owner_count() == right.get().owner_count(), "nondeterministic association", @@ -569,6 +613,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI .facts() .associated_document(right) .map_err(|_| "second associated document")?; + comparison::corresponding(a, b, &first_documents, &second_documents)?; require( first .facts() @@ -603,9 +648,10 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI let a = left.get(); let b = right.get(); require( - a.subject == b.subject && a.reason == b.reason && a.node.node() == b.node.node(), + a.subject == b.subject && a.reason == b.reason, "nondeterministic qualifications", )?; + identity::evidence(Some(a.node), Some(b.node))?; let a = first .qualified_owner(left) .map_err(|_| "first qualified owner")? @@ -621,6 +667,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI let b = second .qualified_document(right) .map_err(|_| "second qualified document")?; + comparison::corresponding(a, b, &first_documents, &second_documents)?; require( first .facts() @@ -637,11 +684,10 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI let a = left.get(); let b = right.get(); require( - a.axis == b.axis - && a.reason == b.reason - && a.node.map(NodeEvidence::node) == b.node.map(NodeEvidence::node), + a.axis == b.axis && a.reason == b.reason, "nondeterministic assessments", )?; + identity::evidence(a.node, b.node)?; let a = first .assessed_document(left) .map_err(|_| "first assessed document")? @@ -667,6 +713,7 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI let b = second .evidence_fragment(right) .map_err(|_| "second evidence fragment")?; + comparison::corresponding(a, b, &first_fragments, &second_fragments)?; require( a.get().source() == b.get().source(), "nondeterministic evidence source", @@ -699,5 +746,6 @@ pub(super) fn repeat<'s>(first: &DocumentationIndex<'s>, second: &DocumentationI "foreign candidate evidence accepted", )?; } + observation::record(Event::Repeat); Ok(()) } diff --git a/fuzz/src/documentation/repeat.rs b/fuzz/src/documentation/repeat.rs new file mode 100644 index 000000000..a3fa40795 --- /dev/null +++ b/fuzz/src/documentation/repeat.rs @@ -0,0 +1,93 @@ +use std::collections::HashMap; + +use big_code_analysis_ast::documentation::{CompleteText, DocumentationIndex, FactRef, Owner}; + +use super::{ + Check, + identity::{address, evidence}, + require, +}; + +pub(super) fn ordinals<'i, T: 'i>( + facts: impl Iterator>, +) -> HashMap<*const T, usize> { + facts + .enumerate() + .map(|(at, fact)| (address(fact), at)) + .collect() +} + +pub(super) fn corresponding( + left: FactRef<'_, T>, + right: FactRef<'_, T>, + a: &HashMap<*const T, usize>, + b: &HashMap<*const T, usize>, +) -> Check { + let left = a.get(&address(left)).ok_or("first unenumerated record")?; + let right = b.get(&address(right)).ok_or("second unenumerated record")?; + require(left == right, "nondeterministic linked identity") +} + +pub(super) fn complete( + left: Option>, + right: Option>, +) -> Check { + match (left, right) { + (Some(left), Some(right)) => require( + left.text() == right.text() && left.mappings() == right.mappings(), + "nondeterministic source-cleaned text", + ), + (None, None) => Ok(()), + _ => Err("nondeterministic source-cleaned availability"), + } +} + +pub(super) fn owners<'s>( + first: &DocumentationIndex<'s>, + second: &DocumentationIndex<'s>, + a: &HashMap<*const Owner<'s>, usize>, + b: &HashMap<*const Owner<'s>, usize>, +) -> Check { + for (left, right) in first.facts().owners().zip(second.facts().owners()) { + match (left.get(), right.get()) { + (Owner::Node(a), Owner::Node(b)) | (Owner::File(a), Owner::File(b)) => { + evidence(Some(*a), Some(*b))?; + } + (Owner::Slot(x), Owner::Slot(y)) => { + require( + x.role == y.role && x.ordinal == y.ordinal && x.source == y.source, + "nondeterministic slot fields", + )?; + corresponding( + first + .facts() + .slot_enclosing(left) + .map_err(|_| "first slot enclosure")?, + second + .facts() + .slot_enclosing(right) + .map_err(|_| "second slot enclosure")?, + a, + b, + )?; + } + (Owner::Group(a), Owner::Group(b)) => { + evidence(Some(a.scope), Some(b.scope))?; + require( + a.pieces.len() == b.pieces.len(), + "nondeterministic group pieces", + )?; + for (a, b) in a.pieces.iter().zip(&b.pieces) { + require(a.source == b.source, "nondeterministic group source")?; + evidence(a.node, b.node)?; + } + } + (Owner::Virtual(a), Owner::Virtual(b)) => require( + a.name == b.name && a.declaration == b.declaration, + "nondeterministic virtual spelling", + )?, + _ => return Err("nondeterministic owner variant"), + } + } + Ok(()) +} diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index 60bb56ead..b068a5435 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -241,7 +241,20 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: } "shared" => { assert_eq!(index.documents().len(), 1); - assert_eq!(index.associations().next().unwrap().get().owner_count(), 2); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), 2); + for position in 0..2 { + let owner = index + .facts() + .associated_owner(association, position) + .unwrap(); + let Owner::Slot(slot) = owner.get() else { + panic!("shared Field slot") + }; + assert_eq!(slot.role, SlotRole::Field); + assert_eq!(slot.ordinal, position); + } assert_eq!(text(index).text(), "audit"); } "gathered" => { @@ -254,6 +267,15 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: assert_eq!(index.documents().len(), 1); assert_eq!(index.associations().len(), 1); let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(if candidate { + UnresolvedReason::Ambiguous + } else { + UnresolvedReason::Conditional + }), + "seed association resolution" + ); assert_eq!( association.get().owner_count(), if candidate { 2 } else { 1 } @@ -292,9 +314,17 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: if candidate { let owner = index.facts().associated_owner(association, 0).unwrap(); assert_eq!(index.qualified_owner(qualification).unwrap(), Some(owner)); - assert_eq!(&index.source()[node.byte_range()], b"void f(int x = );"); + assert_eq!( + &index.source()[node.byte_range()], + b"void f(int x = );", + "candidate source evidence" + ); } else { - assert_eq!(&index.source()[node.byte_range()], b"/**@fn f*/"); + assert_eq!( + &index.source()[node.byte_range()], + b"/**@fn f*/", + "reference source evidence" + ); } } } @@ -610,3 +640,5 @@ fn qualification_oracle_rejects_same_reasons_on_the_wrong_candidate() { }); assert_eq!(result, Ok(Outcome::Checked)); } + +mod remediation; diff --git a/fuzz/src/documentation/tests/remediation.rs b/fuzz/src/documentation/tests/remediation.rs new file mode 100644 index 000000000..43818cd24 --- /dev/null +++ b/fuzz/src/documentation/tests/remediation.rs @@ -0,0 +1,490 @@ +use super::*; +use crate::documentation::{ + identity, + observation::{self, Event}, + properties, +}; + +#[test] +fn decoder_mode_table_is_independent() { + use Mode::{ActiveScope, CancelledScope, IncludedRanges, Raw}; + let cases = [ + (0, Raw, false, false), + (1, Raw, true, false), + (2, Raw, false, true), + (3, Raw, true, true), + (4, IncludedRanges, false, false), + (5, IncludedRanges, true, false), + (6, IncludedRanges, false, true), + (7, IncludedRanges, true, true), + (8, CancelledScope, false, false), + (9, CancelledScope, true, false), + (10, CancelledScope, false, true), + (11, CancelledScope, true, true), + (12, ActiveScope, false, false), + (13, ActiveScope, true, false), + (14, ActiveScope, false, true), + (15, ActiveScope, true, true), + ]; + for (byte, mode, repeat, identity) in cases { + let bytes = [0, byte, 0x61, 0xff, b'\r']; + let input = Input::decode(&bytes).unwrap(); + assert_eq!( + (input.mode, input.repeat, input.identity), + (mode, repeat, identity) + ); + assert_eq!(input.options.profile, Profile::Rust); + assert!(input.options.retain_unbound && input.options.retain_directives); + assert_eq!(input.source, &[0xff, b'\r']); + } + for (bytes, profile, language) in [ + ([16, 0, 14], Profile::Rdoc, LANG::Ruby), + ([6, 0, 8], Profile::PhpDocumentor, LANG::Php), + ] { + assert_eq!( + exercise(&bytes), + Ok(Outcome::Rejected(CollectionError::AdapterUnavailable { + language, + profile + })) + ); + } +} + +fn operations(events: &[Event]) -> Vec { + let subjects = events + .iter() + .filter(|event| matches!(event, Event::NodeProjection)) + .count(); + let queries = events + .iter() + .filter(|event| { + matches!( + event, + Event::OwnerQuery + | Event::NodeProjection + | Event::NodeOwners + | Event::NodeAssociations + ) + }) + .count(); + assert!(subjects <= 4); + assert!(queries <= 20, "query ceiling: {events:?}"); + events + .iter() + .copied() + .filter(|event| { + !matches!( + event, + Event::OwnerQuery + | Event::NodeProjection + | Event::NodeOwners + | Event::NodeAssociations + ) + }) + .collect() +} + +#[test] +#[allow(clippy::too_many_lines)] // Explicit independent outcomes for all sixteen mode combinations. +fn mode_calls_and_active_scope_are_observed() { + use Event::{ + ActiveWitness, CloneRejected, Collection, EditRejected, IncludedParse, Parse, Repeat, + ShiftRejected, + }; + let success = Collection(Ok(())); + let cancelled = Collection(Err(CollectionError::Cancelled)); + let payload = b"///audit\nfn f() {}"; + let cases = [ + (0, vec![Parse, success]), + (1, vec![Parse, success, success, Repeat]), + ( + 2, + vec![Parse, success, CloneRejected, ShiftRejected, EditRejected], + ), + ( + 3, + vec![ + Parse, + success, + CloneRejected, + ShiftRejected, + EditRejected, + success, + Repeat, + ], + ), + (4, vec![IncludedParse(18), success]), + (5, vec![IncludedParse(18), success, success, Repeat]), + ( + 6, + vec![ + IncludedParse(18), + success, + CloneRejected, + ShiftRejected, + EditRejected, + ], + ), + ( + 7, + vec![ + IncludedParse(18), + success, + CloneRejected, + ShiftRejected, + EditRejected, + success, + Repeat, + ], + ), + (8, vec![Parse, cancelled, success]), + (9, vec![Parse, cancelled, success, success, Repeat]), + ( + 10, + vec![ + Parse, + cancelled, + success, + CloneRejected, + ShiftRejected, + EditRejected, + ], + ), + ( + 11, + vec![ + Parse, + cancelled, + success, + CloneRejected, + ShiftRejected, + EditRejected, + success, + Repeat, + ], + ), + (12, vec![Parse, success, ActiveWitness]), + (13, vec![Parse, success, success, Repeat, ActiveWitness]), + ( + 14, + vec![ + Parse, + success, + CloneRejected, + ShiftRejected, + EditRejected, + ActiveWitness, + ], + ), + ( + 15, + vec![ + Parse, + success, + CloneRejected, + ShiftRejected, + EditRejected, + success, + Repeat, + ActiveWitness, + ], + ), + ]; + for (mode, expected) in cases { + let bytes = [vec![0, mode, 0], payload.to_vec()].concat(); + let (result, events) = observation::capture(|| { + exercise_with(&bytes, |index, _| { + let index = index.unwrap(); + assert_eq!(text(index).text(), "audit"); + assert_eq!( + index.associations().next().unwrap().get().resolution, + Resolution::Resolved + ); + Ok(()) + }) + }); + assert_eq!(result, Ok(Outcome::Checked), "mode {mode}"); + assert_eq!(operations(&events), expected, "mode {mode}"); + assert_eq!( + exercise(b"\0\0\0///audit\nfn f() {}"), + Ok(Outcome::Checked), + "restoration after {mode}" + ); + } +} + +#[test] +fn observation_scope_restores_on_rejection_skip_and_unwind() { + for bytes in [&[25, 0, 0][..], &[0, 4, 0], &[0, 4, 0, 0]] { + let (result, events) = observation::capture(|| exercise(bytes)); + assert!(matches!(result, Ok(Outcome::Skipped(_)))); + assert!(events.is_empty()); + } + let (result, events) = observation::capture(|| exercise(&[1, 0, 0])); + let error = CollectionError::AdapterUnavailable { + language: LANG::Python, + profile: Profile::Python, + }; + assert_eq!(result, Ok(Outcome::Rejected(error))); + assert_eq!(events, [Event::Parse, Event::Collection(Err(error))]); + let ((), outer) = observation::capture(|| { + assert!( + std::panic::catch_unwind(|| observation::capture(|| panic!("recorder unwind control"))) + .is_err() + ); + exercise(&[1, 0, 0]).unwrap(); + }); + assert_eq!(outer, events); +} + +#[test] +fn evidence_validation_rejects_same_id_changed_context_and_wrong_document() { + let parser = AnyParser::parse( + LANG::Cpp, + b"/**one*/\nvoid f();\n/**two*/\nvoid g();".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let documents: Vec<_> = index.documents().collect(); + assert_eq!(documents.len(), 2); + let node = index + .facts() + .document_fragment(documents[0], 0) + .unwrap() + .get() + .node() + .unwrap(); + let mut references = identity::References::default(); + references.insert(documents[0], node); + assert_eq!(references.validate(documents[0], node), Ok(())); + assert_eq!( + references.validate(documents[1], node), + Err("qualification reference evidence is not a document fragment") + ); + let mut edited = node.node(); + edited.edit(&tree_sitter::InputEdit { + start_byte: 0, + old_end_byte: 0, + new_end_byte: 1, + start_position: tree_sitter::Point::new(0, 0), + old_end_position: tree_sitter::Point::new(0, 0), + new_end_position: tree_sitter::Point::new(0, 1), + }); + assert_eq!(node.node().id(), edited.id()); + let edited = SourceContext::new(parser.ts_tree(), parser.code()) + .node(edited) + .unwrap(); + let owner = Owner::Node(node); + assert_eq!(identity::candidate(&owner, node), Ok(())); + assert_eq!( + identity::candidate(&owner, edited), + Err("qualification candidate evidence differs from owner") + ); + let root = SourceContext::new(parser.ts_tree(), parser.code()) + .node(parser.ts_tree().root_node()) + .unwrap(); + assert_eq!( + identity::candidate(&owner, root), + Err("qualification candidate evidence differs from owner") + ); + assert_eq!(identity::candidate(&Owner::File(root), root), Ok(())); + assert_eq!( + references.validate(documents[0], edited), + Err("qualification reference evidence is not a document fragment") + ); + assert_eq!( + identity::evidence(Some(node), Some(edited)), + Err("nondeterministic node evidence") + ); + // The ID bucket must retain distinct contexts rather than overwrite one. + references.insert(documents[0], edited); + assert_eq!(references.validate(documents[0], node), Ok(())); + assert_eq!(references.validate(documents[0], edited), Ok(())); +} + +#[test] +fn inherited_512_construct_source_still_reaches_documentation() { + use arbitrary::{Arbitrary, Unstructured}; + let nesting = + crate::nested::Nesting::arbitrary(&mut Unstructured::new(&[0, 255, 1, 0])).unwrap(); + let source = nesting.render(); + assert_eq!(source.len(), 1050); + let ast = Ast::parse(big_code_analysis::Source::from_bytes(LANG::Rust, source)).unwrap(); + assert!(!ast.as_tree_sitter().root_node().has_error()); + let (result, events) = observation::capture(|| check_ast(&ast)); + assert_eq!(result, Ok(Outcome::Checked)); + assert_eq!(operations(&events), [Event::Collection(Ok(()))]); +} + +#[test] +fn producer_qualification_runtime_and_registry_controls() { + let mutation = std::env::var("BCA_FUZZ_PRODUCER_CASE").unwrap_or_default(); + for (name, class) in [ + ("cpp-candidate-qualification", "candidate-qualification"), + ("cpp-reference-qualification", "reference-qualification"), + ] { + let bytes = std::fs::read( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("corpus/documentation") + .join(name), + ) + .unwrap(); + let input = Input::decode(&bytes).unwrap(); + let parser = AnyParser::parse(input.language, input.source.to_vec(), None, None).unwrap(); + let index = parser + .documentation(&DocumentationContext::default(), &input.options) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let candidate = class == "candidate-qualification"; + assert_eq!( + index.associations().next().unwrap().get().owner_count(), + if candidate { 2 } else { 1 } + ); + let affected = mutation.starts_with(if candidate { + "candidate-" + } else { + "reference-" + }); + let expected = if affected && mutation.ends_with("root") { + Err(if candidate { + "qualification candidate evidence differs from owner" + } else { + "qualification reference evidence is not a document fragment" + }) + } else { + Ok(Outcome::Checked) + }; + assert_eq!(exercise(&bytes), expected, "runtime {name} {mutation}"); + let registry = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + edge(class, Some(&index), parser.ts_tree()); + })); + assert_eq!(registry.is_err(), affected, "registry {name} {mutation}"); + if let Err(panic) = registry { + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or(""); + let expected = if mutation.ends_with("resolution") { + "seed association resolution" + } else if candidate { + "candidate source evidence" + } else { + "reference source evidence" + }; + assert!( + message.contains(expected), + "wrong registry rejection: {message}" + ); + } + } +} + +#[test] +fn producer_second_collection_repeat_control() { + let mutation = std::env::var("BCA_FUZZ_PRODUCER_CASE").unwrap_or_default(); + let source = if mutation == "repeat-binding" || mutation == "repeat-scope" { + b"/**audit*/\nexport function f() {}".as_slice() + } else { + b"/**audit*/\nint a, b;".as_slice() + }; + let language = if mutation == "repeat-binding" || mutation == "repeat-scope" { + LANG::Javascript + } else { + LANG::C + }; + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error()); + let first = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!( + properties::check(&first, parser.ts_tree(), parser.code()), + Ok(()) + ); + assert_eq!(text(&first).text(), "audit"); + if language == LANG::C { + edge("shared", Some(&first), parser.ts_tree()); + } else { + let association = first.associations().next().unwrap(); + assert_eq!( + association.get().binding.unwrap().node().kind(), + "export_statement" + ); + assert_eq!(association.get().lexical_scope.node().kind(), "program"); + } + let second = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let expected = match mutation.as_str() { + "repeat-slot" => Err("nondeterministic slot fields"), + "repeat-binding" | "repeat-scope" => Err("nondeterministic node evidence"), + _ => Ok(()), + }; + assert_eq!( + properties::repeat(&first, &second), + expected, + "second collection {mutation}" + ); +} + +#[test] +fn repeat_checks_nondefault_context_and_options() { + let parser = AnyParser::parse(LANG::Rust, b"///audit\nfn f() {}".to_vec(), None, None).unwrap(); + let context = DocumentationContext { + logical_filename: Some("named.rs".into()), + }; + let options = DocumentationOptions { + profile: Profile::Rust, + retain_unbound: true, + retain_directives: true, + }; + let first = parser.documentation(&context, &options).unwrap(); + for (context, options) in [ + (DocumentationContext::default(), options), + ( + context.clone(), + DocumentationOptions { + profile: Profile::Default, + ..options + }, + ), + ( + context.clone(), + DocumentationOptions { + retain_unbound: false, + ..options + }, + ), + ( + context.clone(), + DocumentationOptions { + retain_directives: false, + ..options + }, + ), + ] { + let second = parser.documentation(&context, &options).unwrap(); + assert_eq!( + properties::repeat(&first, &second), + Err("nondeterministic index context/options") + ); + } + let second = parser.documentation(&context, &options).unwrap(); + assert_eq!(properties::repeat(&first, &second), Ok(())); +} From 7c139410c947bc006cb2435209d891cf2994ee30 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:43:31 -0800 Subject: [PATCH 057/221] test(fuzz): validate evidence against collected owners --- fuzz/src/documentation/tests/remediation.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/fuzz/src/documentation/tests/remediation.rs b/fuzz/src/documentation/tests/remediation.rs index 43818cd24..606cec9d0 100644 --- a/fuzz/src/documentation/tests/remediation.rs +++ b/fuzz/src/documentation/tests/remediation.rs @@ -282,20 +282,31 @@ fn evidence_validation_rejects_same_id_changed_context_and_wrong_document() { let edited = SourceContext::new(parser.ts_tree(), parser.code()) .node(edited) .unwrap(); - let owner = Owner::Node(node); - assert_eq!(identity::candidate(&owner, node), Ok(())); + let owner = index + .facts() + .associated_owner(index.associations().next().unwrap(), 0) + .unwrap(); + let Owner::Node(owner_node) = owner.get() else { + panic!("real declaration owner") + }; + assert_eq!(identity::candidate(owner.get(), *owner_node), Ok(())); assert_eq!( - identity::candidate(&owner, edited), + identity::candidate(owner.get(), edited), Err("qualification candidate evidence differs from owner") ); let root = SourceContext::new(parser.ts_tree(), parser.code()) .node(parser.ts_tree().root_node()) .unwrap(); assert_eq!( - identity::candidate(&owner, root), + identity::candidate(owner.get(), root), Err("qualification candidate evidence differs from owner") ); - assert_eq!(identity::candidate(&Owner::File(root), root), Ok(())); + let file = index + .facts() + .owners() + .find(|owner| matches!(owner.get(), Owner::File(_))) + .unwrap(); + assert_eq!(identity::candidate(file.get(), root), Ok(())); assert_eq!( references.validate(documents[0], edited), Err("qualification reference evidence is not a document fragment") From 04dc92190555aa5ca6be55f95babd12f74a14a89 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:59:58 -0800 Subject: [PATCH 058/221] fix(fuzz): require valid negative setup and exact rejection Pin ambiguous resolution outside catch_unwind and require the first owner-identity diagnostic. Keep allocating included-range observations test-only. Extend producer verification and document its explicit invocation and environment contract. --- docs/development/fuzzing.md | 8 ++++++++ fuzz/check_documentation_producers.py | 11 +++++++++++ fuzz/documentation-perturb.json | 9 ++++++++- fuzz/src/documentation/mod.rs | 1 + fuzz/src/documentation/observation.rs | 1 + fuzz/src/documentation/tests.rs | 22 +++++++++++++++++++++- 6 files changed, 50 insertions(+), 2 deletions(-) diff --git a/docs/development/fuzzing.md b/docs/development/fuzzing.md index 230bdcd4b..6535a46c3 100644 --- a/docs/development/fuzzing.md +++ b/docs/development/fuzzing.md @@ -392,6 +392,14 @@ successful index and performs no extra call in a fuzz campaign. Recorder scopes success, rejection, and unwind. Removing scope installation must fail the witness's result assertion, not just an operation count. +Run `python3 -B fuzz/check_documentation_producers.py --out "$out"` separately to +verify the producer controls. Set `out` to a unique evidence directory created with +`mktemp -d` under an owned location. The driver requires a clean tracked checkout, +temporarily changes the producer, and restores its exact bytes in a `finally` block. +Its `BCA_FUZZ_PRODUCER_CASE` environment variable selects expected outcomes only in +the two `producer_*` tests; leave it unset for ordinary validation. This explicit +verification command is not part of `make fuzz-check`. + Run the finite documentation validation sequence one heavy operation at a time: ```bash diff --git a/fuzz/check_documentation_producers.py b/fuzz/check_documentation_producers.py index 971833ebb..38c587e6e 100644 --- a/fuzz/check_documentation_producers.py +++ b/fuzz/check_documentation_producers.py @@ -148,6 +148,16 @@ def main(): and message in text and f"{ordinary_test} ... FAILED" in text ), (name, "wrong ordinary failure") + setup_guard = None + if name == "candidate-resolution": + guard = "documentation::tests::qualification_oracle_rejects_same_reasons_on_the_wrong_candidate" + setup_guard, text = run(out, name + "-negative-setup", guard, None) + assert ( + setup_guard["exit"] == 101 + and f"{guard} ... FAILED" in text + and "wrong-candidate setup resolution" in text + and "candidate owner identity" not in text + ), (name, "negative control swallowed invalid resolution setup") records.append( { "name": name, @@ -155,6 +165,7 @@ def main(): "baseline": baseline, "controlled": controlled, "ordinary": ordinary, + "negative_setup_guard": setup_guard, "rejection": message, "original_sha256": hashlib.sha256(original).hexdigest(), } diff --git a/fuzz/documentation-perturb.json b/fuzz/documentation-perturb.json index c02edf0ce..956b48fa8 100644 --- a/fuzz/documentation-perturb.json +++ b/fuzz/documentation-perturb.json @@ -33,7 +33,7 @@ { "name": "lose-qualified-candidate-identity", "file": "fuzz/src/documentation/tests.rs", - "old": " assert_eq!(index.qualified_owner(qualification).unwrap(), Some(owner));", + "old": " assert_eq!(\n index.qualified_owner(qualification).unwrap(),\n Some(owner),\n \"candidate owner identity\"\n );", "new": " let _ = owner;\n assert!(index.qualified_owner(qualification).unwrap().is_some());", "expect": ["documentation::tests::qualification_oracle_rejects_same_reasons_on_the_wrong_candidate"] }, @@ -99,6 +99,13 @@ "old": "flag.run(|| {\n let outcome = check()?;\n #[cfg(test)]\n observation::active_witness(&flag, &parsed, input.options)?;\n Ok(outcome)\n })", "new": "{\n let outcome = check()?;\n #[cfg(test)]\n observation::active_witness(&flag, &parsed, input.options)?;\n Ok(outcome)\n }", "expect": ["documentation::tests::remediation::mode_calls_and_active_scope_are_observed"] + }, + { + "name": "wrong-candidate-resolution-setup", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " Ok(builder.index)\n}", + "new": " for association in &mut builder.index.facts.associations {\n if association.resolution == Resolution::Unresolved(UnresolvedReason::Ambiguous) {\n association.resolution = Resolution::Resolved;\n }\n }\n Ok(builder.index)\n}", + "expect": ["documentation::tests::qualification_oracle_rejects_same_reasons_on_the_wrong_candidate", "documentation::tests::registry_executes_every_dispatch_and_edge_assertion"] } ] } diff --git a/fuzz/src/documentation/mod.rs b/fuzz/src/documentation/mod.rs index 2e56952d0..385bf391a 100644 --- a/fuzz/src/documentation/mod.rs +++ b/fuzz/src/documentation/mod.rs @@ -147,6 +147,7 @@ fn exercise_with( let tree = parser .parse(input.source, None) .ok_or("included parse aborted")?; + #[cfg(test)] observation::record(Event::IncludedParse(tree.included_ranges().len())); return check_parse( &Parsed { diff --git a/fuzz/src/documentation/observation.rs b/fuzz/src/documentation/observation.rs index 5141d03be..4d823c82c 100644 --- a/fuzz/src/documentation/observation.rs +++ b/fuzz/src/documentation/observation.rs @@ -10,6 +10,7 @@ use big_code_analysis_ast::{ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum Event { Parse, + #[cfg(test)] IncludedParse(usize), Collection(Result<(), CollectionError>), Repeat, diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index b068a5435..3eb12622e 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -313,7 +313,11 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: let node = qualification.get().node.node(); if candidate { let owner = index.facts().associated_owner(association, 0).unwrap(); - assert_eq!(index.qualified_owner(qualification).unwrap(), Some(owner)); + assert_eq!( + index.qualified_owner(qualification).unwrap(), + Some(owner), + "candidate owner identity" + ); assert_eq!( &index.source()[node.byte_range()], b"void f(int x = );", @@ -607,6 +611,11 @@ fn qualification_oracle_rejects_same_reasons_on_the_wrong_candidate() { assert_eq!(index.documents().len(), 1); assert_eq!(index.associations().len(), 1); let association = index.associations().next().unwrap(); + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::Ambiguous), + "wrong-candidate setup resolution" + ); assert_eq!(association.get().owner_count(), 2); let document = index.facts().associated_document(association).unwrap(); let owner = index.facts().associated_owner(association, 1).unwrap(); @@ -636,6 +645,17 @@ fn qualification_oracle_rejects_same_reasons_on_the_wrong_candidate() { rejected.is_err(), "qualification identity oracle accepted the other candidate" ); + let panic = rejected.unwrap_err(); + let message = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or(""); + assert_eq!( + message.lines().next(), + Some("assertion `left == right` failed: candidate owner identity"), + "wrong-candidate rejection site" + ); Ok(()) }); assert_eq!(result, Ok(Outcome::Checked)); From 00f0920d8da412abfc935d645ab63b27f2c28300 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:21:52 -0800 Subject: [PATCH 059/221] fix(bench): calibrate source repetitions with bounded real batches Retain ordered calibration evidence and partial failures, validate first-stop decisions and scheduled-count agreement, and keep smoke preparation explicit. Add deterministic duration cases, real-operation counter guards, and maintained perturbations. Source-only checkpoint for #1662. Heavy hooks and all Cargo, test, mutation, gate, and timing execution are intentionally deferred to the parent-assigned validation slot. --- .../documentation-calibration.json | 146 +++++ .../src/documentation/combined.rs | 5 + .../src/documentation/runner.rs | 201 +++++-- .../src/documentation/runner/calibration.rs | 255 +++++++++ .../documentation/runner/calibration_tests.rs | 509 ++++++++++++++++++ docs/development/benchmarking.md | 88 ++- 6 files changed, 1134 insertions(+), 70 deletions(-) create mode 100644 big-code-analysis-bench/perturbations/documentation-calibration.json create mode 100644 big-code-analysis-bench/src/documentation/runner/calibration.rs create mode 100644 big-code-analysis-bench/src/documentation/runner/calibration_tests.rs diff --git a/big-code-analysis-bench/perturbations/documentation-calibration.json b/big-code-analysis-bench/perturbations/documentation-calibration.json new file mode 100644 index 000000000..549878f07 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-calibration.json @@ -0,0 +1,146 @@ +{ + "cwd": ".", + "provenance": { + "starting_checkpoint": "2eb9b8103477d1d02e76620c4475b47b0a37a5d2", + "proposal_sha256": "4d50b20c066ec4b405745c1afe40b51cb5e376492d926c318c8488f96663ca47", + "status": "Source-only checkpoint; mutation execution awaits the parent's local validation slot.", + "usage": "python3 -B utils/perturb.py big-code-analysis-bench/perturbations/documentation-calibration.json", + "preservation": "The 15 documentation.json, 3 documentation-audit.json and 9 documentation-remediation.json cases retain their substitutions and expected guards. Cap tests inject durations; real batch counters independently guard execution. Build failures are not kills. Historical result manifests describe only their recorded revisions." + }, + "command": ["cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation", "--no-fail-fast"], + "cases": [ + { + "name": "calibrate with one operation instead of the declared batch count", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "let elapsed = measure(count).map_err(|error| {", + "new": "let elapsed = measure(1).map_err(|error| {", + "expect": ["documentation::runner::calibration_tests::real_calibration_batches_execute_three_times_each_tested_count", "documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts"] + }, + { + "name": "take only two calibration samples", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "for sample in 0..3 {", + "new": "for sample in 0..2 {", + "expect": ["documentation::runner::calibration_tests::first_qualified_stage_stops_after_exactly_three_samples"] + }, + { + "name": "select fastest calibration sample", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "Ok(times[1])", + "new": "Ok(times[0])", + "expect": ["documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample"] + }, + { + "name": "select slowest calibration sample", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "Ok(times[1])", + "new": "Ok(times[2])", + "expect": ["documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample"] + }, + { + "name": "skip intermediate powers of two", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "count *= 2;", + "new": "count *= 4;", + "expect": ["documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample", "documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling"] + }, + { + "name": "continue after the first qualifying stage", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "if observed >= SOURCE_TARGET_SAMPLE {", + "new": "if count >= 2 && observed >= SOURCE_TARGET_SAMPLE {", + "expect": ["documentation::runner::calibration_tests::first_qualified_stage_stops_after_exactly_three_samples"] + }, + { + "name": "accept unresolved cap median", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "if observed >= MIN_SOURCE_SAMPLE {", + "new": "if observed >= Duration::ZERO {", + "expect": ["documentation::runner::calibration_tests::cap_outcomes_use_the_three_sample_median_and_exact_boundaries"] + }, + { + "name": "skip post-completion calibration budget check", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "check_budget(id, size, elapsed, count, budget).map_err(|error| {", + "new": "check_budget(id, size, Duration::ZERO, count, budget).map_err(|error| {", + "expect": ["documentation::runner::calibration_tests::custom_budget_is_checked_for_every_observation_before_the_next_call", "documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix"] + }, + { + "name": "discard the offending calibration budget sample", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "*outcome = CalibrationOutcome::BudgetExceeded;", + "new": "stages[at].samples.pop();\n *outcome = CalibrationOutcome::BudgetExceeded;", + "expect": ["documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix"] + }, + { + "name": "invent zero duration for failed calibration operation", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "*outcome = CalibrationOutcome::OperationFailed;", + "new": "stages[at].samples.push(Duration::ZERO);\n *outcome = CalibrationOutcome::OperationFailed;", + "expect": ["documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix"] + }, + { + "name": "discard earlier completed calibration cells on failure", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "retained_error(error, &raw[..=at])", + "new": "retained_error(error, &raw[at..=at])", + "expect": ["documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix", "documentation::runner::calibration_tests::smoke_setup_failure_has_no_fabricated_elapsed_sample"] + }, + { + "name": "trust frozen count without matching the final tested count", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "iterations == stage.iterations,", + "new": "iterations > 0,", + "expect": ["documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement"] + }, + { + "name": "accept skipped or reordered calibration counts", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "stage.iterations == 1 << at && stage.iterations <= SOURCE_MAX_ITERATIONS,", + "new": "stage.iterations > 0 && stage.iterations <= SOURCE_MAX_ITERATIONS,", + "expect": ["documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement"] + }, + { + "name": "trust a trace that continued after qualifying", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "observed < SOURCE_TARGET_SAMPLE,", + "new": "observed <= Duration::MAX,", + "expect": ["documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement"] + }, + { + "name": "accept sub-target target-reached outcome", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "CalibrationOutcome::TargetReached => observed >= SOURCE_TARGET_SAMPLE,", + "new": "CalibrationOutcome::TargetReached => observed >= Duration::ZERO,", + "expect": ["documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement"] + }, + { + "name": "accept below-minimum cap-limited trace", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "&& (MIN_SOURCE_SAMPLE..SOURCE_TARGET_SAMPLE).contains(&observed)", + "new": "&& (Duration::ZERO..SOURCE_TARGET_SAMPLE).contains(&observed)", + "expect": ["documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement"] + }, + { + "name": "ignore custom calibration budget during revalidation", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "check_budget(\"calibration\", at, elapsed, stage.iterations, budget)?;", + "new": "check_budget(\"calibration\", at, elapsed, stage.iterations, budget.max(Duration::from_secs(20)))?;", + "expect": ["documentation::runner::calibration_tests::custom_budget_is_checked_for_every_observation_before_the_next_call", "documentation::runner::tests::report_revalidates_batches_counts_and_statistic"] + }, + { + "name": "allow smoke to claim a calibration ladder", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "require(mode != Mode::Smoke, \"smoke must not claim calibration\")?;", + "new": "require(true, \"smoke must not claim calibration\")?;", + "expect": ["documentation::runner::calibration_tests::smoke_records_one_setup_and_never_claims_calibration"] + }, + { + "name": "print rounded calibration trace durations", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "for sample in &stage.samples {\n write!(f, \" {}\", sample.as_nanos())?;\n }\n writeln!(f)?;", + "new": "for sample in &stage.samples {\n write!(f, \" {}\", sample.as_micros() * 1000)?;\n }\n writeln!(f)?;", + "expect": ["documentation::runner::calibration_tests::calibration_formatter_preserves_sample_order_and_integer_nanoseconds"] + } + ] +} diff --git a/big-code-analysis-bench/src/documentation/combined.rs b/big-code-analysis-bench/src/documentation/combined.rs index 1219a60c9..8f7d47893 100644 --- a/big-code-analysis-bench/src/documentation/combined.rs +++ b/big-code-analysis-bench/src/documentation/combined.rs @@ -141,6 +141,7 @@ impl CombinedReport { #[cfg(test)] mod tests { + use super::super::runner::calibration_tests::target_trace; use super::super::runner::{Batch, SourceCell, SourceResult, Statistic}; use super::*; @@ -192,6 +193,8 @@ mod tests { bytes: size, segments: 1, iterations: 1, + calibration: target_trace(1), + budget: scaling::MAX_CELL_WALK, batches: (0..3).map(|round| Batch { round, elapsed }).collect(), batch_min: elapsed, batch_median: elapsed, @@ -357,6 +360,8 @@ mod tests { bytes: size, segments: 1, iterations: 1, + calibration: target_trace(1), + budget: scaling::MAX_CELL_WALK, batches: (0..3).map(|round| Batch { round, elapsed }).collect(), batch_min: elapsed, batch_median: elapsed, diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index 40c88e939..96d87f9e2 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -9,6 +9,15 @@ use super::{HarnessError, Parsed, Prepared, SourceCounts, SourceProbe, Statistic use crate::cli::Mode; use crate::scaling::{MAX_CELL_WALK, SMOKE_SIZES, WARMUP_ROUNDS, schedule}; +mod calibration; +#[cfg(test)] +pub(super) mod calibration_tests; +pub use calibration::{Calibration, CalibrationOutcome, CalibrationStage}; +use calibration::{calibrate, write_calibration}; + +/// Exact-nanosecond report schema and premeasurement selection policy. +pub const SOURCE_CALIBRATION_POLICY: &str = "source-batches-v2/powers-of-two-median-three"; + /// Target elapsed duration for source-only calibration; legacy calibration is unchanged. pub const SOURCE_TARGET_SAMPLE: Duration = Duration::from_millis(2); /// Maximum source repetitions in one batch. @@ -16,18 +25,6 @@ pub const SOURCE_MAX_ITERATIONS: u32 = 1 << 20; /// A full-size cell with a shorter measured median is unresolved, never a pass. pub const MIN_SOURCE_SAMPLE: Duration = Duration::from_micros(200); -/// Source calibration, frozen before warmup/measurement. A zero calibration -/// observation saturates the cap; measured zero batches still fail validation. -#[must_use] -pub fn iterations_for(single: Duration) -> u32 { - let needed = SOURCE_TARGET_SAMPLE - .as_nanos() - .div_ceil(single.as_nanos().max(1)); - u32::try_from(needed) - .unwrap_or(SOURCE_MAX_ITERATIONS) - .clamp(1, SOURCE_MAX_ITERATIONS) -} - /// One actual scheduled batch, retained before any per-operation division. #[derive(Clone, Debug)] pub struct Batch { @@ -50,6 +47,10 @@ pub struct SourceCell { pub segments: usize, /// Frozen repetitions for every warmup/measured round. pub iterations: u32, + /// Ordered premeasurement evidence, separate from scheduled samples. + pub calibration: Calibration, + /// Actual post-completion per-operation budget used for this cell. + pub budget: Duration, /// Complete samples in scheduled-round order. pub batches: Vec, /// Shortest actual batch. @@ -152,6 +153,8 @@ impl SourceReport { bytes: cell.bytes, segments: cell.segments, iterations: cell.iterations, + calibration: cell.calibration.clone(), + budget: cell.budget, batches: cell.batches.clone(), }, self.rounds, @@ -203,6 +206,7 @@ impl fmt::Display for SourceReport { self.rounds, self.mode )?; + writeln!(f, "source-calibration-policy: {SOURCE_CALIBRATION_POLICY}")?; for result in &self.results { if self.mode == Mode::Smoke { writeln!( @@ -251,6 +255,7 @@ impl fmt::Display for SourceReport { write!(f, " {}:{}", batch.round, batch.elapsed.as_nanos())?; } writeln!(f)?; + write_calibration(f, &cell.calibration, cell.budget)?; writeln!(f, " dimensions: {:?}", cell.counts)?; } } @@ -266,6 +271,8 @@ struct RawCell { bytes: usize, segments: usize, iterations: u32, + calibration: Calibration, + budget: Duration, batches: Vec, } @@ -342,25 +349,67 @@ pub fn run_with_budget( for (at, operation) in prepared.iter().enumerate() { let probe = &probes[at / 3]; let size = probe.sizes[at % 3]; - let single = batch(operation, 1).map_err(|e| context(probe.id, size, e))?; - check_budget(probe.id, size, single, 1, budget)?; raw.push(RawCell { counts: operation.counts(), id: probe.id, size, bytes: parsed[at].source().len(), segments: operation.segments(), - iterations: if mode == Mode::Smoke { - 1 - } else { - iterations_for(single) - }, + iterations: 1, + calibration: Calibration::new(mode), + budget, batches: Vec::with_capacity(rounds), }); } + calibrate_cells(&mut raw, |at, count| batch(&prepared[at], count))?; measure_schedule(&prepared, &mut raw, rounds, budget)?; - reduce(&probes, rounds, mode, raw.clone()) - .map_err(|error| HarnessError(format!("{error}\nretained source batches: {raw:#?}"))) + reduce(&probes, rounds, mode, raw.clone()).map_err(|error| retained_error(error, &raw)) +} + +fn calibrate_cells( + raw: &mut [RawCell], + mut measure: impl FnMut(usize, u32) -> Result, +) -> Result<(), HarnessError> { + for at in 0..raw.len() { + let cell = &mut raw[at]; + let result = calibrate( + &mut cell.calibration, + cell.id, + cell.size, + cell.budget, + |count| measure(at, count), + ); + raw[at].iterations = result.map_err(|error| retained_error(error, &raw[..=at]))?; + } + Ok(()) +} + +#[allow(clippy::needless_pass_by_value)] // map_err transfers the primary diagnostic. +fn retained_error(error: HarnessError, raw: &[RawCell]) -> HarnessError { + use std::fmt::Write; + + let mut output = format!( + "{error}\nsource-calibration-policy: {SOURCE_CALIBRATION_POLICY}\nretained source batches:\n" + ); + for cell in raw { + let _ = writeln!( + output, + " {} size {} iterations {}", + cell.id, cell.size, cell.iterations + ); + let _ = writeln!( + output, + " bytes {} segments {} dimensions: {:?}", + cell.bytes, cell.segments, cell.counts + ); + let _ = write_calibration(&mut output, &cell.calibration, cell.budget); + let _ = write!(output, " raw-batches-ns:"); + for batch in &cell.batches { + let _ = write!(output, " {}:{}", batch.round, batch.elapsed.as_nanos()); + } + let _ = writeln!(output); + } + HarnessError(output) } fn measure_schedule( @@ -387,12 +436,7 @@ fn measure_schedule( )?; Ok(elapsed) }) - .map_err(|error| { - HarnessError(format!( - "{}\nretained source batches: {raw:#?}", - context(cell.id, cell.size, error) - )) - })?; + .map_err(|error| retained_error(context(cell.id, cell.size, error), raw))?; if round >= WARMUP_ROUNDS { raw[at].batches.push(Batch { round: round - WARMUP_ROUNDS, @@ -424,7 +468,7 @@ fn check_budget( budget: Duration, ) -> Result<(), HarnessError> { require( - elapsed.as_secs_f64() / f64::from(iterations) <= budget.as_secs_f64(), + elapsed.as_nanos() <= budget.as_nanos() * u128::from(iterations), format!( "AbandonedCell: {id} size {size}, {iterations} iterations, batch {elapsed:?}, per-operation budget {budget:?}" ), @@ -514,6 +558,9 @@ fn reduce_cell(raw: RawCell, rounds: usize, mode: Mode) -> Result 0 && raw.iterations > 0 && raw.iterations <= SOURCE_MAX_ITERATIONS, format!("{}: invalid cell work/count", raw.id), )?; + raw.calibration + .validate(mode, raw.iterations, raw.budget) + .map_err(|error| context(raw.id, raw.size, error))?; require( raw.batches.len() == rounds, format!("{} size {}: missing samples", raw.id, raw.size), @@ -547,6 +594,8 @@ fn reduce_cell(raw: RawCell, rounds: usize, mode: Mode) -> Result Vec { @@ -620,6 +670,8 @@ mod tests { bytes: size, segments: size, iterations: 1, + calibration: target_trace(1), + budget: MAX_CELL_WALK, batches: (0..3) .map(|round| Batch { round, @@ -632,10 +684,23 @@ mod tests { #[test] fn calibration_caps_zero_and_preserves_ceiling() { - assert_eq!(iterations_for(Duration::ZERO), 1 << 20); - assert_eq!(iterations_for(Duration::from_nanos(3)), 666_667); - assert_eq!(iterations_for(Duration::from_millis(3)), 1); - assert_eq!(iterations_for(Duration::from_micros(1)), 2000); + let mut evidence = Calibration::new(Mode::Gate); + let mut counts = Vec::new(); + let error = calibrate(&mut evidence, "zero", 1, MAX_CELL_WALK, |count| { + counts.push(count); + Ok(Duration::ZERO) + }) + .unwrap_err(); + assert!(error.0.contains("CalibrationUnresolved")); + assert_eq!(counts.len(), 63); + assert_eq!(counts.last(), Some(&(1 << 20))); + assert_eq!(counts.iter().map(|&n| u64::from(n)).sum::(), 6_291_453); + let Calibration::Batches { stages, outcome } = evidence else { + panic!("expected ladder") + }; + assert_eq!(outcome, CalibrationOutcome::Unresolved); + assert_eq!(stages.len(), 21); + assert!(stages.iter().all(|s| s.samples == [Duration::ZERO; 3])); } #[test] @@ -644,12 +709,19 @@ mod tests { let mut cells = raw(&probe, [199_999; 3]); for cell in &mut cells { cell.iterations = SOURCE_MAX_ITERATIONS; + cell.calibration = target_trace(SOURCE_MAX_ITERATIONS); } let error = reduce(&[probe], 3, Mode::Gate, cells).unwrap_err(); assert!(error.0.contains("UnresolvedCell")); assert!(error.0.contains("1048576")); assert!(reduce(&[probe], 3, Mode::ReportOnly, raw(&probe, [199_999; 3])).is_err()); - assert!(reduce(&[probe], 3, Mode::Smoke, raw(&probe, [1; 3])).is_ok()); + let mut smoke = raw(&probe, [1; 3]); + for cell in &mut smoke { + cell.calibration = Calibration::Smoke { + elapsed: Some(Duration::ZERO), + }; + } + assert!(reduce(&[probe], 3, Mode::Smoke, smoke).is_ok()); } #[test] @@ -661,6 +733,13 @@ mod tests { assert!(reduce(&[probe], 3, mode, vec![]).is_err()); for mutation in 0..9 { let mut cells = raw(&probe, [200_000; 3]); + if mode == Mode::Smoke { + for cell in &mut cells { + cell.calibration = Calibration::Smoke { + elapsed: Some(Duration::ZERO), + }; + } + } match mutation { 0 => cells[0].id = "unknown", 1 => cells[0].size *= 2, @@ -690,6 +769,7 @@ mod tests { let mut cells = raw(&probe, [200_000, 400_000, 800_000]); for cell in &mut cells { cell.iterations = SOURCE_MAX_ITERATIONS; + cell.calibration = target_trace(SOURCE_MAX_ITERATIONS); } let report = reduce(&[probe], 3, Mode::Gate, cells).unwrap(); assert!((report.results[0].statistic.value() - 4.0).abs() < 1e-12); @@ -709,6 +789,7 @@ mod tests { let mut cells = raw(&probe, batches); for (cell, iterations) in cells.iter_mut().zip([1, 2, 4]) { cell.iterations = iterations; + cell.calibration = target_trace(iterations); } let report = reduce(&[probe], 3, Mode::Gate, cells).unwrap(); // Doubling both batch time and work keeps cost fixed; holding @@ -769,14 +850,17 @@ mod tests { let probe = REGISTRY[18]; let report = reduce(&[probe], 3, Mode::Gate, raw(&probe, [200_000; 3])).unwrap(); assert!(report.validate_data().is_ok()); - for mutation in 0..5 { + for mutation in 0..8 { let mut invalid = report.clone(); match mutation { 0 => invalid.results[0].cells[0].ns_per_operation = f64::NAN, 1 => invalid.results[0].statistic = Statistic::FixedOutputRatio(f64::INFINITY), 2 => invalid.results[0].bound = f64::NAN, 3 => invalid.results[0].cells[0].batches.clear(), - _ => invalid.results[0].cells[0].iterations = SOURCE_MAX_ITERATIONS + 1, + 4 => invalid.results[0].cells[0].iterations = SOURCE_MAX_ITERATIONS + 1, + 5 => invalid.results[0].cells[0].calibration = Calibration::new(Mode::Gate), + 6 => invalid.results[0].cells[0].calibration = target_trace(2), + _ => invalid.results[0].cells[0].budget = Duration::from_nanos(1_999_999), } assert!(invalid.validate_data().is_err(), "mutation {mutation}"); } @@ -803,7 +887,8 @@ mod tests { let probe = REGISTRY[18]; let mut cells = raw(&probe, [200_001; 3]); for cell in &mut cells { - cell.iterations = 3; + cell.iterations = 4; + cell.calibration = target_trace(4); cell.batches[0].elapsed = Duration::from_nanos(900_001); cell.batches[1].elapsed = Duration::from_nanos(200_002); } @@ -812,7 +897,7 @@ mod tests { assert_eq!(cell.batch_min, Duration::from_nanos(200_001)); assert_eq!(cell.batch_median, Duration::from_nanos(200_002)); assert_eq!(cell.batch_max, Duration::from_nanos(900_001)); - assert!((cell.ns_per_operation - 200_002.0 / 3.0).abs() < 1e-9); + assert!((cell.ns_per_operation - 200_002.0 / 4.0).abs() < 1e-9); assert_eq!(cell.batches[0].elapsed, Duration::from_nanos(900_001)); assert_eq!( cell.batches.iter().map(|b| b.round).collect::>(), @@ -838,15 +923,33 @@ mod tests { .find(|p| p.id == "documentation/cold/width") .unwrap(); let before = big_code_analysis_ast::documentation::observations(); - let report = run(&[*probe], 1, Mode::Smoke).unwrap(); + let budget = Duration::from_secs(30); + let report = run_with_budget(&[*probe], 1, Mode::Smoke, budget).unwrap(); let after = big_code_analysis_ast::documentation::observations(); - // Per rung: one initial index, one calibration, two warmups and one + // Per rung: one initial index, one smoke preparation, two warmups and one // measured collection. Each collection renders one document per sibling. assert_eq!( after.renders - before.renders, 5 * SMOKE_SIZES.iter().sum::() ); assert_eq!(report.results[0].cells.len(), 3); + report.validate_data().unwrap(); + assert!( + report.results[0] + .cells + .iter() + .all(|cell| cell.budget == budget) + ); + assert!( + report.to_string().contains( + "source-calibration-policy: source-batches-v2/powers-of-two-median-three" + ) + ); + assert!( + report + .to_string() + .contains("per-operation-budget-ns: 30000000000") + ); assert!( report.results[0] .cells @@ -892,7 +995,17 @@ mod tests { let before = big_code_analysis_ast::documentation::observations(); let mut raw = Vec::new(); for ((operation, size), iterations) in prepared.iter().zip(sizes).zip(counts) { - let _calibration = batch(operation, 1).unwrap(); + let mut calibration = Calibration::new(Mode::Gate); + let selected = calibrate(&mut calibration, probe.id, size, MAX_CELL_WALK, |count| { + batch(operation, count)?; + Ok(if count == iterations { + Duration::from_millis(2) + } else { + Duration::ZERO + }) + }) + .unwrap(); + assert_eq!(selected, iterations); raw.push(RawCell { counts: operation.counts(), id: probe.id, @@ -900,14 +1013,16 @@ mod tests { bytes: size, segments: 1, iterations, + calibration, + budget: MAX_CELL_WALK, batches: vec![], }); } measure_schedule(&prepared, &mut raw, 3, MAX_CELL_WALK).unwrap(); let after = big_code_analysis_ast::documentation::observations(); - // Calibration renders 2+4+8 documents. Each scheduled round renders - // 2*1+4*2+8*4; two warmups plus three measured rounds gives 224 total. - assert_eq!(after.renders - before.renders, 224); + // expected: calibration 3*(2*1+4*(1+2)+8*(1+2+4)) = 210; + // two warmups and three measured rounds add 5*(2*1+4*2+8*4) = 210. + assert_eq!(after.renders - before.renders, 420); for (cell, count) in raw.iter().zip(counts) { assert_eq!(cell.iterations, count); assert_eq!( diff --git a/big-code-analysis-bench/src/documentation/runner/calibration.rs b/big-code-analysis-bench/src/documentation/runner/calibration.rs new file mode 100644 index 000000000..a428f542f --- /dev/null +++ b/big-code-analysis-bench/src/documentation/runner/calibration.rs @@ -0,0 +1,255 @@ +use std::fmt; +use std::time::Duration; + +use super::{ + HarnessError, MIN_SOURCE_SAMPLE, Mode, SOURCE_MAX_ITERATIONS, SOURCE_TARGET_SAMPLE, + check_budget, context, require, +}; + +/// One tested repetition count, with observed durations in execution order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CalibrationStage { + /// Power-of-two repetitions actually requested from each batch. + pub iterations: u32, + /// Three samples on completion; only the observed prefix on failure. + pub samples: Vec, +} + +/// Decision at the end of the retained calibration prefix. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CalibrationOutcome { + /// Calibration has not yet produced a terminal decision. + Pending, + /// The first stage whose median is at least two milliseconds. + TargetReached, + /// The cap median resolves at 200 microseconds but misses the target. + CapLimited, + /// The cap median remains below 200 microseconds. + Unresolved, + /// The next batch failed without yielding an elapsed duration. + OperationFailed, + /// The last retained batch exceeded the per-operation budget. + BudgetExceeded, +} + +impl CalibrationOutcome { + fn label(self) -> &'static str { + match self { + Self::Pending => "pending", + Self::TargetReached => "target-reached", + Self::CapLimited => "cap-limited", + Self::Unresolved => "unresolved", + Self::OperationFailed => "operation-failed", + Self::BudgetExceeded => "budget-exceeded", + } + } +} + +/// Smoke preparation or the bounded premeasurement batch ladder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Calibration { + /// One semantic setup execution, without a calibration claim. + Smoke { + /// Actual elapsed setup time, absent if the operation failed. + elapsed: Option, + }, + /// At most 21 tested counts and 63 actual elapsed samples. + Batches { + /// Counts and ordered samples, including any failing-stage prefix. + stages: Vec, + /// Terminal decision, or pending during preparation. + outcome: CalibrationOutcome, + }, +} + +impl Calibration { + pub(super) fn new(mode: Mode) -> Self { + if mode == Mode::Smoke { + Self::Smoke { elapsed: None } + } else { + Self::Batches { + stages: Vec::new(), + outcome: CalibrationOutcome::Pending, + } + } + } + + pub(super) fn validate( + &self, + mode: Mode, + iterations: u32, + budget: Duration, + ) -> Result<(), HarnessError> { + match self { + Self::Smoke { elapsed } => { + require( + mode == Mode::Smoke && iterations == 1, + "invalid smoke preparation", + )?; + let elapsed = + elapsed.ok_or_else(|| HarnessError("missing smoke preparation".into()))?; + check_budget("smoke preparation", 0, elapsed, 1, budget) + } + Self::Batches { stages, outcome } => { + require(mode != Mode::Smoke, "smoke must not claim calibration")?; + validate_stages(stages, *outcome, iterations, budget) + } + } + } +} + +fn median(samples: &[Duration]) -> Result { + let mut times: [Duration; 3] = samples + .try_into() + .map_err(|_| HarnessError("calibration stage requires three samples".into()))?; + times.sort_unstable(); + Ok(times[1]) +} + +fn validate_stages( + stages: &[CalibrationStage], + outcome: CalibrationOutcome, + iterations: u32, + budget: Duration, +) -> Result<(), HarnessError> { + require( + !stages.is_empty() && stages.len() <= 21, + "invalid calibration stage count", + )?; + for (at, stage) in stages.iter().enumerate() { + require( + stage.iterations == 1 << at && stage.iterations <= SOURCE_MAX_ITERATIONS, + "invalid calibration count ladder", + )?; + let observed = median(&stage.samples)?; + for &elapsed in &stage.samples { + check_budget("calibration", at, elapsed, stage.iterations, budget)?; + } + if at + 1 < stages.len() { + require( + observed < SOURCE_TARGET_SAMPLE, + "calibration continued after qualifying stage", + )?; + } else { + require( + iterations == stage.iterations, + "calibration and scheduled counts differ", + )?; + let valid = match outcome { + CalibrationOutcome::TargetReached => observed >= SOURCE_TARGET_SAMPLE, + CalibrationOutcome::CapLimited => { + stage.iterations == SOURCE_MAX_ITERATIONS + && (MIN_SOURCE_SAMPLE..SOURCE_TARGET_SAMPLE).contains(&observed) + } + _ => false, + }; + require(valid, "invalid calibration outcome")?; + } + } + Ok(()) +} + +pub(super) fn calibrate( + evidence: &mut Calibration, + id: &str, + size: usize, + budget: Duration, + mut measure: impl FnMut(u32) -> Result, +) -> Result { + let Calibration::Batches { stages, outcome } = evidence else { + let elapsed = measure(1).map_err(|error| { + context( + id, + size, + HarnessError(format!("smoke preparation count 1 sample 0: {error}")), + ) + })?; + *evidence = Calibration::Smoke { + elapsed: Some(elapsed), + }; + check_budget(id, size, elapsed, 1, budget)?; + return Ok(1); + }; + require( + stages.is_empty() && *outcome == CalibrationOutcome::Pending, + "calibration already started", + )?; + let mut count = 1; + loop { + let at = stages.len(); + stages.push(CalibrationStage { + iterations: count, + samples: Vec::with_capacity(3), + }); + for sample in 0..3 { + let elapsed = measure(count).map_err(|error| { + *outcome = CalibrationOutcome::OperationFailed; + HarnessError(format!("{id} size {size}: calibration stage {at} count {count} sample {sample}: {error}")) + })?; + stages[at].samples.push(elapsed); + check_budget(id, size, elapsed, count, budget).map_err(|error| { + *outcome = CalibrationOutcome::BudgetExceeded; + HarnessError(format!( + "calibration stage {at} count {count} sample {sample}: {error}" + )) + })?; + } + let observed = median(&stages[at].samples)?; + if observed >= SOURCE_TARGET_SAMPLE { + *outcome = CalibrationOutcome::TargetReached; + return Ok(count); + } + if count == SOURCE_MAX_ITERATIONS { + if observed >= MIN_SOURCE_SAMPLE { + *outcome = CalibrationOutcome::CapLimited; + return Ok(count); + } + *outcome = CalibrationOutcome::Unresolved; + return Err(HarnessError(format!( + "CalibrationUnresolved: {id} size {size}, stage {at} count {count} sample 2, median-ns {} < {}", + observed.as_nanos(), + MIN_SOURCE_SAMPLE.as_nanos() + ))); + } + count *= 2; + } +} + +pub(super) fn write_calibration( + f: &mut impl fmt::Write, + evidence: &Calibration, + budget: Duration, +) -> fmt::Result { + writeln!(f, " per-operation-budget-ns: {}", budget.as_nanos())?; + match evidence { + Calibration::Smoke { elapsed } => { + write!(f, " smoke-preparation-ns:")?; + if let Some(elapsed) = elapsed { + write!(f, " {}", elapsed.as_nanos())?; + } + writeln!(f, "; no calibration or performance claim") + } + Calibration::Batches { stages, outcome } => { + for (at, stage) in stages.iter().enumerate() { + write!(f, " calibration-stage-ns: {at} {}", stage.iterations)?; + for sample in &stage.samples { + write!(f, " {}", sample.as_nanos())?; + } + writeln!(f)?; + } + if let Some(stage) = stages.last() { + write!( + f, + " calibration-final-ns: {} {}", + stages.len() - 1, + stage.iterations + )?; + for sample in &stage.samples { + write!(f, " {}", sample.as_nanos())?; + } + writeln!(f, " {}", outcome.label())?; + } + Ok(()) + } + } +} diff --git a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs new file mode 100644 index 000000000..1e0ce6df4 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs @@ -0,0 +1,509 @@ +use super::*; + +pub(crate) fn target_trace(iterations: u32) -> Calibration { + assert!(iterations.is_power_of_two() && iterations <= 1 << 20); + Calibration::Batches { + stages: (0..=iterations.ilog2()) + .map(|at| CalibrationStage { + iterations: 1 << at, + samples: vec![ + if 1 << at == iterations { + Duration::from_millis(2) + } else { + Duration::ZERO + }; + 3 + ], + }) + .collect(), + outcome: CalibrationOutcome::TargetReached, + } +} + +fn stages_mut(evidence: &mut Calibration) -> &mut Vec { + let Calibration::Batches { stages, .. } = evidence else { + panic!("expected batch evidence") + }; + stages +} + +fn outcome_mut(evidence: &mut Calibration) -> &mut CalibrationOutcome { + let Calibration::Batches { outcome, .. } = evidence else { + panic!("expected batch evidence") + }; + outcome +} + +#[test] +fn slow_first_call_does_not_freeze_or_select_the_fastest_sample() { + let durations = [9_000_000, 10, 20, 0, 100, 200, 2_000_001, 0, 2_000_000]; + let mut calls = Vec::new(); + let mut evidence = Calibration::new(Mode::Gate); + let iterations = calibrate(&mut evidence, "ladder", 8, MAX_CELL_WALK, |count| { + let elapsed = Duration::from_nanos(durations[calls.len()]); + calls.push(count); + Ok(elapsed) + }) + .unwrap(); + assert_eq!(iterations, 4); + assert_eq!(calls, [1, 1, 1, 2, 2, 2, 4, 4, 4]); + let Calibration::Batches { stages, outcome } = &evidence else { + panic!("expected ladder") + }; + assert_eq!(*outcome, CalibrationOutcome::TargetReached); + assert_eq!( + stages + .iter() + .flat_map(|s| &s.samples) + .map(Duration::as_nanos) + .collect::>(), + durations.map(u128::from) + ); + evidence + .validate(Mode::Gate, iterations, MAX_CELL_WALK) + .unwrap(); +} + +#[test] +fn first_qualified_stage_stops_after_exactly_three_samples() { + let mut calls = 0; + let mut evidence = Calibration::new(Mode::ReportOnly); + let iterations = calibrate(&mut evidence, "first", 1, MAX_CELL_WALK, |count| { + calls += 1; + assert_eq!(count, 1); + assert!(calls <= 3, "no next stage or extra sample"); + Ok(Duration::from_millis(2)) + }) + .unwrap(); + assert_eq!(calls, 3); + assert_eq!(iterations, 1); + assert_eq!(evidence, target_trace(1)); +} + +#[test] +fn cap_outcomes_use_the_three_sample_median_and_exact_boundaries() { + for (ns, outcome) in [ + (199_999, CalibrationOutcome::Unresolved), + (200_000, CalibrationOutcome::CapLimited), + (1_999_999, CalibrationOutcome::CapLimited), + (2_000_000, CalibrationOutcome::TargetReached), + ] { + let mut evidence = Calibration::new(Mode::Gate); + let mut calls = Vec::new(); + let result = calibrate(&mut evidence, "cap", 2, MAX_CELL_WALK, |count| { + calls.push(count); + Ok(Duration::from_nanos(if count == 1 << 20 { ns } else { 0 })) + }); + assert_eq!(calls.len(), 63); + for (at, samples) in calls.chunks_exact(3).enumerate() { + assert_eq!(samples, [1 << at; 3]); + } + assert_eq!(*outcome_mut(&mut evidence), outcome); + if outcome == CalibrationOutcome::Unresolved { + assert!(result.unwrap_err().0.contains("CalibrationUnresolved")); + assert!( + evidence + .validate(Mode::Gate, 1 << 20, MAX_CELL_WALK) + .is_err() + ); + } else { + assert_eq!(result.unwrap(), 1 << 20); + evidence + .validate(Mode::Gate, 1 << 20, MAX_CELL_WALK) + .unwrap(); + } + } +} + +#[test] +fn real_calibration_batches_execute_three_times_each_tested_count() { + let probe = &super::super::REGISTRY[1]; + let parsed = Parsed::new(probe, 4).unwrap(); + let index = parsed.collect(probe).unwrap(); + let operation = Prepared::new(probe, 4, &parsed, &index).unwrap(); + let before = big_code_analysis_ast::documentation::observations(); + let mut evidence = Calibration::new(Mode::Gate); + let mut completed = Vec::new(); + let count = calibrate(&mut evidence, probe.id, 4, MAX_CELL_WALK, |count| { + let before = big_code_analysis_ast::documentation::observations(); + batch(&operation, count)?; + let after = big_code_analysis_ast::documentation::observations(); + assert_eq!(after.renders - before.renders, 4 * count as usize); + assert_eq!( + after.visits - before.visits, + parsed.nodes().len() * count as usize + ); + completed.push(count); + Ok(if count == 4 { + Duration::from_millis(2) + } else { + Duration::ZERO + }) + }) + .unwrap(); + let after = big_code_analysis_ast::documentation::observations(); + assert_eq!(count, 4); + assert_eq!(completed, [1, 1, 1, 2, 2, 2, 4, 4, 4]); + // expected: four documents for each of 3*(1+2+4) real executions. + assert_eq!(after.renders - before.renders, 84); + assert_eq!(after.visits - before.visits, 21 * parsed.nodes().len()); +} + +#[test] +fn trace_validation_rejects_forged_decisions_and_count_disagreement() { + for mode in [Mode::Gate, Mode::ReportOnly] { + let valid = target_trace(4); + valid.validate(mode, 4, MAX_CELL_WALK).unwrap(); + for mutation in 0..16 { + let mut invalid = valid.clone(); + let mut iterations = 4; + match mutation { + 0 => { + stages_mut(&mut invalid).remove(1); + } + 1 => stages_mut(&mut invalid)[0].iterations = 0, + 2 => stages_mut(&mut invalid)[1].iterations = 3, + 3 => stages_mut(&mut invalid)[1].iterations = 1, + 4 => stages_mut(&mut invalid)[2].iterations = u32::MAX, + 5 => { + stages_mut(&mut invalid)[2].samples.pop(); + } + 6 => stages_mut(&mut invalid)[0].samples.push(Duration::ZERO), + 7 => stages_mut(&mut invalid)[1].samples = vec![Duration::from_millis(2); 3], + 8 => stages_mut(&mut invalid)[2].samples = vec![Duration::from_nanos(1_999_999); 3], + 9 => *outcome_mut(&mut invalid) = CalibrationOutcome::CapLimited, + 10 => *outcome_mut(&mut invalid) = CalibrationOutcome::Pending, + 11 => iterations = 2, + 12 => stages_mut(&mut invalid).clear(), + 13 => stages_mut(&mut invalid).push(CalibrationStage { + iterations: 8, + samples: vec![Duration::from_millis(2); 3], + }), + 14 => stages_mut(&mut invalid).swap(0, 1), + _ => { + invalid = Calibration::Smoke { + elapsed: Some(Duration::ZERO), + } + } + } + assert!( + invalid.validate(mode, iterations, MAX_CELL_WALK).is_err(), + "mutation {mutation}, {mode:?}" + ); + } + let mut too_long = target_trace(1 << 20); + stages_mut(&mut too_long).push(CalibrationStage { + iterations: 1 << 21, + samples: vec![Duration::ZERO; 3], + }); + assert!(too_long.validate(mode, 1 << 21, MAX_CELL_WALK).is_err()); + for ns in [0, 199_999, 2_000_000] { + let mut invalid = target_trace(1 << 20); + *outcome_mut(&mut invalid) = CalibrationOutcome::CapLimited; + stages_mut(&mut invalid).last_mut().unwrap().samples = + vec![Duration::from_nanos(ns); 3]; + assert!( + invalid.validate(mode, 1 << 20, MAX_CELL_WALK).is_err(), + "cap median {ns}" + ); + } + } +} + +#[test] +fn custom_budget_is_checked_for_every_observation_before_the_next_call() { + // The median qualifies, but a single outlier still exceeds the exact budget. + let mut trace = target_trace(1); + stages_mut(&mut trace)[0].samples[1] = Duration::from_nanos(2_000_001); + assert!( + trace + .validate(Mode::Gate, 1, Duration::from_millis(2)) + .is_err() + ); + trace + .validate(Mode::Gate, 1, Duration::from_nanos(2_000_001)) + .unwrap(); + + for failing_call in 0..6 { + let mut evidence = Calibration::new(Mode::Gate); + let mut calls = 0; + let error = calibrate( + &mut evidence, + "budget", + 9, + Duration::from_nanos(10), + |count| { + let ns = if calls == failing_call { + u64::from(count) * 10 + 1 + } else { + 0 + }; + calls += 1; + Ok(Duration::from_nanos(ns)) + }, + ) + .unwrap_err(); + assert_eq!(calls, failing_call + 1); + assert!(error.0.contains("AbandonedCell")); + assert!(error.0.contains(&format!( + "stage {} count {} sample {}", + failing_call / 3, + 1 << (failing_call / 3), + failing_call % 3 + ))); + assert_eq!( + *outcome_mut(&mut evidence), + CalibrationOutcome::BudgetExceeded + ); + let stages = stages_mut(&mut evidence); + assert_eq!(stages.len(), failing_call / 3 + 1); + assert_eq!(stages.last().unwrap().samples.len(), failing_call % 3 + 1); + assert_eq!( + stages.last().unwrap().samples.last().unwrap().as_nanos(), + u128::from(stages.last().unwrap().iterations) * 10 + 1 + ); + } + check_budget( + "boundary", + 1, + Duration::from_nanos(20), + 2, + Duration::from_nanos(10), + ) + .unwrap(); + assert!( + check_budget( + "boundary", + 1, + Duration::from_nanos(21), + 2, + Duration::from_nanos(10) + ) + .is_err() + ); + check_budget("largest", 1, Duration::MAX, u32::MAX, Duration::MAX).unwrap(); +} + +fn pending_cells() -> Vec { + ["complete", "failing", "must-not-run"] + .into_iter() + .map(|id| RawCell { + counts: SourceCounts::default(), + id, + size: 8, + bytes: 8, + segments: 1, + iterations: 1, + calibration: Calibration::new(Mode::Gate), + budget: Duration::from_millis(3), + batches: Vec::new(), + }) + .collect() +} + +#[test] +fn failures_preserve_previous_cells_stages_and_exact_observed_prefix() { + for budget_failure in [false, true] { + for failing_sample in 0..3 { + let mut raw = pending_cells(); + let mut calls = [0; 3]; + let error = calibrate_cells(&mut raw, |at, count| { + calls[at] += 1; + if at == 0 { + return Ok(Duration::from_millis(2)); + } + if count == 2 && calls[at] == 4 + failing_sample { + return if budget_failure { + Ok(Duration::from_nanos(6_000_001)) + } else { + Err(HarnessError("primary-operation-failure".into())) + }; + } + Ok(Duration::from_nanos(17)) + }) + .unwrap_err(); + assert_eq!(calls, [3, 4 + failing_sample, 0]); + assert_eq!(raw[0].calibration, target_trace(1)); + let Calibration::Batches { stages, outcome } = &raw[1].calibration else { + panic!("expected trace") + }; + assert_eq!( + *outcome, + if budget_failure { + CalibrationOutcome::BudgetExceeded + } else { + CalibrationOutcome::OperationFailed + } + ); + assert_eq!(stages.len(), 2); + assert_eq!(stages[0].samples, [Duration::from_nanos(17); 3]); + assert_eq!( + stages[1].samples.len(), + failing_sample + usize::from(budget_failure) + ); + let primary = if budget_failure { + "AbandonedCell" + } else { + "primary-operation-failure" + }; + assert!(error.0.lines().next().unwrap().contains(primary), "{error}"); + assert!( + error + .0 + .contains(&format!("stage 1 count 2 sample {failing_sample}")), + "{error}" + ); + assert!(error.0.contains("complete size 8"), "{error}"); + assert!(!error.0.contains("must-not-run"), "{error}"); + let mut expected = " calibration-stage-ns: 1 2".to_owned(); + for _ in 0..failing_sample { + expected.push_str(" 17"); + } + if budget_failure { + expected.push_str(" 6000001"); + } + assert!(error.0.lines().any(|line| line == expected), "{error}"); + } + } +} + +#[test] +fn first_operation_failure_retains_an_empty_stage_and_stops() { + let mut raw = pending_cells(); + let mut calls = Vec::new(); + let error = calibrate_cells(&mut raw, |at, count| { + calls.push((at, count)); + Err(HarnessError("first-operation-failed".into())) + }) + .unwrap_err(); + assert_eq!(calls, [(0, 1)]); + assert_eq!( + raw[0].calibration, + Calibration::Batches { + stages: vec![CalibrationStage { + iterations: 1, + samples: Vec::new() + }], + outcome: CalibrationOutcome::OperationFailed, + } + ); + assert!( + error + .0 + .lines() + .next() + .unwrap() + .contains("calibration stage 0 count 1 sample 0: first-operation-failed"), + "{error}" + ); + assert!( + error + .0 + .lines() + .any(|line| line == " calibration-stage-ns: 0 1"), + "{error}" + ); + assert!(!error.0.contains("failing size"), "{error}"); +} + +#[test] +fn smoke_records_one_setup_and_never_claims_calibration() { + let mut evidence = Calibration::new(Mode::Smoke); + let mut calls = Vec::new(); + assert_eq!( + calibrate(&mut evidence, "smoke", 1, Duration::ZERO, |count| { + calls.push(count); + Ok(Duration::ZERO) + }) + .unwrap(), + 1 + ); + assert_eq!(calls, [1]); + assert_eq!( + evidence, + Calibration::Smoke { + elapsed: Some(Duration::ZERO) + } + ); + evidence.validate(Mode::Smoke, 1, Duration::ZERO).unwrap(); + assert!(evidence.validate(Mode::Smoke, 2, MAX_CELL_WALK).is_err()); + assert!( + Calibration::new(Mode::Smoke) + .validate(Mode::Smoke, 1, MAX_CELL_WALK) + .is_err() + ); + assert!( + target_trace(1) + .validate(Mode::Smoke, 1, MAX_CELL_WALK) + .is_err() + ); + let mut text = String::new(); + write_calibration(&mut text, &evidence, Duration::ZERO).unwrap(); + assert_eq!( + text, + " per-operation-budget-ns: 0\n smoke-preparation-ns: 0; no calibration or performance claim\n" + ); +} + +#[test] +fn smoke_setup_failure_has_no_fabricated_elapsed_sample() { + let mut raw = pending_cells(); + for cell in &mut raw { + cell.calibration = Calibration::new(Mode::Smoke); + } + let mut calls = Vec::new(); + let error = calibrate_cells(&mut raw, |at, count| { + calls.push((at, count)); + if at == 0 { + Ok(Duration::from_nanos(19)) + } else { + Err(HarnessError("setup-failed".into())) + } + }) + .unwrap_err(); + assert_eq!(calls, [(0, 1), (1, 1)]); + assert_eq!( + raw[0].calibration, + Calibration::Smoke { + elapsed: Some(Duration::from_nanos(19)) + } + ); + assert_eq!(raw[1].calibration, Calibration::Smoke { elapsed: None }); + assert!( + error + .0 + .lines() + .next() + .unwrap() + .contains("failing size 8: smoke preparation count 1 sample 0: setup-failed"), + "{error}" + ); + assert!(error.0.contains("smoke-preparation-ns: 19;"), "{error}"); + assert!(error.0.contains("smoke-preparation-ns:;"), "{error}"); + assert!(!error.0.contains("must-not-run"), "{error}"); +} + +#[test] +fn calibration_formatter_preserves_sample_order_and_integer_nanoseconds() { + let trace = Calibration::Batches { + stages: vec![CalibrationStage { + iterations: 1, + samples: vec![ + Duration::from_nanos(2_000_001), + Duration::ZERO, + Duration::from_nanos(2_000_003), + ], + }], + outcome: CalibrationOutcome::TargetReached, + }; + let mut text = String::new(); + write_calibration(&mut text, &trace, Duration::from_nanos(3_000_007)).unwrap(); + assert_eq!( + text, + concat!( + " per-operation-budget-ns: 3000007\n", + " calibration-stage-ns: 0 1 2000001 0 2000003\n", + " calibration-final-ns: 0 1 2000001 0 2000003 target-reached\n" + ) + ); +} diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index a56d0fcdc..64ccef21b 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -193,36 +193,70 @@ varying the other factor. It reports legitimate association-edge and qualificati separately; a references-times-candidates product is output work, not proof of excessive overhead. -Each cell calibrates once before warmup. Its repetition count is -`ceil(2 ms / max(single-operation time, 1 ns))`, clamped to `1..=2^20`. The runner freezes this -count for all warmup and measured rounds. It stores actual batch durations and derives fractional -nanoseconds per operation only during reduction. It never reconstructs a batch from rounded -per-operation durations or applies the legacy fit's timing floor to a ratio. +Each prepared cell runs one calibration ladder before any scheduled warmup or measurement: + +1. Test repetition counts `1, 2, 4, ..., 2^20` in order. +2. At each count, execute three actual batches and retain their durations in call order. + Check the per-operation budget immediately after each completed batch. +3. Freeze the first tested count whose three-duration median reaches 2 milliseconds. +4. At the cap, accept a median at least 200 microseconds but below 2 milliseconds as `cap-limited`. + A lower median produces `CalibrationUnresolved` and exit 2 before scheduling. + +After every cell qualifies, the runner freezes its count for two warmup rounds and the requested +odd number of measured rounds. Calibration durations never enter the performance statistic. +Zero calibration durations remain observations; the runner neither divides by them nor replaces +them. It derives fractional nanoseconds per operation from scheduled batches only during +reduction, without the legacy fit's timing floor. + +Repeated calibration warms code and data and changes allocator/cache history. It estimates the +cost of repeated prepared operations, not first-call latency. Cold collection still creates and +destroys an index on every operation. Three samples prevent one unusually slow observation from +determining the median; two slow observations can still freeze an inadequate count. Full-size gate and report modes require a measured median batch of at least 200 microseconds. A shorter batch produces `UnresolvedCell` and exit 2, with its ID, size, iterations and actual -duration. A cold calibration call can overestimate later cost, so even an ordinary workload can -fail this resolution check. The runner does not retry or increase repetitions after observing a -short batch. Preserve the failed run for analysis. - -Inspect the cell's frozen repetition count and retained batches. Calibration may have -overestimated steady-state cost or reached the repetition cap. More rounds do not directly -change that count, and report-only still enforces source resolution. A new calibration or -workload policy requires review before another qualification campaign; retain the failed run -with the proposal. Do not repeat an unchanged campaign until it passes or adjust thresholds -based on observed results. - -Reports include raw scheduled batches, iteration counts, batch minimum/median/maximum and -floating-point nanoseconds per operation. Untimed counts report nodes, depth, width, fragments, -documents, owner edges, qualifications, rendered bytes, map segments, included ranges, -intersections and query output. Missing cells or rounds, duplicate identities, zero -durations, wrong membership and nonfinite statistics are harness errors. Smoke uses small -inputs and bounded repetitions, skips the resolution requirement and prints no performance -verdict. Structural and malformed-data checks still apply. - -The per-operation budget detects excessive time after an operation or batch finishes. It cannot -interrupt the first execution or a dependency call. An external deadline can bound the whole -campaign; it does not provide per-operation cancellation. +duration. Calibration does not guarantee scheduled resolution: later conditions can change the +cost. The runner does not retry or increase repetitions after observing a short batch. Preserve +the failed run for analysis. + +Inspect the cell's calibration trace, outcome, frozen count and scheduled batches. A +`cap-limited` outcome identifies a tested count that resolves below the calibration target. +More rounds do not change that count, and report-only still enforces source resolution. +A new calibration or workload policy requires review before another qualification campaign; +retain the failed run with the proposal. Do not repeat an unchanged campaign until it passes +or adjust thresholds based on observed results. + +Reports identify the `source-batches-v2/powers-of-two-median-three` policy. They print each +calibration stage and a compact final-stage summary with the stage index, count, three integer +nanosecond durations and outcome. Stage and sample indexes start at zero. The report retains the +actual per-operation budget, including custom budgets, and prints it in integer nanoseconds. +Scheduled batches have their own exact-nanosecond records, iteration counts, +minimum/median/maximum and floating-point nanoseconds per operation. Untimed counts report +nodes, depth, width, fragments, documents, owner edges, qualifications, rendered bytes, +map segments, included ranges, intersections and query output. Missing cells or rounds, +duplicate identities, zero scheduled durations, wrong membership and nonfinite statistics are +harness errors. Smoke uses +small inputs, one setup execution and one repetition per scheduled batch. Its explicit smoke +preparation record makes no calibration or performance claim. Structural and malformed-data +checks still apply. + +Validation recomputes calibration decisions without executing operations. It checks the complete +doubling ladder, three samples per stage, every sample's budget, the first qualifying stop, +the declared outcome and agreement with scheduled repetitions. This checks consistency, not +authenticity of arbitrarily rewritten records; retain artifact provenance separately. + +An operation or budget failure stops calibration immediately. Its diagnostic retains completed +earlier cells and stages plus the observed prefix of the failing stage. Budget failure retains +the offending duration. An operation failure supplies no duration, so the trace adds no sample +for it. The primary diagnostic identifies the cell, stage, count and sample. Treat exit 2 as an +unsuccessful run and stop subsequent campaign phases. + +Calibration stores at most 63 durations across 21 stages per cell, separate from scheduled data +proportional to cells times rounds. Its maximum declared work is +`3 * (1 + 2 + ... + 2^20) = 6,291,453` operation executions per cell. These are work and storage +bounds, not wall-time guarantees. The per-operation budget detects excessive time after a batch +finishes. It cannot interrupt the first execution or a dependency call. An external deadline +can bound the whole campaign; it does not provide per-operation cancellation. ### Controlled comparisons and coverage limits From 4723bb73abd1358eb3db1131af9d2de573960f89 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:39:04 -0800 Subject: [PATCH 060/221] feat(documentation): decode Rust literal attributes with mapped mixed cleanup --- .bca-baseline.toml | 116 ++- CHANGELOG.md | 7 + big-code-analysis-ast/src/documentation.rs | 5 +- .../src/documentation/canonical.rs | 2 + .../src/documentation/collector.rs | 145 ++- .../src/documentation/collector/assembly.rs | 42 +- .../collector/remediation_tests.rs | 4 +- .../src/documentation/collector/rust.rs | 144 +++ .../src/documentation/collector/rust_tests.rs | 822 ++++++++++++++++++ .../src/documentation/collector/tests.rs | 6 +- .../src/documentation/recognition.rs | 7 + .../src/documentation/text.rs | 1 + .../src/documentation/text/cleanup.rs | 18 +- .../src/documentation/text/comments.rs | 28 +- .../src/documentation/text/rust.rs | 163 ++++ .../src/documentation/text/rust/literal.rs | 201 +++++ .../src/lang_helpers/doc_comment.rs | 16 +- .../tests/rust_documentation_grammar.rs | 134 +++ .../documentation/rust-literal-continuation | Bin 0 -> 32 bytes fuzz/corpus/documentation/rust-literal-empty | Bin 0 -> 24 bytes fuzz/corpus/documentation/rust-literal-margin | Bin 0 -> 45 bytes fuzz/corpus/documentation/rust-literal-raw | Bin 0 -> 35 bytes fuzz/corpus/documentation/rust-literal-scalar | Bin 0 -> 33 bytes .../documentation/rust-pending-metadata | Bin 0 -> 27 bytes fuzz/documentation-seeds.json | 74 +- fuzz/generate_documentation_seeds.py | 8 +- fuzz/src/documentation/tests.rs | 78 +- src/metrics/loc/documentation_tests.rs | 83 ++ tests/fixtures/documentation/forms.json | 2 +- tests/fixtures/documentation/provenance.json | 1 + .../documentation/rust-unit1-provenance.json | 28 + utils/documentation-collector-perturb.json | 10 +- utils/documentation-rust-literal-perturb.json | 91 ++ 33 files changed, 2070 insertions(+), 166 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/collector/rust.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/rust_tests.rs create mode 100644 big-code-analysis-ast/src/documentation/text/rust.rs create mode 100644 big-code-analysis-ast/src/documentation/text/rust/literal.rs create mode 100644 big-code-analysis-ast/tests/rust_documentation_grammar.rs create mode 100644 fuzz/corpus/documentation/rust-literal-continuation create mode 100644 fuzz/corpus/documentation/rust-literal-empty create mode 100644 fuzz/corpus/documentation/rust-literal-margin create mode 100644 fuzz/corpus/documentation/rust-literal-raw create mode 100644 fuzz/corpus/documentation/rust-literal-scalar create mode 100644 fuzz/corpus/documentation/rust-pending-metadata create mode 100644 tests/fixtures/documentation/rust-unit1-provenance.json create mode 100644 utils/documentation-rust-literal-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index f4c449f99..21124962d 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,13 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 966.0 +value = 961.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 137.0 +value = 134.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -455,19 +455,19 @@ value = 13.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::recognize" metric = "halstead.effort" -value = 86240.41224844726 +value = 72422.98375857045 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::recognize" metric = "nexits" -value = 8.0 +value = 7.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::record_children" metric = "halstead.effort" -value = 67267.11040846657 +value = 123556.27877545246 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -505,65 +505,47 @@ qualified = "Builder<'s>::register" metric = "nexits" value = 6.0 -[[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::rust_attribute" -metric = "abc" -value = 38.948684188300895 - [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::rust_attribute" metric = "halstead.effort" -value = 127301.51843197798 - -[[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::rust_attribute" -metric = "nexits" -value = 5.0 - -[[entry]] -path = "big-code-analysis-ast/src/documentation/collector.rs" -qualified = "Builder<'s>::rust_carrier" -metric = "nexits" -value = 7.0 +value = 143073.56545441947 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "abc" -value = 49.85980344927164 +value = 54.286278192559855 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "cognitive" -value = 17.0 +value = 21.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "halstead.effort" -value = 182593.08399265425 +value = 224208.069491629 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::walk" metric = "nexits" -value = 9.0 +value = 10.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "abc" -value = 57.3149195236284 +value = 58.29236656715869 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "halstead.effort" -value = 98332.32124623262 +value = 99507.69266781778 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -581,7 +563,7 @@ value = 13.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>" metric = "wmc" -value = 79.0 +value = 81.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -593,31 +575,31 @@ value = 48218.38058500087 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::combine_pending" metric = "halstead.effort" -value = 58850.75713727861 +value = 71442.25234889281 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "abc" -value = 52.44044240850758 +value = 53.61902647381804 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cognitive" -value = 23.0 +value = 24.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "cyclomatic" -value = 22.0 +value = 23.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "halstead.effort" -value = 143957.07071732648 +value = 155069.99356991026 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -653,7 +635,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::render_draft" metric = "halstead.effort" -value = 56025.386626091306 +value = 59532.42614212931 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -897,7 +879,7 @@ value = 66174.94088354147 [[entry]] path = "big-code-analysis-ast/src/documentation/recognition.rs" -qualified = "NativeRules::target::" +qualified = "NativeRules::target::" metric = "cyclomatic" value = 17.0 @@ -1019,7 +1001,13 @@ value = 8.0 path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" qualified = "Projection<'_, 's>::copy" metric = "halstead.effort" -value = 76728.81532849002 +value = 86098.43456577566 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "Projection<'_, 's>::copy" +metric = "nexits" +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" @@ -1091,7 +1079,7 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "" metric = "loc.ploc" -value = 583.0 +value = 587.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1129,6 +1117,12 @@ qualified = "beautify" metric = "nexits" value = 16.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "blank" +metric = "halstead.effort" +value = 49441.34419913078 + [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "blank" @@ -1211,7 +1205,7 @@ value = 16.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "lines" metric = "halstead.effort" -value = 62992.207215869705 +value = 65731.40015873815 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1235,7 +1229,7 @@ value = 28.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "prepare" metric = "halstead.effort" -value = 176271.65882530835 +value = 182561.73428562423 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1321,6 +1315,18 @@ qualified = "expand_tabs" metric = "nexits" value = 7.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/rust/literal.rs" +qualified = "escape" +metric = "cyclomatic" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/rust/literal.rs" +qualified = "unicode" +metric = "nexits" +value = 5.0 + [[entry]] path = "big-code-analysis-ast/src/getter.rs" qualified = "Getter::is_braced_literal_slot" @@ -1361,7 +1367,7 @@ value = 101217.532578918 path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "" metric = "loc.ploc" -value = 909.0 +value = 921.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -1459,11 +1465,17 @@ qualified = "collect_stretch" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "collect_stretch_with_budget" +metric = "cognitive" +value = 15.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "collect_stretch_with_budget" metric = "halstead.effort" -value = 66915.85266413665 +value = 79913.2034194401 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" @@ -1555,17 +1567,29 @@ qualified = "stretch_end" metric = "nargs" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end_with_budget" +metric = "abc" +value = 40.8166632639171 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end_with_budget" +metric = "cognitive" +value = 17.0 + [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "stretch_end_with_budget" metric = "cyclomatic" -value = 15.0 +value = 17.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" qualified = "stretch_end_with_budget" metric = "halstead.effort" -value = 113377.45845370996 +value = 123841.80744856672 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index ea48a4e28..afb3aca8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,13 @@ for historical reference. ### Added +- The unstable Rust AST documentation collector now decodes direct cooked/raw + `doc` strings and composes them with comments using Rust 1.99.0 cleanup and + exact forward origins. Invalid encoding, unsupported byte/C prefixes, recovery + and excluded source retain explicit unavailable states. Metadata and computed + carriers, additional owner projections and publication interpretation remain + pending. Legacy documentation rows and test pruning are preserved. (#1664, Unit1) + - Added an unstable borrowed AST documentation collector with prepared canonical owner queries, explicit pending-adapter assessments, and retained local text and forward-origin views. Basic comment paths cover the 17 streamed language diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index 3f4119f94..5e087fb6c 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -25,6 +25,9 @@ //! Known candidate/reference qualifications are separate immutable records, indexed //! by document and owner. Ambiguity preserves each candidate's conditional/recovery //! facts; pending assessments describe unsupported matching rather than those facts. +//! Rust direct cooked/raw doc attributes share whole-document cleanup with comments. +//! Decoded-coordinate cleanup composes retained escape origins; metadata and computed +//! carriers remain pending, independently of existing owner projections and publication. pub(crate) mod budget; pub(crate) mod byte_scan; @@ -212,7 +215,7 @@ pub enum FragmentForm { Preamble, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) struct FragmentId(pub(crate) usize); #[derive(Clone, Copy, Debug)] pub(crate) struct DocumentId(pub(crate) usize); diff --git a/big-code-analysis-ast/src/documentation/canonical.rs b/big-code-analysis-ast/src/documentation/canonical.rs index 915b819b4..4cbd22d81 100644 --- a/big-code-analysis-ast/src/documentation/canonical.rs +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -29,6 +29,7 @@ pub(super) struct CanonicalNode<'s> { pub(super) qualifications: Vec, pub(super) pending_parent: Option, pub(super) following: Option, + pub(super) following_gap: bool, pub(super) owner_context: NodeId, pub(super) name_scope: NodeId, pub(super) qualification: super::qualifications::QualificationSet, @@ -75,6 +76,7 @@ impl<'s> CanonicalNodes<'s> { qualifications: Vec::new(), pending_parent: None, following: None, + following_gap: false, owner_context: id, name_scope: NodeId(0), qualification: super::qualifications::QualificationSet::default(), diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index ed384e9ee..1f2262de4 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -10,6 +10,7 @@ use crate::{Ancestors, Checker, FoldCache, Node, SiblingCache}; mod assembly; mod projections; mod qualifications; +mod rust; enum Visit { Enter(NodeId, usize), @@ -75,6 +76,7 @@ pub(crate) fn collect_typed<'s, T: Checker + crate::traits::LanguageInfo>( }, drafts: Vec::new(), pending_attributes: Vec::new(), + rust_values: std::collections::HashMap::new(), names: super::names::Names::default(), }; let root_id = builder @@ -115,6 +117,7 @@ struct Builder<'s> { index: DocumentationIndex<'s>, drafts: Vec>, pending_attributes: Vec<(NodeId, FragmentId, Option)>, + rust_values: std::collections::HashMap, names: super::names::Names, } @@ -187,6 +190,17 @@ impl<'s> Builder<'s> { if self.index.profile != Profile::Helper { self.finalize_projection(id, budget)?; } + if self.index.profile == Profile::Rust + && matches!( + self.index.canonical.nodes[id.0].evidence.node().kind(), + "attribute_item" | "inner_attribute_item" + ) + { + let node = Node::from_tree_sitter( + self.index.canonical.nodes[id.0].evidence.node(), + ); + self.rust_attribute(id, &node, budget)?; + } let record = &self.index.canonical.nodes[id.0]; let complex = record.signature_complex || matches!( @@ -252,6 +266,7 @@ impl<'s> Builder<'s> { fields: &mut Vec>, budget: &CollectionBudget, ) -> Result<(), CollectionError> { + // bca: suppress(abc, cognitive, nexits) -- the canonical batch records fields, following targets and coverage barriers in one reverse pass. let node = self.index.canonical.nodes[id.0].evidence.node(); children.clear(); fields.clear(); @@ -278,6 +293,8 @@ impl<'s> Builder<'s> { .canonical .batch(id, children, &self.index.source, budget)?; let mut following = None; + let mut next_start = None; + let mut following_gap = false; for (&child, field) in self.index.canonical.children [self.index.canonical.nodes[id.0].children.clone()] .iter() @@ -286,11 +303,27 @@ impl<'s> Builder<'s> { { budget.step()?; let record = &mut self.index.canonical.nodes[child.0]; + if self.index.profile == Profile::Rust + && let Some(start) = next_start + { + following_gap |= !self + .index + .source + .covers_with_budget(record.evidence.node().end_byte()..start, budget)?; + } record.field = *field; record.following = following; + record.following_gap = following_gap; let child_node = Node::from_tree_sitter(record.evidence.node()); + next_start = Some(child_node.start_byte()); if !T::is_comment(&child_node) && child_node.kind() != "attribute_item" { following = Some(child); + following_gap = false; + } else if self.index.profile == Profile::Rust && child_node.kind() != "attribute_item" { + following_gap |= !self + .index + .source + .covers_with_budget(child_node.start_byte()..child_node.end_byte(), budget)?; } } Ok(()) @@ -397,11 +430,6 @@ impl<'s> Builder<'s> { budget: &CollectionBudget, ) -> Result<(), CollectionError> { budget.step()?; - if self.index.profile == Profile::Rust - && matches!(node.kind(), "attribute_item" | "inner_attribute_item") - { - self.rust_attribute(id, node, budget)?; - } if !T::is_comment(node) { return Ok(()); } @@ -718,8 +746,8 @@ impl<'s> Builder<'s> { node: &Node<'s>, budget: &CollectionBudget, ) -> Result<(), CollectionError> { - let carrier = self.rust_carrier(node, budget)?; - if carrier == Some(false) { + let carrier = self.rust_carrier(id, budget)?; + if matches!(carrier, rust::Carrier::Other) { return Ok(()); } let mut target = if node.kind() == "attribute_item" { @@ -739,34 +767,35 @@ impl<'s> Builder<'s> { }) } }; - if let Some(candidate) = target { - let target_node = self.index.canonical.nodes[candidate.0].evidence.node(); - if node.kind() == "attribute_item" - && !self - .index - .source - .covers_with_budget(node.end_byte()..target_node.start_byte(), budget)? - { - target = None; - } + if node.kind() == "attribute_item" && self.index.canonical.nodes[id.0].following_gap { + target = None; + } + let unassessed = matches!( + carrier, + rust::Carrier::Unknown | rust::Carrier::Doc(rust::Value::Pending) + ); + if unassessed { + let assessment = self.index.assessments.len(); + self.index.assessments.push(Assessment { + axis: AssessmentAxis::Occurrence, + reason: if matches!(carrier, rust::Carrier::Unknown) { + "Excluded or recovered Rust attribute path may carry documentation" + } else { + "Structured Rust doc/cfg_attr carrier awaits interpretation" + }, + node: Some(self.index.canonical.nodes[id.0].evidence), + document: None, + }); + let pending_scope = target + .or(self.index.canonical.nodes[id.0].parent) + .unwrap_or(NodeId(0)); + self.index.canonical.nodes[pending_scope.0] + .pending + .push(assessment); } - let assessment = self.index.assessments.len(); - self.index.assessments.push(Assessment { - axis: AssessmentAxis::Occurrence, - reason: if carrier.is_none() { - "Excluded or recovered Rust attribute path may carry documentation" - } else { - "Structured Rust doc/cfg_attr carrier awaits interpretation" - }, - node: Some(self.index.canonical.nodes[id.0].evidence), - document: None, - }); let pending_scope = target .or(self.index.canonical.nodes[id.0].parent) .unwrap_or(NodeId(0)); - self.index.canonical.nodes[pending_scope.0] - .pending - .push(assessment); let publication = self.index.assessments.len(); self.index.assessments.push(Assessment { axis: AssessmentAxis::Publication, @@ -777,9 +806,9 @@ impl<'s> Builder<'s> { self.index.canonical.nodes[pending_scope.0] .pending .push(publication); - if carrier.is_none() { + let rust::Carrier::Doc(value) = carrier else { return Ok(()); - } + }; let source = self .index .source @@ -790,45 +819,10 @@ impl<'s> Builder<'s> { FragmentForm::Attribute, ); self.pending_attributes.push((id, fragment, target)); + self.rust_values.insert(fragment, value); Ok(()) } - fn rust_carrier( - &self, - node: &Node<'s>, - budget: &CollectionBudget, - ) -> Result, CollectionError> { - for child in node.children() { - budget.step()?; - bounds(child.as_tree_sitter(), self.index.source.bytes().len())?; - if child.kind() != "attribute" { - continue; - } - for path in child.children() { - budget.step()?; - bounds(path.as_tree_sitter(), self.index.source.bytes().len())?; - if !path.is_named() { - continue; - } - if !self - .index - .source - .covers_with_budget(path.start_byte()..path.end_byte(), budget)? - { - return Ok(None); - } - return Ok(Some( - path.kind() == "identifier" - && matches!( - &self.index.source.bytes()[path.start_byte()..path.end_byte()], - b"doc" | b"cfg_attr" - ), - )); - } - } - Ok((!node.has_error()).then_some(false)) - } - fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { self.coalesce_rust(budget)?; self.combine_pending(budget)?; @@ -967,11 +961,12 @@ fn needs_slot(profile: Profile, kind: &str) -> bool { } fn fields_needed(profile: Profile, kind: &str) -> bool { - (profile == Profile::Doxygen - && (matches!( - kind, - "declaration" | "field_declaration" | "function_definition" - ) || kind.ends_with("declarator"))) + (profile == Profile::Rust && kind == "attribute") + || (profile == Profile::Doxygen + && (matches!( + kind, + "declaration" | "field_declaration" | "function_definition" + ) || kind.ends_with("declarator"))) || (matches!(profile, Profile::Jsdoc | Profile::BcaTypescriptSource) && kind == "export_statement") || (profile == Profile::Yard && matches!(kind, "if_modifier" | "unless_modifier")) @@ -1014,4 +1009,6 @@ mod projection_tests; #[cfg(test)] mod remediation_tests; #[cfg(test)] +mod rust_tests; +#[cfg(test)] mod tests; diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index c0a3d3663..e7bb5be89 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -67,9 +67,10 @@ impl<'s> Builder<'s> { } for (node, fragment, target) in std::mem::take(&mut self.pending_attributes) { budget.step()?; + let pending = matches!(self.rust_values.get(&fragment), Some(rust::Value::Pending)); if let Some(&index) = target.as_ref().and_then(|target| by_target.get(target)) { self.drafts[index].fragments.push(fragment); - self.drafts[index].pending = true; + self.drafts[index].pending |= pending; } else { let scope = self.index.canonical.nodes[target.unwrap_or(node).0] .parent @@ -89,7 +90,7 @@ impl<'s> Builder<'s> { .map(|id| self.index.canonical.nodes[id.0].evidence), role: target.map_or(DocumentRole::Primary, |id| self.rust_role(id)), unresolved: None, - pending: true, + pending: pending || target.is_none(), gap: false, }); } @@ -169,7 +170,17 @@ impl<'s> Builder<'s> { draft.unresolved = None; } if pending { - self.pending_document(&draft, document, &owners, attribute, budget)?; + let unassessed_content = matches!( + self.index.facts.documents[document.0].content, + Content::PendingAdapter + ); + self.pending_document( + &draft, + document, + &owners, + attribute && unassessed_content, + budget, + )?; self.pending_conditional_selection(draft.target, document); } if (!owners.is_empty() && (!pending || draft.target.is_some())) @@ -331,24 +342,25 @@ impl<'s> Builder<'s> { attribute |= fragment.form == FragmentForm::Attribute; fragments.push(fragment); } - let content = if attribute { - Content::PendingAdapter + let result = if attribute { + self.rust_content(draft, budget) } else if draft.gap { - Content::Unavailable(UnavailableReason::ExcludedGap) + Ok(Content::Unavailable(UnavailableReason::ExcludedGap)) } else { - match crate::documentation::text::comments::render( + crate::documentation::text::comments::render( self.index.profile, &self.index.source, &fragments, budget, - ) { - Ok(content) => content, - Err(crate::documentation::text::TextError::Source(error)) => { - return Err(error.into()); - } - Err(crate::documentation::text::TextError::Unavailable(reason)) => { - Content::Unavailable(reason) - } + ) + }; + let content = match result { + Ok(content) => content, + Err(crate::documentation::text::TextError::Source(error)) => { + return Err(error.into()); + } + Err(crate::documentation::text::TextError::Unavailable(reason)) => { + Content::Unavailable(reason) } }; Ok((content, attribute)) diff --git a/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs b/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs index a389f5a5f..17c862c46 100644 --- a/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/remediation_tests.rs @@ -23,7 +23,7 @@ fn rust_same_target_composition_and_roles_are_independent_of_placement() { ( "/// outer\n#[doc = \"attribute\"]\nfn f() { //! inner\n}\n", "function_item", - None, + Some("outer\nattribute\ninner"), 3, DocumentRole::Primary, ), @@ -51,7 +51,7 @@ fn rust_same_target_composition_and_roles_are_independent_of_placement() { ( "//! first\n#![doc = \"middle\"]\n//! second\n", "source_file", - None, + Some("first\nmiddle\nsecond"), 3, DocumentRole::FilePackage, ), diff --git a/big-code-analysis-ast/src/documentation/collector/rust.rs b/big-code-analysis-ast/src/documentation/collector/rust.rs new file mode 100644 index 000000000..75ddd2efa --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/rust.rs @@ -0,0 +1,144 @@ +//! Direct Rust attribute fields, assessed independently of owner projection. + +use super::*; +use std::ops::Range; + +pub(super) enum Carrier { + Other, + Unknown, + Doc(Value), +} + +pub(super) enum Value { + Pending, + Boundary, + Literal(Range), +} + +#[derive(Default)] +struct AttributeFields<'s> { + path: Option>, + value: Option>, + arguments: bool, +} + +impl<'s> AttributeFields<'s> { + fn read( + canonical: &CanonicalNodes<'s>, + attribute: NodeId, + budget: &CollectionBudget, + ) -> Result { + let mut fields = Self::default(); + for &child in &canonical.children[canonical.nodes[attribute.0].children.clone()] { + budget.step()?; + let record = &canonical.nodes[child.0]; + let node = record.evidence.node(); + match record.field { + Some("value") => fields.value = Some(node), + Some("arguments") => fields.arguments = true, + None if fields.path.is_none() + && node.is_named() + && !matches!(node.kind(), "line_comment" | "block_comment") => + { + fields.path = Some(node); + } + _ => {} + } + } + Ok(fields) + } + + fn value(&self, recovered: bool) -> Value { + if recovered { + Value::Boundary + } else if self.arguments { + Value::Pending + } else { + match self.value { + Some(value) if matches!(value.kind(), "string_literal" | "raw_string_literal") => { + Value::Literal(value.byte_range()) + } + Some(_) => Value::Pending, + None => Value::Boundary, + } + } + } +} + +impl<'s> Builder<'s> { + pub(super) fn rust_carrier( + &self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result { + // bca: suppress(nexits, halstead) -- each uncertain path and unsupported carrier has a distinct early result. + let canonical = &self.index.canonical; + let item = &canonical.nodes[id.0]; + for &child in &canonical.children[item.children.clone()] { + budget.step()?; + let attribute = &canonical.nodes[child.0]; + if attribute.evidence.node().kind() != "attribute" { + continue; + } + let fields = AttributeFields::read(canonical, child, budget)?; + let Some(path) = fields.path else { + return Ok(Carrier::Unknown); + }; + if path.has_error() + || path.is_missing() + || !self + .index + .source + .covers_with_budget(path.byte_range(), budget)? + { + return Ok(Carrier::Unknown); + } + if path.kind() != "identifier" { + return Ok(Carrier::Other); + } + match &self.index.source.bytes()[path.byte_range()] { + b"cfg_attr" => return Ok(Carrier::Doc(Value::Pending)), + b"doc" => {} + _ => return Ok(Carrier::Other), + } + return Ok(Carrier::Doc(fields.value(item.evidence.node().has_error()))); + } + Ok(if item.evidence.node().has_error() { + Carrier::Unknown + } else { + Carrier::Other + }) + } + + pub(super) fn rust_content( + &self, + draft: &Draft<'_>, + budget: &CollectionBudget, + ) -> Result, super::super::text::TextError> { + use super::super::text::rust::{Input, render}; + let mut pending = false; + let mut gap = draft.gap; + let mut boundary = false; + let mut inputs = Vec::new(); + for &id in &draft.fragments { + budget.step()?; + let fragment = &self.index.facts.fragments[id.0]; + gap |= fragment.source.has_excluded_gap(); + match self.rust_values.get(&id) { + Some(Value::Pending) => pending = true, + Some(Value::Boundary) => boundary = true, + Some(Value::Literal(range)) => inputs.push(Input::Literal(fragment, range.clone())), + None => inputs.push(Input::Comment(fragment)), + } + } + if pending { + Ok(Content::PendingAdapter) + } else if gap { + Ok(Content::Unavailable(UnavailableReason::ExcludedGap)) + } else if boundary { + Ok(Content::Unavailable(UnavailableReason::GrammarBoundary)) + } else { + render(&self.index.source, &inputs, budget) + } + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs new file mode 100644 index 000000000..912462cd3 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs @@ -0,0 +1,822 @@ +#![allow( + clippy::single_range_in_vec_init, + clippy::semicolon_if_nothing_returned, + clippy::naive_bytecount +)] + +use crate::documentation::*; +use crate::{AnyParser, LANG}; +use std::ops::Range; + +#[cfg(feature = "rust")] +fn indexes(source: &[u8], check: impl Fn(&DocumentationIndex<'_>)) { + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Rust, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + check(&index); + } +} + +#[cfg(feature = "rust")] +fn text<'i, 's>(index: &'i DocumentationIndex<'s>) -> CompleteText<'i, 's> { + assert_eq!(index.documents().len(), 1); + index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap() +} + +#[cfg(feature = "rust")] +type ExpectedMapping = (Range, &'static str, Vec>); + +#[cfg(feature = "rust")] +fn maps(complete: CompleteText<'_, '_>) -> Vec { + complete + .mappings() + .iter() + .map(|mapping| { + let (kind, pieces) = match &mapping.origin { + Origin::Copied(pieces) => ("copied", pieces.pieces()), + Origin::Decoded(pieces) => ("decoded", pieces.pieces()), + Origin::Expanded(pieces) => ("expanded", pieces.pieces()), + Origin::Synthetic => ("synthetic", &[][..]), + }; + ( + mapping.output.range(), + kind, + pieces.iter().map(SourcePiece::range).collect(), + ) + }) + .collect() +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_complete_has_exact_owner_raw_fragments_and_prepared_queries() { + let source = b"/// first\n#[doc = r\"second\"]\nfn f() {}"; + indexes(source, |index| { + let complete = text(index); + assert_eq!(complete.text(), "first\nsecond"); + assert_eq!( + maps(complete), + vec![ + (0..5, "copied", vec![4..9]), + (5..6, "synthetic", vec![]), + (6..12, "copied", vec![20..26]) + ] + ); + assert_eq!(index.associations().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().composition(), Composition::AttributeSequence); + assert_eq!(document.get().fragment_count(), 2); + for (position, span, form) in [ + (0, 0..9, FragmentForm::Comment), + (1, 10..28, FragmentForm::Attribute), + ] { + let fragment = index.facts().document_fragment(document, position).unwrap(); + assert_eq!(fragment.get().form(), form); + assert_eq!(fragment.get().source().pieces()[0].range(), span); + assert_eq!(fragment.get().source().pieces()[0].bytes(), &source[span]); + } + let association = index.associations().next().unwrap(); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().publication, Publication::Unknown); + assert_eq!(association.get().owner_count(), 1); + assert_eq!( + association.get().binding.unwrap().node().byte_range(), + 29..38 + ); + assert_eq!(association.get().lexical_scope.node().byte_range(), 0..38); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("function owner") + }; + assert_eq!(node.node().kind(), "function_item"); + assert_eq!(node.node().byte_range(), 29..38); + let query = index.node_associations(node.node()).unwrap(); + assert_eq!(query.associations().collect::>(), vec![association]); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); + assert!(!index.assessments().any(|a| matches!( + a.get().axis, + AssessmentAxis::Occurrence | AssessmentAxis::Composition + ))); + assert_eq!(complete.origins(12..12).unwrap().count(), 0); + assert_eq!( + complete.origins(13..13).unwrap_err(), + TextRangeError::Bounds + ); + }); +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces() { + for (source, expected) in [ + ( + "/// hello\n#[doc = \"another\"]\nfn f() {}", + " hello\nanother", + ), + ( + "#[doc = \"another\"]\n/// hello\nfn f() {}", + "another\n hello", + ), + ("#[doc = \"\"] fn f() {}", ""), + ("#[doc = \"\"] #[doc = \"\"] fn f() {}", "\n"), + ("#[doc = \"a\\n\"] fn f() {}", "a"), + ("#[doc = \"a\\n\\n\"] fn f() {}", "a\n"), + ("#[doc = \"a\\r\"] fn f() {}", "a\r"), + ("#[doc = \"a\\r\nb\"] fn f() {}", "a\nb"), + ("#[doc = \"a\\n\\t b\"] fn f() {}", "a\n\t b"), + ("#[doc = r\"a\n\nb\"] fn f() {}", "a\n\nb"), + ("#[doc = \" \"] #[doc = \"\"] fn f() {}", " \n"), + ("#[doc = \"\\t a \"] fn f() {}", "a "), + ("#[doc = \"\\u{2003}\\n a\"] fn f() {}", "\u{2003}\na"), + ( + "/**\n * first \n */\n#[doc = \"second\"] fn f() {}", + "first \nsecond", + ), + ("/*! a */ /*! b */ fn f() { work()?; }", "a \nb "), + ( + "#[/* extra */ doc /* after */ = \"audit\"] fn f() {}", + "audit", + ), + ("#[doc = r###\"a\"#b\"###] fn f() {}", "a\"#b"), + ] { + indexes(source.as_bytes(), |index| { + assert_eq!(text(index).text(), expected, "{source:?}") + }); + } +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_escape_origins_are_complete_tokens_after_cleanup() { + indexes(b"#[doc = r\"a\n\nb\"] fn f() {}", |index| { + assert_eq!( + maps(text(index)), + vec![ + (0..1, "copied", vec![10..11]), + (1..2, "copied", vec![11..12]), + (2..3, "copied", vec![12..13]), + (3..4, "copied", vec![13..14]) + ] + ); + }); + for (source, expected, origins) in [ + ( + r#"#[doc = " \u{1F600}\n z"] fn f() {}"#, + "😀\nz", + vec![ + (0..4, "decoded", vec![11..20]), + (4..5, "decoded", vec![20..22]), + (5..6, "copied", vec![24..25]), + ], + ), + ( + r#"#[doc = "a\r\nb"] fn f() {}"#, + "a\nb", + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "decoded", vec![12..14]), + (2..3, "copied", vec![14..15]), + ], + ), + ( + "#[doc = \"a\r\nb\"] fn f() {}", + "a\nb", + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "decoded", vec![10..12]), + (2..3, "copied", vec![12..13]), + ], + ), + ( + "#[doc = r\"a\r\nb\"] fn f() {}", + "a\nb", + vec![ + (0..1, "copied", vec![10..11]), + (1..2, "decoded", vec![11..13]), + (2..3, "copied", vec![13..14]), + ], + ), + ( + "#[doc = \"a\\\n \t\r\nb\"] fn f() {}", + "ab", + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "copied", vec![16..17]), + ], + ), + ( + "#[doc = \"a\\\r\n \t\nb\"] fn f() {}", + "ab", + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "copied", vec![16..17]), + ], + ), + ] { + indexes(source.as_bytes(), |index| { + let complete = text(index); + assert_eq!(complete.text(), expected, "{source:?}"); + assert_eq!(maps(complete), origins, "{source:?}"); + if expected.starts_with('😀') { + assert_eq!( + complete.origins(1..4).unwrap_err(), + TextRangeError::ScalarBoundary + ); + let origin = complete.origins(0..4).unwrap().next().unwrap(); + let OriginView::Decoded(pieces) = origin.origin else { + panic!("escape") + }; + assert_eq!( + pieces.iter().map(SourcePiece::range).collect::>(), + vec![11..20] + ); + } + }); + } + indexes(br#"#[doc = "\"\'\\\n\r\t\0\x41"] fn f() {}"#, |index| { + assert_eq!(text(index).text(), "\"'\\\n\r\t\0A") + }); +} + +#[test] +#[cfg(feature = "rust")] +#[allow(clippy::too_many_lines)] // The table pins priority between contributor states in both source orders. +fn rust_literal_state_priority_is_pending_gap_boundary_then_source_order() { + use UnavailableReason::{GrammarBoundary, InvalidEncoding, NonScalar, UnsupportedDecoding}; + for (value, reason) in [ + (r#"b"\xff""#, UnsupportedDecoding), + (r#"c"a""#, UnsupportedDecoding), + (r##"br#"a"#"##, UnsupportedDecoding), + (r##"cr#"a"#"##, UnsupportedDecoding), + (r#""\q""#, InvalidEncoding), + (r#""\x80""#, InvalidEncoding), + (r#""\u0041""#, InvalidEncoding), + (r#""\u{D800}""#, NonScalar), + (r#""\u{110000}""#, NonScalar), + (r#""\u{1_f600}""#, GrammarBoundary), + (r#""\x1""#, GrammarBoundary), + (r#""\xGG""#, GrammarBoundary), + (r#""\xé1""#, GrammarBoundary), + (r#""\u{}""#, GrammarBoundary), + (r#""\u{1234567}""#, InvalidEncoding), + ("\"a\rb\"", InvalidEncoding), + ("\"a\\\n \rb\"", InvalidEncoding), + ("r\"a\rb\"", InvalidEncoding), + ] { + let source = format!("#[doc = {value}] fn f() {{}}"); + indexes(source.as_bytes(), |index| { + assert_eq!(index.documents().len(), 1, "{source}"); + assert!( + matches!(index.documents().next().unwrap().get().content(), Content::Unavailable(actual) if *actual == reason), + "{source}" + ); + assert_eq!(index.associations().len(), 1); + }); + } + for (first, second, reason) in [ + (r#""\x80""#, r#""\u{D800}""#, InvalidEncoding), + (r#""\u{D800}""#, r#""\x80""#, NonScalar), + (r#"b"x""#, r#""\x80""#, UnsupportedDecoding), + (r#""\x80""#, r#"b"x""#, InvalidEncoding), + ] { + let source = format!("#[doc = {first}] #[doc = {second}] fn f() {{}}"); + indexes(source.as_bytes(), |index| { + assert!( + matches!(index.documents().next().unwrap().get().content(), Content::Unavailable(actual) if *actual == reason), + "{source}" + ) + }); + } + for source in [ + "#[doc = b\"x\"] #[doc(hidden)] fn f() {}", + "#[doc(hidden)] #[doc = b\"x\"] fn f() {}", + "#[doc(alias = \"not prose\")] #[doc = \"known\"] fn f() {}", + "#[doc = \"known\"] #[doc = concat!(\"computed\")] fn f() {}", + ] { + indexes(source.as_bytes(), |index| { + assert!( + matches!( + index.documents().next().unwrap().get().content(), + Content::PendingAdapter + ), + "{source}" + ) + }); + } + for (source, reason) in [ + ( + b"#[doc = b\"\xff\"] fn f() {}".as_slice(), + UnsupportedDecoding, + ), + (b"#[doc = \"\xff\"] fn f() {}", InvalidEncoding), + ] { + indexes(source, |index| { + assert!( + matches!(index.documents().next().unwrap().get().content(), Content::Unavailable(actual) if *actual == reason) + ) + }); + } + for source in [ + b"/// a\xff\n#[doc = b\"x\"] fn f() {}".as_slice(), + b"#[doc = \"\xff\\u{D800}\"] fn f() {}", + ] { + indexes(source, |index| { + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(InvalidEncoding) + )) + }); + } + indexes(b"#[doc = \"\\u{D800}\xff\"] fn f() {}", |index| { + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(NonScalar) + )) + }); + for source in [ + "#[doc = \"\\x80\"] #[doc = ] fn f() {}", + "#[doc = ] #[doc = \"\\x80\"] fn f() {}", + ] { + indexes(source.as_bytes(), |index| { + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(GrammarBoundary) + )) + }); + } +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_recovery_keeps_a_valid_neighbor_and_owner_uncertainty() { + indexes(b"#[doc = \"tail\"]", |index| { + assert_eq!(text(index).text(), "tail"); + assert_eq!(index.associations().len(), 0); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner) + ); + }); + for broken in [ + "#[doc = ]", + "#[doc \"a\"]", + "#[doc = \"a\"", + "#[doc = \"a]", + "#[doc]", + ] { + let source = format!("{broken} fn f() {{}}\n/// good\nfn g() {{}}"); + indexes(source.as_bytes(), |index| { + assert_eq!(index.documents().len(), 2, "{source}"); + assert!( + matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::GrammarBoundary) + ), + "{source}" + ); + let last = index.documents().last().unwrap(); + assert_eq!(index.complete_text(last).unwrap().unwrap().text(), "good"); + }); + } + indexes(b"struct S(#[doc = \"slot\"] u32);", |index| { + assert_eq!(text(index).text(), "slot"); + assert_eq!(index.associations().len(), 0); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner) + ); + assert!( + !index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Composition) + ); + }); +} + +#[cfg(feature = "rust")] +fn included( + source: &[u8], + gaps: &[Range], + split: bool, + check: impl Fn(&DocumentationIndex<'_>), +) { + // bca: suppress(halstead) -- exact included-byte and physical-point construction keeps the supplied parse reproducible. + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + let point = |at| { + let prefix = &source[..at]; + tree_sitter::Point::new( + prefix.iter().filter(|&&b| b == b'\n').count(), + prefix + .iter() + .rposition(|&b| b == b'\n') + .map_or(at, |lf| at - lf - 1), + ) + }; + let mut spans: Vec> = Vec::new(); + for at in 0..source.len() { + if gaps.iter().any(|gap| gap.contains(&at)) { + continue; + } + if !split + && let Some(last) = spans.last_mut() + && last.end == at + { + last.end += 1; + } else { + spans.push(at..at + 1); + } + } + let ranges: Vec<_> = spans + .into_iter() + .map(|span| tree_sitter::Range { + start_byte: span.start, + end_byte: span.end, + start_point: point(span.start), + end_point: point(span.end), + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + let index = collect( + LANG::Rust, + &tree, + source, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + check(&index); +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes() { + let source = b"#[doc = \"\\x80\"] #[doc = \"bXc\"] fn f() {}"; + included(source, &[26..27], false, |index| { + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::ExcludedGap) + )) + }); + included( + b"/// a\n#[doXc = \"b\"] fn f() {}", + &[10..11], + false, + |index| { + assert_eq!(text(index).text(), "a"); + assert_eq!(index.documents().next().unwrap().get().fragment_count(), 1); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Occurrence) + ); + }, + ); + included( + b"#[doXc = \"b\"]\n/// a\nfn f() {}", + &[4..5], + false, + |index| { + assert_eq!(text(index).text(), "a"); + assert_eq!(index.documents().next().unwrap().get().fragment_count(), 1); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Occurrence) + ); + }, + ); + included( + b"#[doc = \"bXc\"]\n/// a\nfn f() {}", + &[10..11], + false, + |index| { + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::ExcludedGap) + )); + assert_eq!(index.documents().next().unwrap().get().fragment_count(), 2); + }, + ); + for suffix in ["", " #[doc = \"\\x80\"]", " #[doc = ]"] { + let source = format!("/// a\n#[doc = \"bXc\"]{suffix} fn f() {{}}"); + included(source.as_bytes(), &[16..17], false, |index| { + assert_eq!(index.documents().len(), 1); + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::ExcludedGap) + )); + let fragment = index + .facts() + .document_fragment(index.documents().next().unwrap(), 1) + .unwrap(); + assert_eq!( + fragment + .get() + .source() + .pieces() + .iter() + .map(SourcePiece::range) + .collect::>(), + vec![6..16, 17..20] + ); + }); + } + for (source, gap) in [ + ("#[doc = \"bXc\"] #[doc(hidden)] fn f() {}", 10..11), + ("#[doc(hidden)] #[doc = \"bXc\"] fn f() {}", 25..26), + ] { + included(source.as_bytes(), &[gap], false, |index| { + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::PendingAdapter + )) + }); + } + included( + "#[doc = \"é\\u{1F600}\"] fn f() {}".as_bytes(), + &[], + true, + |index| { + let complete = text(index); + assert_eq!(complete.text(), "é😀"); + assert_eq!( + maps(complete), + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "copied", vec![10..11]), + (2..6, "decoded", (11..20).map(|at| at..at + 1).collect()) + ] + ); + }, + ); +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_inner_root_module_function_and_private_nested_source_owners() { + for (source, kinds, texts) in [ + ("#![doc = \"root\"]", vec!["source_file"], vec!["root"]), + ( + "#[doc = \"outer\"] mod m { #![doc = \"inner\"] }", + vec!["mod_item"], + vec!["outer\ninner"], + ), + ( + "#[doc = \"outer\"] fn f() { #![doc = \"inner\"] }", + vec!["function_item"], + vec!["outer\ninner"], + ), + ( + "#[test] #[doc = \"test\"] fn f() { #[doc = \"nested\"] fn g() {} }", + vec!["function_item", "function_item"], + vec!["test", "nested"], + ), + ] { + indexes(source.as_bytes(), |index| { + assert_eq!(index.documents().len(), texts.len()); + assert_eq!(index.associations().len(), kinds.len()); + for ((document, association), (kind, expected)) in index + .documents() + .zip(index.associations()) + .zip(kinds.iter().zip(&texts)) + { + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + *expected + ); + assert_eq!( + document.get().role(), + if *kind == "function_item" { + DocumentRole::Primary + } else { + DocumentRole::FilePackage + } + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let (Owner::Node(node) | Owner::File(node)) = owner.get() else { + panic!("owner") + }; + assert_eq!(node.node().kind(), *kind); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .count(), + 1 + ); + } + }); + } +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_same_row_declarations_keep_distinct_source_owners() { + indexes( + b"#[doc = \"a\"] fn f() {} #[doc = \"b\"] fn f() {}", + |index| { + assert_eq!(index.documents().len(), 2); + assert_eq!(index.associations().len(), 2); + for ((document, association), (expected, span)) in index + .documents() + .zip(index.associations()) + .zip([("a", 13..22), ("b", 36..45)]) + { + assert_eq!( + index.complete_text(document).unwrap().unwrap().text(), + expected + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("function") + }; + assert_eq!(node.node().byte_range(), span); + assert_eq!(association.get().binding.unwrap().node().byte_range(), span); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); + } + }, + ); +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_plain_trivia_and_real_interstitial_gaps_do_not_become_prose() { + indexes( + b"/// a\n#[inline]\n// plain\n#[doc = \"b\"]\n/// c\nfn f() {}", + |index| { + assert_eq!(text(index).text(), "a\nb\nc"); + assert_eq!(index.documents().next().unwrap().get().fragment_count(), 3); + }, + ); + included(b"#[doc = \"a\"] X fn f() {}", &[13..14], false, |index| { + assert_eq!(text(index).text(), "a"); + assert_eq!(index.associations().len(), 0); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner) + ); + }); +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_materializes_once_and_prices_decoding_projection_and_retained_reads() { + use crate::documentation::text::{cleanup::projection_visits, rust::literal::decoded_units}; + for size in [8, 32, 128] { + for (source, expected, units, copies, projections) in [ + ( + format!("{}fn f() {{}}", "/// a\n#[doc = \"b\"]\n".repeat(size)), + String::new(), + size, + 5 * size - 1, + size, + ), + ( + format!("#[doc = \"{}\"] fn f() {{}}", "a\\x42".repeat(size)), + "aB".repeat(size), + 2 * size, + 2 * size + 1, + 2 * size, + ), + ( + format!("#[doc = r\"{}\"] fn f() {{}}", "ab".repeat(size)), + "ab".repeat(size), + 2 * size, + 2, + 1, + ), + ] { + let expected = if expected.is_empty() { + ["a", "b"].repeat(size).join("\n") + } else { + expected + }; + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + let before = observations(); + let scanned = decoded_units::observed(); + let projected = projection_visits::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + let complete = text(&index); + assert_eq!(complete.text(), expected); + // Each source scalar/escape is visited once; each decoded map is projected once. + // Mixed rows copy two content runs and one temporary literal, plus 2N-1 joins. + // Cooked values copy 2N temporary runs plus one projected line; raw values copy twice. + assert_eq!(decoded_units::observed() - scanned, units); + assert_eq!(projection_visits::observed() - projected, projections); + assert_eq!(after.copy_chunks - before.copy_chunks, copies); + assert_eq!(after.renders - before.renders, 1); + let retained = observations(); + for _ in 0..20 { + let last = complete.text().len(); + assert_eq!(complete.origins(last - 1..last).unwrap().count(), 1); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .count(), + 1 + ); + } + assert_eq!(observations().renders, retained.renders); + assert_eq!(observations().copy_chunks, retained.copy_chunks); + } + let source = format!( + "{}{}fn f() {{}}{}", + "mod m {".repeat(size), + "#[doc = \"a\"]\n".repeat(size), + "}".repeat(size) + ); + indexes(source.as_bytes(), |index| { + assert_eq!(text(index).text(), vec!["a"; size].join("\n")); + assert_eq!( + index.documents().next().unwrap().get().fragment_count(), + size + ); + }); + } +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_many_adjacent_pieces_do_not_restart_global_intersections() { + use crate::documentation::text::source_cursor::fragment_piece_visits; + for size in [8, 32, 128] { + let source = format!("#[doc = \"{}\"] fn f() {{}}", "\\x41".repeat(size)); + let before = fragment_piece_visits::observed(); + included(source.as_bytes(), &[], true, |index| { + assert_eq!(text(index).text(), "A".repeat(size)); + assert_eq!(text(index).mappings().len(), size); + // Nine prefix pieces, four bytes per escape, and one lookahead per escape. + assert_eq!(fragment_piece_visits::observed() - before, 9 + 5 * size); + }); + } +} + +#[test] +#[cfg(feature = "rust")] +fn rust_literal_text_phase_cancellation_restores_next_collection() { + use crate::documentation::budget::{WorkPhase, cancel_in_phase}; + for source in [ + format!("#[doc = \"{}\"] fn f() {{}}", "\\x41".repeat(20_000)), + format!("#[doc = r\"{}\"] fn f() {{}}", "raw".repeat(20_000)), + format!("{}fn f() {{}}", "#[doc = \"a\"]\n".repeat(5000)), + ] { + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + let collect = || { + parser.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + }; + assert!(matches!( + cancel_in_phase(WorkPhase::Text, collect), + Err(CollectionError::Cancelled) + )); + assert_eq!(collect().unwrap().documents().len(), 1); + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/tests.rs b/big-code-analysis-ast/src/documentation/collector/tests.rs index 0e1ffbabf..740980899 100644 --- a/big-code-analysis-ast/src/documentation/collector/tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/tests.rs @@ -310,15 +310,15 @@ fn rust_joint_smoke_pins_exact_composition_and_maps() { fn rust_pending_attributes_never_report_complete_partial_text() { for (source, forms) in [ ( - "#[doc = \"audit\"]\nfn f() {}", + "#[doc = concat!(\"audit\")]\nfn f() {}", vec![FragmentForm::Attribute], ), ( - "/// first\n#[doc = \"second\"]\nfn f() {}", + "/// first\n#[doc(alias = \"second\")]\nfn f() {}", vec![FragmentForm::Comment, FragmentForm::Attribute], ), ( - "#[doc = \"first\"]\n/// second\nfn f() {}", + "#[doc = include_str!(\"first\")]\n/// second\nfn f() {}", vec![FragmentForm::Attribute, FragmentForm::Comment], ), ("#[doc(hidden)]\nfn f() {}", vec![FragmentForm::Attribute]), diff --git a/big-code-analysis-ast/src/documentation/recognition.rs b/big-code-analysis-ast/src/documentation/recognition.rs index d3f7c4573..93acad8bb 100644 --- a/big-code-analysis-ast/src/documentation/recognition.rs +++ b/big-code-analysis-ast/src/documentation/recognition.rs @@ -18,6 +18,9 @@ crate::observation::counter!( pub(crate) trait SourceRules { type Checker: Checker; + fn separately_assessed_trivia(_node: &Node<'_>) -> bool { + false + } fn start_row(node: &Node<'_>, budget: &B) -> Result; fn marker(node: &Node<'_>, code: &[u8], budget: &B) -> Result; @@ -54,6 +57,10 @@ pub(crate) struct NativeRules(PhantomData); impl SourceRules for NativeRules { type Checker = T; + fn separately_assessed_trivia(node: &Node<'_>) -> bool { + // Attribute interiors have their own occurrence/content assessment; only intervening gaps break binding. + T::lang() == crate::LANG::Rust && node.kind() == "attribute_item" + } fn start_row(node: &Node<'_>, budget: &B) -> Result { if T::lang() == crate::LANG::Ruby { crate::checker::ruby::start_row_with_budget(node, budget) diff --git a/big-code-analysis-ast/src/documentation/text.rs b/big-code-analysis-ast/src/documentation/text.rs index d2a915458..40d1280f0 100644 --- a/big-code-analysis-ast/src/documentation/text.rs +++ b/big-code-analysis-ast/src/documentation/text.rs @@ -13,6 +13,7 @@ pub(super) mod cleanup; pub(super) mod comments; #[allow(dead_code)] pub(super) mod literals; +pub(super) mod rust; pub(super) mod source_cursor; #[derive(Debug)] diff --git a/big-code-analysis-ast/src/documentation/text/cleanup.rs b/big-code-analysis-ast/src/documentation/text/cleanup.rs index 4fffff5ff..cb5f3d592 100644 --- a/big-code-analysis-ast/src/documentation/text/cleanup.rs +++ b/big-code-analysis-ast/src/documentation/text/cleanup.rs @@ -5,25 +5,37 @@ use crate::documentation::budget::WorkBudget; use crate::documentation::{Content, Mapping, Origin, SourcePieces, TextRange, UnavailableReason}; use std::ops::Range; -struct Projection<'i, 's> { +pub(super) struct Projection<'i, 's> { text: &'i str, mappings: &'i [Mapping<'s>], at: usize, } impl<'s> Projection<'_, 's> { - fn copy( + pub(super) fn new<'i>(value: &'i TextBuilder<'s>) -> Projection<'i, 's> { + Projection { + text: &value.text, + mappings: &value.mappings, + at: 0, + } + } + + pub(super) fn copy( &mut self, range: Range, output: &mut TextBuilder<'s>, budget: &B, ) -> Result<(), TextError> { + if range.is_empty() { + return Ok(()); + } let start = output.text.len(); output.append_utf8(self.text[range.clone()].as_bytes(), budget)?; while let Some(mapping) = self.mappings.get(self.at) { budget .step() .map_err(|error| TextError::Source(error.into()))?; + projection_visits::record(); let span = mapping.output.range(); if span.start >= range.end { break; @@ -119,6 +131,8 @@ impl<'s> Projection<'_, 's> { } } +crate::observation::counter!(projection_visits, cfg(any(test, feature = "test-support"))); + fn copy_pieces<'s, B: WorkBudget>( pieces: &SourcePieces<'s>, budget: &B, diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs index 7f7bc8a21..d7a2a2f36 100644 --- a/big-code-analysis-ast/src/documentation/text/comments.rs +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -6,15 +6,15 @@ use crate::documentation::budget::WorkBudget; use crate::documentation::{Content, Fragment, Origin, Profile, SourceContext, UnavailableReason}; use std::ops::Range; -struct Line { - content: Range, - ending: Range, +pub(super) struct Line { + pub(super) content: Range, + pub(super) ending: Range, } -struct Block { - lines: Vec, - rust_decoration: bool, - markdown: bool, +pub(super) struct Block { + pub(super) lines: Vec, + pub(super) rust_decoration: bool, + pub(super) markdown: bool, } fn charge(budget: &B) -> Result<(), TextError> { @@ -23,7 +23,7 @@ fn charge(budget: &B) -> Result<(), TextError> { .map_err(|error| TextError::Source(error.into())) } -fn margin(bytes: &[u8], budget: &B) -> Result { +pub(super) fn margin(bytes: &[u8], budget: &B) -> Result { let mut count = 0; for byte in bytes { charge(budget)?; @@ -45,7 +45,7 @@ fn splice(bytes: &[u8], at: usize) -> usize { } } -fn lines( +pub(super) fn lines( bytes: &[u8], range: Range, splices: bool, @@ -177,7 +177,7 @@ fn delimiters( Ok((start.min(end)..end, block, raw.starts_with(b"/*"))) } -fn prepare( +pub(super) fn prepare( profile: Profile, context: &SourceContext<'_>, fragment: &Fragment<'_>, @@ -431,7 +431,11 @@ fn empty_block(block: &Block, budget: &B) -> Result(bytes: &[u8], unicode: bool, budget: &B) -> Result { +pub(super) fn blank( + bytes: &[u8], + unicode: bool, + budget: &B, +) -> Result { budget .step() .map_err(|error| TextError::Source(error.into()))?; @@ -469,7 +473,7 @@ fn blank(bytes: &[u8], unicode: bool, budget: &B) -> Result( +pub(super) fn rust_fragments( blocks: &mut [Block], bytes: &[u8], budget: &B, diff --git a/big-code-analysis-ast/src/documentation/text/rust.rs b/big-code-analysis-ast/src/documentation/text/rust.rs new file mode 100644 index 000000000..0188b9ec7 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/rust.rs @@ -0,0 +1,163 @@ +//! Rust mixed-fragment cleanup in decoded coordinates with composed origins. + +use super::cleanup::Projection; +use super::comments::{self, Block, blank, margin}; +use super::source_cursor::SourceCursor; +use super::{TextBuilder, TextError}; +use crate::documentation::budget::WorkBudget; +use crate::documentation::{Content, Fragment, Origin, Profile, SourceContext}; +use std::ops::Range; + +pub(in crate::documentation) mod literal; + +pub(in crate::documentation) enum Input<'f, 's> { + Comment(&'f Fragment<'s>), + Literal(&'f Fragment<'s>, Range), +} + +struct Prepared<'s> { + block: Block, + decoded: Option>, +} + +impl<'s> Prepared<'s> { + fn new( + context: &SourceContext<'s>, + input: &Input<'_, 's>, + budget: &B, + ) -> Result { + // bca: suppress(nexits) -- decoding, source validation and beautification propagate independent failures. + let (mut block, decoded) = match input { + Input::Comment(fragment) => { + let block = comments::prepare(Profile::Rust, context, fragment, budget, false)?; + for line in &block.lines { + budget.step().map_err(Into::into)?; + literal::validate(&context.bytes()[line.content.clone()], budget)?; + } + (block, None) + } + Input::Literal(fragment, range) => { + let value = literal::decode(context, fragment, range.clone(), budget)?; + let block = Block { + lines: comments::lines( + value.text.as_bytes(), + 0..value.text.len(), + false, + budget, + )?, + rust_decoration: false, + markdown: false, + }; + (block, Some(value)) + } + }; + let bytes = decoded + .as_ref() + .map_or(context.bytes(), |value| value.text.as_bytes()); + comments::rust_fragments(std::slice::from_mut(&mut block), bytes, budget)?; + Ok(Self { block, decoded }) + } + + fn bytes<'a>(&'a self, context: &'a SourceContext<'_>) -> &'a [u8] { + self.decoded + .as_ref() + .map_or(context.bytes(), |value| value.text.as_bytes()) + } + + fn minimum( + &self, + context: &SourceContext<'s>, + add: usize, + budget: &B, + ) -> Result { + let mut minimum = usize::MAX; + for line in &self.block.lines { + budget.step().map_err(Into::into)?; + let text = &self.bytes(context)[line.content.clone()]; + if !blank(text, true, budget)? { + minimum = minimum + .min(margin(text, budget)? + if self.decoded.is_some() { add } else { 0 }); + } + } + Ok(minimum) + } +} + +pub(in crate::documentation) fn render<'s, B: WorkBudget>( + context: &SourceContext<'s>, + inputs: &[Input<'_, 's>], + budget: &B, +) -> Result, TextError> { + // bca: suppress(nexits, halstead) -- whole-document preparation, margin selection and mapped emission are separately fallible passes. + let mut prepared = Vec::new(); + let mut sugared = false; + let mut nonsugared = false; + for input in inputs { + budget.step().map_err(Into::into)?; + sugared |= matches!(input, Input::Comment(_)); + nonsugared |= matches!(input, Input::Literal(_, _)); + prepared.push(Prepared::new(context, input, budget)?); + } + let add = usize::from(sugared && nonsugared); + let mut minimum = usize::MAX; + for fragment in &prepared { + budget.step().map_err(Into::into)?; + minimum = minimum.min(fragment.minimum(context, add, budget)?); + } + let mut output = TextBuilder::default(); + for (position, (fragment, input)) in prepared.iter().zip(inputs).enumerate() { + budget.step().map_err(Into::into)?; + if position != 0 { + output.transformed("\n", Origin::Synthetic, budget)?; + } + let indent = if minimum == usize::MAX { + 0 + } else { + minimum.saturating_sub(if fragment.decoded.is_some() { add } else { 0 }) + }; + emit(fragment, input, context, indent, &mut output, budget)?; + } + Ok(output.finish()) +} + +fn emit<'s, B: WorkBudget>( + fragment: &Prepared<'s>, + input: &Input<'_, 's>, + context: &SourceContext<'s>, + indent: usize, + output: &mut TextBuilder<'s>, + budget: &B, +) -> Result<(), TextError> { + // bca: suppress(cognitive, halstead, nargs, nexits) -- one ordered pass emits source or decoded coordinates with distinct newline origins. + let (Input::Comment(raw) | Input::Literal(raw, _)) = input; + let mut source = SourceCursor::new(&raw.source); + let mut projection = fragment.decoded.as_ref().map(Projection::new); + for (position, line) in fragment.block.lines.iter().enumerate() { + budget.step().map_err(Into::into)?; + let mut range = line.content.clone(); + if !blank(&fragment.bytes(context)[range.clone()], true, budget)? { + range.start += indent; + } + if let Some(projection) = &mut projection { + projection.copy(range, output, budget)?; + if position + 1 < fragment.block.lines.len() && !line.ending.is_empty() { + // str::lines removes a decoded CR; only the LF token is responsible. + projection.copy(line.ending.end - 1..line.ending.end, output, budget)?; + } + } else { + source.copy(output, range, budget)?; + if position + 1 < fragment.block.lines.len() { + if line.ending.len() == 2 { + output.transformed( + "\n", + Origin::Decoded(source.pieces(line.ending.clone(), budget)?), + budget, + )?; + } else { + source.copy(output, line.ending.clone(), budget)?; + } + } + } + } + Ok(()) +} diff --git a/big-code-analysis-ast/src/documentation/text/rust/literal.rs b/big-code-analysis-ast/src/documentation/text/rust/literal.rs new file mode 100644 index 000000000..6304e2646 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/text/rust/literal.rs @@ -0,0 +1,201 @@ +//! Static Rust strings; syntax validation precedes any copied/decoded output. + +use super::*; +use crate::documentation::UnavailableReason; + +fn invalid() -> TextError { + TextError::Unavailable(UnavailableReason::InvalidEncoding) +} + +fn scalar_width(bytes: &[u8], at: usize, budget: &B) -> Result { + let width = match bytes[at] { + 0..=0x7f => 1, + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => return Err(invalid()), + }; + budget.bytes(width).map_err(Into::into)?; + std::str::from_utf8(bytes.get(at..at + width).ok_or_else(invalid)?).map_err(|_| invalid())?; + Ok(width) +} + +pub(super) fn validate(bytes: &[u8], budget: &B) -> Result<(), TextError> { + let mut at = 0; + while at < bytes.len() { + at += scalar_width(bytes, at, budget)?; + } + Ok(()) +} + +pub(super) fn decode<'s, B: WorkBudget>( + context: &SourceContext<'s>, + fragment: &Fragment<'s>, + range: Range, + budget: &B, +) -> Result, TextError> { + // bca: suppress(cognitive, halstead, nexits) -- the literal state machine preserves source-order failures and complete escape origins. + let bytes = &context.bytes()[range.clone()]; + if matches!(bytes.first(), Some(b'b' | b'c')) { + return Err(TextError::Unavailable( + UnavailableReason::UnsupportedDecoding, + )); + } + let (body, raw) = delimiters(bytes, budget)?; + let bytes = &bytes[..body.end]; + let mut source = SourceCursor::new(&fragment.source); + let mut output = TextBuilder::default(); + let mut at = body.start; + let mut copied = at; + while at < body.end { + budget.bytes(1).map_err(Into::into)?; + decoded_units::record(); + let start = at; + if bytes[at] == b'\r' || (!raw && bytes[at] == b'\\') { + source.copy(&mut output, range.start + copied..range.start + at, budget)?; + let scalar = if bytes[at] == b'\r' { + if bytes.get(at + 1) != Some(&b'\n') { + return Err(invalid()); + } + at += 2; + Some('\n') + } else { + escape(bytes, &mut at, budget)? + }; + if let Some(scalar) = scalar { + let mut buffer = [0; 4]; + output.transformed( + scalar.encode_utf8(&mut buffer), + Origin::Decoded(source.pieces(range.start + start..range.start + at, budget)?), + budget, + )?; + } + copied = at; + } else { + // Validate copied text before a later escape can select a different failure. + at += scalar_width(bytes, at, budget)?; + } + } + source.copy(&mut output, range.start + copied..range.start + at, budget)?; + Ok(output) +} + +fn delimiters(bytes: &[u8], budget: &B) -> Result<(Range, bool), TextError> { + // bca: suppress(halstead, nexits) -- exact raw hash delimiters and cooked boundaries have separate rejection points. + let boundary = || TextError::Unavailable(UnavailableReason::GrammarBoundary); + if bytes.first() == Some(&b'"') && bytes.len() >= 2 && bytes.last() == Some(&b'"') { + return Ok((1..bytes.len() - 1, false)); + } + if bytes.first() != Some(&b'r') { + return Err(boundary()); + } + let mut at = 1; + while bytes.get(at) == Some(&b'#') { + budget.bytes(1).map_err(Into::into)?; + at += 1; + } + let hashes = at - 1; + if hashes > 255 || bytes.get(at) != Some(&b'"') || bytes.len() < at + 2 + hashes { + return Err(boundary()); + } + let end = bytes.len() - hashes - 1; + if bytes[end] != b'"' { + return Err(boundary()); + } + for byte in &bytes[end + 1..] { + budget.bytes(1).map_err(Into::into)?; + if *byte != b'#' { + return Err(boundary()); + } + } + Ok((at + 1..end, true)) +} + +fn escape( + bytes: &[u8], + at: &mut usize, + budget: &B, +) -> Result, TextError> { + // bca: suppress(abc, halstead, nexits) -- exhaustive Rust escape dispatch includes fallible token reads and continuation removal. + *at += 1; + let byte = *bytes.get(*at).ok_or_else(invalid)?; + budget.bytes(1).map_err(Into::into)?; + *at += 1; + let scalar = match byte { + b'"' => '"', + b'\'' => '\'', + b'\\' => '\\', + b'n' => '\n', + b'r' => '\r', + b't' => '\t', + b'0' => '\0', + b'x' => { + let high = digit(*bytes.get(*at).ok_or_else(invalid)?)?; + let low = digit(*bytes.get(*at + 1).ok_or_else(invalid)?)?; + budget.bytes(2).map_err(Into::into)?; + *at += 2; + let value = high * 16 + low; + if value > 0x7f { + return Err(invalid()); + } + char::from_u32(value).ok_or_else(invalid)? + } + b'u' => unicode(bytes, at, budget)?, + b'\n' | b'\r' => { + if byte == b'\r' { + if bytes.get(*at) != Some(&b'\n') { + return Err(invalid()); + } + budget.bytes(1).map_err(Into::into)?; + *at += 1; + } + while matches!(bytes.get(*at), Some(b' ' | b'\t' | b'\n' | b'\r')) { + budget.bytes(1).map_err(Into::into)?; + if bytes[*at] == b'\r' && bytes.get(*at + 1) != Some(&b'\n') { + return Err(invalid()); + } + *at += 1; + } + return Ok(None); + } + _ => return Err(invalid()), + }; + Ok(Some(scalar)) +} + +fn digit(byte: u8) -> Result { + match byte { + b'0'..=b'9' => Ok(u32::from(byte - b'0')), + b'a'..=b'f' => Ok(u32::from(byte - b'a') + 10), + b'A'..=b'F' => Ok(u32::from(byte - b'A') + 10), + _ => Err(invalid()), + } +} + +fn unicode(bytes: &[u8], at: &mut usize, budget: &B) -> Result { + if bytes.get(*at) != Some(&b'{') { + return Err(invalid()); + } + *at += 1; + let mut value = 0; + let mut digits = 0; + loop { + budget.bytes(1).map_err(Into::into)?; + let byte = *bytes.get(*at).ok_or_else(invalid)?; + *at += 1; + match byte { + b'}' if digits != 0 => break, + b'_' if digits != 0 => {} + _ => { + if digits == 6 { + return Err(invalid()); + } + value = value * 16 + digit(byte)?; + digits += 1; + } + } + } + char::from_u32(value).ok_or(TextError::Unavailable(UnavailableReason::NonScalar)) +} + +crate::observation::counter!(decoded_units, cfg(test)); diff --git a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs index 7e9caeffa..3865eac84 100644 --- a/big-code-analysis-ast/src/lang_helpers/doc_comment.rs +++ b/big-code-analysis-ast/src/lang_helpers/doc_comment.rs @@ -542,7 +542,12 @@ pub(crate) fn stretch_end_with_budget<'a, R: SourceRules, B: WorkBudget>( let mut target = None; for n in after { budget.step()?; - continuous = view.covers_with_budget(boundary..n.end_byte(), budget)?; + let end = if matches!(view, CandidateView::Source(_)) && R::separately_assessed_trivia(&n) { + n.start_byte() + } else { + n.end_byte() + }; + continuous = view.covers_with_budget(boundary..end, budget)?; boundary = n.end_byte(); if !continuous || (!skips(&n, ancestors)? @@ -691,7 +696,14 @@ pub(crate) fn collect_stretch_with_budget<'a, R: SourceRules, B: WorkBudget>( // above it instead of the one the tool attaches. for sibling in ancestors.siblings_before_with_budget(comment, budget)? { budget.step()?; - if !view.covers_with_budget(sibling.start_byte()..boundary, budget)? { + let start = if matches!(view, CandidateView::Source(_)) + && R::separately_assessed_trivia(&sibling) + { + sibling.end_byte() + } else { + sibling.start_byte() + }; + if !view.covers_with_budget(start..boundary, budget)? { prefix_gap = true; break; } diff --git a/big-code-analysis-ast/tests/rust_documentation_grammar.rs b/big-code-analysis-ast/tests/rust_documentation_grammar.rs new file mode 100644 index 000000000..e98beecce --- /dev/null +++ b/big-code-analysis-ast/tests/rust_documentation_grammar.rs @@ -0,0 +1,134 @@ +//! Pinned Rust grammar evidence for direct documentation literals and recovery. +#![cfg(feature = "rust")] + +use std::ops::Range; + +#[allow(clippy::naive_bytecount)] +fn dump(source: &[u8], excluded: Option>) -> tree_sitter::Tree { + // bca: suppress(halstead) -- the grammar probe records source ranges, fields and recovery flags together. + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&tree_sitter_rust::LANGUAGE.into()) + .unwrap(); + if let Some(gap) = excluded { + let point = |at: usize| { + let prefix = &source[..at]; + tree_sitter::Point::new( + prefix.iter().filter(|&&byte| byte == b'\n').count(), + prefix + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(at, |lf| at - lf - 1), + ) + }; + let ranges: Vec<_> = [0..gap.start, gap.end..source.len()] + .into_iter() + .filter(|range| !range.is_empty()) + .map(|range| tree_sitter::Range { + start_byte: range.start, + end_byte: range.end, + start_point: point(range.start), + end_point: point(range.end), + }) + .collect(); + parser.set_included_ranges(&ranges).unwrap(); + } + let tree = parser.parse(source, None).unwrap(); + println!("SOURCE {source:?} INCLUDED {:?}", tree.included_ranges()); + let mut cursor = tree.walk(); + let mut depth = 0; + loop { + let node = cursor.node(); + println!( + "{depth}: {} id={} field={:?} bytes={:?} error={} missing={}", + node.kind(), + node.kind_id(), + cursor.field_name(), + node.byte_range(), + node.has_error(), + node.is_missing(), + ); + if cursor.goto_first_child() { + depth += 1; + } else { + while !cursor.goto_next_sibling() { + if !cursor.goto_parent() { + drop(cursor); + return tree; + } + depth -= 1; + } + } + } +} + +#[test] +fn rust_documentation_grammar_direct_value_and_recovery() { + for (source, value, arguments) in [ + ( + "#[doc = \"audit\"] fn f() {}", + Some("string_literal"), + false, + ), + ( + "#[/* extra */ doc = r###\"a\"#b\"###] fn f() {}", + Some("raw_string_literal"), + false, + ), + ("#[doc(hidden)] fn f() {}", None, true), + ("#[doc(alias = \"audit\")] fn f() {}", None, true), + ( + "#[doc = concat!(\"a\", \"b\")] fn f() {}", + Some("macro_invocation"), + false, + ), + ] { + let tree = dump(source.as_bytes(), None); + let item = tree.root_node().named_child(0).unwrap(); + assert_eq!(item.kind_id(), 170); + let mut cursor = item.walk(); + let attr = item + .named_children(&mut cursor) + .find(|node| node.kind() == "attribute") + .unwrap(); + assert_eq!(attr.kind_id(), 172); + assert_eq!( + attr.child_by_field_name("value").map(|node| node.kind()), + value + ); + assert_eq!(attr.child_by_field_name("arguments").is_some(), arguments); + } + for source in [ + "#[doc = r\"raw\"] fn f() {}", + "#[doc = b\"\\xff\"] fn f() {}", + "#[doc = c\"text\"] fn f() {}", + "#[doc = br#\"raw\"#] fn f() {}", + "#[doc = cr#\"raw\"#] fn f() {}", + "#[doc = \"\\u{1_f600}\"] fn f() {}", + "#[doc = \"\\u{D800}\"] fn f() {}", + "#[doc = \"\\u{110000}\"] fn f() {}", + "#[doc = \"\\u0041\"] fn f() {}", + "#[doc = \"\\x80\"] fn f() {}", + "#[doc = \"\\x1\"] fn f() {}", + "#[doc = \"\\xGG\"] fn f() {}", + "#[doc = \"\\xé1\"] fn f() {}", + "#[doc = \"\\u{}\"] fn f() {}", + "#[doc = \"\\u{1234567}\"] fn f() {}", + "#[doc = \"\\q\"] fn f() {}", + "#[doc = \"a\\\n \t\r\nb\"] fn f() {}", + "#[doc = \"a\\\n \rb\"] fn f() {}", + "#[doc = \"a\r\nb\"] fn f() {}", + "#[doc = \"a\rb\"] fn f() {}", + "#[doc = ] fn f() {}\n/// good\nfn g() {}", + "#[doc \"a\"] fn f() {}\n/// good\nfn g() {}", + "#[doc = \"a\" fn f() {}\n/// good\nfn g() {}", + "#[doc = \"a] fn f() {}\n/// good\nfn g() {}", + "#[doc] fn f() {}", + ] { + dump(source.as_bytes(), None); + } + dump(b"#[doc = b\"\xff\"] fn f() {}", None); + dump(b"#[doc = \"\xff\"] fn f() {}", None); + dump(b"/// a\n#[doXc = \"b\"] fn f() {}", Some(10..11)); + dump(b"/// a\n#[doc = \"bXc\"] fn f() {}", Some(16..17)); +} diff --git a/fuzz/corpus/documentation/rust-literal-continuation b/fuzz/corpus/documentation/rust-literal-continuation new file mode 100644 index 0000000000000000000000000000000000000000..9a24404043c4d4d9bec96a3d5c9b397c1e41720e GIT binary patch literal 32 ncmZQzW>Ah!$xl|WRZvQd;pI}`Ah!$xl|WRZvojRY=QINYl_%sICP7J(2~v literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-literal-margin b/fuzz/corpus/documentation/rust-literal-margin new file mode 100644 index 0000000000000000000000000000000000000000..018d2f2f20d96ea13427bf3347efb5e28bb18ae1 GIT binary patch literal 45 xcmZQzX3*EyR{(*G)SR4rF6HQy{A2}N1*OEi{F02+BBfZav^<404NZmWS^({b3*P_$ literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-literal-raw b/fuzz/corpus/documentation/rust-literal-raw new file mode 100644 index 0000000000000000000000000000000000000000..f232e300063a713efb32687874d4dc286ea97575 GIT binary patch literal 35 ocmZQzW>Ah!$xl|WRVY$cR#r+>Qch9=GGZ0d@)XiEG!?3A0fIsZ1poj5 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-literal-scalar b/fuzz/corpus/documentation/rust-literal-scalar new file mode 100644 index 0000000000000000000000000000000000000000..fb2f50358c4a701e82d447810227a71276ae7a93 GIT binary patch literal 33 ocmZQzXHbq#$xl|WRZxm4tu}NsGcc%Cid9IAh!$xqhE$V^E|&C`rkNXt`5)6i6?t_1*MdIz-t literal 0 HcmV?d00001 diff --git a/fuzz/documentation-seeds.json b/fuzz/documentation-seeds.json index 829faad9d..9a4ece9ea 100644 --- a/fuzz/documentation-seeds.json +++ b/fuzz/documentation-seeds.json @@ -383,11 +383,83 @@ 0 ], "sha256": "aac39c7cc5bc121b5a806cc7e48af010226c50176197ef51fd62cef6ce0f45d5", - "class": "pending-content", + "class": "rust-literal-mixed", "provenance": "tests/fixtures/documentation/forms.json", "fixture": "rust-attribute.rs", "has_error": false }, + { + "name": "rust-literal-empty", + "header": [ + 0, + 3, + 0 + ], + "sha256": "c26860901119f987717d9e5d68326c7328d17c9f1eb7cd5c0b16084c5d2fa4f8", + "class": "rust-literal-empty", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", + "has_error": false + }, + { + "name": "rust-literal-raw", + "header": [ + 0, + 3, + 0 + ], + "sha256": "f4958c10dba07edbcb03772333194a2c97812f5243a5a58a21b0247c9923e9b3", + "class": "rust-literal-raw", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", + "has_error": false + }, + { + "name": "rust-literal-scalar", + "header": [ + 0, + 7, + 0 + ], + "sha256": "05cff0ff398c6b754572b486133e967ca77298f1feb6770420f9d0e7e7ebc0a2", + "class": "rust-literal-scalar", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs::rust_literal_escape_origins_are_complete_tokens_after_cleanup", + "has_error": false + }, + { + "name": "rust-literal-continuation", + "header": [ + 0, + 3, + 0 + ], + "sha256": "63a7d593904affe3e0166eddbdf49e2a37576f09e51553cfb322980a3248379c", + "class": "rust-literal-continuation", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs::rust_literal_escape_origins_are_complete_tokens_after_cleanup", + "has_error": false + }, + { + "name": "rust-literal-margin", + "header": [ + 0, + 3, + 0 + ], + "sha256": "52986541aa9c95a35b72265d66bb2ef0f67119ce375b530f1a66edea63a74039", + "class": "rust-literal-margin", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", + "has_error": false + }, + { + "name": "rust-pending-metadata", + "header": [ + 0, + 3, + 0 + ], + "sha256": "ce15503ce0bec5bbe8a14dc49bcf8bae27823c6d866d5669cc44e2c2a1edaeaf", + "class": "pending-content", + "provenance": "big-code-analysis-ast/src/documentation/collector/tests.rs::rust_pending_attributes_never_report_complete_partial_text", + "has_error": false + }, { "name": "rust-join", "header": [ diff --git a/fuzz/generate_documentation_seeds.py b/fuzz/generate_documentation_seeds.py index c72364f3c..91036fcd7 100644 --- a/fuzz/generate_documentation_seeds.py +++ b/fuzz/generate_documentation_seeds.py @@ -88,7 +88,7 @@ def add(name, header, payload, assertion, provenance, **expected): for name, fixture, assertion in [ ("rust-eof", "rust-eof.rs", "eof"), ("rust-crlf", "rust-crlf.rs", "crlf"), - ("rust-attribute", "rust-attribute.rs", "pending-content"), + ("rust-attribute", "rust-attribute.rs", "rust-literal-mixed"), ]: add( name, @@ -101,6 +101,12 @@ def add(name, header, payload, assertion, provenance, **expected): ) cases = [ + ("rust-literal-empty", [0, 3, 0], b'#[doc = ""] fn f() {}', "rust-literal-empty", "rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", False), + ("rust-literal-raw", [0, 3, 0], b'#[doc = r###"a"#b"###] fn f() {}', "rust-literal-raw", "rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", False), + ("rust-literal-scalar", [0, 7, 0], b'#[doc = "\\u{1F600}"] fn f() {}', "rust-literal-scalar", "rust_tests.rs::rust_literal_escape_origins_are_complete_tokens_after_cleanup", False), + ("rust-literal-continuation", [0, 3, 0], b'#[doc = "a\\\r\n \t\nb"] fn f() {}', "rust-literal-continuation", "rust_tests.rs::rust_literal_escape_origins_are_complete_tokens_after_cleanup", False), + ("rust-literal-margin", [0, 3, 0], b'/// hello\n#[doc = "another"]\nfn f() {}', "rust-literal-margin", "rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", False), + ("rust-pending-metadata", [0, 3, 0], b'#[doc(hidden)] fn f() {}', "pending-content", "tests.rs::rust_pending_attributes_never_report_complete_partial_text", False), ( "rust-join", [0, 3, 0], diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index 3eb12622e..3001b25fe 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -203,6 +203,74 @@ fn registry_executes_every_dispatch_and_edge_assertion() { assert_eq!(actual, names); } +#[allow(clippy::single_range_in_vec_init)] +fn rust_literal_seed(class: &str, index: &DocumentationIndex<'_>) { + let (expected, fragments, origins) = match class { + "rust-literal-mixed" => ( + "first\nsecond", + 2, + vec![ + (0..5, false, vec![4..9]), + (5..6, false, vec![]), + (6..12, false, vec![20..26]), + ], + ), + "rust-literal-empty" => ("", 1, vec![]), + "rust-literal-raw" => ("a\"#b", 1, vec![(0..4, false, vec![13..17])]), + "rust-literal-scalar" => ( + "😀", + 1, + vec![(0..4, true, (9..18).map(|at| at..at + 1).collect())], + ), + "rust-literal-continuation" => ( + "ab", + 1, + vec![(0..1, false, vec![9..10]), (1..2, false, vec![16..17])], + ), + "rust-literal-margin" => ( + " hello\nanother", + 2, + vec![ + (0..9, false, vec![4..13]), + (9..10, false, vec![]), + (10..17, false, vec![23..30]), + ], + ), + _ => panic!("registered literal class"), + }; + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), fragments); + assert_eq!(text(index).text(), expected); + let actual: Vec<_> = text(index) + .mappings() + .iter() + .map(|mapping| { + let (decoded, pieces) = match &mapping.origin { + Origin::Copied(pieces) => (false, pieces.pieces()), + Origin::Decoded(pieces) => (true, pieces.pieces()), + Origin::Synthetic => (false, &[][..]), + Origin::Expanded(_) => panic!("Rust does not expand indentation"), + _ => panic!("unexpected Rust origin"), + }; + ( + mapping.output.range(), + decoded, + pieces.iter().map(SourcePiece::range).collect::>(), + ) + }) + .collect(); + assert_eq!(actual, origins); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().publication, Publication::Unknown); + assert!(!index.assessments().any(|a| matches!( + a.get().axis, + AssessmentAxis::Occurrence | AssessmentAxis::Composition + ))); +} + #[allow(clippy::too_many_lines)] // Independent expected outcomes for the finite registered edge families. fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter::Tree) { if matches!(class, "incompatible-profile" | "deferred-profile") { @@ -231,6 +299,14 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: .any(|a| a.get().axis == AssessmentAxis::Composition) ); } + "rust-literal-mixed" + | "rust-literal-empty" + | "rust-literal-raw" + | "rust-literal-scalar" + | "rust-literal-continuation" + | "rust-literal-margin" => { + rust_literal_seed(class, index); + } "join" => { assert_eq!(text(index).text(), "a\nb"); assert_eq!(text(index).mappings().len(), 3); @@ -550,7 +626,7 @@ fn registry_oracles_reject_actual_wrong_payloads_and_foreign_nodes() { result.is_err(), "same-shaped wrong text must fail the real positive oracle" ); - let bytes = b"\0\x01\0#[doc = \"audit\"]\nfn f() {}"; + let bytes = b"\0\x01\0#[doc(hidden)]\nfn f() {}"; let result = std::panic::catch_unwind(|| { exercise_with(bytes, |index, tree| { edge("active-scope", index, tree); diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index f269fade0..5e3593891 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -5,6 +5,89 @@ use serde_json::{Value, json}; use crate::{LANG, Metric, MetricsOptions, Source, analyze}; +#[cfg(feature = "rust")] +#[test] +fn documentation_rust_literal_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::{AnyParser, documentation::*}; + let source = b"/// first\n#[doc = r\"second\"]\nfn f() {}"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!( + index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap() + .text(), + "first\nsecond" + ); + for exclude in [false, true] { + let before = observations(); + let space = analyze( + Source::new(LANG::Rust, source), + MetricsOptions::default() + .with_only(&[Metric::Loc, Metric::Tokens]) + .with_exclude_tests(exclude), + ) + .unwrap(); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + [3, 2, 0, 1, 0, 1] + ); + // Raw attribute: # [ doc = string_content ]; function: fn f ( ) { }. + assert_eq!(space.metrics.tokens.tokens_sum(), 12); + assert_eq!(observations().renders, before.renders); + assert_eq!(observations().visits, before.visits); + } +} + +#[cfg(feature = "rust")] +#[test] +fn documentation_rust_literal_test_pruning_changes_only_legacy_population() { + use big_code_analysis_ast::{AnyParser, documentation::*}; + let source = b"#[doc = \"removed\"] #[test]\nfn t() {}\n/// kept\nfn k() {}"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!( + index + .documents() + .map(|doc| index.complete_text(doc).unwrap().unwrap().text()) + .collect::>(), + ["removed", "kept"] + ); + for (exclude, tokens, functions) in [(false, 24, 2), (true, 6, 1)] { + let space = analyze( + Source::new(LANG::Rust, source), + MetricsOptions::default() + .with_only(&[Metric::Loc, Metric::Tokens]) + .with_exclude_tests(exclude), + ) + .unwrap(); + assert_eq!(space.spaces.len(), functions); + assert_eq!(space.metrics.tokens.tokens_sum(), tokens); + assert_eq!(space.metrics.loc.cloc(), 1); + assert_eq!(space.metrics.loc.dloc(), 1); + } +} + #[cfg(any(feature = "go", feature = "ruby", feature = "lua"))] #[derive(Clone, Copy)] struct PositionalRows<'a> { diff --git a/tests/fixtures/documentation/forms.json b/tests/fixtures/documentation/forms.json index 96d10a9d2..f92e33efc 100644 --- a/tests/fixtures/documentation/forms.json +++ b/tests/fixtures/documentation/forms.json @@ -18,7 +18,7 @@ {"path":"rust-reach.rs","documents":[{"fragment_spelling":"#[doc = { #[cfg(test)] fn helper() { if a {} } \"\" }]","owner":"fn f() {}","availability":"unavailable computed expression"}],"limitation":"#1786: consuming procedural macro can accept expression-valued attribute; retained reach keeps helper even with exclude_tests. No macro execution or repaired-pruning claim."}, {"path":"rust-eof.rs","documents":[],"evidence":[{"fragment_spelling":"/// tail","owner":null,"text":"tail","association":"dangling"}],"raw":"No final newline."}, {"path":"rust-crlf.rs","documents":[{"fragment_spelling":"/// kept","owner":"fn kept() { work()?; }","text":"kept"}],"evidence":[{"fragment_spelling":"/// tail","owner":null,"text":"tail","association":"dangling"}],"raw":"CRLF including final terminator; fragment excludes both bytes."}, - {"path":"rust-same-row.rs","documents":[{"fragment_spellings":["/*! a */","/*! b */"],"owner":"file","text":"a\nb"}],"legacy":"Two comments share physical row 0; DLOC is one."}, + {"path":"rust-same-row.rs","documents":[{"fragment_spellings":["/*! a */","/*! b */"],"owner":"file","text":"a \nb "}],"derivation":"Rust 1.99.0 retains interiors ' a ' and ' b ', removes their common one-character left margin, joins with LF and preserves both trailing spaces.","legacy":"Two comments share physical row 0; DLOC is one."}, {"path":"python-runs.py","documents":[{"fragment_spelling":"\"\"","owner":"f","text":"","role":"primary"},{"fragment_spelling":"\"extra\"","owner":"f","text":"extra","role":"additional"},{"fragment_spelling":"#: setting","owner":"x binding","text":"setting","role":"Sphinx"},{"fragment_spelling":"\"attribute\"","owner":"x binding","text":"attribute","role":"attribute-binding"}]}, {"path":"python-paren.py","documents":[{"fragments":[[14,19],[36,41]],"owner":"f","text":"@audit","role":"primary","origins":[[0,3,15,18],[3,6,37,40]]}],"legacy":"Parentheses and ordinary comment rows remain coverage, never documentation text."}, {"path":"python-named.py","documents":[{"fragment_spelling":"\"\\N{COMMERCIAL AT}audit\"","owner":"f","availability":"unavailable named Unicode escape","role":"primary"}],"legacy":"The whole literal row is DLOC. Python itself decodes @audit; initial BCA decoder deliberately does not."}, diff --git a/tests/fixtures/documentation/provenance.json b/tests/fixtures/documentation/provenance.json index 57ec30beb..df361224e 100644 --- a/tests/fixtures/documentation/provenance.json +++ b/tests/fixtures/documentation/provenance.json @@ -30,6 +30,7 @@ "scope": "Selected characterization fixtures only. Full repository corpus capture deferred to parent. CLI/default/recovery oracle protocol retained and self-tested separately." }, "independent_expectations": { + "rust_same_row_correction": "Unit1 V2 council, 2026-11-20: source-derived Rust 1.99.0 beautify_doc_string/unindent_doc_fragments contract gives 'a \\nb ' from retained ' a '/' b ' interiors; no right trimming. Production assertion: collector/rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces. Legacy row oracle is unchanged.", "revision": "42d39ad8cb854536e432dcce164fb7392121cccb", "sources": ["docs/development/documentation_extraction.md", "docs/development/documentation_extraction_cases.md"], "reference_record": "https://gist.github.com/dekobon/acb5b4fd9ada1c2b63f86ae0f0514524", diff --git a/tests/fixtures/documentation/rust-unit1-provenance.json b/tests/fixtures/documentation/rust-unit1-provenance.json new file mode 100644 index 000000000..f5a465374 --- /dev/null +++ b/tests/fixtures/documentation/rust-unit1-provenance.json @@ -0,0 +1,28 @@ +{ + "scope": "Direct cooked/raw Rust doc attributes and mixed mapped text on existing owners; Unit1 of #1664", + "base": "04dc92190555aa5ca6be55f95babd12f74a14a89", + "grammar": {"runtime": "0.26.13", "rust": "0.24.2"}, + "grammar_evidence": "big-code-analysis-ast/tests/rust_documentation_grammar.rs", + "production_oracles": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs", + "legacy_oracles": "src/metrics/loc/documentation_tests.rs", + "mutation_manifest": "utils/documentation-rust-literal-perturb.json", + "preserved_rust_attribute_payload_sha256": "aac39c7cc5bc121b5a806cc7e48af010226c50176197ef51fd62cef6ce0f45d5", + "cleanup_sources": [ + "https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_ast/src/util/comments.rs", + "https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_resolve/src/rustdoc.rs" + ], + "independent_derivations": { + "mixed_margin": "Sugared ' hello' has margin five; nonsugared 'another' participates with add=1. Global minimum one removes one from the comment and zero from the attribute: four spaces remain.", + "empty_join": "Each empty prose fragment contributes an assembly LF; one final assembly LF is removed. Two empty attributes produce one LF.", + "same_row": "Single-line interiors ' a ' and ' b ' lose their common left space, preserving both right spaces: 'a \\nb '. Physical legacy DLOC remains one.", + "decoded_crlf": "Cooked a\\r\\nb decodes CR and LF separately. str::lines removes CR; LF output maps only to the complete \\n escape. Physical CRLF instead maps to both physical bytes.", + "unicode_underscores": "Pinned grammar recovers \\u{1_f600} into ERROR plus a missing-delimiter value. Production content is GrammarBoundary; the decoder's valid underscore syntax cannot establish lost supplied-tree boundaries." + }, + "pending": [ + "Additional field, variant, associated-type and tuple-slot owner projections", + "Metadata, computed/conditional carriers and publication interpretation", + "Macro attribute-token evidence and inner impl normalization", + "Parent-ordered simplification, optimization, test audit and seven review roles", + "Coordinated adapter performance fixtures and finite fuzz campaigns" + ] +} diff --git a/utils/documentation-collector-perturb.json b/utils/documentation-collector-perturb.json index 6d58c4f54..e3ffde387 100644 --- a/utils/documentation-collector-perturb.json +++ b/utils/documentation-collector-perturb.json @@ -62,8 +62,8 @@ { "name": "kotlin-owner-pending-hides-text", "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", - "old": "let content = if attribute {", - "new": "let content = if attribute || draft.pending {", + "old": "let result = if attribute {", + "new": "let result = if draft.pending { Ok(Content::PendingAdapter) } else if attribute {", "expect": ["documentation::collector::assessment_tests::kotlin_local_pending_owner_keeps_complete_text_and_known_leading_association"] }, { @@ -89,9 +89,9 @@ }, { "name": "pending-composition-becomes-empty-complete", - "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", - "old": "let content = if attribute {\n Content::PendingAdapter", - "new": "let content = if attribute {\n Content::Complete { text: String::new(), mappings: Vec::new() }", + "file": "big-code-analysis-ast/src/documentation/collector/rust.rs", + "old": "Ok(Content::PendingAdapter)", + "new": "Ok(Content::Complete { text: String::new(), mappings: Vec::new() })", "expect": ["documentation::collector::tests::rust_pending_attributes_never_report_complete_partial_text"] }, { diff --git a/utils/documentation-rust-literal-perturb.json b/utils/documentation-rust-literal-perturb.json new file mode 100644 index 000000000..2718be1da --- /dev/null +++ b/utils/documentation-rust-literal-perturb.json @@ -0,0 +1,91 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], + "cases": [ + { + "name": "empty-output-range-emits-zero-width-map", + "file": "big-code-analysis-ast/src/documentation/text/cleanup.rs", + "old": "if range.is_empty() {\n return Ok(());\n }", + "new": "if false && range.is_empty() {\n return Ok(());\n }", + "expect": ["documentation::collector::rust_tests::rust_literal_escape_origins_are_complete_tokens_after_cleanup"] + }, + { + "name": "direct-literal-remains-unassessed", + "file": "big-code-analysis-ast/src/documentation/collector/rust.rs", + "old": "Value::Literal(value.byte_range())", + "new": "{ let _ = value; Value::Pending }", + "expect": ["documentation::collector::rust_tests::rust_literal_complete_has_exact_owner_raw_fragments_and_prepared_queries", "metrics::loc::documentation_tests::documentation_rust_literal_source_and_legacy_views_are_independent"] + }, + { + "name": "byte-prefix-inspects-invalid-interior-first", + "file": "big-code-analysis-ast/src/documentation/text/rust/literal.rs", + "old": "if matches!(bytes.first(), Some(b'b' | b'c')) {", + "new": "if matches!(bytes.first(), Some(b'b' | b'c')) { validate(bytes, budget)?;", + "expect": ["documentation::collector::rust_tests::rust_literal_state_priority_is_pending_gap_boundary_then_source_order"] + }, + { + "name": "mixed-margin-extra-position-removed", + "file": "big-code-analysis-ast/src/documentation/text/rust.rs", + "old": "let add = usize::from(sugared && nonsugared);", + "new": "let add = usize::from(sugared && nonsugared) * 0;", + "expect": ["documentation::collector::rust_tests::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces"] + }, + { + "name": "trailing-content-spaces-trimmed", + "file": "big-code-analysis-ast/src/documentation/text/rust.rs", + "old": "let mut range = line.content.clone();", + "new": "let mut range = line.content.clone(); while range.end > range.start && fragment.bytes(context)[range.end - 1] == b' ' { range.end -= 1; }", + "expect": ["documentation::collector::rust_tests::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces"] + }, + { + "name": "empty-fragment-separator-dropped", + "file": "big-code-analysis-ast/src/documentation/text/rust.rs", + "old": "if position != 0 {", + "new": "if position != 0 && !output.text.is_empty() {", + "expect": ["documentation::collector::rust_tests::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces"] + }, + { + "name": "escape-origin-clipped-to-last-byte", + "file": "big-code-analysis-ast/src/documentation/text/rust/literal.rs", + "old": "range.start + start..range.start + at", + "new": "range.start + start.max(at - 1)..range.start + at", + "expect": ["documentation::collector::rust_tests::rust_literal_escape_origins_are_complete_tokens_after_cleanup"] + }, + { + "name": "covered-attribute-path-required", + "file": "big-code-analysis-ast/src/documentation/collector/rust.rs", + "old": ".covers_with_budget(path.byte_range(), budget)?", + "new": ".covers_with_budget(path.start_byte()..path.start_byte(), budget)?", + "expect": ["documentation::collector::rust_tests::rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes"] + }, + { + "name": "attribute-internal-gap-blocks-known-comment", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": "T::lang() == crate::LANG::Rust && node.kind() == \"attribute_item\"", + "new": "false && T::lang() == crate::LANG::Rust && node.kind() == \"attribute_item\"", + "expect": ["documentation::collector::rust_tests::rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes"] + }, + { + "name": "required-gap-loses-state-priority", + "file": "big-code-analysis-ast/src/documentation/collector/rust.rs", + "old": "gap |= fragment.source.has_excluded_gap();", + "new": "gap |= false && fragment.source.has_excluded_gap();", + "expect": ["documentation::collector::rust_tests::rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes"] + }, + { + "name": "escape-piece-cursor-restarts-at-prefix", + "file": "big-code-analysis-ast/src/documentation/text/rust/literal.rs", + "old": "let start = at;", + "new": "let start = at; source = SourceCursor::new(&fragment.source);", + "expect": ["documentation::collector::rust_tests::rust_literal_many_adjacent_pieces_do_not_restart_global_intersections"] + }, + { + "name": "document-rendered-twice", + "file": "big-code-analysis-ast/src/documentation/collector/rust.rs", + "old": "render(&self.index.source, &inputs, budget)", + "new": "{ let _ = render(&self.index.source, &inputs, budget)?; render(&self.index.source, &inputs, budget) }", + "expect": ["documentation::collector::rust_tests::rust_literal_materializes_once_and_prices_decoding_projection_and_retained_reads"] + } + ] +} From 3739f0df1aaaee16f83964510a0ef011a1f15099 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:58:53 -0800 Subject: [PATCH 061/221] test(bench): use fixed-size calibration sample chunks Address focused Clippy findings without changing the declared ladder or expected counts. Preserve the empty remainder in assertion diagnostics. Full gate and all-files hooks follow the frozen mutation sweep. --- .../src/documentation/runner/calibration_tests.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs index 1e0ce6df4..98334a994 100644 --- a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs +++ b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs @@ -95,8 +95,10 @@ fn cap_outcomes_use_the_three_sample_median_and_exact_boundaries() { Ok(Duration::from_nanos(if count == 1 << 20 { ns } else { 0 })) }); assert_eq!(calls.len(), 63); - for (at, samples) in calls.chunks_exact(3).enumerate() { - assert_eq!(samples, [1 << at; 3]); + let (stages, remainder) = calls.as_chunks::<3>(); + assert_eq!(remainder, []); + for (at, samples) in stages.iter().enumerate() { + assert_eq!(*samples, [1 << at; 3]); } assert_eq!(*outcome_mut(&mut evidence), outcome); if outcome == CalibrationOutcome::Unresolved { From 7189327c2e37ceb502f98349278671c231cf1b28 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 16:59:23 -0800 Subject: [PATCH 062/221] test(bench): disambiguate empty calibration remainder Use an explicit u32 empty array because serde_json adds another PartialEq candidate. Focused all-target pedantic Clippy and all 360 combined documentation tests pass; preserve earlier compiler and lint failures in validation evidence. --- .../src/documentation/runner/calibration_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs index 98334a994..cebe42cd5 100644 --- a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs +++ b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs @@ -96,7 +96,7 @@ fn cap_outcomes_use_the_three_sample_median_and_exact_boundaries() { }); assert_eq!(calls.len(), 63); let (stages, remainder) = calls.as_chunks::<3>(); - assert_eq!(remainder, []); + assert_eq!(remainder, [] as [u32; 0]); for (at, samples) in stages.iter().enumerate() { assert_eq!(*samples, [1 << at; 3]); } From 69e69b5e3d81231fc308a433713757a02e590265 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:35:58 -0800 Subject: [PATCH 063/221] refactor(documentation): reuse mapped text primitives and skip unused work Share budgeted scalar validation and physical newline emission. Avoid unused attribute-document references and ordinary-sibling coverage checks, with a discriminating work guard. Refresh the generated headroom baseline. Refs #1664 --- .bca-baseline.toml | 28 +++++-------- .../src/documentation/canonical.rs | 1 + .../src/documentation/collector.rs | 11 +++-- .../src/documentation/collector/assembly.rs | 29 ++++++------- .../src/documentation/collector/rust_tests.rs | 42 +++++++++++++++++++ .../src/documentation/text.rs | 16 +++++++ .../src/documentation/text/comments.rs | 28 ++----------- .../src/documentation/text/rust.rs | 10 +---- .../src/documentation/text/rust/literal.rs | 20 ++------- .../src/documentation/text/source_cursor.rs | 15 ++++++- utils/documentation-rust-literal-perturb.json | 7 ++++ 11 files changed, 118 insertions(+), 89 deletions(-) diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 21124962d..8ec547e4b 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,13 +359,13 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 961.0 +value = 964.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 134.0 +value = 136.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -467,7 +467,7 @@ value = 7.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::record_children" metric = "halstead.effort" -value = 123556.27877545246 +value = 125839.60029393726 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -635,7 +635,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::render_draft" metric = "halstead.effort" -value = 59532.42614212931 +value = 60244.61690661844 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -1079,7 +1079,7 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "" metric = "loc.ploc" -value = 587.0 +value = 565.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1117,17 +1117,11 @@ qualified = "beautify" metric = "nexits" value = 16.0 -[[entry]] -path = "big-code-analysis-ast/src/documentation/text/comments.rs" -qualified = "blank" -metric = "halstead.effort" -value = 49441.34419913078 - [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "blank" metric = "nexits" -value = 8.0 +value = 5.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1163,25 +1157,25 @@ value = 11.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "emit_blocks" metric = "abc" -value = 46.776062254106 +value = 39.761790704142086 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "emit_blocks" metric = "cognitive" -value = 34.0 +value = 29.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "emit_blocks" metric = "cyclomatic" -value = 19.0 +value = 18.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "emit_blocks" metric = "halstead.effort" -value = 135842.98435141143 +value = 113526.30607942471 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1193,7 +1187,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "emit_blocks" metric = "nexits" -value = 10.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" diff --git a/big-code-analysis-ast/src/documentation/canonical.rs b/big-code-analysis-ast/src/documentation/canonical.rs index 4cbd22d81..5c2039523 100644 --- a/big-code-analysis-ast/src/documentation/canonical.rs +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -29,6 +29,7 @@ pub(super) struct CanonicalNode<'s> { pub(super) qualifications: Vec, pub(super) pending_parent: Option, pub(super) following: Option, + // Binding gaps cover sibling spacing and skipped comments; attribute interiors are assessed separately. pub(super) following_gap: bool, pub(super) owner_context: NodeId, pub(super) name_scope: NodeId, diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 1f2262de4..5acc724f0 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -303,7 +303,11 @@ impl<'s> Builder<'s> { { budget.step()?; let record = &mut self.index.canonical.nodes[child.0]; + let child_node = Node::from_tree_sitter(record.evidence.node()); + let attribute = child_node.kind() == "attribute_item"; + let trivia = T::is_comment(&child_node) || attribute; if self.index.profile == Profile::Rust + && trivia && let Some(start) = next_start { following_gap |= !self @@ -313,13 +317,12 @@ impl<'s> Builder<'s> { } record.field = *field; record.following = following; - record.following_gap = following_gap; - let child_node = Node::from_tree_sitter(record.evidence.node()); + record.following_gap = trivia && following_gap; next_start = Some(child_node.start_byte()); - if !T::is_comment(&child_node) && child_node.kind() != "attribute_item" { + if !trivia { following = Some(child); following_gap = false; - } else if self.index.profile == Profile::Rust && child_node.kind() != "attribute_item" { + } else if self.index.profile == Profile::Rust && !attribute { following_gap |= !self .index .source diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index e7bb5be89..f5ea2aac6 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -209,17 +209,17 @@ impl<'s> Builder<'s> { draft: &Draft<'s>, document: DocumentId, owners: &[OwnerId], - attribute: bool, + pending_attribute_composition: bool, budget: &CollectionBudget, ) -> Result<(), CollectionError> { let assessment = self.index.assessments.len(); self.index.assessments.push(Assessment { - axis: if attribute { + axis: if pending_attribute_composition { AssessmentAxis::Composition } else { AssessmentAxis::Owner }, - reason: if attribute { + reason: if pending_attribute_composition { "Rust doc/cfg_attr carrier awaits adapter composition" } else if self.index.profile == Profile::Doxygen && draft.target.is_none() { "Exact named matching awaits supported signature grammar" @@ -320,33 +320,28 @@ impl<'s> Builder<'s> { budget: &CollectionBudget, ) -> Result<(Content<'s>, bool), CollectionError> { let mut keys = Vec::new(); + let mut attribute = false; for id in &draft.fragments { budget.step()?; - keys.push(( - self.index.facts.fragments[id.0].source.pieces()[0] - .range() - .start, - id.0, - )); + let fragment = &self.index.facts.fragments[id.0]; + attribute |= fragment.form == FragmentForm::Attribute; + keys.push((fragment.source.pieces()[0].range().start, id.0)); } draft.fragments.clear(); for (_, id) in crate::documentation::ordering::ordered(keys, budget)? { budget.step()?; draft.fragments.push(FragmentId(id)); } - let mut fragments = Vec::new(); - let mut attribute = false; - for id in &draft.fragments { - budget.step()?; - let fragment = &self.index.facts.fragments[id.0]; - attribute |= fragment.form == FragmentForm::Attribute; - fragments.push(fragment); - } let result = if attribute { self.rust_content(draft, budget) } else if draft.gap { Ok(Content::Unavailable(UnavailableReason::ExcludedGap)) } else { + let mut fragments = Vec::with_capacity(draft.fragments.len()); + for id in &draft.fragments { + budget.step()?; + fragments.push(&self.index.facts.fragments[id.0]); + } crate::documentation::text::comments::render( self.index.profile, &self.index.source, diff --git a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs index 912462cd3..e0cce4d47 100644 --- a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs @@ -692,6 +692,48 @@ fn rust_literal_plain_trivia_and_real_interstitial_gaps_do_not_become_prose() { .any(|a| a.get().axis == AssessmentAxis::Owner) ); }); + let source = b"#[doc = \"a\"] /* plXain */ fn f() {}"; + let gap = source.iter().position(|&byte| byte == b'X').unwrap(); + included(source, &[gap..gap + 1], false, |index| { + assert_eq!(text(index).text(), "a"); + assert_eq!(index.associations().len(), 0); + assert!( + index + .assessments() + .any(|a| a.get().axis == AssessmentAxis::Owner) + ); + }); +} + +#[test] +#[cfg(feature = "rust")] +fn ordinary_rust_sibling_spacing_adds_no_binding_coverage_searches() { + use crate::documentation::source::included_range_visits; + + for count in [8, 32, 128] { + let mut work = Vec::new(); + let mut nodes = Vec::new(); + for unit in ["fn f(){}", "fn f ( ) { } \n"] { + let parser = + AnyParser::parse(LANG::Rust, unit.repeat(count).into_bytes(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error()); + assert_eq!(parser.ts_tree().root_node().named_child_count(), count); + nodes.push(parser.root_node().preorder().count()); + let before = included_range_visits::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + work.push(included_range_visits::observed() - before); + assert_eq!(index.facts().owners().len(), count + 1); + assert_eq!(index.documents().len(), 0); + } + assert_eq!(nodes[0], nodes[1]); + // expected: spacing changes no binding work when every sibling is ordinary syntax. + assert_eq!(work[1], work[0]); + } } #[test] diff --git a/big-code-analysis-ast/src/documentation/text.rs b/big-code-analysis-ast/src/documentation/text.rs index 40d1280f0..498b93846 100644 --- a/big-code-analysis-ast/src/documentation/text.rs +++ b/big-code-analysis-ast/src/documentation/text.rs @@ -28,6 +28,22 @@ impl From for TextError { } } +pub(super) fn utf8_scalar<'a, B: WorkBudget>( + bytes: &'a [u8], + budget: &B, +) -> Result<&'a str, TextError> { + let invalid = || TextError::Unavailable(UnavailableReason::InvalidEncoding); + let width = match bytes.first() { + Some(0..=0x7f) => 1, + Some(0xc2..=0xdf) => 2, + Some(0xe0..=0xef) => 3, + Some(0xf0..=0xf4) => 4, + _ => return Err(invalid()), + }; + budget.bytes(width).map_err(Into::into)?; + std::str::from_utf8(bytes.get(..width).ok_or_else(invalid)?).map_err(|_| invalid()) +} + #[derive(Default)] pub(super) struct TextBuilder<'s> { text: String, diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs index d7a2a2f36..6172d68cf 100644 --- a/big-code-analysis-ast/src/documentation/text/comments.rs +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -404,15 +404,7 @@ fn emit_blocks<'s, B: WorkBudget>( budget, )?; if index + first + 1 < end { - if line.ending.len() == 2 { - builder.transformed( - "\n", - Origin::Decoded(source.pieces(line.ending.clone(), budget)?), - budget, - )?; - } else { - source.copy(&mut builder, line.ending.clone(), budget)?; - } + source.newline(&mut builder, line.ending.clone(), budget)?; } } } @@ -450,25 +442,11 @@ pub(super) fn blank( } let mut at = 0; while at < bytes.len() { - let width = match bytes[at] { - 0..=0x7f => 1, - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - 0xf0..=0xf4 => 4, - _ => return Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)), - }; - budget - .bytes(width) - .map_err(|error| TextError::Source(error.into()))?; - let scalar = bytes - .get(at..at + width) - .ok_or(TextError::Unavailable(UnavailableReason::InvalidEncoding))?; - let text = std::str::from_utf8(scalar) - .map_err(|_| TextError::Unavailable(UnavailableReason::InvalidEncoding))?; + let text = super::utf8_scalar(&bytes[at..], budget)?; if text.chars().any(|character| !character.is_whitespace()) { return Ok(false); } - at += width; + at += text.len(); } Ok(true) } diff --git a/big-code-analysis-ast/src/documentation/text/rust.rs b/big-code-analysis-ast/src/documentation/text/rust.rs index 0188b9ec7..cc06fa060 100644 --- a/big-code-analysis-ast/src/documentation/text/rust.rs +++ b/big-code-analysis-ast/src/documentation/text/rust.rs @@ -147,15 +147,7 @@ fn emit<'s, B: WorkBudget>( } else { source.copy(output, range, budget)?; if position + 1 < fragment.block.lines.len() { - if line.ending.len() == 2 { - output.transformed( - "\n", - Origin::Decoded(source.pieces(line.ending.clone(), budget)?), - budget, - )?; - } else { - source.copy(output, line.ending.clone(), budget)?; - } + source.newline(output, line.ending.clone(), budget)?; } } } diff --git a/big-code-analysis-ast/src/documentation/text/rust/literal.rs b/big-code-analysis-ast/src/documentation/text/rust/literal.rs index 6304e2646..6f369e8af 100644 --- a/big-code-analysis-ast/src/documentation/text/rust/literal.rs +++ b/big-code-analysis-ast/src/documentation/text/rust/literal.rs @@ -1,29 +1,17 @@ -//! Static Rust strings; syntax validation precedes any copied/decoded output. +//! Static Rust strings validated and decoded in source order into temporary mapped text. use super::*; use crate::documentation::UnavailableReason; +use crate::documentation::text::utf8_scalar; fn invalid() -> TextError { TextError::Unavailable(UnavailableReason::InvalidEncoding) } -fn scalar_width(bytes: &[u8], at: usize, budget: &B) -> Result { - let width = match bytes[at] { - 0..=0x7f => 1, - 0xc2..=0xdf => 2, - 0xe0..=0xef => 3, - 0xf0..=0xf4 => 4, - _ => return Err(invalid()), - }; - budget.bytes(width).map_err(Into::into)?; - std::str::from_utf8(bytes.get(at..at + width).ok_or_else(invalid)?).map_err(|_| invalid())?; - Ok(width) -} - pub(super) fn validate(bytes: &[u8], budget: &B) -> Result<(), TextError> { let mut at = 0; while at < bytes.len() { - at += scalar_width(bytes, at, budget)?; + at += utf8_scalar(&bytes[at..], budget)?.len(); } Ok(()) } @@ -73,7 +61,7 @@ pub(super) fn decode<'s, B: WorkBudget>( copied = at; } else { // Validate copied text before a later escape can select a different failure. - at += scalar_width(bytes, at, budget)?; + at += utf8_scalar(&bytes[at..], budget)?.len(); } } source.copy(&mut output, range.start + copied..range.start + at, budget)?; diff --git a/big-code-analysis-ast/src/documentation/text/source_cursor.rs b/big-code-analysis-ast/src/documentation/text/source_cursor.rs index da696710d..15a4eda79 100644 --- a/big-code-analysis-ast/src/documentation/text/source_cursor.rs +++ b/big-code-analysis-ast/src/documentation/text/source_cursor.rs @@ -2,7 +2,7 @@ use super::{TextBuilder, TextError}; use crate::documentation::budget::WorkBudget; -use crate::documentation::{SourcePiece, SourcePieces, UnavailableReason}; +use crate::documentation::{Origin, SourcePiece, SourcePieces, UnavailableReason}; use std::ops::Range; pub(super) struct SourceCursor<'f, 's> { @@ -64,6 +64,19 @@ impl<'f, 's> SourceCursor<'f, 's> { } Ok(()) } + + pub(super) fn newline( + &mut self, + builder: &mut TextBuilder<'s>, + range: Range, + budget: &B, + ) -> Result<(), TextError> { + if range.len() == 2 { + builder.transformed("\n", Origin::Decoded(self.pieces(range, budget)?), budget) + } else { + self.copy(builder, range, budget) + } + } } crate::observation::counter!( diff --git a/utils/documentation-rust-literal-perturb.json b/utils/documentation-rust-literal-perturb.json index 2718be1da..8970cdef5 100644 --- a/utils/documentation-rust-literal-perturb.json +++ b/utils/documentation-rust-literal-perturb.json @@ -3,6 +3,13 @@ "runner": "cargo", "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], "cases": [ + { + "name": "ordinary-siblings-pay-discarded-coverage-searches", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "if self.index.profile == Profile::Rust\n && trivia\n && let Some(start) = next_start", + "new": "if self.index.profile == Profile::Rust\n && let Some(start) = next_start", + "expect": ["documentation::collector::rust_tests::ordinary_rust_sibling_spacing_adds_no_binding_coverage_searches"] + }, { "name": "empty-output-range-emits-zero-width-map", "file": "big-code-analysis-ast/src/documentation/text/cleanup.rs", From ddb25af4b412a56bf5599c709baaa02fa5d14d84 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:49:52 -0800 Subject: [PATCH 064/221] test(bench): distinguish calibration coordination and cap outcomes Pin selected-count writeback, cap-only median decisions, below-cap validation and multistage final summaries. Each closes a verified surviving mutation from the documentation test audit. Refs #1662 --- .../documentation-calibration.json | 28 ++++ .../documentation/runner/calibration_tests.rs | 136 ++++++++++++++++++ 2 files changed, 164 insertions(+) diff --git a/big-code-analysis-bench/perturbations/documentation-calibration.json b/big-code-analysis-bench/perturbations/documentation-calibration.json index 549878f07..4cb395ce4 100644 --- a/big-code-analysis-bench/perturbations/documentation-calibration.json +++ b/big-code-analysis-bench/perturbations/documentation-calibration.json @@ -9,6 +9,34 @@ }, "command": ["cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation", "--no-fail-fast"], "cases": [ + { + "name": "omit calibrated repetition writeback", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "raw[at].iterations = result.map_err(|error| retained_error(error, &raw[..=at]))?;", + "new": "let _ = result.map_err(|error| retained_error(error, &raw[..=at]))?;", + "expect": ["documentation::runner::calibration_tests::cell_coordinator_stores_each_selected_repetition_count"] + }, + { + "name": "cap decision uses first sample", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "if observed >= MIN_SOURCE_SAMPLE {", + "new": "if stages[at].samples[0] >= MIN_SOURCE_SAMPLE {", + "expect": ["documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples"] + }, + { + "name": "cap-limited outcome accepted below cap", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "stage.iterations == SOURCE_MAX_ITERATIONS\n && (MIN_SOURCE_SAMPLE..SOURCE_TARGET_SAMPLE).contains(&observed)", + "new": "(MIN_SOURCE_SAMPLE..SOURCE_TARGET_SAMPLE).contains(&observed)", + "expect": ["documentation::runner::calibration_tests::cap_limited_trace_requires_the_iteration_cap"] + }, + { + "name": "final summary uses first stage", + "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", + "old": "if let Some(stage) = stages.last() {", + "new": "if let Some(stage) = stages.first() {", + "expect": ["documentation::runner::calibration_tests::calibration_formatter_preserves_sample_order_and_integer_nanoseconds"] + }, { "name": "calibrate with one operation instead of the declared batch count", "file": "big-code-analysis-bench/src/documentation/runner/calibration.rs", diff --git a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs index cebe42cd5..4c68d3115 100644 --- a/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs +++ b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs @@ -117,6 +117,59 @@ fn cap_outcomes_use_the_three_sample_median_and_exact_boundaries() { } } +#[test] +fn cap_decision_uses_the_median_of_distinct_samples() { + for (samples, expected) in [ + ( + [9_000_000, 199_998, 199_999], + CalibrationOutcome::Unresolved, + ), + ([0, 200_000, 200_001], CalibrationOutcome::CapLimited), + ] { + let mut evidence = Calibration::new(Mode::Gate); + let mut calls = 0; + let result = calibrate(&mut evidence, "cap-median", 1, MAX_CELL_WALK, |count| { + let sample = calls % 3; + calls += 1; + Ok(Duration::from_nanos(if count == 1 << 20 { + samples[sample] + } else { + 0 + })) + }); + assert_eq!(calls, 63); + let Calibration::Batches { stages, outcome } = &evidence else { + panic!("expected batch calibration") + }; + assert_eq!(*outcome, expected); + assert_eq!(stages.len(), 21); + assert_eq!(stages[20].samples, samples.map(Duration::from_nanos)); + match expected { + CalibrationOutcome::Unresolved => { + assert!(result.unwrap_err().0.contains("median-ns 199999 < 200000")); + } + CalibrationOutcome::CapLimited => { + assert_eq!(result.unwrap(), 1 << 20); + evidence + .validate(Mode::Gate, 1 << 20, MAX_CELL_WALK) + .unwrap(); + } + _ => panic!("unexpected case"), + } + } +} + +#[test] +fn cap_limited_trace_requires_the_iteration_cap() { + let mut trace = target_trace(4); + *outcome_mut(&mut trace) = CalibrationOutcome::CapLimited; + stages_mut(&mut trace)[2].samples = vec![Duration::from_micros(200); 3]; + for mode in [Mode::Gate, Mode::ReportOnly] { + let error = trace.validate(mode, 4, MAX_CELL_WALK).unwrap_err(); + assert_eq!(error.0, "invalid calibration outcome"); + } +} + #[test] fn real_calibration_batches_execute_three_times_each_tested_count() { let probe = &super::super::REGISTRY[1]; @@ -303,6 +356,53 @@ fn pending_cells() -> Vec { .collect() } +#[test] +fn cell_coordinator_stores_each_selected_repetition_count() { + let mut raw = pending_cells(); + let expected_counts = [1, 2, 4]; + let mut calls = Vec::new(); + calibrate_cells(&mut raw, |at, count| { + calls.push((at, count)); + Ok(if count == expected_counts[at] { + Duration::from_millis(2) + } else { + Duration::ZERO + }) + }) + .unwrap(); + assert_eq!( + calls, + [ + (0, 1), + (0, 1), + (0, 1), + (1, 1), + (1, 1), + (1, 1), + (1, 2), + (1, 2), + (1, 2), + (2, 1), + (2, 1), + (2, 1), + (2, 2), + (2, 2), + (2, 2), + (2, 4), + (2, 4), + (2, 4), + ] + ); + assert_eq!( + raw.iter().map(|cell| cell.iterations).collect::>(), + expected_counts + ); + for (cell, count) in raw.iter().zip(expected_counts) { + assert_eq!(cell.calibration, target_trace(count)); + assert!(cell.batches.is_empty()); + } +} + #[test] fn failures_preserve_previous_cells_stages_and_exact_observed_prefix() { for budget_failure in [false, true] { @@ -508,4 +608,40 @@ fn calibration_formatter_preserves_sample_order_and_integer_nanoseconds() { " calibration-final-ns: 0 1 2000001 0 2000003 target-reached\n" ) ); + + let trace = Calibration::Batches { + stages: vec![ + CalibrationStage { + iterations: 1, + samples: vec![ + Duration::from_nanos(300), + Duration::from_nanos(100), + Duration::from_nanos(200), + ], + }, + CalibrationStage { + iterations: 2, + samples: vec![ + Duration::from_nanos(2_000_001), + Duration::ZERO, + Duration::from_nanos(2_000_003), + ], + }, + ], + outcome: CalibrationOutcome::TargetReached, + }; + trace + .validate(Mode::Gate, 2, Duration::from_nanos(3_000_007)) + .unwrap(); + let mut text = String::new(); + write_calibration(&mut text, &trace, Duration::from_nanos(3_000_007)).unwrap(); + assert_eq!( + text, + concat!( + " per-operation-budget-ns: 3000007\n", + " calibration-stage-ns: 0 1 300 100 200\n", + " calibration-stage-ns: 1 2 2000001 0 2000003\n", + " calibration-final-ns: 1 2 2000001 0 2000003 target-reached\n" + ) + ); } From fbf41b8d2e9f2f1a18fba74fc33ffe675bd3ee2e Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:10:23 -0800 Subject: [PATCH 065/221] fix(bench): validate retained report budgets before acceptance Check every scheduled sample against the retained custom budget and validate calibration bounds before cloning caller-owned records. Pin the over-budget nonmedian sample and malformed calibration cases. Refs #1662 --- .../documentation-calibration.json | 7 ++ .../src/documentation/combined.rs | 75 +++++++++++++++++++ .../src/documentation/runner.rs | 8 ++ docs/development/benchmarking.md | 2 +- 4 files changed, 91 insertions(+), 1 deletion(-) diff --git a/big-code-analysis-bench/perturbations/documentation-calibration.json b/big-code-analysis-bench/perturbations/documentation-calibration.json index 4cb395ce4..2dd9dc68e 100644 --- a/big-code-analysis-bench/perturbations/documentation-calibration.json +++ b/big-code-analysis-bench/perturbations/documentation-calibration.json @@ -9,6 +9,13 @@ }, "command": ["cargo", "test", "-p", "big-code-analysis-bench", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation", "--no-fail-fast"], "cases": [ + { + "name": "skip scheduled budget during report revalidation", + "file": "big-code-analysis-bench/src/documentation/runner.rs", + "old": "check_budget(raw.id, raw.size, batch.elapsed, raw.iterations, raw.budget)?;", + "new": "let _ = (raw.id, raw.size, batch.elapsed, raw.iterations, raw.budget);", + "expect": ["documentation::combined::tests::validation_rechecks_every_scheduled_batch_against_retained_budget"] + }, { "name": "omit calibrated repetition writeback", "file": "big-code-analysis-bench/src/documentation/runner.rs", diff --git a/big-code-analysis-bench/src/documentation/combined.rs b/big-code-analysis-bench/src/documentation/combined.rs index 8f7d47893..2cfcd9890 100644 --- a/big-code-analysis-bench/src/documentation/combined.rs +++ b/big-code-analysis-bench/src/documentation/combined.rs @@ -221,6 +221,81 @@ mod tests { } } + #[test] + fn validation_rechecks_every_scheduled_batch_against_retained_budget() { + use std::time::Duration; + + for mode in [Mode::Gate, Mode::ReportOnly] { + let mut source = source_reports(false); + source.mode = mode; + source.validate_data().unwrap(); + let ids: Vec<_> = source.results.iter().map(|result| result.id).collect(); + let cell = &mut source.results[0].cells[0]; + assert_eq!(cell.iterations, 1); + assert_eq!(cell.batch_median, Duration::from_micros(200)); + cell.budget = Duration::from_millis(2); + cell.batches[0].elapsed = Duration::from_millis(2); + cell.batch_max = Duration::from_millis(2); + let mut report = CombinedReport { + legacy: None, + source: Some(source), + }; + report.validate(Scope::Source, &[], &ids).unwrap(); + + let cell = &mut report.source.as_mut().unwrap().results[0].cells[0]; + cell.batches[0].elapsed = Duration::from_nanos(2_000_001); + cell.batch_max = Duration::from_nanos(2_000_001); + assert_eq!(cell.batches[1].elapsed, Duration::from_micros(200)); + assert_eq!(cell.batches[2].elapsed, Duration::from_micros(200)); + assert_eq!(cell.batch_median, Duration::from_micros(200)); + let error = report.validate(Scope::Source, &[], &ids).unwrap_err(); + assert!( + error + .0 + .starts_with("AbandonedCell: documentation/cold/depth size 256, 1 iterations,"), + "{error}" + ); + } + } + + #[test] + fn validation_rejects_oversized_calibration_stages_and_samples() { + use super::super::runner::{Calibration, CalibrationStage}; + use std::time::Duration; + + for length in [64, 4096] { + let mut report = source_reports(false); + let cell = &mut report.results[0].cells[0]; + let Calibration::Batches { stages, .. } = &mut cell.calibration else { + panic!("expected calibration trace") + }; + stages[0].samples = vec![Duration::from_millis(2); length]; + let error = report.validate_data().unwrap_err(); + assert!( + error.0.contains("calibration stage requires three samples"), + "{error}" + ); + + let mut report = source_reports(false); + let cell = &mut report.results[0].cells[0]; + let Calibration::Batches { stages, .. } = &mut cell.calibration else { + panic!("expected calibration trace") + }; + *stages = vec![ + CalibrationStage { + iterations: 1, + samples: vec![] + }; + length + ]; + let error = report.validate_data().unwrap_err(); + assert!( + error.0.contains("invalid calibration stage count"), + "{error}" + ); + } + } + #[cfg(unix)] #[test] #[allow(clippy::too_many_lines)] // One rendered log exercises mixed typed failures and the workflow's actual tail size. diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index 96d87f9e2..1739471c6 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -145,6 +145,13 @@ impl SourceReport { "invalid source result ladder", )?; for cell in &result.cells { + cell.calibration + .validate(self.mode, cell.iterations, cell.budget) + .map_err(|error| context(result.id, cell.size, error))?; + require( + cell.batches.len() == self.rounds, + format!("{} size {}: missing samples", result.id, cell.size), + )?; let verified = reduce_cell( RawCell { counts: cell.counts, @@ -573,6 +580,7 @@ fn reduce_cell(raw: RawCell, rounds: usize, mode: Mode) -> Result Date: Fri, 20 Nov 2026 18:15:59 -0800 Subject: [PATCH 066/221] test(documentation): guard Rust carrier work and exact graph links --- .../src/documentation/collector/rust.rs | 6 + .../src/documentation/collector/rust_tests.rs | 348 +++++++++++++++++- .../src/documentation/source.rs | 4 + .../src/documentation/text/rust/literal.rs | 3 + .../documentation/text/rust/literal/tests.rs | 155 ++++++++ .../tests/rust_documentation_grammar.rs | 205 ++++++++++- .../documentation/rust-unit1-provenance.json | 12 + utils/documentation-rust-audit-perturb.json | 49 +++ 8 files changed, 760 insertions(+), 22 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/text/rust/literal/tests.rs create mode 100644 utils/documentation-rust-audit-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector/rust.rs b/big-code-analysis-ast/src/documentation/collector/rust.rs index 75ddd2efa..5fe5caae1 100644 --- a/big-code-analysis-ast/src/documentation/collector/rust.rs +++ b/big-code-analysis-ast/src/documentation/collector/rust.rs @@ -3,6 +3,10 @@ use super::*; use std::ops::Range; +// Count actual child examinations; duplicate carrier work preserves every output. +crate::observation::counter!(carrier_children, cfg(test)); +crate::observation::counter!(attribute_children, cfg(test)); + pub(super) enum Carrier { Other, Unknown, @@ -31,6 +35,7 @@ impl<'s> AttributeFields<'s> { let mut fields = Self::default(); for &child in &canonical.children[canonical.nodes[attribute.0].children.clone()] { budget.step()?; + attribute_children::record(); let record = &canonical.nodes[child.0]; let node = record.evidence.node(); match record.field { @@ -76,6 +81,7 @@ impl<'s> Builder<'s> { let item = &canonical.nodes[id.0]; for &child in &canonical.children[item.children.clone()] { budget.step()?; + carrier_children::record(); let attribute = &canonical.nodes[child.0]; if attribute.evidence.node().kind() != "attribute" { continue; diff --git a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs index e0cce4d47..6dae25fc4 100644 --- a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs @@ -369,14 +369,29 @@ fn rust_literal_state_priority_is_pending_gap_boundary_then_source_order() { #[test] #[cfg(feature = "rust")] +#[allow(clippy::too_many_lines)] // Recovery controls keep content, exact neighbor links and pending-owner evidence together. fn rust_literal_recovery_keeps_a_valid_neighbor_and_owner_uncertainty() { indexes(b"#[doc = \"tail\"]", |index| { assert_eq!(text(index).text(), "tail"); assert_eq!(index.associations().len(), 0); + let document = index.documents().next().unwrap(); + let linked: Vec<_> = index + .assessments() + .filter(|a| { + a.get().axis == AssessmentAxis::Owner + && index.assessed_document(*a).unwrap() == Some(document) + }) + .collect(); + assert_eq!(linked.len(), 1); + assert!(linked[0].get().node.is_none()); + let root = index.canonical.nodes[0].evidence.node(); + assert_eq!(root.byte_range(), 0..15); assert!( index + .node_associations(root) + .unwrap() .assessments() - .any(|a| a.get().axis == AssessmentAxis::Owner) + .any(|a| a == linked[0]) ); }); for broken in [ @@ -398,6 +413,54 @@ fn rust_literal_recovery_keeps_a_valid_neighbor_and_owner_uncertainty() { ); let last = index.documents().last().unwrap(); assert_eq!(index.complete_text(last).unwrap().unwrap().text(), "good"); + // expected: the fixed suffix places the good comment at B+11 and g at B+20. + let comment = index.facts().document_fragment(last, 0).unwrap(); + assert_eq!( + comment.get().source().pieces()[0].range(), + broken.len() + 11..broken.len() + 19 + ); + let good: Vec<_> = index + .associations() + .filter(|association| { + association.get().binding.is_some_and(|node| { + node.node().byte_range() == (broken.len() + 20..broken.len() + 29) + }) + }) + .collect(); + assert_eq!(good.len(), 1); + let association = good[0]; + assert_eq!( + index.facts().associated_document(association).unwrap(), + last + ); + assert_eq!( + association.get().lexical_scope.node().byte_range(), + 0..source.len() + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("good function") + }; + assert_eq!( + node.node().byte_range(), + broken.len() + 20..broken.len() + 29 + ); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .collect::>(), + good + ); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + good + ); }); } indexes(b"struct S(#[doc = \"slot\"] u32);", |index| { @@ -408,6 +471,22 @@ fn rust_literal_recovery_keeps_a_valid_neighbor_and_owner_uncertainty() { .assessments() .any(|a| a.get().axis == AssessmentAxis::Owner) ); + let document = index.documents().next().unwrap(); + let linked: Vec<_> = index + .assessments() + .filter(|a| { + a.get().axis == AssessmentAxis::Owner + && index.assessed_document(*a).unwrap() == Some(document) + }) + .collect(); + assert_eq!(linked.len(), 1); + let candidate = linked[0].get().node.unwrap().node(); + assert_eq!(candidate.byte_range(), 25..28); + assert_eq!(candidate.kind(), "primitive_type"); + let query = index.node_associations(candidate).unwrap(); + assert!(query.projection_pending()); + assert_eq!(query.associations().len(), 0); + assert!(query.assessments().any(|a| a == linked[0])); assert!( !index .assessments() @@ -476,6 +555,7 @@ fn included( #[test] #[cfg(feature = "rust")] +#[allow(clippy::too_many_lines)] // Both gap orderings pin contributor ranges, state priority and graph links. fn rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes() { let source = b"#[doc = \"\\x80\"] #[doc = \"bXc\"] fn f() {}"; included(source, &[26..27], false, |index| { @@ -496,6 +576,7 @@ fn rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes() { .assessments() .any(|a| a.get().axis == AssessmentAxis::Occurrence) ); + assert_path_gap_links(index, 6..19, 20..29, 0..5); }, ); included( @@ -510,6 +591,7 @@ fn rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes() { .assessments() .any(|a| a.get().axis == AssessmentAxis::Occurrence) ); + assert_path_gap_links(index, 0..13, 20..29, 14..19); }, ); included( @@ -546,6 +628,29 @@ fn rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes() { .collect::>(), vec![6..16, 17..20] ); + let attribute = fragment.get().node().unwrap().node(); + let attribute = attribute.named_child(0).unwrap(); + let path = attribute.named_child(0).unwrap(); + assert_eq!(path.byte_range(), 8..11); + assert!(index.source.covers(path.byte_range())); + assert_eq!(&index.source()[path.byte_range()], b"doc"); + let value = attribute.child_by_field_name("value").unwrap(); + assert_eq!(value.byte_range(), 14..19); + assert!(!index.source.covers(value.byte_range())); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!( + index.facts().associated_document(association).unwrap(), + index.documents().next().unwrap() + ); + assert_eq!( + association.get().binding.unwrap().node().byte_range(), + 21 + suffix.len()..30 + suffix.len() + ); + assert_eq!( + association.get().lexical_scope.node().byte_range(), + 0..source.len() + ); }); } for (source, gap) in [ @@ -578,35 +683,119 @@ fn rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes() { ); } +#[cfg(feature = "rust")] +fn assert_path_gap_links( + index: &DocumentationIndex<'_>, + attribute: Range, + owner_span: Range, + comment: Range, +) { + // bca: suppress(halstead) -- the same occurrence/document/owner handles are checked through both prepared views. + let occurrences: Vec<_> = index + .assessments() + .filter(|a| a.get().axis == AssessmentAxis::Occurrence) + .collect(); + assert_eq!(occurrences.len(), 1); + let occurrence = occurrences[0]; + assert_eq!( + occurrence.get().node.unwrap().node().byte_range(), + attribute + ); + assert_eq!(index.assessed_document(occurrence).unwrap(), None); + let document = index.documents().next().unwrap(); + assert_eq!( + index + .facts() + .document_fragment(document, 0) + .unwrap() + .get() + .source() + .pieces()[0] + .range(), + comment + ); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!( + index.facts().associated_document(association).unwrap(), + document + ); + assert_eq!( + association.get().binding.unwrap().node().byte_range(), + owner_span + ); + assert_eq!( + association.get().lexical_scope.node().byte_range(), + 0..index.source().len() + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("documented function") + }; + assert_eq!(node.node().byte_range(), owner_span); + let query = index.node_associations(node.node()).unwrap(); + assert_eq!(query.associations().collect::>(), vec![association]); + assert!(query.assessments().any(|a| a == occurrence)); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); +} + #[test] #[cfg(feature = "rust")] fn rust_literal_inner_root_module_function_and_private_nested_source_owners() { - for (source, kinds, texts) in [ - ("#![doc = \"root\"]", vec!["source_file"], vec!["root"]), + for (source, kinds, texts, owners, bindings, scopes) in [ + ( + "#![doc = \"root\"]", + vec!["source_file"], + vec!["root"], + vec![0..16], + vec![None], + vec![0..16], + ), ( "#[doc = \"outer\"] mod m { #![doc = \"inner\"] }", vec!["mod_item"], vec!["outer\ninner"], + vec![17..44], + vec![Some(17..44)], + vec![0..44], ), ( "#[doc = \"outer\"] fn f() { #![doc = \"inner\"] }", vec!["function_item"], vec!["outer\ninner"], + vec![17..45], + vec![Some(17..45)], + vec![0..45], ), ( "#[test] #[doc = \"test\"] fn f() { #[doc = \"nested\"] fn g() {} }", vec!["function_item", "function_item"], vec!["test", "nested"], + vec![24..62, 51..60], + vec![Some(24..62), Some(51..60)], + vec![0..62, 31..62], ), ] { indexes(source.as_bytes(), |index| { assert_eq!(index.documents().len(), texts.len()); assert_eq!(index.associations().len(), kinds.len()); - for ((document, association), (kind, expected)) in index + for (position, ((document, association), (kind, expected))) in index .documents() .zip(index.associations()) .zip(kinds.iter().zip(&texts)) + .enumerate() { + assert_eq!( + index.facts().associated_document(association).unwrap(), + document + ); assert_eq!( index.complete_text(document).unwrap().unwrap().text(), *expected @@ -624,13 +813,38 @@ fn rust_literal_inner_root_module_function_and_private_nested_source_owners() { panic!("owner") }; assert_eq!(node.node().kind(), *kind); + assert_eq!(node.node().byte_range(), owners[position]); + assert_eq!( + association + .get() + .binding + .map(|node| node.node().byte_range()), + bindings[position] + ); + assert_eq!( + association.get().lexical_scope.node().byte_range(), + scopes[position] + ); assert_eq!( index .node_associations(node.node()) .unwrap() .associations() - .count(), - 1 + .collect::>(), + vec![association] + ); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); + let linked = index.facts().associated_document(association).unwrap(); + assert_eq!( + index.complete_text(linked).unwrap().unwrap().text(), + *expected ); } }); @@ -823,19 +1037,127 @@ fn rust_literal_materializes_once_and_prices_decoding_projection_and_retained_re } } +#[test] +#[cfg(feature = "rust")] +fn rust_carrier_child_work_depends_on_width_not_depth() { + use super::rust::{attribute_children, carrier_children}; + for size in [8, 32, 128] { + for (depth, width) in [(0, size), (size, 1), (size, size)] { + let source = format!( + "{}{}fn f() {{}}{}", + "mod m {".repeat(depth), + "#[doc = \"a\"]\n".repeat(width), + "}".repeat(depth) + ); + let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + for raw in [false, true] { + let before = (carrier_children::observed(), attribute_children::observed()); + let index = if raw { + collect( + LANG::Rust, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + } else { + parser.documentation(&context, &options) + } + .unwrap(); + // expected: #, [, attribute (return before ]); path, =, value. No extras in this fixture. + assert_eq!(carrier_children::observed() - before.0, 3 * width); + assert_eq!(attribute_children::observed() - before.1, 3 * width); + assert_eq!(text(&index).text(), vec!["a"; width].join("\n")); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), width); + for at in 0..width { + let fragment = index.facts().document_fragment(document, at).unwrap(); + assert_eq!(fragment.get().form(), FragmentForm::Attribute); + assert_eq!( + fragment.get().source().pieces()[0].bytes(), + b"#[doc = \"a\"]" + ); + } + } + } + } +} + #[test] #[cfg(feature = "rust")] fn rust_literal_many_adjacent_pieces_do_not_restart_global_intersections() { + use crate::documentation::source::piece_copies; use crate::documentation::text::source_cursor::fragment_piece_visits; for size in [8, 32, 128] { let source = format!("#[doc = \"{}\"] fn f() {{}}", "\\x41".repeat(size)); - let before = fragment_piece_visits::observed(); - included(source.as_bytes(), &[], true, |index| { - assert_eq!(text(index).text(), "A".repeat(size)); - assert_eq!(text(index).mappings().len(), size); - // Nine prefix pieces, four bytes per escape, and one lookahead per escape. - assert_eq!(fragment_piece_visits::observed() - before, 9 + 5 * size); - }); + for split in [true, false] { + let before = fragment_piece_visits::observed(); + let copies = piece_copies::observed(); + included(source.as_bytes(), &[], split, |index| { + assert_eq!(text(index).text(), "A".repeat(size)); + assert_eq!(text(index).mappings().len(), size); + // expected: split tokens clone four responsible pieces; contiguous tokens clone one. + assert_eq!( + piece_copies::observed() - copies, + if split { 4 * size } else { size } + ); + // Split cursor: nine prefix pieces, four bytes and one lookahead per escape. + assert_eq!( + fragment_piece_visits::observed() - before, + if split { 9 + 5 * size } else { size } + ); + let expected: Vec<_> = (0..size) + .map(|at| { + let range = 9 + 4 * at..13 + 4 * at; + let pieces = if split { + range.map(|byte| byte..byte + 1).collect() + } else { + vec![range] + }; + (at..at + 1, "decoded", pieces) + }) + .collect(); + assert_eq!(maps(text(index)), expected); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 1); + let fragment = index.facts().document_fragment(document, 0).unwrap(); + assert_eq!( + fragment.get().node().unwrap().node().byte_range(), + 0..11 + 4 * size + ); + assert_eq!( + fragment.get().source().pieces().len(), + if split { 11 + 4 * size } else { 1 } + ); + let retained = piece_copies::observed(); + for _ in 0..20 { + let complete = text(index); + let portions: Vec<_> = complete.origins(size - 1..size).unwrap().collect(); + assert_eq!(portions.len(), 1); + let OriginView::Decoded(pieces) = &portions[0].origin else { + panic!("last escape") + }; + assert_eq!( + pieces.iter().map(SourcePiece::range).collect::>(), + expected[size - 1].2 + ); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); + } + assert_eq!(piece_copies::observed() - retained, 0); + }); + } } } diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index 00108dd9c..5cbf81192 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -10,6 +10,9 @@ crate::observation::counter!( cfg(any(test, feature = "test-support")) ); +// Responsible-piece cloning is work that retained-map equality cannot reveal. +crate::observation::counter!(piece_copies, cfg(test)); + /// A nonempty, half-open source byte range and its borrowed raw bytes. #[derive(Clone, Debug, PartialEq, Eq)] pub struct SourcePiece<'s> { @@ -59,6 +62,7 @@ impl<'s> SourcePieces<'s> { for piece in &self.pieces { budget.step()?; pieces.push(piece.clone()); + piece_copies::record(); } Ok(Self { pieces, diff --git a/big-code-analysis-ast/src/documentation/text/rust/literal.rs b/big-code-analysis-ast/src/documentation/text/rust/literal.rs index 6f369e8af..5ba814084 100644 --- a/big-code-analysis-ast/src/documentation/text/rust/literal.rs +++ b/big-code-analysis-ast/src/documentation/text/rust/literal.rs @@ -187,3 +187,6 @@ fn unicode(bytes: &[u8], at: &mut usize, budget: &B) -> Result, + steps: Cell, + checkpoints: Cell, + fail_byte: Option, +} + +#[cfg(feature = "rust")] +impl WorkBudget for CountingBudget { + type Error = SourceError; + + fn checkpoint(&self) -> Result<(), SourceError> { + self.checkpoints.set(self.checkpoints.get() + 1); + Ok(()) + } + + fn step(&self) -> Result<(), SourceError> { + self.steps.set(self.steps.get() + 1); + Ok(()) + } + + #[cfg(feature = "rust")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + if self.fail_byte.is_some_and(|at| self.bytes.get() >= at) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } +} + +#[cfg(feature = "rust")] +impl CountingBudget { + #[cfg(feature = "rust")] + fn counts(&self) -> (usize, usize, usize) { + (self.bytes.get(), self.steps.get(), self.checkpoints.get()) + } +} + +#[cfg(feature = "rust")] +fn parsed_literal(body: &str, check: impl FnOnce(&SourceContext<'_>, &Fragment<'_>, Range)) { + let source = format!("#[doc = \"{body}\"] fn f() {{}}"); + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + assert!(!root.has_error()); + let item = root.named_child(0).unwrap(); + assert_eq!(item.kind(), "attribute_item"); + let attribute = item.named_child(0).unwrap(); + assert_eq!(attribute.kind(), "attribute"); + assert!(attribute.child_by_field_name("arguments").is_none()); + let value = attribute.child_by_field_name("value").unwrap(); + assert_eq!(value.kind(), "string_literal"); + assert_eq!(value.byte_range(), 8..10 + body.len()); + assert!(!value.has_error() && !value.is_missing()); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let fragment = Fragment { + source: context.pieces(item.byte_range()).unwrap(), + node: Some(context.node(item).unwrap()), + form: FragmentForm::Attribute, + }; + check(&context, &fragment, value.byte_range()); +} + +#[test] +#[cfg(feature = "rust")] +fn continuation_whitespace_is_charged_before_any_append() { + for size in [8, 32, 128] { + for (ending, prefix_bytes) in [("\n", 2), ("\r\n", 3)] { + for (unit, width) in [(" ", 1), (" \t\n\r\n", 5)] { + let body = format!("\\{ending}{}", unit.repeat(size)); + parsed_literal(&body, |context, fragment, range| { + let budget = CountingBudget { + fail_byte: Some(prefix_bytes + 1), + ..CountingBudget::default() + }; + let copies = crate::documentation::text::copy_chunks::observed(); + assert!(matches!( + decode(context, fragment, range.clone(), &budget), + Err(TextError::Source(SourceError::Cancelled)) + )); + // expected: backslash, LF/CR, optional LF, then the first whitespace byte. + assert_eq!(budget.counts(), (prefix_bytes + 1, 0, 0)); + assert_eq!( + crate::documentation::text::copy_chunks::observed() - copies, + 0 + ); + + let budget = CountingBudget::default(); + let decoded = decode(context, fragment, range, &budget).unwrap(); + assert_eq!(decoded.text, ""); + assert_eq!(decoded.mappings, []); + // expected: all physical continuation whitespace is consumed once, without output. + assert_eq!(budget.counts(), (prefix_bytes + width * size, 0, 0)); + assert_eq!( + crate::documentation::text::copy_chunks::observed() - copies, + 0 + ); + }); + } + } + } +} + +#[test] +#[cfg(feature = "rust")] +fn unicode_digits_are_charged_before_piece_gathering_and_append() { + for size in [1, 8, 32, 128] { + parsed_literal(&"\\u{1F600}".repeat(size), |context, fragment, range| { + let budget = CountingBudget { + fail_byte: Some(3), + ..CountingBudget::default() + }; + let copies = crate::documentation::text::copy_chunks::observed(); + assert!(matches!( + decode(context, fragment, range.clone(), &budget), + Err(TextError::Source(SourceError::Cancelled)) + )); + // expected: backslash + u + first digit; no source-piece step or append checkpoint yet. + assert_eq!(budget.counts(), (3, 0, 0)); + assert_eq!( + crate::documentation::text::copy_chunks::observed() - copies, + 0 + ); + + let budget = CountingBudget::default(); + let decoded = decode(context, fragment, range, &budget).unwrap(); + assert_eq!(decoded.text, "😀".repeat(size)); + assert_eq!(decoded.mappings.len(), size); + // expected per token: 2 outer bytes + 5 digits + } + two four-byte append charges. + // One retained source piece is examined; the append makes two checkpoints and one copy. + assert_eq!(budget.counts(), (16 * size, size, 2 * size)); + assert_eq!( + crate::documentation::text::copy_chunks::observed() - copies, + size + ); + for (at, mapping) in decoded.mappings.iter().enumerate() { + assert_eq!(mapping.output.range(), 4 * at..4 * at + 4); + let Origin::Decoded(pieces) = &mapping.origin else { + panic!("Unicode token origin") + }; + assert_eq!(pieces.pieces().len(), 1); + assert_eq!(pieces.pieces()[0].range(), 9 + 9 * at..18 + 9 * at); + assert_eq!(pieces.pieces()[0].bytes(), b"\\u{1F600}"); + } + }); + } +} diff --git a/big-code-analysis-ast/tests/rust_documentation_grammar.rs b/big-code-analysis-ast/tests/rust_documentation_grammar.rs index e98beecce..670aa6aac 100644 --- a/big-code-analysis-ast/tests/rust_documentation_grammar.rs +++ b/big-code-analysis-ast/tests/rust_documentation_grammar.rs @@ -4,7 +4,7 @@ use std::ops::Range; #[allow(clippy::naive_bytecount)] -fn dump(source: &[u8], excluded: Option>) -> tree_sitter::Tree { +fn parse(source: &[u8], excluded: Option>) -> tree_sitter::Tree { // bca: suppress(halstead) -- the grammar probe records source ranges, fields and recovery flags together. let mut parser = tree_sitter::Parser::new(); parser @@ -34,6 +34,13 @@ fn dump(source: &[u8], excluded: Option>) -> tree_sitter::Tree { parser.set_included_ranges(&ranges).unwrap(); } let tree = parser.parse(source, None).unwrap(); + if std::env::var_os("BCA_DUMP_RUST_DOC_GRAMMAR").is_some() { + dump(source, &tree); + } + tree +} + +fn dump(source: &[u8], tree: &tree_sitter::Tree) { println!("SOURCE {source:?} INCLUDED {:?}", tree.included_ranges()); let mut cursor = tree.walk(); let mut depth = 0; @@ -53,8 +60,7 @@ fn dump(source: &[u8], excluded: Option>) -> tree_sitter::Tree { } else { while !cursor.goto_next_sibling() { if !cursor.goto_parent() { - drop(cursor); - return tree; + return; } depth -= 1; } @@ -83,7 +89,7 @@ fn rust_documentation_grammar_direct_value_and_recovery() { false, ), ] { - let tree = dump(source.as_bytes(), None); + let tree = parse(source.as_bytes(), None); let item = tree.root_node().named_child(0).unwrap(); assert_eq!(item.kind_id(), 170); let mut cursor = item.walk(); @@ -125,10 +131,191 @@ fn rust_documentation_grammar_direct_value_and_recovery() { "#[doc = \"a] fn f() {}\n/// good\nfn g() {}", "#[doc] fn f() {}", ] { - dump(source.as_bytes(), None); + parse(source.as_bytes(), None); + } + parse(b"#[doc = b\"\xff\"] fn f() {}", None); + parse(b"#[doc = \"\xff\"] fn f() {}", None); + parse(b"/// a\n#[doXc = \"b\"] fn f() {}", Some(10..11)); + parse(b"/// a\n#[doc = \"bXc\"] fn f() {}", Some(16..17)); +} + +fn child<'t>(parent: tree_sitter::Node<'t>, kind: &str) -> tree_sitter::Node<'t> { + let mut cursor = parent.walk(); + let matches: Vec<_> = parent + .children(&mut cursor) + .filter(|node| node.kind() == kind) + .collect(); + assert_eq!(matches.len(), 1, "{kind} under {}", parent.kind()); + matches[0] +} + +fn shape(node: tree_sitter::Node<'_>, kind: &str, range: Range, flags: (bool, bool, bool)) { + assert_eq!(node.kind(), kind); + assert_eq!(node.byte_range(), range); + assert_eq!( + (node.has_error(), node.is_error(), node.is_missing()), + flags + ); +} + +#[test] +fn rust_documentation_grammar_clean_invalid_escape_retains_direct_value() { + let tree = parse(br#"#[doc = "\q"] fn f() {}"#, None); + assert!(!tree.root_node().has_error()); + let item = child(tree.root_node(), "attribute_item"); + shape(item, "attribute_item", 0..13, (false, false, false)); + let attribute = child(item, "attribute"); + shape(attribute, "attribute", 2..12, (false, false, false)); + shape( + child(attribute, "identifier"), + "identifier", + 2..5, + (false, false, false), + ); + let value = attribute.child_by_field_name("value").unwrap(); + shape(value, "string_literal", 8..12, (false, false, false)); + shape( + child(value, "escape_sequence"), + "escape_sequence", + 9..11, + (false, false, false), + ); + assert!(attribute.child_by_field_name("arguments").is_none()); +} + +#[test] +fn rust_documentation_grammar_short_hex_and_underscore_unicode_recover_differently() { + let tree = parse(br#"#[doc = "\x1"] fn f() {}"#, None); + let item = child(tree.root_node(), "attribute_item"); + shape(item, "attribute_item", 0..14, (true, false, false)); + let attribute = child(item, "attribute"); + shape(attribute, "attribute", 2..5, (false, false, false)); + shape( + child(attribute, "identifier"), + "identifier", + 2..5, + (false, false, false), + ); + assert!(attribute.child_by_field_name("value").is_none()); + let error = child(item, "ERROR"); + shape(error, "ERROR", 6..13, (true, true, false)); + shape(child(error, "ERROR"), "ERROR", 9..12, (false, true, false)); + shape(child(item, "]"), "]", 13..14, (false, false, false)); + + let tree = parse(br#"#[doc = "\u{1_f600}"] fn f() {}"#, None); + let item = child(tree.root_node(), "attribute_item"); + shape(item, "attribute_item", 0..21, (true, false, false)); + let attribute = child(item, "attribute"); + shape(attribute, "attribute", 2..20, (true, false, false)); + shape( + child(attribute, "identifier"), + "identifier", + 2..5, + (false, false, false), + ); + shape( + child(attribute, "ERROR"), + "ERROR", + 8..19, + (true, true, false), + ); + let value = attribute.child_by_field_name("value").unwrap(); + shape(value, "string_literal", 19..20, (true, false, false)); + let mut cursor = value.walk(); + let missing: Vec<_> = value + .children(&mut cursor) + .filter(tree_sitter::Node::is_missing) + .collect(); + assert_eq!(missing.len(), 1); + shape(missing[0], "\"", 20..20, (true, false, true)); +} + +#[test] +fn rust_documentation_grammar_missing_bracket_keeps_neighbor_boundaries() { + let tree = parse(b"#[doc = \"a\" fn f() {}\n/// good\nfn g() {}", None); + let root = tree.root_node(); + let item = child(root, "attribute_item"); + shape(item, "attribute_item", 0..11, (true, false, false)); + let attribute = child(item, "attribute"); + shape(attribute, "attribute", 2..11, (false, false, false)); + shape( + attribute.child_by_field_name("value").unwrap(), + "string_literal", + 8..11, + (false, false, false), + ); + shape(child(item, "]"), "]", 11..11, (true, false, true)); + assert_eq!(root.named_child_count(), 4); + shape( + root.named_child(1).unwrap(), + "function_item", + 12..21, + (false, false, false), + ); + shape( + root.named_child(2).unwrap(), + "line_comment", + 22..31, + (false, false, false), + ); + shape( + root.named_child(3).unwrap(), + "function_item", + 31..40, + (false, false, false), + ); +} + +#[test] +fn rust_documentation_grammar_path_and_value_gaps_keep_separate_fields() { + for (source, gap, item_span, path_span, value_span, function_span) in [ + ( + b"/// a\n#[doXc = \"b\"] fn f() {}".as_slice(), + 10..11, + 6..19, + 8..12, + 15..18, + 20..29, + ), + ( + b"/// a\n#[doc = \"bXc\"] fn f() {}".as_slice(), + 16..17, + 6..20, + 8..11, + 14..19, + 21..30, + ), + ] { + let tree = parse(source, Some(gap.clone())); + assert!(!tree.root_node().has_error()); + assert_eq!( + tree.included_ranges() + .iter() + .map(|range| range.start_byte..range.end_byte) + .collect::>(), + vec![0..gap.start, gap.end..source.len()] + ); + let item = child(tree.root_node(), "attribute_item"); + shape(item, "attribute_item", item_span, (false, false, false)); + let attribute = child(item, "attribute"); + shape( + child(attribute, "identifier"), + "identifier", + path_span, + (false, false, false), + ); + shape( + attribute.child_by_field_name("value").unwrap(), + "string_literal", + value_span, + (false, false, false), + ); + assert!(attribute.child_by_field_name("arguments").is_none()); + shape( + child(tree.root_node(), "function_item"), + "function_item", + function_span, + (false, false, false), + ); } - dump(b"#[doc = b\"\xff\"] fn f() {}", None); - dump(b"#[doc = \"\xff\"] fn f() {}", None); - dump(b"/// a\n#[doXc = \"b\"] fn f() {}", Some(10..11)); - dump(b"/// a\n#[doc = \"bXc\"] fn f() {}", Some(16..17)); } diff --git a/tests/fixtures/documentation/rust-unit1-provenance.json b/tests/fixtures/documentation/rust-unit1-provenance.json index f5a465374..23d64f7f1 100644 --- a/tests/fixtures/documentation/rust-unit1-provenance.json +++ b/tests/fixtures/documentation/rust-unit1-provenance.json @@ -6,6 +6,18 @@ "production_oracles": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs", "legacy_oracles": "src/metrics/loc/documentation_tests.rs", "mutation_manifest": "utils/documentation-rust-literal-perturb.json", + "audit_corrections": { + "base": "69e69b5e3d81231fc308a433713757a02e590265", + "mutation_manifest": "utils/documentation-rust-audit-perturb.json", + "budget_oracles": "big-code-analysis-ast/src/documentation/text/rust/literal/tests.rs", + "carrier_work": "For W plain doc attributes, item readers examine #, [, attribute (returning before ]): 3W. Direct attribute readers examine path, =, value: 3W. Typed/raw collections are measured separately across (0,N), (N,1), (N,N) depth/width controls.", + "piece_work": "N four-byte hex escapes clone 4N responsible one-byte pieces or N contiguous token pieces through the actual copy_with_budget loop; retained queries clone zero pieces. Duplicate decoded-origin copying yields 8N split-piece clones.", + "continuation_budget": "Whitespace-only LF continuation charges N+2 bytes; CRLF charges N+3. Failing byte 3/4 respectively precedes any source-piece step, append checkpoint or output copy.", + "unicode_budget": "Each clean parsed 1F600 token charges backslash + u + five digits + closing brace (8 bytes), then two four-byte append charges: 16N total, N source-piece steps, 2N checkpoints, N copies. Failure at byte 3 precedes piece gathering and append.", + "nested_graph": "Exact existing test fixture: f24..62, body31..62, g51..60, root0..62. Both associated_document identity and lexical_scope are asserted separately from enumeration/content and through prepared owner/node queries.", + "grammar_evidence": "Representative q, short hex, underscore Unicode, missing bracket and included path/value-gap assertions preserve the previously captured pinned grammar fields/ranges/flags. has_error, is_error and is_missing are separate observations.", + "runtime_obligation": "Three unconditional observation recorders add production overhead; test-only accessors do not make that overhead free. Counter/budget tests establish only their named work, not a universal complexity or performance bound. Runtime qualification remains pending." + }, "preserved_rust_attribute_payload_sha256": "aac39c7cc5bc121b5a806cc7e48af010226c50176197ef51fd62cef6ce0f45d5", "cleanup_sources": [ "https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_ast/src/util/comments.rs", diff --git a/utils/documentation-rust-audit-perturb.json b/utils/documentation-rust-audit-perturb.json new file mode 100644 index 000000000..8b65854ff --- /dev/null +++ b/utils/documentation-rust-audit-perturb.json @@ -0,0 +1,49 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], + "cases": [ + { + "name": "duplicate-rust-carrier-lookup", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " let carrier = self.rust_carrier(id, budget)?;", + "new": " let _ = self.rust_carrier(id, budget)?;\n let carrier = self.rust_carrier(id, budget)?;", + "expect": ["documentation::collector::rust_tests::rust_carrier_child_work_depends_on_width_not_depth"] + }, + { + "name": "delete-continuation-inner-byte-charge", + "file": "big-code-analysis-ast/src/documentation/text/rust/literal.rs", + "old": " while matches!(bytes.get(*at), Some(b' ' | b'\\t' | b'\\n' | b'\\r')) {\n budget.bytes(1).map_err(Into::into)?;", + "new": " while matches!(bytes.get(*at), Some(b' ' | b'\\t' | b'\\n' | b'\\r')) {", + "expect": ["documentation::text::rust::literal::tests::continuation_whitespace_is_charged_before_any_append"] + }, + { + "name": "delete-unicode-inner-byte-charge", + "file": "big-code-analysis-ast/src/documentation/text/rust/literal.rs", + "old": " let mut digits = 0;\n loop {\n budget.bytes(1).map_err(Into::into)?;", + "new": " let mut digits = 0;\n loop {", + "expect": ["documentation::text::rust::literal::tests::unicode_digits_are_charged_before_piece_gathering_and_append"] + }, + { + "name": "duplicate-decoded-origin-piece-copy", + "file": "big-code-analysis-ast/src/documentation/text/cleanup.rs", + "old": " Origin::Decoded(pieces) => Origin::Decoded(copy_pieces(pieces, budget)?),", + "new": " Origin::Decoded(pieces) => {\n let _ = copy_pieces(pieces, budget)?;\n Origin::Decoded(copy_pieces(pieces, budget)?)\n },", + "expect": ["documentation::collector::rust_tests::rust_literal_many_adjacent_pieces_do_not_restart_global_intersections"] + }, + { + "name": "nested-g-association-document-points-to-f", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " self.index.facts.associations.push(Association {\n document,", + "new": " let audit_document = if self.index.profile == Profile::Rust && self.index.source.bytes() == b\"#[test] #[doc = \\\"test\\\"] fn f() { #[doc = \\\"nested\\\"] fn g() {} }\" && draft.binding.is_some_and(|node| node.node().byte_range() == (51..60)) {\n DocumentId(0)\n } else { document };\n self.index.facts.associations.push(Association {\n document: audit_document,", + "expect": ["documentation::collector::rust_tests::rust_literal_inner_root_module_function_and_private_nested_source_owners"] + }, + { + "name": "nested-g-association-scope-points-to-root", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence,", + "new": " lexical_scope: if self.index.profile == Profile::Rust && self.index.source.bytes() == b\"#[test] #[doc = \\\"test\\\"] fn f() { #[doc = \\\"nested\\\"] fn g() {} }\" && draft.binding.is_some_and(|node| node.node().byte_range() == (51..60)) {\n self.index.canonical.nodes[0].evidence\n } else { self.index.canonical.nodes[draft.scope.0].evidence },", + "expect": ["documentation::collector::rust_tests::rust_literal_inner_root_module_function_and_private_nested_source_owners"] + } + ] +} From 573590eb1e1a5492bdcad649e3d51bf90f85ef76 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:35:13 -0800 Subject: [PATCH 067/221] fix(documentation): preserve Rust bindings and cleanup boundaries --- .bca-baseline.toml | 16 +- CHANGELOG.md | 5 +- .../src/documentation/collector/assembly.rs | 18 +- .../collector/rust_remediation_tests.rs | 434 ++++++++++++++++++ .../src/documentation/collector/rust_tests.rs | 4 + .../src/documentation/text/comments.rs | 128 +++++- fuzz/corpus/documentation/rust-outer-binding | Bin 0 -> 40 bytes .../documentation/rust-pending-inner-binding | Bin 0 -> 38 bytes .../corpus/documentation/rust-second-lines-cr | Bin 0 -> 34 bytes .../documentation/rust-second-lines-terminal | Bin 0 -> 35 bytes .../documentation/rust-second-lines-triple-cr | Bin 0 -> 36 bytes .../documentation/rust-unicode-first-star | Bin 0 -> 42 bytes fuzz/documentation-seeds.json | 72 +++ fuzz/generate_documentation_seeds.py | 6 + fuzz/src/documentation/tests.rs | 89 +++- .../documentation/rust-unit1-provenance.json | 24 + ...ocumentation-rust-remediation-perturb.json | 28 ++ 17 files changed, 803 insertions(+), 21 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs create mode 100644 fuzz/corpus/documentation/rust-outer-binding create mode 100644 fuzz/corpus/documentation/rust-pending-inner-binding create mode 100644 fuzz/corpus/documentation/rust-second-lines-cr create mode 100644 fuzz/corpus/documentation/rust-second-lines-terminal create mode 100644 fuzz/corpus/documentation/rust-second-lines-triple-cr create mode 100644 fuzz/corpus/documentation/rust-unicode-first-star create mode 100644 utils/documentation-rust-remediation-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 8ec547e4b..783211471 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -575,7 +575,7 @@ value = 48218.38058500087 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::combine_pending" metric = "halstead.effort" -value = 71442.25234889281 +value = 77507.87166066223 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -1079,7 +1079,7 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "" metric = "loc.ploc" -value = 565.0 +value = 584.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1091,13 +1091,13 @@ value = 6.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "abc" -value = 69.28924880528002 +value = 67.21606950722423 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "cognitive" -value = 38.0 +value = 36.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1109,7 +1109,7 @@ value = 28.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "beautify" metric = "halstead.effort" -value = 409210.04703845707 +value = 385472.6566078847 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" @@ -1261,6 +1261,12 @@ qualified = "render_local" metric = "nexits" value = 8.0 +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "rust_fragments" +metric = "cognitive" +value = 16.0 + [[entry]] path = "big-code-analysis-ast/src/documentation/text/literals.rs" qualified = "decode" diff --git a/CHANGELOG.md b/CHANGELOG.md index afb3aca8d..72e088d56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,10 @@ for historical reference. - The unstable Rust AST documentation collector now decodes direct cooked/raw `doc` strings and composes them with comments using Rust 1.99.0 cleanup and - exact forward origins. Invalid encoding, unsupported byte/C prefixes, recovery + exact forward origins. Outer attributes retain their binding when combined with + inner comments. Changed fragments receive rustdoc's second CRLF interpretation; + Unicode first-line eligibility preserves ASCII-only decoration rules. + Invalid encoding, unsupported byte/C prefixes, recovery and excluded source retain explicit unavailable states. Metadata and computed carriers, additional owner projections and publication interpretation remain pending. Legacy documentation rows and test pruning are preserved. (#1664, Unit1) diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index f5ea2aac6..004f219e1 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -68,9 +68,16 @@ impl<'s> Builder<'s> { for (node, fragment, target) in std::mem::take(&mut self.pending_attributes) { budget.step()?; let pending = matches!(self.rust_values.get(&fragment), Some(rust::Value::Pending)); + let binding = target + .filter(|_| { + self.index.canonical.nodes[node.0].evidence.node().kind() == "attribute_item" + }) + .map(|id| self.index.canonical.nodes[id.0].evidence); if let Some(&index) = target.as_ref().and_then(|target| by_target.get(target)) { - self.drafts[index].fragments.push(fragment); - self.drafts[index].pending |= pending; + let draft = &mut self.drafts[index]; + draft.fragments.push(fragment); + draft.pending |= pending; + draft.binding = draft.binding.or(binding); } else { let scope = self.index.canonical.nodes[target.unwrap_or(node).0] .parent @@ -82,12 +89,7 @@ impl<'s> Builder<'s> { fragments: vec![fragment], target, scope, - binding: target - .filter(|_| { - self.index.canonical.nodes[node.0].evidence.node().kind() - == "attribute_item" - }) - .map(|id| self.index.canonical.nodes[id.0].evidence), + binding, role: target.map_or(DocumentRole::Primary, |id| self.rust_role(id)), unresolved: None, pending: pending || target.is_none(), diff --git a/big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs b/big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs new file mode 100644 index 000000000..97ecee87b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs @@ -0,0 +1,434 @@ +use super::*; + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn outer_attribute_merges_binding_into_inner_comment_document() { + for (source, kind, owner, raw, inner) in [ + ( + "#[doc = \"outer\"]\nfn f() { //! inner\n}", + "function_item", + 17..37, + 26..35, + 30..35, + ), + ( + "#[doc = \"outer\"]\nmod m { //! inner\n}", + "mod_item", + 17..36, + 25..34, + 29..34, + ), + ( + "#[doc = \"outer\"]\nfn f() { /*! inner*/ }", + "function_item", + 17..39, + 26..37, + 30..35, + ), + ( + "#[doc = \"outer\"]\nmod m { /*! inner*/ }", + "mod_item", + 17..38, + 25..36, + 29..34, + ), + ] { + indexes(source.as_bytes(), |index| { + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 2); + assert_eq!(document.get().composition(), Composition::AttributeSequence); + assert_eq!( + document.get().role(), + if kind == "mod_item" { + DocumentRole::FilePackage + } else { + DocumentRole::Primary + } + ); + assert_eq!(text(index).text(), "outer\ninner"); + assert_eq!( + maps(text(index)), + vec![ + (0..5, "copied", vec![9..14]), + (5..6, "synthetic", vec![]), + (6..11, "copied", vec![inner.clone()]), + ] + ); + for (at, span, form) in [ + (0, 0..16, FragmentForm::Attribute), + (1, raw.clone(), FragmentForm::Comment), + ] { + let fragment = index.facts().document_fragment(document, at).unwrap(); + assert_eq!(fragment.get().form(), form); + assert_eq!(fragment.get().source().pieces()[0].range(), span); + assert_eq!( + fragment.get().source().pieces()[0].bytes(), + &source.as_bytes()[span] + ); + } + assert_bound_document(index, kind, owner.clone()); + }); + } +} + +// test-lang-gates: hand-written(rust) — shared only by Rust parser-backed regressions. +#[cfg(feature = "rust")] +fn assert_bound_document(index: &DocumentationIndex<'_>, kind: &str, span: Range) { + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let document = index.documents().next().unwrap(); + let association = index.associations().next().unwrap(); + assert_eq!( + index.facts().associated_document(association).unwrap(), + document + ); + assert_eq!( + association + .get() + .binding + .map(|node| node.node().byte_range()), + Some(span.clone()) + ); + assert_eq!( + association.get().lexical_scope.node().byte_range(), + 0..index.source().len() + ); + assert_eq!(association.get().owner_count(), 1); + assert_eq!(association.get().publication, Publication::Unknown); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("item owner") + }; + assert_eq!(node.node().kind(), kind); + assert_eq!(node.node().byte_range(), span); + assert_eq!( + index + .node_associations(node.node()) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + vec![association] + ); +} + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn outer_metadata_keeps_binding_on_pending_composition() { + indexes(b"#[doc(hidden)]\nfn f() { //! inner\n}", |index| { + let document = index.documents().next().unwrap(); + assert!(matches!(document.get().content(), Content::PendingAdapter)); + assert_eq!(document.get().fragment_count(), 2); + assert_eq!(document.get().role(), DocumentRole::Primary); + for (at, span) in [(0, 0..14), (1, 24..33)] { + assert_eq!( + index + .facts() + .document_fragment(document, at) + .unwrap() + .get() + .source() + .pieces()[0] + .range(), + span + ); + } + let assessments: Vec<_> = index + .assessments() + .filter(|a| a.get().axis == AssessmentAxis::Composition) + .collect(); + assert_eq!(assessments.len(), 1); + assert_eq!( + assessments[0].get().node.map(|n| n.node().byte_range()), + Some(15..35) + ); + assert_eq!( + index.assessed_document(assessments[0]).unwrap(), + Some(document) + ); + assert_bound_document(index, "function_item", 15..35); + }); +} + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn inner_only_and_existing_outer_bindings_remain_distinct() { + for (source, binding, expected) in [ + ("fn f() { //! inner\n}", None, "inner"), + ("fn f() { #![doc = \"inner\"] }", None, "inner"), + ( + "/// outer\nfn f() { //! inner\n}", + Some(10..30), + "outer\ninner", + ), + ( + "/// outer\nfn f() { #![doc = \"inner\"] }", + Some(10..38), + "outer\ninner", + ), + ] { + indexes(source.as_bytes(), |index| { + assert_eq!(text(index).text(), expected); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().binding.map(|n| n.node().byte_range()), + binding + ); + }); + } +} + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn changed_beautification_reinterprets_one_cr_before_terminal_empty() { + // Rust 1.99.0's unchanged cleanup bodies independently establish these texts. + // Escape offsets below are counted from the source spelling, not oracle spans. + for (source, expected, origins) in [ + ( + r#"#[doc = "\na\r\r\nb"] fn f() {}"#, + "a\nb", + vec![ + (0..1, "copied", vec![11..12]), + (1..2, "decoded", vec![16..18]), + (2..3, "copied", vec![18..19]), + ], + ), + ( + r#"#[doc = "a\r\r\nb"] fn f() {}"#, + "a\r\nb", + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "decoded", vec![10..12]), + (2..3, "decoded", vec![14..16]), + (3..4, "copied", vec![16..17]), + ], + ), + ( + r#"#[doc = "\na\r\n"] fn f() {}"#, + "a", + vec![(0..1, "copied", vec![11..12])], + ), + ( + r#"#[doc = "\na\r\r\n\n"] fn f() {}"#, + "a", + vec![(0..1, "copied", vec![11..12])], + ), + ( + r#"#[doc = "\na\r\r\r\nb"] fn f() {}"#, + "a\r\nb", + vec![ + (0..1, "copied", vec![11..12]), + (1..2, "decoded", vec![12..14]), + (2..3, "decoded", vec![18..20]), + (3..4, "copied", vec![20..21]), + ], + ), + ( + r#"#[doc = "a\r\r\r\nb"] fn f() {}"#, + "a\r\r\nb", + vec![ + (0..1, "copied", vec![9..10]), + (1..2, "decoded", vec![10..12]), + (2..3, "decoded", vec![12..14]), + (3..4, "decoded", vec![16..18]), + (4..5, "copied", vec![18..19]), + ], + ), + ] { + indexes(source.as_bytes(), |index| { + assert_eq!(text(index).text(), expected, "{source}"); + assert_eq!(maps(text(index)), origins, "{source}"); + }); + } +} + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn second_line_interpretation_preserves_comment_newline_origins() { + // Bare CR in comments is collector policy, not accepted Rust/rustdoc parity. + for (source, expected, origins) in [ + ( + "/**\na\r\r\nb*/ fn f() {}", + "a\nb", + vec![ + (0..1, "copied", vec![4..5]), + (1..2, "decoded", vec![6..8]), + (2..3, "copied", vec![8..9]), + ], + ), + ( + "/**\na\r\r\nb*/ #[doc = \"z\"] fn f() {}", + "a\nb\nz", + vec![ + (0..1, "copied", vec![4..5]), + (1..2, "decoded", vec![6..8]), + (2..3, "copied", vec![8..9]), + (3..4, "synthetic", vec![]), + (4..5, "copied", vec![21..22]), + ], + ), + ( + "/// z\n#[doc = \"\\na\\r\\r\\r\\nb\"] fn f() {}", + "z\na\r\nb", + vec![ + (0..1, "copied", vec![4..5]), + (1..2, "synthetic", vec![]), + (2..3, "copied", vec![17..18]), + (3..4, "decoded", vec![18..20]), + (4..5, "decoded", vec![24..26]), + (5..6, "copied", vec![26..27]), + ], + ), + ] { + indexes(source.as_bytes(), |index| { + assert_eq!(text(index).text(), expected, "{source:?}"); + assert_eq!(maps(text(index)), origins, "{source:?}"); + }); + } +} + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn unicode_first_line_star_keeps_ascii_decoration_and_exact_origins() { + for space in ["\u{2003}", "\u{a0}"] { + for mixed in [false, true] { + let suffix = if mixed { "\n#[doc = \"z\"]" } else { "" }; + let source = format!("/**{space}* a\n * b*/{suffix}\nfn f() {{}}"); + let width = space.len(); + indexes(source.as_bytes(), |index| { + let expected = format!("{space}* a\n * b{}", if mixed { "\nz" } else { "" }); + assert_eq!(text(index).text(), expected); + let mut origins = vec![ + (0..width + 3, "copied", vec![3..width + 6]), + (width + 3..width + 4, "copied", vec![width + 6..width + 7]), + (width + 4..width + 8, "copied", vec![width + 7..width + 11]), + ]; + if mixed { + origins.extend([ + (width + 8..width + 9, "synthetic", vec![]), + ( + width + 9..width + 10, + "copied", + vec![width + 23..width + 24], + ), + ]); + } + assert_eq!(maps(text(index)), origins); + assert_bound_document( + index, + "function_item", + width + 14 + suffix.len()..source.len(), + ); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), if mixed { 2 } else { 1 }); + assert_eq!( + index + .facts() + .document_fragment(document, 0) + .unwrap() + .get() + .source() + .pieces()[0] + .range(), + 0..width + 13 + ); + let star = text(index) + .origins(width + 5..width + 6) + .unwrap() + .next() + .unwrap(); + let OriginView::Copied(pieces) = star.origin else { + panic!("second star copied") + }; + assert_eq!(pieces.range(), width + 8..width + 9); + }); + } + } +} + +// test-lang-gates: hand-written(rust) — parent indexes helper parses Rust through use super::*. +#[test] +#[cfg(feature = "rust")] +fn first_line_eligibility_controls_ascii_blank_nonstar_and_invalid_utf8() { + for (source, expected) in [ + ("/** * a\n * b*/ fn f() {}", "a\nb"), + ("/** title\n * b*/ fn f() {}", "title\n b"), + ("/**\n * a\n * b\n */ fn f() {}", "a\nb"), + ("/**\u{2003}\n * b*/ fn f() {}", "\u{2003}\nb"), + ] { + indexes(source.as_bytes(), |index| { + assert_eq!(text(index).text(), expected, "{source:?}") + }); + } + // Comment-only rendering reaches eligibility without mixed-renderer prevalidation. + indexes(b"/**\xff* a\n * b*/ fn f() {}", |index| { + assert_eq!(index.documents().len(), 1); + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::InvalidEncoding) + )); + }); +} + +#[test] +#[cfg(feature = "rust")] +fn reported_late_boundaries_are_grammar_controls_not_priority_counterexamples() { + let hashes = "#".repeat(256); + let raw = format!("#[doc = r{hashes}\"a\"{hashes}]"); + for source in [ + format!(r#"#[doc = "\x80"] {raw} fn f() {{}}"#), + format!(r#"{raw} #[doc = "\x80"] fn f() {{}}"#), + ] { + let parser = AnyParser::parse(LANG::Rust, source.as_bytes().to_vec(), None, None).unwrap(); + let attribute = parser + .root_node() + .preorder() + .find(|n| { + n.kind() == "attribute_item" + && source.as_bytes()[n.as_tree_sitter().byte_range()].starts_with(b"#[doc = r") + }) + .unwrap(); + assert!(attribute.as_tree_sitter().has_error()); + assert!(attribute.preorder().any(|n| n.kind() == "ERROR")); + indexes(source.as_bytes(), |index| { + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 2); + assert!(matches!( + document.get().content(), + Content::Unavailable(UnavailableReason::GrammarBoundary) + )); + }); + } + let source = b"#![doc = \"\\x80\"]\n/*! unclosed"; + let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); + assert!(parser.root_node().preorder().any(|n| n.kind() == "ERROR")); + assert!( + !parser + .root_node() + .preorder() + .any(|n| n.kind() == "block_comment") + ); + indexes(source, |index| { + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 1); + assert!(matches!( + document.get().content(), + Content::Unavailable(UnavailableReason::InvalidEncoding) + )); + }); +} diff --git a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs index 6dae25fc4..6a66b5272 100644 --- a/big-code-analysis-ast/src/documentation/collector/rust_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/rust_tests.rs @@ -8,6 +8,9 @@ use crate::documentation::*; use crate::{AnyParser, LANG}; use std::ops::Range; +#[path = "rust_remediation_tests.rs"] +mod remediation; + #[cfg(feature = "rust")] fn indexes(source: &[u8], check: impl Fn(&DocumentationIndex<'_>)) { let parser = AnyParser::parse(LANG::Rust, source.to_vec(), None, None).unwrap(); @@ -1169,6 +1172,7 @@ fn rust_literal_text_phase_cancellation_restores_next_collection() { format!("#[doc = \"{}\"] fn f() {{}}", "\\x41".repeat(20_000)), format!("#[doc = r\"{}\"] fn f() {{}}", "raw".repeat(20_000)), format!("{}fn f() {{}}", "#[doc = \"a\"]\n".repeat(5000)), + format!("/**{}* a\n * b*/ fn f() {{}}", "\u{2003}".repeat(20_000)), ] { let parser = AnyParser::parse(LANG::Rust, source.into_bytes(), None, None).unwrap(); let collect = || { diff --git a/big-code-analysis-ast/src/documentation/text/comments.rs b/big-code-analysis-ast/src/documentation/text/comments.rs index 6172d68cf..011f3c5de 100644 --- a/big-code-analysis-ast/src/documentation/text/comments.rs +++ b/big-code-analysis-ast/src/documentation/text/comments.rs @@ -471,6 +471,17 @@ pub(super) fn rust_fragments( block.lines.pop(); } let changed = beautify(block, bytes, budget)?; + if changed { + // Rejoining adds LF after every retained line except the last. The + // second str::lines pass removes one CR, even before a terminal empty. + let rejoined = block.lines.len().saturating_sub(1); + for line in &mut block.lines[..rejoined] { + budget.step().map_err(Into::into)?; + if bytes[line.content.clone()].last() == Some(&b'\r') { + line.content.end -= 1; + } + } + } if changed && block.lines.len() > 1 && block @@ -484,6 +495,18 @@ pub(super) fn rust_fragments( Ok(()) } +fn rust_first_line_star(bytes: &[u8], budget: &B) -> Result { + let mut at = 0; + while at < bytes.len() { + let scalar = super::utf8_scalar(&bytes[at..], budget)?; + if scalar.chars().any(|character| !character.is_whitespace()) { + return Ok(scalar == "*"); + } + at += scalar.len(); + } + Ok(false) +} + fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Result { if block.lines.len() < 2 && block @@ -522,11 +545,10 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul let mut start = 0; let mut end = block.lines.len(); if block.rust_decoration { - if let Some(line) = block.lines.first() { - let indent = margin(&bytes[line.content.clone()], budget)?; - if bytes.get(line.content.start + indent) != Some(&b'*') { - start = 1; - } + if let Some(line) = block.lines.first() + && !rust_first_line_star(&bytes[line.content.clone()], budget)? + { + start = 1; } while start < end && blank(&bytes[block.lines[start].content.clone()], true, budget)? { start += 1; @@ -588,7 +610,103 @@ fn beautify(block: &mut Block, bytes: &[u8], budget: &B) -> Resul #[cfg(test)] mod remediation_tests { use super::*; + use crate::documentation::SourceError; use crate::documentation::budget::{CollectionBudget, WorkPhase, cancel_in_phase}; + use std::cell::Cell; + + #[derive(Default)] + struct CountingBudget { + bytes: Cell, + steps: Cell, + fail_byte: Option, + fail_step: Option, + } + + impl WorkBudget for CountingBudget { + type Error = SourceError; + + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + + fn step(&self) -> Result<(), SourceError> { + self.steps.set(self.steps.get() + 1); + if self.fail_step == Some(self.steps.get()) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + if self.fail_byte.is_some_and(|at| self.bytes.get() >= at) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + } + + #[test] + fn unicode_first_line_scan_is_bounded_and_charges_each_scalar() { + for size in [8, 32, 4096] { + let source = format!("{}*", "\u{2003}".repeat(size)); + let budget = CountingBudget::default(); + assert!(rust_first_line_star(source.as_bytes(), &budget).unwrap()); + // expected: N three-byte scalars followed by one ASCII star, no line steps. + assert_eq!((budget.bytes.get(), budget.steps.get()), (3 * size + 1, 0)); + let budget = CountingBudget { + fail_byte: Some(6), + ..CountingBudget::default() + }; + assert!(matches!( + rust_first_line_star(source.as_bytes(), &budget), + Err(TextError::Source(SourceError::Cancelled)) + )); + assert_eq!(budget.bytes.get(), 6); + } + for bytes in [b"".as_slice(), b" \t", "\u{a0}".as_bytes()] { + assert!(!rust_first_line_star(bytes, &CountingBudget::default()).unwrap()); + } + let bytes = "\u{2003}*".as_bytes(); + assert!(matches!( + rust_first_line_star(&bytes[..2], &CountingBudget::default()), + Err(TextError::Unavailable(UnavailableReason::InvalidEncoding)) + )); + assert!(!rust_first_line_star(&bytes[..3], &CountingBudget::default()).unwrap()); + } + + #[test] + fn second_line_inspection_is_charged_before_trimming() { + let bytes = b"\na\r\r\nb"; + for fail_step in [None, Some(5)] { + let mut block = Block { + lines: lines(bytes, 0..bytes.len(), false, &CountingBudget::default()).unwrap(), + rust_decoration: false, + markdown: false, + }; + let budget = CountingBudget { + fail_step, + ..CountingBudget::default() + }; + let result = rust_fragments(std::slice::from_mut(&mut block), bytes, &budget); + // expected: one block, two selected lines, one decoration and one rejoined inspection. + assert_eq!(budget.steps.get(), 5); + assert_eq!(budget.bytes.get(), 2); // last-line all-stars and first-line ASCII margin. + if fail_step.is_some() { + assert!(matches!( + result, + Err(TextError::Source(SourceError::Cancelled)) + )); + assert_eq!(block.lines[0].content, 1..3); + } else { + result.unwrap(); + assert_eq!(block.lines[0].content, 1..2); + } + assert_eq!(block.lines[0].ending, 3..5); + } + } #[test] fn star_column_pass_cancels_on_line_budget_before_byte_budget() { diff --git a/fuzz/corpus/documentation/rust-outer-binding b/fuzz/corpus/documentation/rust-outer-binding new file mode 100644 index 0000000000000000000000000000000000000000..7f6a65db676e64f4db1019797f2a0727b223dacd GIT binary patch literal 40 vcmZQzW>Ah!$xl|WRZz+=ElDj>iseenQ%KX$RH#Ah!$xqhE$V^E|&C`tKO3PD7)6i6?R?yd1RLIQBOD*E61pvY?3WNXv literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-second-lines-cr b/fuzz/corpus/documentation/rust-second-lines-cr new file mode 100644 index 0000000000000000000000000000000000000000..2bc42c65b741f1cfb60fc5509416dae194c5c5e3 GIT binary patch literal 34 ncmZQzW>Ah!$xl|WRZxn_ON=Q3!n`DAh!$xl|WRZxn_ON=Q3!n~L~rC5cuJcTq3O@-=O0Hu5i6aWAK literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-second-lines-triple-cr b/fuzz/corpus/documentation/rust-second-lines-triple-cr new file mode 100644 index 0000000000000000000000000000000000000000..8b40ab197542d74d00db94222ecfbce96d116cc9 GIT binary patch literal 36 ncmZQzW>Ah!$xl|WRZxn_ON=Q3!@MM=ScSAag)|LKh3Z-Wv1kf< literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-unicode-first-star b/fuzz/corpus/documentation/rust-unicode-first-star new file mode 100644 index 0000000000000000000000000000000000000000..4003a9115951e3b6484aac54a820d977ef9c2f15 GIT binary patch literal 42 xcmZQzX3*EtdeqRYrI5&_prw$crO%}tosyrdV5^{1r4-ARmZy-Wp{Y<^3jomZ3TXfU literal 0 HcmV?d00001 diff --git a/fuzz/documentation-seeds.json b/fuzz/documentation-seeds.json index 9a4ece9ea..1d988de05 100644 --- a/fuzz/documentation-seeds.json +++ b/fuzz/documentation-seeds.json @@ -388,6 +388,78 @@ "fixture": "rust-attribute.rs", "has_error": false }, + { + "name": "rust-outer-binding", + "header": [ + 0, + 3, + 0 + ], + "sha256": "36028f36eb6a0632c886be72a574cfcb978111e7eb72a47c2123a4f17194ae49", + "class": "rust-outer-binding", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs::outer_attribute_merges_binding_into_inner_comment_document", + "has_error": false + }, + { + "name": "rust-pending-inner-binding", + "header": [ + 0, + 3, + 0 + ], + "sha256": "78fac0de145d5649f0f3599c6967f36e7bcf37687ce0a2372a25c5da35b0ad11", + "class": "rust-pending-inner-binding", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs::outer_metadata_keeps_binding_on_pending_composition", + "has_error": false + }, + { + "name": "rust-second-lines-cr", + "header": [ + 0, + 3, + 0 + ], + "sha256": "6ca796396427b5b91d4e1dd7f6ab02d78936ebf01cec351582cf0e71470b408c", + "class": "rust-second-lines-cr", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", + "has_error": false + }, + { + "name": "rust-second-lines-terminal", + "header": [ + 0, + 3, + 0 + ], + "sha256": "62d255558078494685e9d47dc7ccbdf9bb54db447fcc2062d4484eae32c14241", + "class": "rust-second-lines-terminal", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", + "has_error": false + }, + { + "name": "rust-second-lines-triple-cr", + "header": [ + 0, + 3, + 0 + ], + "sha256": "187fc91f5f02e06071009d1db9ca18985e66cd380f15f94accdc7e2167c3954d", + "class": "rust-second-lines-triple-cr", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", + "has_error": false + }, + { + "name": "rust-unicode-first-star", + "header": [ + 0, + 3, + 0 + ], + "sha256": "e21ad513bf862ed7bc748f9a545da213b5aa5b1ec345392dacfce923e479fa13", + "class": "rust-unicode-first-star", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs::unicode_first_line_star_keeps_ascii_decoration_and_exact_origins", + "has_error": false + }, { "name": "rust-literal-empty", "header": [ diff --git a/fuzz/generate_documentation_seeds.py b/fuzz/generate_documentation_seeds.py index 91036fcd7..9a42bdf65 100644 --- a/fuzz/generate_documentation_seeds.py +++ b/fuzz/generate_documentation_seeds.py @@ -101,6 +101,12 @@ def add(name, header, payload, assertion, provenance, **expected): ) cases = [ + ("rust-outer-binding", [0, 3, 0], b'#[doc = "outer"]\nfn f() { //! inner\n}', "rust-outer-binding", "rust_remediation_tests.rs::outer_attribute_merges_binding_into_inner_comment_document", False), + ("rust-pending-inner-binding", [0, 3, 0], b'#[doc(hidden)]\nfn f() { //! inner\n}', "rust-pending-inner-binding", "rust_remediation_tests.rs::outer_metadata_keeps_binding_on_pending_composition", False), + ("rust-second-lines-cr", [0, 3, 0], b'#[doc = "\\na\\r\\r\\nb"] fn f() {}', "rust-second-lines-cr", "rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", False), + ("rust-second-lines-terminal", [0, 3, 0], b'#[doc = "\\na\\r\\r\\n\\n"] fn f() {}', "rust-second-lines-terminal", "rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", False), + ("rust-second-lines-triple-cr", [0, 3, 0], b'#[doc = "\\na\\r\\r\\r\\nb"] fn f() {}', "rust-second-lines-triple-cr", "rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", False), + ("rust-unicode-first-star", [0, 3, 0], '/**\u2003* a\n * b*/\n#[doc = "z"]\nfn f() {}'.encode(), "rust-unicode-first-star", "rust_remediation_tests.rs::unicode_first_line_star_keeps_ascii_decoration_and_exact_origins", False), ("rust-literal-empty", [0, 3, 0], b'#[doc = ""] fn f() {}', "rust-literal-empty", "rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", False), ("rust-literal-raw", [0, 3, 0], b'#[doc = r###"a"#b"###] fn f() {}', "rust-literal-raw", "rust_tests.rs::rust_literal_cleanup_pins_mixed_margin_empty_joins_and_trailing_spaces", False), ("rust-literal-scalar", [0, 7, 0], b'#[doc = "\\u{1F600}"] fn f() {}', "rust-literal-scalar", "rust_tests.rs::rust_literal_escape_origins_are_complete_tokens_after_cleanup", False), diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index 3001b25fe..196e1baf5 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -204,8 +204,49 @@ fn registry_executes_every_dispatch_and_edge_assertion() { } #[allow(clippy::single_range_in_vec_init)] +#[allow(clippy::too_many_lines)] // Independent text/origin tables for registered Rust literal and cleanup seeds. fn rust_literal_seed(class: &str, index: &DocumentationIndex<'_>) { let (expected, fragments, origins) = match class { + "rust-outer-binding" => ( + "outer\ninner", + 2, + vec![ + (0..5, false, vec![9..14]), + (5..6, false, vec![]), + (6..11, false, vec![30..35]), + ], + ), + "rust-second-lines-cr" => ( + "a\nb", + 1, + vec![ + (0..1, false, vec![11..12]), + (1..2, true, vec![16..18]), + (2..3, false, vec![18..19]), + ], + ), + "rust-second-lines-terminal" => ("a", 1, vec![(0..1, false, vec![11..12])]), + "rust-second-lines-triple-cr" => ( + "a\r\nb", + 1, + vec![ + (0..1, false, vec![11..12]), + (1..2, true, vec![12..14]), + (2..3, true, vec![18..20]), + (3..4, false, vec![20..21]), + ], + ), + "rust-unicode-first-star" => ( + "\u{2003}* a\n * b\nz", + 2, + vec![ + (0..6, false, vec![3..9]), + (6..7, false, vec![9..10]), + (7..11, false, vec![10..14]), + (11..12, false, vec![]), + (12..13, false, vec![26..27]), + ], + ), "rust-literal-mixed" => ( "first\nsecond", 2, @@ -265,12 +306,35 @@ fn rust_literal_seed(class: &str, index: &DocumentationIndex<'_>) { let association = index.associations().next().unwrap(); assert_eq!(association.get().resolution, Resolution::Resolved); assert_eq!(association.get().publication, Publication::Unknown); + if class == "rust-outer-binding" { + assert_rust_inner_binding(index, 17..37); + } assert!(!index.assessments().any(|a| matches!( a.get().axis, AssessmentAxis::Occurrence | AssessmentAxis::Composition ))); } +fn assert_rust_inner_binding(index: &DocumentationIndex<'_>, span: std::ops::Range) { + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!( + association.get().binding.map(|n| n.node().byte_range()), + Some(span.clone()) + ); + let document = index.documents().next().unwrap(); + assert_eq!( + index.facts().associated_document(association).unwrap(), + document + ); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Node(node) = owner.get() else { + panic!("function owner") + }; + assert_eq!(node.node().kind(), "function_item"); + assert_eq!(node.node().byte_range(), span); +} + #[allow(clippy::too_many_lines)] // Independent expected outcomes for the finite registered edge families. fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter::Tree) { if matches!(class, "incompatible-profile" | "deferred-profile") { @@ -287,7 +351,7 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: assert!(index.source().windows(2).any(|bytes| bytes == b"\r\n")); assert_eq!(text(index).text(), "kept"); } - "pending-content" => { + "pending-content" | "rust-pending-inner-binding" => { assert_eq!(index.documents().len(), 1); assert!(matches!( index.documents().next().unwrap().get().content(), @@ -298,13 +362,34 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: .assessments() .any(|a| a.get().axis == AssessmentAxis::Composition) ); + if class == "rust-pending-inner-binding" { + assert_rust_inner_binding(index, 15..35); + let assessments: Vec<_> = index + .assessments() + .filter(|a| a.get().axis == AssessmentAxis::Composition) + .collect(); + assert_eq!(assessments.len(), 1); + assert_eq!( + assessments[0].get().node.map(|n| n.node().byte_range()), + Some(15..35) + ); + assert_eq!( + index.assessed_document(assessments[0]).unwrap(), + index.documents().next() + ); + } } "rust-literal-mixed" | "rust-literal-empty" | "rust-literal-raw" | "rust-literal-scalar" | "rust-literal-continuation" - | "rust-literal-margin" => { + | "rust-literal-margin" + | "rust-outer-binding" + | "rust-second-lines-cr" + | "rust-second-lines-terminal" + | "rust-second-lines-triple-cr" + | "rust-unicode-first-star" => { rust_literal_seed(class, index); } "join" => { diff --git a/tests/fixtures/documentation/rust-unit1-provenance.json b/tests/fixtures/documentation/rust-unit1-provenance.json index 23d64f7f1..6b2e20352 100644 --- a/tests/fixtures/documentation/rust-unit1-provenance.json +++ b/tests/fixtures/documentation/rust-unit1-provenance.json @@ -24,12 +24,36 @@ "https://github.com/rust-lang/rust/blob/1.99.0/compiler/rustc_resolve/src/rustdoc.rs" ], "independent_derivations": { + "outer_binding": "The outer attribute explicitly targets function17..37 or module17..36 in the line-comment fixtures. Inner block variants end at 39 and 38 respectively. Metadata targets function15..35 and its pending Composition assessment must retain that same node/document link. Inner-only attributes/comments supply no invented outer binding.", + "changed_second_lines": "Rust 1.99.0 beautify_doc_string rejoins only changed fragments. add_doc_fragment then calls lines again: decoded \\na\\r\\r\\nb becomes a LF b. Copied a11..12, decoded LF16..18, copied b18..19 survive; both CR escape origins are absent. Unchanged a\\r\\r\\nb retains the first CR10..12. Only one additional CR is removed: changed triple-CR retains one, unchanged retains two.", + "terminal_second_lines": "Decoded \\na\\r\\r\\n\\n beautifies to a CR LF, whose second lines pass yields a. The CR must be trimmed before removing the terminal empty line. Decoded \\na\\r\\n also yields a. Both retain only copied a11..12.", + "unicode_first_star": "EM SPACE and NBSP are Unicode whitespace for initial trim_start eligibility, so their first-line stars participate. ASCII-only decoration validation then rejects that non-ASCII prefix. For EM SPACE the second star output8..9 copies source11..12; mixed z retains EM SPACE '* a LF * b LF z'. Unicode is never treated as removable ASCII margin.", + "comment_cr_policy": "The bare-CR comment control is collector policy rather than Rust/rustdoc source parity. In /** LF a CR CR LF b*/, removed content CR5..6 must not enlarge the retained physical CRLF origin6..8. The mixed literal renderer preserves the same origin.", + "withdrawn_priority_examples": "Exactly 256 raw-string hashes in either order with x80 produce attribute ERROR descendants and two-fragment GrammarBoundary before decoding. The unclosed inner block spelling is ERROR, not block_comment, and leaves one literal contributor with InvalidEncoding. These are pinned grammar/content controls, not a global-priority rewrite.", "mixed_margin": "Sugared ' hello' has margin five; nonsugared 'another' participates with add=1. Global minimum one removes one from the comment and zero from the attribute: four spaces remain.", "empty_join": "Each empty prose fragment contributes an assembly LF; one final assembly LF is removed. Two empty attributes produce one LF.", "same_row": "Single-line interiors ' a ' and ' b ' lose their common left space, preserving both right spaces: 'a \\nb '. Physical legacy DLOC remains one.", "decoded_crlf": "Cooked a\\r\\nb decodes CR and LF separately. str::lines removes CR; LF output maps only to the complete \\n escape. Physical CRLF instead maps to both physical bytes.", "unicode_underscores": "Pinned grammar recovers \\u{1_f600} into ERROR plus a missing-delimiter value. Production content is GrammarBoundary; the decoder's valid underscore syntax cannot establish lost supplied-tree boundaries." }, + "three_fix_remediation": { + "base": "6c3201abaa30618062e1e63cf0e0f020fff27ed1", + "proposal_sha256": "db399713f8b79faa1e561e0370b8f511678d127676c5334702d6b49d4d773f41", + "production_oracles": "big-code-analysis-ast/src/documentation/collector/rust_remediation_tests.rs", + "budget_oracles": "big-code-analysis-ast/src/documentation/text/comments.rs::remediation_tests", + "mutation_manifest": "utils/documentation-rust-remediation-perturb.json", + "oracle_scope": "Executed unchanged Rust 1.99.0 beautify_doc_string, unindent_doc_fragments, add_doc_fragment and Attributes::opt_doc_value bodies with minimal safe symbol/fragment wrappers. This is a decoded-text cleanup oracle, not a full rustdoc compiler or source-span oracle. Source mappings are independently counted from fixture bytes.", + "upstream_source_sha256": { + "https://raw.githubusercontent.com/rust-lang/rust/1.99.0/compiler/rustc_ast/src/util/comments.rs": "c8c64ea483fb455a85c110e88abd3988b0381b350dcf1ce255dacc7fecbde521", + "https://raw.githubusercontent.com/rust-lang/rust/1.99.0/compiler/rustc_resolve/src/rustdoc.rs": "7a486aa7d72eb16979a55563d2995b61b9616d9e3d6474cd6e6d7bfc2f163b42", + "https://raw.githubusercontent.com/rust-lang/rust/1.99.0/src/librustdoc/clean/types.rs": "8b351e27a5b3ec9302622e0832b6c425439c1200fb5e60f2af51cc09ed44e7eb" + }, + "extracted_body_sha256": { + "beautify_doc_string": "229813f1b1159e51ffd4e7924b08dd8f7f6be0948ed256f4e19da505f3782239", + "unindent_doc_fragments_and_add_doc_fragment": "c4b54894e9d0587ea61700598c013beba33f1720544ebc6784b56d621a1877b4", + "Attributes_opt_doc_value": "f376ade2f45a5ced85c6cb845d2fb08076d3bc7797d629100c1183d20fef3458" + } + }, "pending": [ "Additional field, variant, associated-type and tuple-slot owner projections", "Metadata, computed/conditional carriers and publication interpretation", diff --git a/utils/documentation-rust-remediation-perturb.json b/utils/documentation-rust-remediation-perturb.json new file mode 100644 index 000000000..b0054fe01 --- /dev/null +++ b/utils/documentation-rust-remediation-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "-p", "big-code-analysis", "--all-features", "--lib", "--no-fail-fast", "documentation"], + "cases": [ + { + "name": "drop-outer-binding-existing-draft-merge", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " draft.binding = draft.binding.or(binding);", + "new": " let _ = binding;", + "expect": ["documentation::collector::rust_tests::remediation::outer_attribute_merges_binding_into_inner_comment_document", "documentation::collector::rust_tests::remediation::outer_metadata_keeps_binding_on_pending_composition"] + }, + { + "name": "neutralize-changed-second-line-interpretation", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let rejoined = block.lines.len().saturating_sub(1);", + "new": " let rejoined = block.lines.len().saturating_sub(1) * 0;", + "expect": ["documentation::collector::rust_tests::remediation::changed_beautification_reinterprets_one_cr_before_terminal_empty", "documentation::collector::rust_tests::remediation::second_line_interpretation_preserves_comment_newline_origins", "documentation::text::comments::remediation_tests::second_line_inspection_is_charged_before_trimming"] + }, + { + "name": "restore-ascii-only-first-line-eligibility", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "&& !rust_first_line_star(&bytes[line.content.clone()], budget)?", + "new": "&& bytes[line.content.clone()].get(margin(&bytes[line.content.clone()], budget)?) != Some(&b'*')", + "expect": ["documentation::collector::rust_tests::remediation::unicode_first_line_star_keeps_ascii_decoration_and_exact_origins"] + } + ] +} From 9ac309aaee407f456615d76b37f6f8eb7124c9b2 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:19:53 -0800 Subject: [PATCH 068/221] test(documentation): qualify Rust literal workloads and fuzz inputs --- .bca-baseline.toml | 2 +- Cargo.lock | 1 + Makefile | 28 +- big-code-analysis-ast/src/documentation.rs | 15 + .../src/documentation/collector.rs | 2 + .../src/documentation/collector/rust.rs | 4 +- .../src/documentation/source.rs | 2 +- .../src/documentation/text/rust/literal.rs | 2 +- big-code-analysis-bench/Cargo.toml | 1 + .../src/documentation/fixtures.rs | 130 +++- .../src/documentation/mod.rs | 3 + .../src/documentation/operation.rs | 51 +- .../src/documentation/runner.rs | 4 +- .../src/documentation/rust_tests.rs | 268 +++++++++ .../src/documentation/rust_validation.rs | 557 ++++++++++++++++++ .../src/documentation/tests.rs | 36 +- .../src/documentation/validation.rs | 3 + docs/development/benchmarking.md | 12 + docs/development/fuzzing.md | 11 + .../rust-literal-raw-crlf-pieces | Bin 0 -> 29 bytes .../documentation/rust-literal-value-gap | Bin 0 -> 27 bytes fuzz/documentation-seeds.json | 26 + fuzz/generate_documentation_seeds.py | 7 +- fuzz/src/documentation/tests.rs | 216 +++++++ ...umentation-rust-qualification-perturb.json | 42 ++ utils/fuzz-make-perturb.json | 28 + utils/fuzz-make-test.py | 133 +++++ 27 files changed, 1556 insertions(+), 28 deletions(-) create mode 100644 big-code-analysis-bench/src/documentation/rust_tests.rs create mode 100644 big-code-analysis-bench/src/documentation/rust_validation.rs create mode 100644 fuzz/corpus/documentation/rust-literal-raw-crlf-pieces create mode 100644 fuzz/corpus/documentation/rust-literal-value-gap create mode 100644 utils/documentation-rust-qualification-perturb.json create mode 100644 utils/fuzz-make-perturb.json create mode 100644 utils/fuzz-make-test.py diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 783211471..0d555a463 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,7 +359,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 964.0 +value = 966.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" diff --git a/Cargo.lock b/Cargo.lock index d29f156bd..c9b5a7b00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -516,6 +516,7 @@ dependencies = [ "big-code-analysis-ast", "criterion", "serde_json", + "sha2", "tempfile", ] diff --git a/Makefile b/Makefile index 46a29b533..c5da2963f 100644 --- a/Makefile +++ b/Makefile @@ -463,10 +463,14 @@ toml-lint: @echo "Linting TOML files..." @taplo lint || { echo "TOML lint found issues"; exit 1; } -makefile-check: +makefile-check: fuzz-make-test @echo "Linting Makefile with checkmake..." @checkmake --config $(BASE_DIR).checkmake.ini $(BASE_DIR)Makefile || { echo "checkmake found issues"; exit 1; } +.PHONY: fuzz-make-test +fuzz-make-test: + @python3 -B "$(BASE_DIR)utils/fuzz-make-test.py" + # actionlint scans every workflow under .github/workflows/ and shells # out to shellcheck (when present on PATH) for the `run:` blocks. It # takes no file arguments here: invoked at the repo root it discovers @@ -1474,6 +1478,10 @@ FUZZ_RUNS ?= 100000 FUZZ_TIMEOUT ?= 60 FUZZ_TARGET ?= parse_cpp FUZZ_INPUT ?= +# Shell-quoted libFuzzer arguments; recipe-owned run/timeout limits come last. +FUZZ_ARGS ?= +# Read-only corpus root, with one subdirectory per target. +FUZZ_CORPUS ?= $(BASE_DIR)fuzz/corpus # ASan on the Rust side is cargo-fuzz's own doing. The tree-sitter # grammars are C, compiled by build scripts through the `cc` crate, and @@ -1534,8 +1542,8 @@ FUZZ_CC_ENV = CFLAGS_$(subst -,_,$(FUZZ_HOST_TRIPLE))="$(FUZZ_SAN_FLAGS)" \ # the failure this comment exists to prevent. FUZZ_SYMBOLIZER = $(shell command -v llvm-symbolizer 2>/dev/null || \ ls -1 /usr/lib/llvm-*/bin/llvm-symbolizer 2>/dev/null | sort -V | tail -1) -FUZZ_RUN_ENV = LSAN_OPTIONS=suppressions=$(BASE_DIR)fuzz/lsan-suppressions.txt \ - ASAN_SYMBOLIZER_PATH=$(FUZZ_SYMBOLIZER) +FUZZ_RUN_ENV = LSAN_OPTIONS="suppressions=$(BASE_DIR)fuzz/lsan-suppressions.txt" \ + ASAN_SYMBOLIZER_PATH="$(FUZZ_SYMBOLIZER)" # Fail with the reason rather than with an unsuppressed leak report. # One line, not a `define`: a multi-line define carries embedded newlines @@ -1615,11 +1623,11 @@ fuzz-replay: $(FUZZ_REQUIRE_SYMBOLIZER); \ for t in $$(cargo +nightly fuzz list); do \ echo "Replaying committed seeds for $$t..."; \ - mkdir -p $(FUZZ_WORK)/"$$t"; \ + mkdir -p "$(FUZZ_WORK)/$$t"; \ $(FUZZ_CC_ENV) $(FUZZ_RUN_ENV) cargo +nightly fuzz run \ --target $(FUZZ_HOST_TRIPLE) "$$t" \ - $(FUZZ_WORK)/"$$t" $(BASE_DIR)fuzz/corpus/"$$t" \ - -- -runs=0 -timeout=$(FUZZ_TIMEOUT); \ + "$(FUZZ_WORK)/$$t" "$(FUZZ_CORPUS)/$$t" \ + -- $(FUZZ_ARGS) -runs=0 -timeout=$(FUZZ_TIMEOUT); \ done; \ else \ echo "nightly toolchain or cargo-fuzz not found; skipping fuzz-replay"; \ @@ -1632,13 +1640,13 @@ fuzz-run: if [ -n "$(FUZZ_INPUT)" ]; then \ echo "Replaying $(FUZZ_TARGET) against $(FUZZ_INPUT)..."; \ $(FUZZ_CC_ENV) $(FUZZ_RUN_ENV) cargo +nightly fuzz run --target $(FUZZ_HOST_TRIPLE) $(FUZZ_TARGET) \ - "$(FUZZ_INPUT)" -- -timeout=$(FUZZ_TIMEOUT); \ + "$(FUZZ_INPUT)" -- $(FUZZ_ARGS) -timeout=$(FUZZ_TIMEOUT); \ else \ echo "Fuzzing $(FUZZ_TARGET) for $(FUZZ_RUNS) runs..."; \ - mkdir -p $(FUZZ_WORK)/$(FUZZ_TARGET); \ + mkdir -p "$(FUZZ_WORK)/$(FUZZ_TARGET)"; \ $(FUZZ_CC_ENV) $(FUZZ_RUN_ENV) cargo +nightly fuzz run --target $(FUZZ_HOST_TRIPLE) $(FUZZ_TARGET) \ - $(FUZZ_WORK)/$(FUZZ_TARGET) $(BASE_DIR)fuzz/corpus/$(FUZZ_TARGET) \ - -- -runs=$(FUZZ_RUNS) -timeout=$(FUZZ_TIMEOUT); \ + "$(FUZZ_WORK)/$(FUZZ_TARGET)" "$(FUZZ_CORPUS)/$(FUZZ_TARGET)" \ + -- $(FUZZ_ARGS) -runs=$(FUZZ_RUNS) -timeout=$(FUZZ_TIMEOUT); \ fi; \ else \ echo "nightly toolchain or cargo-fuzz not found; skipping fuzz-run"; \ diff --git a/big-code-analysis-ast/src/documentation.rs b/big-code-analysis-ast/src/documentation.rs index d1c3f01e1..95205c987 100644 --- a/big-code-analysis-ast/src/documentation.rs +++ b/big-code-analysis-ast/src/documentation.rs @@ -121,6 +121,16 @@ pub struct Observations { pub map_searches: usize, /// Output-map runs consumed by a query. pub map_runs_visited: usize, + /// Direct Rust carrier children examined during attribute recognition. + pub carrier_children: usize, + /// Direct Rust attribute children examined during literal classification. + pub attribute_children: usize, + /// Responsible source pieces copied with the work budget. + pub piece_copies: usize, + /// Outer Rust literal decoder iterations, excluding inner-byte charges. + pub decoded_units: usize, + /// Retained mapping runs examined by decoded-coordinate cleanup. + pub projection_visits: usize, } /// Read qualification counters without resetting other consumers' observations. @@ -158,6 +168,11 @@ pub fn observations() -> Observations { qualification_memberships: collector::qualifications::memberships::observed(), map_searches: content::map_searches::observed(), map_runs_visited: content::map_runs_visited::observed(), + carrier_children: collector::carrier_children::observed(), + attribute_children: collector::attribute_children::observed(), + piece_copies: source::piece_copies::observed(), + decoded_units: text::rust::literal::decoded_units::observed(), + projection_visits: text::cleanup::projection_visits::observed(), } } diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index abcf6d50f..d11b966f2 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -11,6 +11,8 @@ mod assembly; mod projections; pub(super) mod qualifications; mod rust; +#[cfg(any(test, feature = "test-support"))] +pub(super) use rust::{attribute_children, carrier_children}; enum Visit { Enter(NodeId, usize), diff --git a/big-code-analysis-ast/src/documentation/collector/rust.rs b/big-code-analysis-ast/src/documentation/collector/rust.rs index 5fe5caae1..1dcf8708a 100644 --- a/big-code-analysis-ast/src/documentation/collector/rust.rs +++ b/big-code-analysis-ast/src/documentation/collector/rust.rs @@ -4,8 +4,8 @@ use super::*; use std::ops::Range; // Count actual child examinations; duplicate carrier work preserves every output. -crate::observation::counter!(carrier_children, cfg(test)); -crate::observation::counter!(attribute_children, cfg(test)); +crate::observation::counter!(carrier_children, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(attribute_children, cfg(any(test, feature = "test-support"))); pub(super) enum Carrier { Other, diff --git a/big-code-analysis-ast/src/documentation/source.rs b/big-code-analysis-ast/src/documentation/source.rs index 5cbf81192..f89b4ec52 100644 --- a/big-code-analysis-ast/src/documentation/source.rs +++ b/big-code-analysis-ast/src/documentation/source.rs @@ -11,7 +11,7 @@ crate::observation::counter!( ); // Responsible-piece cloning is work that retained-map equality cannot reveal. -crate::observation::counter!(piece_copies, cfg(test)); +crate::observation::counter!(piece_copies, cfg(any(test, feature = "test-support"))); /// A nonempty, half-open source byte range and its borrowed raw bytes. #[derive(Clone, Debug, PartialEq, Eq)] diff --git a/big-code-analysis-ast/src/documentation/text/rust/literal.rs b/big-code-analysis-ast/src/documentation/text/rust/literal.rs index 5ba814084..58e17498c 100644 --- a/big-code-analysis-ast/src/documentation/text/rust/literal.rs +++ b/big-code-analysis-ast/src/documentation/text/rust/literal.rs @@ -186,7 +186,7 @@ fn unicode(bytes: &[u8], at: &mut usize, budget: &B) -> Result { StatisticClass::Exponent } - Operation::Map => StatisticClass::LogMapRatio, + Operation::Map | Operation::MapPieces => StatisticClass::LogMapRatio, _ => StatisticClass::FixedOutputRatio, }, bound: 1.50, @@ -98,8 +99,7 @@ const fn probe( } } -/// The original 31 workloads followed by fifteen finite missing-axis ladders. -/// Original generators, options and all 93 full-size cells are preserved. +/// The original workloads followed by infrastructure and Rust literal ladders. pub const REGISTRY: &[SourceProbe] = &[ probe( "documentation/cold/depth", @@ -481,6 +481,100 @@ pub const REGISTRY: &[SourceProbe] = &[ Operation::Render, "grow F=n,S=2n-1,text=2n-1; one document/owner", ), + probe( + "documentation/rust-unit1/mixed-fragments", + "rust-mixed", + LANG::Rust, + false, + Operation::Collect, + "grow mixed F=2n+1,text=14n+5,S=6n+1; D=E=1, depth fixed", + ), + SourceProbe { + sizes: [4096, 8192, 16384], + ..probe( + "documentation/rust-unit1/cooked-large", + "rust-cooked", + LANG::Rust, + false, + Operation::Collect, + "grow cooked escape bytes and cleanup; F=D=E=1,text=S=2n+1", + ) + }, + SourceProbe { + sizes: [4096, 8192, 16384], + ..probe( + "documentation/rust-unit1/raw-large", + "rust-raw", + LANG::Rust, + false, + Operation::Collect, + "grow raw physical CRLF bytes; F=D=E=1,text=6n+1,S=2n+1", + ) + }, + probe( + "documentation/rust-unit1/attribute-width", + "rust-attribute-width", + LANG::Rust, + false, + Operation::Collect, + "grow attribute width w=n at d=0; F=n,text=S=2n-1,D=E=1", + ), + probe( + "documentation/rust-unit1/attribute-depth", + "rust-attribute-depth", + LANG::Rust, + false, + Operation::Collect, + "grow module depth d=n at w=1; F=D=E=text=S=1", + ), + probe( + "documentation/rust-unit1/attribute-depth-width", + "rust-attribute-depth-width", + LANG::Rust, + false, + Operation::Collect, + "grow d=w=n; affine nodes/bytes/output, F=n,text=S=2n-1,D=E=1", + ), + probe( + "documentation/rust-unit1/escapes-contiguous", + "rust-escapes-contiguous", + LANG::Rust, + true, + Operation::Collect, + "grow n escapes; text=S=n,F=D=E=R=1, one responsible piece/token", + ), + probe( + "documentation/rust-unit1/escapes-split", + "rust-escapes-split", + LANG::Rust, + true, + Operation::Collect, + "grow n escapes; text=S=n,F=D=E=1,R=21+4n, four pieces/token", + ), + probe( + "documentation/rust-unit1/mixed-retained", + "rust-mixed", + LANG::Rust, + false, + Operation::Retained, + "grow mixed F=2n+1,text=14n+5,S=6n+1; one borrowed text/map view K=1", + ), + probe( + "documentation/rust-unit1/mixed-owner", + "rust-mixed", + LANG::Rust, + false, + Operation::Owner, + "grow mixed F=2n+1,text=14n+5,S=6n+1; canonical function association K=1", + ), + probe( + "documentation/rust-unit1/split-late-map", + "rust-escapes-split", + LANG::Rust, + true, + Operation::MapPieces, + "grow S=n; query final byte, consume one origin and four borrowed pieces, normalize log2(S+1)", + ), ]; impl SourceProbe { @@ -629,6 +723,36 @@ impl SourceProbe { "package p\n{}func F() {{}}", "//go:generate command\n".repeat(size) ), + "rust-mixed" => format!( + "{}fn f() {{ //!inner\n}}", + "/**\u{2003}* a\n * b*/\n#[doc = \"z\"]\n".repeat(size) + ), + "rust-cooked" => format!("#[doc = \"\\n{}b\"] fn f() {{}}", "a\\r\\r\\n".repeat(size)), + "rust-raw" => format!( + "#[doc = r###\"{}b\"###] fn f() {{}}", + "a\\x42\r\n".repeat(size) + ), + "rust-attribute-width" | "rust-attribute-depth" | "rust-attribute-depth-width" => { + let d = if self.key == "rust-attribute-width" { + 0 + } else { + size + }; + let w = if self.key == "rust-attribute-depth" { + 1 + } else { + size + }; + format!( + "{}{}fn f() {{}}{}", + "mod m {".repeat(d), + "#[doc = \"a\"]\n".repeat(w), + "}".repeat(d) + ) + } + "rust-escapes-contiguous" | "rust-escapes-split" => { + format!("#[doc = \"{}\"] fn f() {{}}", "\\x41".repeat(size)) + } _ => { return Err(HarnessError(format!( "unregistered source fixture {}", diff --git a/big-code-analysis-bench/src/documentation/mod.rs b/big-code-analysis-bench/src/documentation/mod.rs index 8c799bb0c..974ec435c 100644 --- a/big-code-analysis-bench/src/documentation/mod.rs +++ b/big-code-analysis-bench/src/documentation/mod.rs @@ -6,6 +6,9 @@ mod fixtures; mod operation; pub mod runner; #[cfg(test)] +mod rust_tests; +mod rust_validation; +#[cfg(test)] mod tests; mod validation; #[cfg(all(test, unix))] diff --git a/big-code-analysis-bench/src/documentation/operation.rs b/big-code-analysis-bench/src/documentation/operation.rs index aa1dec42d..4c1f6fefe 100644 --- a/big-code-analysis-bench/src/documentation/operation.rs +++ b/big-code-analysis-bench/src/documentation/operation.rs @@ -6,7 +6,7 @@ use big_code_analysis::{Ast, Source}; use big_code_analysis_ast::documentation::render_probe::PreparedRender; use big_code_analysis_ast::documentation::{ CompleteText, Content, Document, DocumentationContext, DocumentationIndex, - DocumentationOptions, FactRef, Owner, collect, + DocumentationOptions, FactRef, OriginView, Owner, SourcePiece, collect, }; use big_code_analysis_ast::{LANG, tree_sitter}; @@ -35,7 +35,10 @@ impl Parsed { /// Rejects invalid fixture generation, grammar setup and incomplete parses. pub fn new(probe: &SourceProbe, size: usize) -> Result { let source = probe.source(size)?; - if !matches!(probe.key, "ranges" | "multiline-adjacent-ranges") { + if !matches!( + probe.key, + "ranges" | "multiline-adjacent-ranges" | "rust-escapes-split" + ) { return Ast::parse(Source::new(probe.language, &source)) .map(Self::Ordinary) .map_err(failure); @@ -299,6 +302,7 @@ impl<'i, 's> Prepared<'i, 's> { Operation::Owner | Operation::Retained | Operation::Map + | Operation::MapPieces | Operation::OwnerQualifications | Operation::DocumentQualifications => 1, Operation::Pending => { @@ -321,10 +325,10 @@ impl<'i, 's> Prepared<'i, 's> { let node = self .node .ok_or_else(|| HarnessError("owner node absent".into()))?; - let expected = if self.probe.key == "width" { - (size - 1) * 19 + 9 - } else { - 5 * size + let expected = match self.probe.key { + "width" => (size - 1) * 19 + 9, + "rust-mixed" => 30 * size, + _ => 5 * size, }; require( node.start_byte() == expected, @@ -401,6 +405,12 @@ impl<'i, 's> Prepared<'i, 's> { require(self.text.is_some(), "complete prepared text absent")?; self.execute()?; } + Operation::MapPieces => { + let text = self + .text + .ok_or_else(|| HarnessError("map pieces text absent".into()))?; + super::rust_validation::late_map(text, size, self.parsed.source())?; + } } Ok(()) } @@ -495,6 +505,15 @@ impl<'i, 's> Prepared<'i, 's> { .map_err(failure)?, ); } + Operation::MapPieces => { + let text = black_box( + self.text + .ok_or_else(|| HarnessError("map pieces text absent".into()))?, + ); + consume_map_pieces(text, |piece| { + black_box(piece); + })?; + } } Ok(()) } @@ -511,3 +530,23 @@ impl<'i, 's> Prepared<'i, 's> { self.counts } } + +pub(super) fn consume_map_pieces<'i, 's>( + text: CompleteText<'i, 's>, + mut consume: impl FnMut(&'i SourcePiece<'s>), +) -> Result<(), HarnessError> { + let end = text.text().len(); + require(end > 0, "late map pieces query has no text")?; + for portion in text.origins(black_box(end - 1..end)).map_err(failure)? { + let OriginView::Decoded(pieces) = black_box(portion).origin else { + return Err(HarnessError("late map pieces origin not decoded".into())); + }; + let [a, b, c, d] = pieces else { + return Err(HarnessError("late map requires four pieces".into())); + }; + for piece in [a, b, c, d] { + consume(piece); + } + } + Ok(()) +} diff --git a/big-code-analysis-bench/src/documentation/runner.rs b/big-code-analysis-bench/src/documentation/runner.rs index 1739471c6..72cd206ca 100644 --- a/big-code-analysis-bench/src/documentation/runner.rs +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -916,10 +916,10 @@ mod tests { #[test] fn source_smoke_exercises_every_registered_cell() { let report = run(super::super::REGISTRY, 1, Mode::Smoke).unwrap(); - assert_eq!(report.results.len(), 46); + assert_eq!(report.results.len(), 57); assert_eq!( report.results.iter().map(|r| r.cells.len()).sum::(), - 138 + 171 ); assert!(!report.to_string().contains(" ok")); } diff --git a/big-code-analysis-bench/src/documentation/rust_tests.rs b/big-code-analysis-bench/src/documentation/rust_tests.rs new file mode 100644 index 000000000..1b282fb82 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/rust_tests.rs @@ -0,0 +1,268 @@ +use super::*; +use big_code_analysis_ast::documentation::*; + +#[test] +fn rust_unit1_full_rungs_validate_source_text_maps_and_identity() { + let probes = ®ISTRY[46..]; + assert_eq!(probes.len(), 11); + for probe in probes { + for n in probe.sizes { + let parsed = Parsed::new(probe, n).unwrap(); + let index = parsed.collect(probe).unwrap(); + let prepared = Prepared::new(probe, n, &parsed, &index) + .unwrap_or_else(|error| panic!("{}/{n}: {error}", probe.id)); + let counts = prepared.counts(); + assert_eq!(counts.documents, 1); + assert_eq!(counts.edges, 1); + assert_eq!(counts.qualifications, 0); + } + } +} + +#[test] +fn rust_origin_validator_rejects_wrong_token_with_unchanged_counts_and_text() { + let probe = REGISTRY + .iter() + .find(|p| p.key == "rust-escapes-split") + .unwrap(); + let parsed = Parsed::new(probe, 2).unwrap(); + let index = parsed.collect(probe).unwrap(); + let text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + let expected = [ + (0..1, rust_validation::ExpectedOrigin::Decoded(9..13)), + (1..2, rust_validation::ExpectedOrigin::Decoded(13..17)), + ]; + rust_validation::mappings(text.mappings(), &expected, parsed.source(), true).unwrap(); + let mut corrupted = text.mappings().to_vec(); + corrupted[1].origin = corrupted[0].origin.clone(); + assert_eq!(corrupted.len(), 2); + assert_eq!(text.text(), "AA"); + assert_eq!( + rust_validation::mappings(&corrupted, &expected, parsed.source(), true) + .unwrap_err() + .0, + "Rust responsible piece range/bytes" + ); +} + +#[test] +fn rust_graph_validator_rejects_equal_source_with_foreign_canonical_links() { + let probe = REGISTRY.iter().find(|p| p.key == "rust-mixed").unwrap(); + let parsed = Parsed::new(probe, 2).unwrap(); + let other = Parsed::new(probe, 2).unwrap(); + let index = other.collect(probe).unwrap(); + assert_eq!(parsed.source(), other.source()); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + assert_eq!(index.facts().fragments().len(), 5); + assert_eq!( + rust_validation::validate(probe, 2, &parsed, &index) + .unwrap_err() + .0, + "Rust binding/scope identity" + ); +} + +#[test] +fn rust_split_map_consumes_each_borrowed_piece_in_order() { + let probe = REGISTRY.last().unwrap(); + assert_eq!(probe.id, "documentation/rust-unit1/split-late-map"); + let parsed = Parsed::new(probe, 8).unwrap(); + let index = parsed.collect(probe).unwrap(); + let text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + let Origin::Decoded(expected) = &text.mappings()[7].origin else { + panic!("decoded") + }; + let mut consumed = Vec::new(); + operation::consume_map_pieces(text, |piece| consumed.push(piece)).unwrap(); + assert_eq!(consumed.len(), 4); + for (at, (piece, original)) in consumed.iter().zip(expected.pieces()).enumerate() { + assert!(std::ptr::eq(*piece, original)); + assert_eq!(piece.range(), 37 + at..38 + at); + assert_eq!(piece.bytes(), &b"\\x41"[at..=at]); + } +} + +#[test] +fn rust_work_counters_separate_depth_width_and_piece_axes() { + for n in [32, 64, 128] { + for probe in ®ISTRY[46..54] { + let parsed = Parsed::new(probe, n).unwrap(); + let before = observations(); + let index = parsed.collect(probe).unwrap(); + let after = observations(); + let (attributes, units, copies, projections, pieces, visits) = match probe.key { + // expected: block copies three runs, attribute copies temporary/projected z, + // two joins per unit and one final inner-comment copy. Only z is decoded/projected. + "rust-mixed" => (n, n, 7 * n + 1, n, 0, 4 * n + 1), + // expected: decode LF + n*(a, CR, CR, LF) + b; temporary 4n+2 appends, + // final 2n+1 appends. Projection crosses 4n+2 maps plus 2n lookaheads. + // Only the n retained LF tokens copy responsible pieces. + "rust-cooked" => (1, 4 * n + 2, 6 * n + 3, 6 * n + 2, n, 4 * n + 2), + // expected: raw unit has five ordinary bytes and one physical CRLF token; + // both passes append 2n+1 runs, projection adds 2n lookaheads. + "rust-raw" => (1, 6 * n + 1, 4 * n + 2, 4 * n + 1, n, 2 * n + 1), + "rust-attribute-width" | "rust-attribute-depth" | "rust-attribute-depth-width" => { + let w = if probe.key == "rust-attribute-depth" { + 1 + } else { + n + }; + // expected: one decode and projection per a; two copies and w-1 joins. + (w, w, 3 * w - 1, w, 0, w) + } + "rust-escapes-contiguous" | "rust-escapes-split" => { + let split = probe.key == "rust-escapes-split"; + // expected: n token appends plus one projected line; split cursor visits + // nine prefix pieces and four responsible bytes plus lookahead per token. + ( + 1, + n, + n + 1, + n, + if split { 4 * n } else { n }, + if split { 9 + 5 * n } else { n }, + ) + } + _ => unreachable!(), + }; + assert_eq!( + after.carrier_children - before.carrier_children, + 3 * attributes, + "{}", + probe.id + ); + assert_eq!( + after.attribute_children - before.attribute_children, + 3 * attributes, + "{}", + probe.id + ); + assert_eq!( + after.decoded_units - before.decoded_units, + units, + "{}", + probe.id + ); + assert_eq!( + after.copy_chunks - before.copy_chunks, + copies, + "{}", + probe.id + ); + assert_eq!( + after.projection_visits - before.projection_visits, + projections, + "{}", + probe.id + ); + assert_eq!( + after.piece_copies - before.piece_copies, + pieces, + "{}", + probe.id + ); + assert_eq!( + after.fragment_piece_visits - before.fragment_piece_visits, + visits, + "{}", + probe.id + ); + assert_eq!(after.renders - before.renders, 1, "{}", probe.id); + assert_eq!(index.documents().len(), 1); + } + } +} + +#[test] +fn rust_registry_has_exact_operations_classes_and_ladders() { + use fixtures::Operation::*; + let expected = [ + ("mixed-fragments", Collect, [256, 512, 1024]), + ("cooked-large", Collect, [4096, 8192, 16384]), + ("raw-large", Collect, [4096, 8192, 16384]), + ("attribute-width", Collect, [256, 512, 1024]), + ("attribute-depth", Collect, [256, 512, 1024]), + ("attribute-depth-width", Collect, [256, 512, 1024]), + ("escapes-contiguous", Collect, [1024, 2048, 4096]), + ("escapes-split", Collect, [1024, 2048, 4096]), + ("mixed-retained", Retained, [256, 512, 1024]), + ("mixed-owner", Owner, [256, 512, 1024]), + ("split-late-map", MapPieces, [1024, 2048, 4096]), + ]; + assert_eq!(REGISTRY.len(), 57); + for (probe, (id, operation, sizes)) in REGISTRY[46..].iter().zip(expected) { + assert_eq!(probe.id, format!("documentation/rust-unit1/{id}")); + assert_eq!(probe.operation, operation); + assert_eq!(probe.sizes, sizes); + assert_eq!(probe.bound, 1.50); + assert_eq!( + probe.class, + match operation { + Collect => StatisticClass::Exponent, + MapPieces => StatisticClass::LogMapRatio, + _ => StatisticClass::FixedOutputRatio, + } + ); + } + for (class, expected) in [ + (StatisticClass::Exponent, 47), + (StatisticClass::FixedOutputRatio, 8), + (StatisticClass::LogMapRatio, 2), + ] { + assert_eq!( + REGISTRY.iter().filter(|p| p.class == class).count(), + expected + ); + } +} + +#[test] +fn infrastructure_registry_preserves_every_original_cell_and_policy() { + use sha2::{Digest, Sha256}; + use std::fmt::Write; + let mut manifest = String::new(); + for p in ®ISTRY[..46] { + for n in p.sizes { + let source = p.source(n).unwrap(); + let options = p.options(); + writeln!( + manifest, + "{}\t{}\t{:?}\t{:?}\t{:?}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{:?}\t{}\t{:?}", + p.id, + n, + p.language, + p.class, + p.operation, + p.bound, + options.retain_unbound, + options.retain_directives, + p.dimensions, + p.timing, + p.key, + p.policy, + options.profile, + p.evidence, + source + ) + .unwrap(); + } + } + // Frozen by executing fixtures.rs from infrastructure I=3924d45adf9716ec5d64381849b671b298b8b5fe. + // Includes all 138 source buffers and each original operation/options/policy field in order. + assert_eq!( + Sha256::digest(manifest.as_bytes()) + .iter() + .fold(String::new(), |mut hex, byte| { + write!(hex, "{byte:02x}").unwrap(); + hex + }), + "38a4c530ebb06529770d4ef42aba41eee97dfe4251db1fddebe22d6331b15a8d" + ); +} diff --git a/big-code-analysis-bench/src/documentation/rust_validation.rs b/big-code-analysis-bench/src/documentation/rust_validation.rs new file mode 100644 index 000000000..680871439 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/rust_validation.rs @@ -0,0 +1,557 @@ +//! Source-derived Rust literal, mixed-cleanup and attachment oracles. + +use std::collections::HashMap; +use std::ops::Range; + +use big_code_analysis_ast::documentation::{ + AssessmentAxis, CompleteText, Composition, DocumentRole, DocumentationIndex, FragmentForm, + Mapping, Origin, OriginView, Owner, Publication, Resolution, SourcePiece, SourcePieces, +}; +use big_code_analysis_ast::tree_sitter::{Node, Point}; + +use super::{HarnessError, Parsed, SourceProbe, failure, require}; + +#[derive(Debug)] +pub(super) enum ExpectedOrigin { + Copied(Range), + Decoded(Range), + Synthetic, +} + +struct Expected { + source: Vec, + text: String, + maps: Vec<(Range, ExpectedOrigin)>, + fragments: Vec<(Range, FragmentForm)>, + function: Range, + depth: usize, + split: bool, +} + +impl Expected { + #[allow(clippy::too_many_lines)] // Keep each independent source family's bytes and map formulas together. + fn new(key: &str, n: usize) -> Result { + let mut expected = Self { + source: Vec::new(), + text: String::new(), + maps: Vec::new(), + fragments: Vec::new(), + function: 0..0, + depth: 0, + split: key == "rust-escapes-split", + }; + match key { + "rust-mixed" => { + for _ in 0..n { + expected + .source + .extend_from_slice(b"/**\xe2\x80\x83* a\n * b*/\n#[doc = \"z\"]\n"); + } + expected.source.extend_from_slice(b"fn f() { //!inner\n}"); + expected.text = format!("{}inner", "\u{2003}* a\n * b\nz\n".repeat(n)); + for i in 0..n { + let s = 30 * i; + let o = 14 * i; + expected.fragments.extend([ + (s..s + 16, FragmentForm::Comment), + (s + 17..s + 29, FragmentForm::Attribute), + ]); + expected.maps.extend([ + (o..o + 6, ExpectedOrigin::Copied(s + 3..s + 9)), + (o + 6..o + 7, ExpectedOrigin::Copied(s + 9..s + 10)), + (o + 7..o + 11, ExpectedOrigin::Copied(s + 10..s + 14)), + (o + 11..o + 12, ExpectedOrigin::Synthetic), + (o + 12..o + 13, ExpectedOrigin::Copied(s + 26..s + 27)), + (o + 13..o + 14, ExpectedOrigin::Synthetic), + ]); + } + expected + .fragments + .push((30 * n + 9..30 * n + 17, FragmentForm::Comment)); + expected.maps.push(( + 14 * n..14 * n + 5, + ExpectedOrigin::Copied(30 * n + 12..30 * n + 17), + )); + expected.function = 30 * n..30 * n + 19; + } + "rust-cooked" | "rust-raw" => { + let raw = key == "rust-raw"; + expected.source.extend_from_slice(if raw { + b"#[doc = r###\"" + } else { + b"#[doc = \"\\n" + }); + for _ in 0..n { + expected.source.extend_from_slice(if raw { + b"a\\x42\r\n" + } else { + b"a\\r\\r\\n" + }); + } + expected.source.extend_from_slice(if raw { + b"b\"###] fn f() {}" + } else { + b"b\"] fn f() {}" + }); + let (s, width, end) = if raw { (13, 6, 19) } else { (11, 2, 14) }; + expected.text = format!("{}b", if raw { "a\\x42\n" } else { "a\n" }.repeat(n)); + expected + .fragments + .push((0..7 * n + end, FragmentForm::Attribute)); + for i in 0..n { + expected.maps.push(( + width * i..width * i + width - 1, + ExpectedOrigin::Copied(s + 7 * i..s + 7 * i + width - 1), + )); + expected.maps.push(( + width * i + width - 1..width * (i + 1), + ExpectedOrigin::Decoded(s + 7 * i + 5..s + 7 * i + 7), + )); + } + expected.maps.push(( + width * n..width * n + 1, + ExpectedOrigin::Copied(s + 7 * n..s + 7 * n + 1), + )); + expected.function = 7 * n + end + 1..7 * n + end + 10; + } + "rust-attribute-width" | "rust-attribute-depth" | "rust-attribute-depth-width" => { + let d = if key == "rust-attribute-width" { 0 } else { n }; + let w = if key == "rust-attribute-depth" { 1 } else { n }; + expected.depth = d; + for _ in 0..d { + expected.source.extend_from_slice(b"mod m {"); + } + for _ in 0..w { + expected.source.extend_from_slice(b"#[doc = \"a\"]\n"); + } + expected.source.extend_from_slice(b"fn f() {}"); + expected.source.extend(std::iter::repeat_n(b'}', d)); + expected.text = std::iter::repeat_n("a", w).collect::>().join("\n"); + for j in 0..w { + let s = 7 * d + 13 * j; + expected + .fragments + .push((s..s + 12, FragmentForm::Attribute)); + expected + .maps + .push((2 * j..2 * j + 1, ExpectedOrigin::Copied(s + 9..s + 10))); + if j + 1 < w { + expected + .maps + .push((2 * j + 1..2 * j + 2, ExpectedOrigin::Synthetic)); + } + } + expected.function = 7 * d + 13 * w..7 * d + 13 * w + 9; + } + "rust-escapes-contiguous" | "rust-escapes-split" => { + expected.source.extend_from_slice(b"#[doc = \""); + for _ in 0..n { + expected.source.extend_from_slice(b"\\x41"); + } + expected.source.extend_from_slice(b"\"] fn f() {}"); + expected.text = "A".repeat(n); + expected + .fragments + .push((0..11 + 4 * n, FragmentForm::Attribute)); + expected.maps = (0..n) + .map(|i| (i..i + 1, ExpectedOrigin::Decoded(9 + 4 * i..13 + 4 * i))) + .collect(); + expected.function = 12 + 4 * n..21 + 4 * n; + } + _ => return Err(HarnessError(format!("unregistered Rust oracle {key}"))), + } + Ok(expected) + } +} + +fn pieces( + actual: &SourcePieces<'_>, + range: Range, + source: &[u8], + split: bool, +) -> Result<(), HarnessError> { + require(!actual.has_excluded_gap(), "Rust unexpected excluded gap")?; + piece_slice(actual.pieces(), range, source, split) +} + +fn piece_slice( + actual: &[SourcePiece<'_>], + range: Range, + source: &[u8], + split: bool, +) -> Result<(), HarnessError> { + let count = if split { range.len() } else { 1 }; + require(actual.len() == count, "Rust responsible piece count")?; + for (i, piece) in actual.iter().enumerate() { + let span = if split { + range.start + i..range.start + i + 1 + } else { + range.clone() + }; + require( + piece.range() == span && piece.bytes() == &source[span], + "Rust responsible piece range/bytes", + )?; + } + Ok(()) +} + +pub(super) fn mappings( + actual: &[Mapping<'_>], + expected: &[(Range, ExpectedOrigin)], + source: &[u8], + split: bool, +) -> Result<(), HarnessError> { + require(actual.len() == expected.len(), "Rust full map count")?; + for (actual, (output, origin)) in actual.iter().zip(expected) { + require(actual.output.range() == *output, "Rust map output range")?; + match (&actual.origin, origin) { + (Origin::Copied(actual), ExpectedOrigin::Copied(range)) + | (Origin::Decoded(actual), ExpectedOrigin::Decoded(range)) => { + pieces(actual, range.clone(), source, split)?; + } + (Origin::Synthetic, ExpectedOrigin::Synthetic) => {} + _ => return Err(HarnessError("Rust map transformation".into())), + } + } + Ok(()) +} + +pub(super) fn late_map( + text: CompleteText<'_, '_>, + n: usize, + source: &[u8], +) -> Result<(), HarnessError> { + let mut portions = text.origins(n - 1..n).map_err(failure)?; + let portion = portions + .next() + .ok_or_else(|| HarnessError("Rust late map absent".into()))?; + require( + portion.output == (n - 1..n) && portions.next().is_none(), + "Rust late map K/output", + )?; + let OriginView::Decoded(actual) = portion.origin else { + return Err(HarnessError("Rust late map transformation".into())); + }; + piece_slice(actual, 9 + 4 * (n - 1)..13 + 4 * (n - 1), source, true) +} + +type Nodes<'s> = HashMap<(&'static str, usize, usize), Node<'s>>; + +fn node_at<'s>( + nodes: &Nodes<'s>, + kind: &'static str, + range: Range, +) -> Result, HarnessError> { + nodes + .get(&(kind, range.start, range.end)) + .copied() + .ok_or_else(|| HarnessError(format!("Rust canonical {kind} at {range:?} absent"))) +} + +fn shape<'s>(parsed: &'s Parsed, expected: &Expected) -> Result, HarnessError> { + let walk = parsed.nodes(); + require( + walk.iter() + .all(|(node, _)| !node.has_error() && !node.is_missing()), + "Rust clean supplied tree", + )?; + require( + walk.iter() + .filter(|(node, _)| node.kind() == "mod_item") + .count() + == expected.depth, + "Rust module depth", + )?; + require( + walk.iter() + .filter(|(node, _)| node.kind() == "function_item") + .count() + == 1, + "Rust function count", + )?; + let attributes = expected + .fragments + .iter() + .filter(|(_, form)| *form == FragmentForm::Attribute) + .count(); + require( + walk.iter() + .filter(|(node, _)| node.kind() == "attribute_item") + .count() + == attributes, + "Rust attribute width", + )?; + require( + walk.iter() + .filter(|(node, _)| matches!(node.kind(), "string_literal" | "raw_string_literal")) + .count() + == attributes, + "Rust clean literal carriers", + )?; + let mut points = vec![Point::new(0, 0)]; + for byte in parsed.source() { + let mut point = *points + .last() + .ok_or_else(|| HarnessError("Rust source point absent".into()))?; + if *byte == b'\n' { + point.row += 1; + point.column = 0; + } else { + point.column += 1; + } + points.push(point); + } + for (node, _) in &walk { + require( + node.start_position() == points[node.start_byte()] + && node.end_position() == points[node.end_byte()], + "Rust canonical byte/point coordinates", + )?; + } + let ranges = parsed.tree().included_ranges(); + require( + ranges.len() + == if expected.split { + parsed.source().len() + } else { + 1 + }, + "Rust included range count", + )?; + if expected.split { + for (at, range) in ranges.iter().enumerate() { + require( + range.start_byte == at + && range.end_byte == at + 1 + && range.start_point == points[at] + && range.end_point == points[at + 1], + "Rust bytewise included coordinates", + )?; + } + } + Ok(walk + .into_iter() + .map(|(node, _)| ((node.kind(), node.start_byte(), node.end_byte()), node)) + .collect()) +} + +#[allow(clippy::too_many_lines)] // Check the complete document/association/owner graph and canonical navigation together. +fn graph( + index: &DocumentationIndex<'_>, + expected: &Expected, + nodes: &Nodes<'_>, + root: Node<'_>, +) -> Result<(), HarnessError> { + require( + index.documents().len() == 1 && index.associations().len() == 1, + "Rust D/A count", + )?; + require( + index.qualifications().len() == 0 && index.evidence().len() == 0, + "Rust unexpected qualification or evidence", + )?; + let doc = index + .documents() + .next() + .ok_or_else(|| HarnessError("Rust document absent".into()))?; + require( + doc.get().role() == DocumentRole::Primary + && doc.get().composition() == Composition::AttributeSequence, + "Rust role/composition", + )?; + let association = index + .associations() + .next() + .ok_or_else(|| HarnessError("Rust association absent".into()))?; + require( + index + .facts() + .associated_document(association) + .map_err(failure)? + == doc, + "Rust association document identity", + )?; + let function = node_at(nodes, "function_item", expected.function.clone())?; + let scope = if expected.depth == 0 { + root + } else { + node_at( + nodes, + "declaration_list", + 7 * expected.depth - 1..expected.function.end + 1, + )? + }; + let fact = association.get(); + require( + fact.resolution == Resolution::Resolved + && fact.publication == Publication::Unknown + && fact.convention.name() == "Rust" + && fact.owner_count() == 1, + "Rust association disposition", + )?; + require( + fact.binding.is_some_and(|node| node.node() == function) + && fact.lexical_scope.node() == scope, + "Rust binding/scope identity", + )?; + let owner = index + .facts() + .associated_owner(association, 0) + .map_err(failure)?; + require( + matches!(owner.get(), Owner::Node(node) if node.node() == function), + "Rust canonical function owner", + )?; + publication(index, expected, nodes)?; + require( + index.facts().owners().len() == expected.depth + 2, + "Rust complete owner inventory", + )?; + let mut owners = index.facts().owners(); + require( + owners + .next() + .is_some_and(|owner| matches!(owner.get(), Owner::File(node) if node.node() == root)), + "Rust file owner identity", + )?; + for depth in 0..expected.depth { + let module = node_at(nodes, "mod_item", 7 * depth..expected.source.len() - depth)?; + require( + owners.next().is_some_and( + |owner| matches!(owner.get(), Owner::Node(node) if node.node() == module), + ), + "Rust module owner identity", + )?; + } + require( + owners.next() == Some(owner) && owners.next().is_none(), + "Rust function owner inventory identity", + )?; + let query = index.node_associations(function).map_err(failure)?; + require( + !query.projection_pending() + && query.associations().collect::>() == [association] + && query.assessments().collect::>() == index.assessments().collect::>() + && query.qualifications().len() == 0, + "Rust canonical query links", + )?; + require( + index + .owner_associations(owner) + .map_err(failure)? + .associations() + .collect::>() + == [association], + "Rust owner adjacency", + )?; + Ok(()) +} + +fn publication( + index: &DocumentationIndex<'_>, + expected: &Expected, + nodes: &Nodes<'_>, +) -> Result<(), HarnessError> { + let attributes = expected + .fragments + .iter() + .filter(|(_, form)| *form == FragmentForm::Attribute); + require( + index.assessments().len() == attributes.clone().count(), + "Rust publication assessment count", + )?; + for (assessment, (range, _)) in index.assessments().zip(attributes) { + let node = node_at(nodes, "attribute_item", range.clone())?; + require( + assessment.get().axis == AssessmentAxis::Publication + && assessment.get().reason + == "Rust documentation/publication metadata awaits interpretation" + && assessment.get().node.is_some_and(|e| e.node() == node) + && index + .assessed_document(assessment) + .map_err(failure)? + .is_none(), + "Rust publication assessment identity", + )?; + } + Ok(()) +} + +pub(super) fn validate( + probe: &SourceProbe, + n: usize, + parsed: &Parsed, + index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + let expected = Expected::new(probe.key, n)?; + require( + parsed.source() == expected.source && index.source() == parsed.source(), + "Rust exact supplied source", + )?; + let nodes = shape(parsed, &expected)?; + graph(index, &expected, &nodes, parsed.tree().root_node())?; + let doc = index + .documents() + .next() + .ok_or_else(|| HarnessError("Rust document absent".into()))?; + require( + doc.get().fragment_count() == expected.fragments.len() + && index.facts().fragments().len() == expected.fragments.len(), + "Rust raw fragment count", + )?; + let retained: HashMap<_, _> = index + .facts() + .fragments() + .map(|f| (f.get().node().map(|n| n.node().id()), f)) + .collect(); + require( + retained.len() == expected.fragments.len(), + "Rust unique fragment nodes", + )?; + for (at, (range, form)) in expected.fragments.iter().enumerate() { + let fragment_ref = index.facts().document_fragment(doc, at).map_err(failure)?; + require( + retained.get(&fragment_ref.get().node().map(|n| n.node().id())) == Some(&fragment_ref), + "Rust ordered fragment identity", + )?; + let fragment = fragment_ref.get(); + require(fragment.form() == *form, "Rust raw fragment form")?; + pieces( + fragment.source(), + range.clone(), + parsed.source(), + expected.split, + )?; + let kind = if *form == FragmentForm::Attribute { + "attribute_item" + } else if parsed.source()[range.start..].starts_with(b"/**") { + "block_comment" + } else { + "line_comment" + }; + let node = fragment + .node() + .ok_or_else(|| HarnessError("Rust fragment node absent".into()))? + .node(); + require( + node == node_at( + &nodes, + kind, + range.start..range.end + usize::from(kind == "line_comment"), + )?, + "Rust raw canonical fragment node", + )?; + } + let text = index + .complete_text(doc) + .map_err(failure)? + .ok_or_else(|| HarnessError("Rust complete text absent".into()))?; + require(text.text() == expected.text, "Rust complete text bytes")?; + mappings( + text.mappings(), + &expected.maps, + parsed.source(), + expected.split, + ) +} diff --git a/big-code-analysis-bench/src/documentation/tests.rs b/big-code-analysis-bench/src/documentation/tests.rs index 5b723d9b6..4674da41a 100644 --- a/big-code-analysis-bench/src/documentation/tests.rs +++ b/big-code-analysis-bench/src/documentation/tests.rs @@ -113,7 +113,7 @@ fn original_registry_ids_sizes_and_options_are_preserved() { assert_eq!(options.profile, Profile::Default); assert!(!options.retain_unbound && !options.retain_directives); } - assert_eq!(REGISTRY.len() - 31, 15); + assert_eq!(REGISTRY.len() - 31, 26); } #[test] @@ -182,6 +182,7 @@ fn declared_growth_axes_match_full_size_input_and_output_counts() { } #[test] +#[allow(clippy::too_many_lines)] // One exact work contract per prepared operation. fn prepared_query_counters_charge_only_declared_output() { use fixtures::Operation; for size in [32, 64, 128] { @@ -200,6 +201,31 @@ fn prepared_query_counters_charge_only_declared_output() { assert_eq!(after.renders - before.renders, 0, "{}", probe.id); assert_eq!(after.copy_chunks - before.copy_chunks, 0, "{}", probe.id); assert_eq!(after.visits - before.visits, 0, "{}", probe.id); + assert_eq!( + after.carrier_children - before.carrier_children, + 0, + "{}", + probe.id + ); + assert_eq!( + after.attribute_children - before.attribute_children, + 0, + "{}", + probe.id + ); + assert_eq!( + after.decoded_units - before.decoded_units, + 0, + "{}", + probe.id + ); + assert_eq!(after.piece_copies - before.piece_copies, 0, "{}", probe.id); + assert_eq!( + after.projection_visits - before.projection_visits, + 0, + "{}", + probe.id + ); assert_eq!(after.memo_probes - before.memo_probes, 0, "{}", probe.id); assert_eq!( after.fold_slot_probes - before.fold_slot_probes, @@ -251,6 +277,14 @@ fn prepared_query_counters_charge_only_declared_output() { (2 * size - 1).ilog2() as usize + 2 ); } + Operation::MapPieces => { + assert_eq!(after.map_runs_visited - before.map_runs_visited, 1); + // expected: partition_point on S=n (power of two) makes log2(n)+1 comparisons. + assert_eq!( + after.map_searches - before.map_searches, + size.ilog2() as usize + 1 + ); + } Operation::Retained => { assert_eq!(after.association_reads - before.association_reads, 0); assert_eq!(after.map_runs_visited - before.map_runs_visited, 0); diff --git a/big-code-analysis-bench/src/documentation/validation.rs b/big-code-analysis-bench/src/documentation/validation.rs index c709f74e4..bec8f6b1f 100644 --- a/big-code-analysis-bench/src/documentation/validation.rs +++ b/big-code-analysis-bench/src/documentation/validation.rs @@ -69,6 +69,9 @@ pub(super) fn fixture( parsed: &Parsed, index: &DocumentationIndex<'_>, ) -> Result<(), HarnessError> { + if probe.key.starts_with("rust-") { + return super::rust_validation::validate(probe, size, parsed, index); + } if matches!( probe.key, "depth" diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 72236759d..80ec4e516 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -162,6 +162,18 @@ including empty text. Cancellation, source errors and unsupported preparation re Counter controls distinguish a fresh render from retained access and shared text from per-owner copies. +The Rust literal ladders use cold collection for decoding and mixed comment/attribute cleanup. +`rust_validation.rs` checks every raw fragment, ordered output mapping and canonical attachment +against source-derived formulas before timing. Attribute depth and width vary independently; +the diagonal grows both without multiplying their source size. The split-escape fixture uses +adjacent bytewise included ranges and retains every responsible escape byte. + +The `split-late-map` operation consumes its final decoded origin and each of its four borrowed +pieces. The earlier late-map operation retains its original boundary: it consumes the portion +without iterating token pieces. These are separate registry operations. Counter tests distinguish +decoder iterations, cleanup projections, responsible-piece copies and append chunks; zero primary +visits alone does not imply zero lookup, copy or instrumentation cost. + The benchmark library enables `test-support` on its ordinary AST dependency. [Cargo feature unification](https://doc.rust-lang.org/cargo/reference/features.html#feature-unification) therefore also enables it for other workspace consumers in the same build. Production diff --git a/docs/development/fuzzing.md b/docs/development/fuzzing.md index 6535a46c3..174c8946b 100644 --- a/docs/development/fuzzing.md +++ b/docs/development/fuzzing.md @@ -58,6 +58,17 @@ Both run targets take `FUZZ_RUNS` (default 100 000) and `FUZZ_TIMEOUT` when nightly or `cargo-fuzz` is absent, so a stable-only checkout is not blocked. +For a controlled run, `FUZZ_CORPUS` selects the read-only corpus root, with one subdirectory per +target. `FUZZ_WORK` selects the writable root. Both `fuzz-run` and `fuzz-replay` pass the writable +directory first. `FUZZ_ARGS` adds shell-quoted libFuzzer arguments after `--`; quote an argument +containing spaces within that value. Recipe-owned `-runs` and `-timeout` arguments come last. +Record the expanded argument list, including duplicate flags, when verifying a campaign's limits. + +The recipes can skip with exit 0 when tools are absent. Qualification controllers must also require +the actual target binary and final `stat::number_of_executed_units` output. A bounded randomized +run must execute its requested unit count; a replay must execute its complete seed inventory. +Missing completion evidence is an incomplete stage. + **Bound runs with `-runs`, never `-max_total_time`.** A wall-clock bound makes a failure non-reproducible across machines of different speeds: the same command finds a crash on one host and not on another, and diff --git a/fuzz/corpus/documentation/rust-literal-raw-crlf-pieces b/fuzz/corpus/documentation/rust-literal-raw-crlf-pieces new file mode 100644 index 0000000000000000000000000000000000000000..82c8026128ca387e7405ad203294195c947d4baf GIT binary patch literal 29 kcmZQzXHbq#$xl|WRVY$Q<{9 literal 0 HcmV?d00001 diff --git a/fuzz/corpus/documentation/rust-literal-value-gap b/fuzz/corpus/documentation/rust-literal-value-gap new file mode 100644 index 0000000000000000000000000000000000000000..c35f9e691c5693346169eab35a171af428693f9b GIT binary patch literal 27 icmZQzXHbq#$xl|WRZvP~NK%SbNXt`5)6i6?t_1*3s0M%l literal 0 HcmV?d00001 diff --git a/fuzz/documentation-seeds.json b/fuzz/documentation-seeds.json index 1d988de05..713420a62 100644 --- a/fuzz/documentation-seeds.json +++ b/fuzz/documentation-seeds.json @@ -388,6 +388,32 @@ "fixture": "rust-attribute.rs", "has_error": false }, + { + "name": "rust-literal-value-gap", + "header": [ + 0, + 7, + 0 + ], + "sha256": "4710f3fe76c114469c63024cfdba4b88386261e3e7b6fe0e1770309b96a54ca0", + "class": "rust-literal-value-gap", + "provenance": "big-code-analysis-ast/src/documentation/collector/rust_tests.rs::rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes", + "has_error": false, + "raw_sha256": "a85aa5ccd0dc2e9b6601a91bb454df2e4711749fe6721abb98315e15c9b72387" + }, + { + "name": "rust-literal-raw-crlf-pieces", + "header": [ + 0, + 7, + 0 + ], + "sha256": "1577f0caec27c23e67c1d35a172c31e20c05fe4973cf1e1b042b293ef05f9e56", + "class": "rust-literal-raw-crlf-pieces", + "provenance": "big-code-analysis-ast/src/documentation/text/rust/literal.rs physical CRLF normalization across included pieces", + "has_error": false, + "raw_sha256": "39a14034283ed3c33f0b77cd7d98c219bf8f2992b5ed78fdbc2c03915467a042" + }, { "name": "rust-outer-binding", "header": [ diff --git a/fuzz/generate_documentation_seeds.py b/fuzz/generate_documentation_seeds.py index 9a42bdf65..ec55edbcb 100644 --- a/fuzz/generate_documentation_seeds.py +++ b/fuzz/generate_documentation_seeds.py @@ -101,6 +101,8 @@ def add(name, header, payload, assertion, provenance, **expected): ) cases = [ + ("rust-literal-value-gap", [0, 7, 0], b'#[doc = "a\x00b"] fn f() {}', "rust-literal-value-gap", "rust_tests.rs::rust_literal_excluded_path_stays_scope_only_and_value_gap_contributes", False), + ("rust-literal-raw-crlf-pieces", [0, 7, 0], b'#[doc = r"a\r\nb"] fn f() {}', "rust-literal-raw-crlf-pieces", "text/rust/literal.rs physical CRLF normalization across included pieces", False), ("rust-outer-binding", [0, 3, 0], b'#[doc = "outer"]\nfn f() { //! inner\n}', "rust-outer-binding", "rust_remediation_tests.rs::outer_attribute_merges_binding_into_inner_comment_document", False), ("rust-pending-inner-binding", [0, 3, 0], b'#[doc(hidden)]\nfn f() { //! inner\n}', "rust-pending-inner-binding", "rust_remediation_tests.rs::outer_metadata_keeps_binding_on_pending_composition", False), ("rust-second-lines-cr", [0, 3, 0], b'#[doc = "\\na\\r\\r\\nb"] fn f() {}', "rust-second-lines-cr", "rust_remediation_tests.rs::changed_beautification_reinterprets_one_cr_before_terminal_empty", False), @@ -315,7 +317,10 @@ def add(name, header, payload, assertion, provenance, **expected): ), ] for name, header, payload, assertion, provenance, has_error in cases: - add(name, header, payload, assertion, provenance, has_error=has_error) + extra = {} + if name in {"rust-literal-value-gap", "rust-literal-raw-crlf-pieces"}: + extra["raw_sha256"] = hashlib.sha256(bytes(header) + payload).hexdigest() + add(name, header, payload, assertion, provenance, has_error=has_error, **extra) corpus = ROOT / "corpus/documentation" corpus.mkdir(parents=True, exist_ok=True) diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index 196e1baf5..e488bb649 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -107,6 +107,15 @@ fn registry_executes_every_dispatch_and_edge_assertion() { .map(|value| u8::try_from(number(value)).unwrap()) .collect(); assert_eq!(&bytes[..3], header); + if let Some(expected) = seed["raw_sha256"].as_str() { + let actual = Sha256::digest(&bytes) + .iter() + .fold(String::new(), |mut hex, byte| { + write!(hex, "{byte:02x}").unwrap(); + hex + }); + assert_eq!(actual, expected); + } assert_eq!( Sha256::digest(&bytes[3..]) .iter() @@ -201,6 +210,210 @@ fn registry_executes_every_dispatch_and_edge_assertion() { .map(|entry| entry.unwrap().file_name().into_string().unwrap()) .collect(); assert_eq!(actual, names); + assert_eq!(registry.len(), 67); + assert_eq!( + registry + .iter() + .filter(|seed| seed["header"][0] == 0) + .count(), + 26 + ); +} + +#[allow(clippy::too_many_lines)] // Exact included-tree, raw-fragment, owner and token oracle for the two registered seeds. +fn rust_included_literal_seed( + class: &str, + index: &DocumentationIndex<'_>, + tree: &tree_sitter::Tree, +) { + let gap = class == "rust-literal-value-gap"; + let source: &[u8] = if gap { + b"#[doc = \"a\0b\"] fn f() {}" + } else { + b"#[doc = r\"a\r\nb\"] fn f() {}" + }; + assert_eq!(index.source(), source); + let mut point = tree_sitter::Point::new(0, 0); + let mut expected_ranges = Vec::new(); + for (at, byte) in source.iter().enumerate() { + let start_point = point; + if *byte == b'\n' { + point.row += 1; + point.column = 0; + } else { + point.column += 1; + } + if *byte != 0 { + expected_ranges.push(tree_sitter::Range { + start_byte: at, + end_byte: at + 1, + start_point, + end_point: point, + }); + } + } + assert_eq!(tree.included_ranges(), expected_ranges); + let canonical = nodes(tree); + assert!( + canonical + .iter() + .all(|node| !node.has_error() && !node.is_missing()) + ); + let function = canonical + .iter() + .find(|node| node.kind() == "function_item") + .unwrap(); + let attribute = canonical + .iter() + .find(|node| node.kind() == "attribute_item") + .unwrap(); + let end = if gap { 14 } else { 16 }; + assert_eq!(attribute.byte_range(), 0..end); + assert_eq!(function.byte_range(), end + 1..end + 10); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!(document.get().fragment_count(), 1); + assert_eq!(document.get().role(), DocumentRole::Primary); + assert_eq!(document.get().composition(), Composition::AttributeSequence); + let fragment = index.facts().document_fragment(document, 0).unwrap(); + assert_eq!(fragment.get().form(), FragmentForm::Attribute); + assert_eq!(fragment.get().node().unwrap().node(), *attribute); + assert_eq!(fragment.get().source().has_excluded_gap(), gap); + let spans: Vec<_> = (0..end) + .filter(|at| !gap || *at != 10) + .map(|at| at..at + 1) + .collect(); + assert_eq!( + fragment + .get() + .source() + .pieces() + .iter() + .map(SourcePiece::range) + .collect::>(), + spans + ); + for piece in fragment.get().source().pieces() { + assert_eq!(piece.bytes(), &source[piece.range()]); + } + let association = index.associations().next().unwrap(); + assert_eq!( + index.facts().associated_document(association).unwrap(), + document + ); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().publication, Publication::Unknown); + assert_eq!(association.get().binding.unwrap().node(), *function); + assert_eq!(association.get().lexical_scope.node(), tree.root_node()); + assert_eq!(association.get().owner_count(), 1); + let owner = index.facts().associated_owner(association, 0).unwrap(); + assert!(matches!(owner.get(), Owner::Node(node) if node.node() == *function)); + assert_eq!( + index + .node_associations(*function) + .unwrap() + .associations() + .collect::>(), + [association] + ); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .collect::>(), + [association] + ); + if gap { + let value = canonical + .iter() + .find(|node| node.kind() == "string_literal") + .unwrap(); + assert_eq!(value.byte_range(), 8..13); + assert!( + canonical + .iter() + .any(|node| node.kind() == "identifier" && node.byte_range() == (2..5)) + ); + assert!(matches!( + document.get().content(), + Content::Unavailable(UnavailableReason::ExcludedGap) + )); + assert!(index.complete_text(document).unwrap().is_none()); + } else { + let complete = text(index); + assert_eq!(complete.text(), "a\nb"); + let portions: Vec<_> = complete.origins(0..3).unwrap().collect(); + assert_eq!(complete.mappings().len(), 3); + assert_eq!(portions.len(), 3); + for (at, portion) in portions.iter().enumerate() { + assert_eq!(portion.output, at..at + 1); + } + for (at, span) in [(0, 10..11), (2, 13..14)] { + let OriginView::Copied(piece) = &portions[at].origin else { + panic!("copied") + }; + assert_eq!(piece.range(), span.clone()); + assert_eq!(piece.bytes(), &source[span]); + } + let OriginView::Decoded(pieces) = &portions[1].origin else { + panic!("physical CRLF") + }; + assert_eq!( + pieces.iter().map(SourcePiece::range).collect::>(), + [11..12, 12..13] + ); + assert_eq!( + pieces.iter().map(SourcePiece::bytes).collect::>(), + [b"\r", b"\n"] + ); + } +} + +#[test] +fn unit1_additions_preserve_every_previous_tagged_and_raw_rust_seed() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")); + for (directory, count, expected) in [ + ( + "documentation", + 65, + "e0b4b8f37651094400115a6e7a3a7b0fe36d6f772c81c9394897d19995ede301", + ), + ( + "parse_rust", + 12, + "9467333cd232ce99f65f924cc4a9e6c66b859d49ecc2f208e03dffe1f0212fba", + ), + ] { + let mut paths: Vec<_> = std::fs::read_dir(root.join("corpus").join(directory)) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| { + !matches!( + path.file_name().unwrap().to_str().unwrap(), + "rust-literal-value-gap" | "rust-literal-raw-crlf-pieces" + ) + }) + .collect(); + paths.sort(); + assert_eq!(paths.len(), count); + let mut hash = Sha256::new(); + for path in paths { + hash.update(path.file_name().unwrap().to_str().unwrap().as_bytes()); + hash.update([0]); + hash.update(std::fs::read(path).unwrap()); + hash.update([0]); + } + // Frozen from clean writer starting HEAD 0fb38da5, before the two additions. + assert_eq!( + hash.finalize().iter().fold(String::new(), |mut hex, byte| { + write!(hex, "{byte:02x}").unwrap(); + hex + }), + expected + ); + } } #[allow(clippy::single_range_in_vec_init)] @@ -343,6 +556,9 @@ fn edge(class: &str, index: Option<&DocumentationIndex<'_>>, tree: &tree_sitter: } let index = index.unwrap(); match class { + "rust-literal-value-gap" | "rust-literal-raw-crlf-pieces" => { + rust_included_literal_seed(class, index, tree); + } "eof" => { assert!(!index.source().ends_with(b"\n")); assert_eq!(index.documents().len(), 0); diff --git a/utils/documentation-rust-qualification-perturb.json b/utils/documentation-rust-qualification-perturb.json new file mode 100644 index 000000000..665dfe265 --- /dev/null +++ b/utils/documentation-rust-qualification-perturb.json @@ -0,0 +1,42 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["timeout", "3600", "cargo", "test", "-p", "big-code-analysis-bench", "--lib", "documentation::rust_tests"], + "cases": [ + { + "name": "validator-forgets-token-coordinates", + "file": "big-code-analysis-bench/src/documentation/rust_validation.rs", + "old": "piece.range() == span && piece.bytes() == &source[span]", + "new": "piece.bytes() == &source[span]", + "expect": ["documentation::rust_tests::rust_origin_validator_rejects_wrong_token_with_unchanged_counts_and_text"] + }, + { + "name": "validator-accepts-foreign-binding-scope", + "file": "big-code-analysis-bench/src/documentation/rust_validation.rs", + "old": "fact.binding.is_some_and(|node| node.node() == function)\n && fact.lexical_scope.node() == scope", + "new": "fact.binding.is_some_and(|node| node.node().byte_range() == function.byte_range())\n && fact.lexical_scope.node().byte_range() == scope.byte_range()", + "expect": ["documentation::rust_tests::rust_graph_validator_rejects_equal_source_with_foreign_canonical_links"] + }, + { + "name": "map-operation-repeats-first-piece", + "file": "big-code-analysis-bench/src/documentation/operation.rs", + "old": "for piece in [a, b, c, d] {", + "new": "let _ = (b, c, d); for piece in [a, a, a, a] {", + "expect": ["documentation::rust_tests::rust_split_map_consumes_each_borrowed_piece_in_order"] + }, + { + "name": "split-cursor-restart-new-counter-guard", + "file": "big-code-analysis-ast/src/documentation/text/rust/literal.rs", + "old": "let start = at;", + "new": "let start = at; source = SourceCursor::new(&fragment.source);", + "expect": ["documentation::rust_tests::rust_work_counters_separate_depth_width_and_piece_axes"] + }, + { + "name": "duplicate-carrier-scan-new-counter-guard", + "file": "big-code-analysis-ast/src/documentation/collector/rust.rs", + "old": "let fields = AttributeFields::read(canonical, child, budget)?;", + "new": "let _ = AttributeFields::read(canonical, child, budget)?; let fields = AttributeFields::read(canonical, child, budget)?;", + "expect": ["documentation::rust_tests::rust_work_counters_separate_depth_width_and_piece_axes"] + } + ] +} diff --git a/utils/fuzz-make-perturb.json b/utils/fuzz-make-perturb.json new file mode 100644 index 000000000..6ed34b401 --- /dev/null +++ b/utils/fuzz-make-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "unittest", + "command": ["python3", "-B", "-m", "unittest", "utils/fuzz-make-test.py"], + "cases": [ + { + "name": "drop-replay-final-statistics-arguments", + "file": "Makefile", + "old": "-- $(FUZZ_ARGS) -runs=0 -timeout=$(FUZZ_TIMEOUT);", + "new": "-- -runs=0 -timeout=$(FUZZ_TIMEOUT);", + "expect": ["utils.fuzz-make-test.FuzzMakeTests.test_replay_forwards_args_and_keeps_fixed_runs_last"] + }, + { + "name": "writable-corpus-order-reversed", + "file": "Makefile", + "old": "\"$(FUZZ_WORK)/$$t\" \"$(FUZZ_CORPUS)/$$t\"", + "new": "\"$(FUZZ_CORPUS)/$$t\" \"$(FUZZ_WORK)/$$t\"", + "expect": ["utils.fuzz-make-test.FuzzMakeTests.test_replay_forwards_args_and_keeps_fixed_runs_last"] + }, + { + "name": "args-override-recipe-run-limit", + "file": "Makefile", + "old": "-- $(FUZZ_ARGS) -runs=0 -timeout=$(FUZZ_TIMEOUT);", + "new": "-- -runs=0 -timeout=$(FUZZ_TIMEOUT) $(FUZZ_ARGS);", + "expect": ["utils.fuzz-make-test.FuzzMakeTests.test_replay_forwards_args_and_keeps_fixed_runs_last"] + } + ] +} diff --git a/utils/fuzz-make-test.py b/utils/fuzz-make-test.py new file mode 100644 index 000000000..df8381474 --- /dev/null +++ b/utils/fuzz-make-test.py @@ -0,0 +1,133 @@ +#!/usr/bin/env python3 +"""Exercise maintained fuzz argv and environment with deterministic fake commands.""" + +import json +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parent.parent + + +class FuzzMakeTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory(prefix="bca-fuzz-make-") + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.bin = self.root / "bin" + self.bin.mkdir() + self.record = self.root / "calls.jsonl" + self.work = self.root / "writable corpus" + self.corpus = self.root / "read only seeds" + for target in ["documentation", "parse_rust"]: + path = self.corpus / target + path.mkdir(parents=True) + (path / "seed").write_bytes(b"seed\x00bytes") + self.before = self.inventory() + self.env = os.environ | {"PATH": str(self.bin), "RECORD": str(self.record)} + for name in ["grep", "sed", "mkdir", "cut", "bash"]: + os.symlink(shutil.which(name), self.bin / name) + self.command("rustup", "print('nightly-aarch64-unknown-linux-gnu')") + self.command("rustc", "print('host: aarch64-unknown-linux-gnu')") + self.command("cargo-fuzz", "pass") + self.command("cargo", """ +import json, os, sys +from pathlib import Path +args = sys.argv[1:] +if args == ['+nightly', 'fuzz', 'list']: + print('documentation\\nparse_rust') +else: + record = {'argv': args, 'env': {k: v for k, v in os.environ.items() if k.startswith(('CFLAGS_', 'CXXFLAGS_', 'LSAN_', 'ASAN_'))}} + with open(os.environ['RECORD'], 'a') as f: + f.write(json.dumps(record) + '\\n') + corpus = args[args.index('--target') + 3:args.index('--')] + if len(corpus) == 2: + assert Path(corpus[0]).is_dir() + assert Path(corpus[1]).is_dir() + (Path(corpus[0]) / 'discovery').write_bytes(b'discovery') +""") + + def command(self, name, body): + path = self.bin / name + path.write_text(f"#!{shutil.which('python3')}\n{body}\n") + path.chmod(0o755) + + def inventory(self): + return {str(p.relative_to(self.corpus)): p.read_bytes() for p in self.corpus.rglob('*') if p.is_file()} + + def run_make(self, target, *settings, symbolizer="/fake/llvm symbolizer"): + command = [shutil.which("make"), "--no-print-directory", "-f", str(ROOT / "Makefile"), target, + f"FUZZ_WORK={self.work}", f"FUZZ_CORPUS={self.corpus}", f"FUZZ_SYMBOLIZER={symbolizer}", *settings] + result = subprocess.run(command, cwd=ROOT, env=self.env, capture_output=True, text=True, timeout=30) + self.assertEqual(self.inventory(), self.before, result.stdout + result.stderr) + return result + + def records(self): + return [json.loads(line) for line in self.record.read_text().splitlines()] if self.record.exists() else [] + + def check_call(self, record, target, flags): + self.assertEqual(record["argv"], ["+nightly", "fuzz", "run", "--target", "aarch64-unknown-linux-gnu", target, + str(self.work / target), str(self.corpus / target), "--", *flags]) + self.assertEqual(record["env"], { + "CFLAGS_aarch64_unknown_linux_gnu": "-fsanitize=address -fno-omit-frame-pointer", + "CXXFLAGS_aarch64_unknown_linux_gnu": "-fsanitize=address -fno-omit-frame-pointer", + "LSAN_OPTIONS": f"suppressions={ROOT}/fuzz/lsan-suppressions.txt", + "ASAN_SYMBOLIZER_PATH": "/fake/llvm symbolizer", + }) + + def test_default_run_flags_and_read_only_second_corpus(self): + result = self.run_make("fuzz-run", "FUZZ_TARGET=documentation") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(len(self.records()), 1) + self.check_call(self.records()[0], "documentation", ["-runs=100000", "-timeout=60"]) + + def test_default_corpus_paths_are_preserved_in_expanded_command(self): + command = [shutil.which("make"), "--no-print-directory", "-n", "-f", str(ROOT / "Makefile"), + "fuzz-run", "FUZZ_SYMBOLIZER=/fake/symbolizer"] + result = subprocess.run(command, cwd=ROOT, env=self.env, capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn(f'"{ROOT}/fuzz/corpus-work/parse_cpp" "{ROOT}/fuzz/corpus/parse_cpp"', result.stdout) + self.assertIn("-- -runs=100000 -timeout=60", result.stdout) + self.assertEqual(self.records(), []) + + def test_replay_forwards_args_and_keeps_fixed_runs_last(self): + result = self.run_make("fuzz-replay", "FUZZ_ARGS=-runs=999 -timeout=1 -print_final_stats=1 '-artifact_prefix=/a path/'", "FUZZ_TIMEOUT=73") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + records = self.records() + self.assertEqual(len(records), 2) + for record, target in zip(records, ["documentation", "parse_rust"]): + self.check_call(record, target, ["-runs=999", "-timeout=1", "-print_final_stats=1", "-artifact_prefix=/a path/", "-runs=0", "-timeout=73"]) + + def test_run_overrides_and_input_replay_preserve_argument_boundaries(self): + result = self.run_make("fuzz-run", "FUZZ_TARGET=documentation", "FUZZ_RUNS=10000", "FUZZ_TIMEOUT=61", "FUZZ_ARGS=-seed=1664001 -print_final_stats=1") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.check_call(self.records()[0], "documentation", ["-seed=1664001", "-print_final_stats=1", "-runs=10000", "-timeout=61"]) + result = self.run_make("fuzz-run", "FUZZ_TARGET=parse_rust", "FUZZ_INPUT=/an input/file", "FUZZ_ARGS=-print_final_stats=1") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(self.records()[1]["argv"][-4:], ["/an input/file", "--", "-print_final_stats=1", "-timeout=60"]) + + def test_missing_tools_are_skips_with_no_target_execution(self): + for missing in ["nightly", "cargo-fuzz"]: + with self.subTest(missing=missing): + if missing == "nightly": + self.command("rustup", "print('stable-aarch64-unknown-linux-gnu')") + else: + self.command("rustup", "print('nightly-aarch64-unknown-linux-gnu')") + (self.bin / "cargo-fuzz").unlink() + result = self.run_make("fuzz-run") + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("skipping fuzz-run", result.stdout) + self.assertEqual(self.records(), []) + + def test_absent_symbolizer_fails_before_any_target(self): + result = self.run_make("fuzz-replay", symbolizer="") + self.assertNotEqual(result.returncode, 0) + self.assertIn("no llvm-symbolizer found", result.stdout) + self.assertEqual(self.records(), []) + + +if __name__ == "__main__": + unittest.main() From ac7191ac702fb2c930ea2441df4fbe3adf55b977 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:58:15 -0800 Subject: [PATCH 069/221] fix(documentation): validate canonical evidence and retain selected make --- Makefile | 2 +- .../src/documentation/rust_validation.rs | 193 ++++++++++++++++-- fuzz/src/documentation/tests.rs | 37 +++- ...umentation-rust-qualification-perturb.json | 11 +- utils/fuzz-make-perturb.json | 14 ++ utils/fuzz-make-test.py | 70 ++++++- 6 files changed, 297 insertions(+), 30 deletions(-) diff --git a/Makefile b/Makefile index c5da2963f..aa1e397ea 100644 --- a/Makefile +++ b/Makefile @@ -469,7 +469,7 @@ makefile-check: fuzz-make-test .PHONY: fuzz-make-test fuzz-make-test: - @python3 -B "$(BASE_DIR)utils/fuzz-make-test.py" + @MAKE="$(MAKE)" python3 -B "$(BASE_DIR)utils/fuzz-make-test.py" # actionlint scans every workflow under .github/workflows/ and shells # out to shellcheck (when present on PATH) for the `run:` blocks. It diff --git a/big-code-analysis-bench/src/documentation/rust_validation.rs b/big-code-analysis-bench/src/documentation/rust_validation.rs index 680871439..9353fd0fc 100644 --- a/big-code-analysis-bench/src/documentation/rust_validation.rs +++ b/big-code-analysis-bench/src/documentation/rust_validation.rs @@ -5,7 +5,8 @@ use std::ops::Range; use big_code_analysis_ast::documentation::{ AssessmentAxis, CompleteText, Composition, DocumentRole, DocumentationIndex, FragmentForm, - Mapping, Origin, OriginView, Owner, Publication, Resolution, SourcePiece, SourcePieces, + Mapping, NodeEvidence, Origin, OriginView, Owner, Publication, Resolution, SourcePiece, + SourcePieces, }; use big_code_analysis_ast::tree_sitter::{Node, Point}; @@ -238,6 +239,37 @@ pub(super) fn late_map( type Nodes<'s> = HashMap<(&'static str, usize, usize), Node<'s>>; +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum EvidenceRole { + Binding, + Scope, + FunctionOwner, + FileOwner, + ModuleOwner, + Publication, + Fragment, +} + +// Substitute retained evidence privately in negative tests; canonical expectations stay untouched. +struct EvidenceCheck(F); + +impl EvidenceCheck { + #[cfg(test)] + fn new<'s>(check: F) -> Self + where + F: Fn(EvidenceRole, NodeEvidence<'s>) -> NodeEvidence<'s>, + { + Self(check) + } + + fn matches<'s>(&self, role: EvidenceRole, actual: NodeEvidence<'s>, expected: Node<'_>) -> bool + where + F: Fn(EvidenceRole, NodeEvidence<'s>) -> NodeEvidence<'s>, + { + (self.0)(role, actual).validate(expected).is_ok() + } +} + fn node_at<'s>( nodes: &Nodes<'s>, kind: &'static str, @@ -337,11 +369,12 @@ fn shape<'s>(parsed: &'s Parsed, expected: &Expected) -> Result, Harne } #[allow(clippy::too_many_lines)] // Check the complete document/association/owner graph and canonical navigation together. -fn graph( - index: &DocumentationIndex<'_>, +fn graph<'s>( + index: &DocumentationIndex<'s>, expected: &Expected, nodes: &Nodes<'_>, root: Node<'_>, + evidence: &EvidenceCheck) -> NodeEvidence<'s>>, ) -> Result<(), HarnessError> { require( index.documents().len() == 1 && index.associations().len() == 1, @@ -391,8 +424,9 @@ fn graph( "Rust association disposition", )?; require( - fact.binding.is_some_and(|node| node.node() == function) - && fact.lexical_scope.node() == scope, + fact.binding + .is_some_and(|node| evidence.matches(EvidenceRole::Binding, node, function)) + && evidence.matches(EvidenceRole::Scope, fact.lexical_scope, scope), "Rust binding/scope identity", )?; let owner = index @@ -400,10 +434,10 @@ fn graph( .associated_owner(association, 0) .map_err(failure)?; require( - matches!(owner.get(), Owner::Node(node) if node.node() == function), + matches!(owner.get(), Owner::Node(node) if evidence.matches(EvidenceRole::FunctionOwner, *node, function)), "Rust canonical function owner", )?; - publication(index, expected, nodes)?; + publication(index, expected, nodes, evidence)?; require( index.facts().owners().len() == expected.depth + 2, "Rust complete owner inventory", @@ -412,14 +446,14 @@ fn graph( require( owners .next() - .is_some_and(|owner| matches!(owner.get(), Owner::File(node) if node.node() == root)), + .is_some_and(|owner| matches!(owner.get(), Owner::File(node) if evidence.matches(EvidenceRole::FileOwner, *node, root))), "Rust file owner identity", )?; for depth in 0..expected.depth { let module = node_at(nodes, "mod_item", 7 * depth..expected.source.len() - depth)?; require( owners.next().is_some_and( - |owner| matches!(owner.get(), Owner::Node(node) if node.node() == module), + |owner| matches!(owner.get(), Owner::Node(node) if evidence.matches(EvidenceRole::ModuleOwner, *node, module)), ), "Rust module owner identity", )?; @@ -448,10 +482,11 @@ fn graph( Ok(()) } -fn publication( - index: &DocumentationIndex<'_>, +fn publication<'s>( + index: &DocumentationIndex<'s>, expected: &Expected, nodes: &Nodes<'_>, + evidence: &EvidenceCheck) -> NodeEvidence<'s>>, ) -> Result<(), HarnessError> { let attributes = expected .fragments @@ -467,7 +502,10 @@ fn publication( assessment.get().axis == AssessmentAxis::Publication && assessment.get().reason == "Rust documentation/publication metadata awaits interpretation" - && assessment.get().node.is_some_and(|e| e.node() == node) + && assessment + .get() + .node + .is_some_and(|e| evidence.matches(EvidenceRole::Publication, e, node)) && index .assessed_document(assessment) .map_err(failure)? @@ -483,6 +521,16 @@ pub(super) fn validate( n: usize, parsed: &Parsed, index: &DocumentationIndex<'_>, +) -> Result<(), HarnessError> { + validate_with(probe, n, parsed, index, &EvidenceCheck(|_, node| node)) +} + +fn validate_with<'s>( + probe: &SourceProbe, + n: usize, + parsed: &Parsed, + index: &DocumentationIndex<'s>, + evidence: &EvidenceCheck) -> NodeEvidence<'s>>, ) -> Result<(), HarnessError> { let expected = Expected::new(probe.key, n)?; require( @@ -490,7 +538,13 @@ pub(super) fn validate( "Rust exact supplied source", )?; let nodes = shape(parsed, &expected)?; - graph(index, &expected, &nodes, parsed.tree().root_node())?; + graph( + index, + &expected, + &nodes, + parsed.tree().root_node(), + evidence, + )?; let doc = index .documents() .next() @@ -532,14 +586,17 @@ pub(super) fn validate( }; let node = fragment .node() - .ok_or_else(|| HarnessError("Rust fragment node absent".into()))? - .node(); + .ok_or_else(|| HarnessError("Rust fragment node absent".into()))?; require( - node == node_at( - &nodes, - kind, - range.start..range.end + usize::from(kind == "line_comment"), - )?, + evidence.matches( + EvidenceRole::Fragment, + node, + node_at( + &nodes, + kind, + range.start..range.end + usize::from(kind == "line_comment"), + )?, + ), "Rust raw canonical fragment node", )?; } @@ -555,3 +612,99 @@ pub(super) fn validate( expected.split, ) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::documentation::REGISTRY; + use big_code_analysis_ast::documentation::{SourceContext, SourceError}; + use big_code_analysis_ast::tree_sitter::InputEdit; + use std::cell::Cell; + + #[test] + fn full_validator_rejects_same_id_edited_evidence_at_every_role() { + for key in ["rust-mixed", "rust-attribute-depth-width"] { + let probe = REGISTRY.iter().find(|p| p.key == key).unwrap(); + let parsed = Parsed::new(probe, 2).unwrap(); + let index = parsed.collect(probe).unwrap(); + validate(probe, 2, &parsed, &index).unwrap(); + let context = SourceContext::new(parsed.tree(), parsed.source()); + let before_text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + let counts = ( + index.documents().len(), + index.associations().len(), + index.facts().fragments().len(), + ); + for (role, message) in [ + (EvidenceRole::Binding, "Rust binding/scope identity"), + (EvidenceRole::Scope, "Rust binding/scope identity"), + (EvidenceRole::FunctionOwner, "Rust canonical function owner"), + (EvidenceRole::FileOwner, "Rust file owner identity"), + (EvidenceRole::ModuleOwner, "Rust module owner identity"), + ( + EvidenceRole::Publication, + "Rust publication assessment identity", + ), + (EvidenceRole::Fragment, "Rust raw canonical fragment node"), + ] { + if role == EvidenceRole::ModuleOwner && key == "rust-mixed" { + continue; + } + let changed = Cell::new(0); + let evidence = EvidenceCheck::new(|at, original| { + if at != role { + return original; + } + let mut edited = original.node(); + edited.edit(&InputEdit { + start_byte: 0, + old_end_byte: 0, + new_end_byte: 1, + start_position: Point::new(0, 0), + old_end_position: Point::new(0, 0), + new_end_position: Point::new(0, 1), + }); + assert_eq!(edited.id(), original.node().id()); + assert_eq!( + edited, + original.node(), + "dependency equality ignores context" + ); + assert_ne!(edited.range(), original.node().range()); + let malformed = context.node(edited).unwrap(); + assert_eq!( + malformed.validate(original.node()), + Err(SourceError::NoncanonicalNode) + ); + if key == "rust-mixed" && role == EvidenceRole::Binding { + assert_eq!(original.node().byte_range(), 60..79); + assert_eq!(edited.byte_range(), 61..80); + } + changed.set(changed.get() + 1); + malformed + }); + let error = validate_with(probe, 2, &parsed, &index, &evidence).unwrap_err(); + assert_eq!(error.0, message, "{key}/{role:?}"); + assert_eq!(changed.get(), 1, "{key}/{role:?}"); + assert_eq!( + counts, + ( + index.documents().len(), + index.associations().len(), + index.facts().fragments().len() + ) + ); + let after_text = index + .complete_text(index.documents().next().unwrap()) + .unwrap() + .unwrap(); + assert_eq!(after_text.text(), before_text.text()); + assert_eq!(after_text.mappings(), before_text.mappings()); + validate(probe, 2, &parsed, &index).unwrap(); + } + } + } +} diff --git a/fuzz/src/documentation/tests.rs b/fuzz/src/documentation/tests.rs index e488bb649..677ff23c8 100644 --- a/fuzz/src/documentation/tests.rs +++ b/fuzz/src/documentation/tests.rs @@ -278,7 +278,7 @@ fn rust_included_literal_seed( assert_eq!(document.get().composition(), Composition::AttributeSequence); let fragment = index.facts().document_fragment(document, 0).unwrap(); assert_eq!(fragment.get().form(), FragmentForm::Attribute); - assert_eq!(fragment.get().node().unwrap().node(), *attribute); + fragment.get().node().unwrap().validate(*attribute).unwrap(); assert_eq!(fragment.get().source().has_excluded_gap(), gap); let spans: Vec<_> = (0..end) .filter(|at| !gap || *at != 10) @@ -304,11 +304,40 @@ fn rust_included_literal_seed( ); assert_eq!(association.get().resolution, Resolution::Resolved); assert_eq!(association.get().publication, Publication::Unknown); - assert_eq!(association.get().binding.unwrap().node(), *function); - assert_eq!(association.get().lexical_scope.node(), tree.root_node()); + association + .get() + .binding + .unwrap() + .validate(*function) + .unwrap(); + association + .get() + .lexical_scope + .validate(tree.root_node()) + .unwrap(); assert_eq!(association.get().owner_count(), 1); let owner = index.facts().associated_owner(association, 0).unwrap(); - assert!(matches!(owner.get(), Owner::Node(node) if node.node() == *function)); + let Owner::Node(node) = owner.get() else { + panic!("function owner") + }; + node.validate(*function).unwrap(); + assert_eq!(index.facts().owners().len(), 2); + let file = index.facts().owners().next().unwrap(); + let Owner::File(node) = file.get() else { + panic!("file owner") + }; + node.validate(tree.root_node()).unwrap(); + let mut publications = index + .assessments() + .filter(|assessment| assessment.get().axis == AssessmentAxis::Publication); + let publication = publications.next().unwrap(); + assert!(publications.next().is_none()); + publication + .get() + .node + .unwrap() + .validate(*attribute) + .unwrap(); assert_eq!( index .node_associations(*function) diff --git a/utils/documentation-rust-qualification-perturb.json b/utils/documentation-rust-qualification-perturb.json index 665dfe265..220870364 100644 --- a/utils/documentation-rust-qualification-perturb.json +++ b/utils/documentation-rust-qualification-perturb.json @@ -1,7 +1,7 @@ { "cwd": ".", "runner": "cargo", - "cargo": ["timeout", "3600", "cargo", "test", "-p", "big-code-analysis-bench", "--lib", "documentation::rust_tests"], + "cargo": ["timeout", "3600", "cargo", "test", "-p", "big-code-analysis-bench", "--lib", "documentation::rust"], "cases": [ { "name": "validator-forgets-token-coordinates", @@ -13,10 +13,17 @@ { "name": "validator-accepts-foreign-binding-scope", "file": "big-code-analysis-bench/src/documentation/rust_validation.rs", - "old": "fact.binding.is_some_and(|node| node.node() == function)\n && fact.lexical_scope.node() == scope", + "old": "fact.binding\n .is_some_and(|node| evidence.matches(EvidenceRole::Binding, node, function))\n && evidence.matches(EvidenceRole::Scope, fact.lexical_scope, scope)", "new": "fact.binding.is_some_and(|node| node.node().byte_range() == function.byte_range())\n && fact.lexical_scope.node().byte_range() == scope.byte_range()", "expect": ["documentation::rust_tests::rust_graph_validator_rejects_equal_source_with_foreign_canonical_links"] }, + { + "name": "validator-restores-id-only-evidence-equality", + "file": "big-code-analysis-bench/src/documentation/rust_validation.rs", + "old": "(self.0)(role, actual).validate(expected).is_ok()", + "new": "(self.0)(role, actual).node() == expected", + "expect": ["documentation::rust_validation::tests::full_validator_rejects_same_id_edited_evidence_at_every_role"] + }, { "name": "map-operation-repeats-first-piece", "file": "big-code-analysis-bench/src/documentation/operation.rs", diff --git a/utils/fuzz-make-perturb.json b/utils/fuzz-make-perturb.json index 6ed34b401..99a39164f 100644 --- a/utils/fuzz-make-perturb.json +++ b/utils/fuzz-make-perturb.json @@ -3,6 +3,20 @@ "runner": "unittest", "command": ["python3", "-B", "-m", "unittest", "utils/fuzz-make-test.py"], "cases": [ + { + "name": "drop-selected-make-recipe-propagation", + "file": "Makefile", + "old": "@MAKE=\"$(MAKE)\" python3 -B \"$(BASE_DIR)utils/fuzz-make-test.py\"", + "new": "@python3 -B \"$(BASE_DIR)utils/fuzz-make-test.py\"", + "expect": ["utils.fuzz-make-test.SelectedMakeTests.test_selected_caller_survives_shadowed_path_make_in_recipe_and_standalone"] + }, + { + "name": "dry-expansion-discards-selected-make", + "file": "utils/fuzz-make-test.py", + "old": "command = [self.make, \"--no-print-directory\", \"-n\",", + "new": "command = [shutil.which(\"make\"), \"--no-print-directory\", \"-n\",", + "expect": ["utils.fuzz-make-test.SelectedMakeTests.test_selected_caller_survives_shadowed_path_make_in_recipe_and_standalone"] + }, { "name": "drop-replay-final-statistics-arguments", "file": "Makefile", diff --git a/utils/fuzz-make-test.py b/utils/fuzz-make-test.py index df8381474..62af115d7 100644 --- a/utils/fuzz-make-test.py +++ b/utils/fuzz-make-test.py @@ -3,17 +3,20 @@ import json import os +import re from pathlib import Path import shutil import subprocess import tempfile import unittest +from unittest.mock import patch ROOT = Path(__file__).resolve().parent.parent class FuzzMakeTests(unittest.TestCase): def setUp(self): + self.make = self._gnu_make_4() self.temp = tempfile.TemporaryDirectory(prefix="bca-fuzz-make-") self.addCleanup(self.temp.cleanup) self.root = Path(self.temp.name) @@ -55,11 +58,23 @@ def command(self, name, body): path.write_text(f"#!{shutil.which('python3')}\n{body}\n") path.chmod(0o755) + def _gnu_make_4(self): + candidates = [os.environ.get("MAKE"), "gmake", "make"] + for candidate in candidates: + found = shutil.which(candidate) if candidate else None + if found is None: + continue + probe = subprocess.run([found, "--version"], capture_output=True, text=True, timeout=30) + match = re.match(r"GNU Make (\d+)\.", probe.stdout) + if probe.returncode == 0 and match and int(match.group(1)) >= 4: + return str(Path(found).absolute()) + self.skipTest(f"no GNU Make 4 among {candidates}; set MAKE or install gmake") + def inventory(self): return {str(p.relative_to(self.corpus)): p.read_bytes() for p in self.corpus.rglob('*') if p.is_file()} def run_make(self, target, *settings, symbolizer="/fake/llvm symbolizer"): - command = [shutil.which("make"), "--no-print-directory", "-f", str(ROOT / "Makefile"), target, + command = [self.make, "--no-print-directory", "-f", str(ROOT / "Makefile"), target, f"FUZZ_WORK={self.work}", f"FUZZ_CORPUS={self.corpus}", f"FUZZ_SYMBOLIZER={symbolizer}", *settings] result = subprocess.run(command, cwd=ROOT, env=self.env, capture_output=True, text=True, timeout=30) self.assertEqual(self.inventory(), self.before, result.stdout + result.stderr) @@ -85,7 +100,7 @@ def test_default_run_flags_and_read_only_second_corpus(self): self.check_call(self.records()[0], "documentation", ["-runs=100000", "-timeout=60"]) def test_default_corpus_paths_are_preserved_in_expanded_command(self): - command = [shutil.which("make"), "--no-print-directory", "-n", "-f", str(ROOT / "Makefile"), + command = [self.make, "--no-print-directory", "-n", "-f", str(ROOT / "Makefile"), "fuzz-run", "FUZZ_SYMBOLIZER=/fake/symbolizer"] result = subprocess.run(command, cwd=ROOT, env=self.env, capture_output=True, text=True, timeout=30) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) @@ -129,5 +144,54 @@ def test_absent_symbolizer_fails_before_any_target(self): self.assertEqual(self.records(), []) +class SelectedMakeTests(unittest.TestCase): + def test_selected_caller_survives_shadowed_path_make_in_recipe_and_standalone(self): + real_make = FuzzMakeTests()._gnu_make_4() + with tempfile.TemporaryDirectory(prefix="bca-selected-make-") as directory: + root = Path(directory) + calls = root / "make-calls.jsonl" + wrong = root / "wrong-make.jsonl" + selected = root / "selected-gmake" + selected.write_text(f"#!{shutil.which('python3')}\n" + "\n".join([ + "import json, os, sys", + f"with open({str(calls)!r}, 'a') as log: log.write(json.dumps(sys.argv[1:]) + '\\n')", + f"os.execv({real_make!r}, [{str(selected)!r}, *sys.argv[1:]])", + ]) + "\n") + selected.chmod(0o755) + for name in ["make", "gmake"]: + sentinel = root / name + sentinel.write_text(f"#!{shutil.which('python3')}\nimport json, sys\nwith open({str(wrong)!r}, 'a') as log: log.write(json.dumps(sys.argv) + '\\n')\nsys.exit(86)\n") + sentinel.chmod(0o755) + env = os.environ | {"PATH": str(root) + os.pathsep + os.environ["PATH"], "BCA_FUZZ_MAKE_SELECTION_CHILD": "1"} + for key in ["MAKE", "MAKEFLAGS", "MFLAGS", "GNUMAKEFLAGS", "MAKEFILES", "MAKEOVERRIDES", "MAKELEVEL"]: + env.pop(key, None) + commands = [ + ([str(selected), "--no-print-directory", "-f", str(ROOT / "Makefile"), "fuzz-make-test"], env), + ([shutil.which("python3"), "-B", str(Path(__file__).resolve()), "FuzzMakeTests"], env | {"MAKE": str(selected)}), + ] + for command, child_env in commands: + with self.subTest(command=command): + calls.write_text("") + result = subprocess.run(command, cwd=ROOT, env=child_env, capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertIn("Ran 6 tests", result.stderr) + recorded = [json.loads(line) for line in calls.read_text().splitlines()] + self.assertEqual(sum("--version" in args for args in recorded), 6) + dry = [args for args in recorded if "-n" in args] + self.assertEqual(dry, [["--no-print-directory", "-n", "-f", str(ROOT / "Makefile"), "fuzz-run", "FUZZ_SYMBOLIZER=/fake/symbolizer"]]) + self.assertEqual(sum("FUZZ_TARGET=documentation" in args for args in recorded), 2) + self.assertFalse(wrong.exists(), wrong.read_text() if wrong.exists() else "") + + def test_standalone_fallback_prefers_valid_gmake_over_old_make(self): + with tempfile.TemporaryDirectory(prefix="bca-make-selection-") as directory: + root = Path(directory) + for name, version in [("caller", "GNU Make 3.82"), ("gmake", "GNU Make 4.3"), ("make", "GNU Make 3.81")]: + path = root / name + path.write_text(f"#!{shutil.which('python3')}\nprint({version!r})\n") + path.chmod(0o755) + with patch.dict(os.environ, {"PATH": str(root), "MAKE": str(root / "caller")}): + self.assertEqual(FuzzMakeTests()._gnu_make_4(), str(root / "gmake")) + + if __name__ == "__main__": - unittest.main() + unittest.main(defaultTest="FuzzMakeTests" if os.environ.get("BCA_FUZZ_MAKE_SELECTION_CHILD") else None) From c7339afac6760c5f7b7baf5453282e032bc76998 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:27:30 -0800 Subject: [PATCH 070/221] test(documentation): pin C# XML documentation owners and text in the source view Collect 51 C# sources through AnyParser::documentation and documentation::collect and compare the published documents, owners and retained candidates: declaration kinds, expression-bodied members, enum members, runs, plain comments and directives, attributes, block comments, XML markup, the empty line, the primary-constructor fixture, excluded placements, comments on a code row and line endings. One test pins the seven grammar shapes these cases depend on. Add the perturbation manifest for the eight deliberate defects that the tests must catch. No production code changes. Refs #1667 --- .../src/documentation/collector.rs | 2 + .../documentation/collector/csharp_tests.rs | 812 ++++++++++++++++++ utils/documentation-csharp-unit1-perturb.json | 63 ++ 3 files changed, 877 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/csharp_tests.rs create mode 100644 utils/documentation-csharp-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index bf17ca2ee..751305a78 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1006,6 +1006,8 @@ mod cancellation_tests; #[cfg(test)] mod cost_tests; #[cfg(test)] +mod csharp_tests; +#[cfg(test)] mod form_tests; #[cfg(test)] mod named_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs b/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs new file mode 100644 index 000000000..17987e12b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs @@ -0,0 +1,812 @@ +//! C# XML documentation in the source view: which declaration owns a comment, the text +//! of the document and where each part of that text comes from. Every source is collected +//! through both entry points. + +#[cfg(feature = "csharp")] +use crate::documentation::*; +#[cfg(feature = "csharp")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "csharp")] +use std::ops::Range; + +#[cfg(feature = "csharp")] +use Run::{Copied, Decoded, Synthetic}; + +/// The origin of one run of a document's text, with the source byte range it reads. +#[cfg(feature = "csharp")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +/// One document: its fragments as source byte ranges, its text, and each run of the +/// text as an output range with its origin. +#[cfg(feature = "csharp")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +/// What one collection published: the documents, the owner of each association as +/// resolution, node kind and byte range, and each retained candidate as disposition and +/// byte range. The default value is an index that holds none of them. +#[cfg(feature = "csharp")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + owners: Vec<(Resolution, &'static str, Range)>, + evidence: Vec<(CandidateDisposition, Range)>, +} + +/// The expected document of one comment. +#[cfg(feature = "csharp")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +/// The expected document of adjacent comments that join. +#[cfg(feature = "csharp")] +fn comment_run( + fragments: [Range; F], + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + composition: Composition::CommentRun, + fragments: fragments.into(), + text: text.to_owned(), + map: map.into(), + } +} + +/// The expected view of one document that one resolved node owns, with no retained +/// candidate. +#[cfg(feature = "csharp")] +fn owned(document: Doc, kind: &'static str, owner: Range) -> View { + View { + documents: vec![document], + owners: vec![(Resolution::Resolved, kind, owner)], + evidence: Vec::new(), + } +} + +/// The byte range of a spelling that is one included piece, as every spelling here is. +#[cfg(feature = "csharp")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "csharp")] +fn run_of(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "csharp")] +fn published(index: &DocumentationIndex<'_>) -> View { + let facts = index.facts(); + let documents = index + .documents() + .map(|document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| { + let fragment = facts.document_fragment(document, at).unwrap(); + span(fragment.get().source()) + }) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|run| (run.output.range(), run_of(&run.origin))) + .collect(), + } + }) + .collect(); + let owners = index + .associations() + .map(|association| { + assert_eq!(association.get().owner_count(), 1); + let owner = facts.associated_owner(association, 0).unwrap(); + let Owner::Node(declared) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + let declaration = declared.node(); + ( + association.get().resolution, + declaration.kind(), + declaration.byte_range(), + ) + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, span(fragment.get().source())) + }) + .collect(); + View { + documents, + owners, + evidence, + } +} + +#[cfg(feature = "csharp")] +fn parse(source: &[u8]) -> AnyParser { + AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap() +} + +/// A parse whose tree holds no syntax error. +#[cfg(feature = "csharp")] +fn clean(source: &[u8]) -> AnyParser { + let parser = parse(source); + assert!(!parser.root_node().has_error(), "{}", source.escape_ascii()); + parser +} + +/// Both entry points over one parse: the typed parser's method, then `collect`. +#[cfg(feature = "csharp")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Csharp, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +/// The view that both entry points publish. +#[cfg(feature = "csharp")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2]) -> View { + let [typed, raw] = indexes.each_ref().map(published); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +/// The view of an error-free parse under the default options. +#[cfg(feature = "csharp")] +fn view(source: &[u8]) -> View { + agreed(&indexes(&clean(source), DocumentationOptions::default())) +} + +/// The view of an error-free parse that also retains the candidates no document uses. +#[cfg(feature = "csharp")] +fn retained(source: &[u8]) -> View { + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + agreed(&indexes(&clean(source), options)) +} + +/// The one node of that kind and byte range. +#[cfg(feature = "csharp")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: &Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|candidate| candidate.as_tree_sitter()) + .filter(|candidate| candidate.kind() == kind && candidate.byte_range() == *range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "csharp")] +fn named_children(parent: tree_sitter::Node<'_>) -> Vec> { + parent.named_children(&mut parent.walk()).collect() +} + +#[cfg(feature = "csharp")] +fn shapes(nodes: &[tree_sitter::Node<'_>]) -> Vec<(&'static str, Range)> { + nodes + .iter() + .map(|found| (found.kind(), found.byte_range())) + .collect() +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_declaration_kinds_own_their_leading_xml_documentation() { + let types: [(&[u8], &str, Range); 5] = [ + (b"///audit\nstruct S {}", "struct_declaration", 9..20), + (b"///audit\nrecord R(int A);", "record_declaration", 9..25), + (b"///audit\ninterface I {}", "interface_declaration", 9..23), + (b"///audit\nenum E { A }", "enum_declaration", 9..21), + ( + b"///audit\ndelegate void D();", + "delegate_declaration", + 9..27, + ), + ]; + for (source, kind, owner) in types { + assert_eq!( + view(source), + owned(comment(0..8, "audit", [(0..5, Copied(3..8))]), kind, owner), + "{kind}" + ); + } + let members: [(&[u8], &str, Range); 8] = [ + ( + b"class C {\n///audit\nvoid M() {}\n}", + "method_declaration", + 19..30, + ), + ( + b"class C {\n///audit\nC() {}\n}", + "constructor_declaration", + 19..25, + ), + ( + b"class C {\n///audit\n~C() {}\n}", + "destructor_declaration", + 19..26, + ), + ( + b"class C {\n///audit\nint P { get; set; }\n}", + "property_declaration", + 19..38, + ), + ( + b"class C {\n///audit\nint this[int i] { get => i; }\n}", + "indexer_declaration", + 19..48, + ), + ( + b"class C {\n///audit\nevent System.Action F { add { } remove { } }\n}", + "event_declaration", + 19..63, + ), + ( + b"class C {\n///audit\npublic static C operator +(C a, C b) => a;\n}", + "operator_declaration", + 19..61, + ), + ( + b"class C {\n///audit\npublic static explicit operator int(C a) => 1;\n}", + "conversion_operator_declaration", + 19..65, + ), + ]; + for (source, kind, owner) in members { + assert_eq!( + view(source), + owned( + comment(10..18, "audit", [(0..5, Copied(13..18))]), + kind, + owner + ), + "{kind}" + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_expression_bodied_property_and_indexer_own_their_documentation() { + let members: [(&[u8], &str, Range); 2] = [ + ( + b"class C {\n///audit\nint P => 1;\n}", + "property_declaration", + 38..49, + ), + ( + b"class C {\n///audit\nint this[int x] => x;\n}", + "indexer_declaration", + 38..59, + ), + ]; + for (source, kind, owner) in members { + let parser = clean(source); + let searches = crate::checker::csharp_accessor_searches::observed(); + let both = indexes(&parser, DocumentationOptions::default()); + // expected: 0, because the accessor search belongs to the callable test of a + // property or an indexer, and neither collection asks that test. + assert_eq!( + crate::checker::csharp_accessor_searches::observed() - searches, + 0, + "{kind}" + ); + assert_eq!( + agreed(&both), + owned( + comment( + 10..37, + "audit", + [(0..24, Copied(13..37))] + ), + kind, + owner + ), + "{kind}" + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_enum_member_owns_its_documentation() { + assert_eq!( + view(b"enum E {\n///audit\nA\n}"), + owned( + comment(9..17, "audit", [(0..5, Copied(12..17))]), + "enum_member_declaration", + 18..19 + ) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_adjacent_documentation_lines_join_into_one_run() { + assert_eq!( + view(b"///a\n///b\nclass C {}"), + owned( + comment_run( + [0..4, 5..9], + "a\nb", + [ + (0..1, Copied(3..4)), + (1..2, Synthetic), + (2..3, Copied(8..9)) + ] + ), + "class_declaration", + 10..20 + ) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_plain_comment_ends_the_run_and_older_lines_are_superseded() { + let source = b"///old\n// plain\n///a\n///b\nclass C {}"; + let joined = || { + comment_run( + [16..20, 21..25], + "a\nb", + [ + (0..1, Copied(19..20)), + (1..2, Synthetic), + (2..3, Copied(24..25)), + ], + ) + }; + // The line at 0..6 is in no document. It is kept as superseded only on request. + assert_eq!(view(source), owned(joined(), "class_declaration", 26..36)); + assert_eq!( + retained(source), + View { + evidence: vec![(CandidateDisposition::Superseded, 0..6)], + ..owned(joined(), "class_declaration", 26..36) + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_plain_comments_and_directives_do_not_detach_documentation() { + // A file that ends at `#endregion` with no line ending leaves a syntax error behind + // the class, so the two region sources do not parse cleanly. + let rows: [(&[u8], bool, Doc, Range); 4] = [ + ( + b"/// a\n// p\nclass C {}", + false, + comment(0..5, "a", [(0..1, Copied(4..5))]), + 11..21, + ), + ( + b"///d\n#nullable enable\nclass C {}", + false, + comment(0..4, "d", [(0..1, Copied(3..4))]), + 22..32, + ), + ( + b"///a\n#region R\n///b\nclass C {}\n#endregion", + true, + comment(15..19, "b", [(0..1, Copied(18..19))]), + 20..30, + ), + ( + b"///r\n#region R\nclass C {}\n#endregion", + true, + comment(0..4, "r", [(0..1, Copied(3..4))]), + 15..25, + ), + ]; + for (source, has_error, document, owner) in rows { + let parser = parse(source); + assert_eq!( + parser.root_node().has_error(), + has_error, + "{}", + source.escape_ascii() + ); + assert!(!node_at(&parser, "class_declaration", &owner).has_error()); + assert_eq!( + agreed(&indexes(&parser, DocumentationOptions::default())), + owned(document, "class_declaration", owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_documentation_attaches_before_an_attribute_and_not_after_it() { + assert_eq!( + view(b"///audit\n[System.Obsolete] class C {}"), + owned( + comment(0..27, "audit", [(0..24, Copied(3..27))]), + "class_declaration", + 28..56 + ) + ); + let after = b"[System.Obsolete]\n///audit\nclass C {}"; + assert_eq!(view(after), View::default()); + assert_eq!( + retained(after), + View { + evidence: vec![(CandidateDisposition::Unattached, 18..26)], + ..View::default() + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_block_documentation_is_cleaned_as_a_block_comment() { + assert_eq!( + view(b"/** audit */\nclass C {}"), + owned( + comment(0..12, "audit", [(0..5, Copied(4..9))]), + "class_declaration", + 13..23 + ) + ); + assert_eq!( + view(b"/**\n * \n * two\n * \n */\nclass C {}"), + owned( + comment( + 0..43, + "\n two\n", + [ + (0..9, Copied(7..16)), + (9..10, Copied(16..17)), + (10..15, Copied(20..25)), + (15..16, Copied(25..26)), + (16..26, Copied(29..39)), + ] + ), + "class_declaration", + 44..54 + ) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_xml_markup_stays_verbatim() { + assert_eq!( + view(b"/// \n/// a < b\n/// \nclass C {}"), + owned( + comment_run( + [0..13, 14..26, 27..41], + "\na < b\n", + [ + (0..9, Copied(4..13)), + (9..10, Synthetic), + (10..18, Copied(18..26)), + (18..19, Synthetic), + (19..29, Copied(31..41)), + ] + ), + "class_declaration", + 42..52 + ) + ); + assert_eq!( + view(b"class C {\n/// \nvoid F() {}\n}"), + owned( + comment(10..27, "", [(0..13, Copied(14..27))]), + "method_declaration", + 28..39 + ) + ); + assert_eq!( + view(b"/// \nclass C {}"), + owned( + comment(0..23, "", [(0..19, Copied(4..23))]), + "class_declaration", + 24..34 + ) + ); + assert_eq!( + view(b"/// \nclass C {}"), + owned( + comment( + 0..36, + "", + [(0..32, Copied(4..36))] + ), + "class_declaration", + 37..47 + ) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_bare_documentation_line_is_a_present_empty_document() { + assert_eq!( + view(b"///\nclass C {}"), + owned(comment(0..3, "", []), "class_declaration", 4..14) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_type_with_primary_constructor_owns_its_documentation() { + let source = crate::test_support::documentation::source("csharp-primary.cs"); + assert_eq!( + source, + b"/// type\nclass C(int x) { int F() { return x + 1; } }\n" + ); + let parser = clean(&source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both), + owned( + comment(0..27, "type", [(0..23, Copied(4..27))]), + "class_declaration", + 28..72 + ) + ); + let class = node_at(&parser, "class_declaration", &(28..72)); + let parameters = node_at(&parser, "parameter_list", &(35..42)); + for index in &both { + assert_eq!( + index.node_associations(class).unwrap().associations().len(), + 1 + ); + assert_eq!( + index.node_projection(parameters).err(), + Some(OwnerError::UnsupportedOwner) + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_excluded_placements_give_no_document() { + let kept_on_request: [(&[u8], Range); 3] = [ + (b"class C { int P { /**audit*/ get; } }", 18..28), + (b"class C(/**audit*/ int x) {}", 8..18), + (b"class C { void F() { ///audit\nint x = 1; } }", 21..29), + ]; + for (source, unattached) in kept_on_request { + assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); + assert_eq!( + retained(source), + View { + evidence: vec![(CandidateDisposition::Unattached, unattached)], + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } + let sources: [&[u8]; 5] = [ + b"///audit\nnamespace N { }", + b"///audit\nnamespace N;", + b"///audit\nusing System;", + b"class C {\n///audit\n}", + b"class C {}\n///audit", + ]; + for source in sources { + assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_documentation_on_a_code_row_attaches_to_the_next_declaration() { + assert_eq!( + view(b"/** t */ class D { }"), + owned( + comment(0..8, "t", [(0..1, Copied(4..5))]), + "class_declaration", + 9..20 + ) + ); + assert_eq!( + view(b"class C { void A() {} /// d\nvoid B() {} }"), + owned( + comment(22..27, "d", [(0..1, Copied(26..27))]), + "method_declaration", + 28..39 + ) + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_line_endings_and_trailing_documentation() { + assert_eq!( + view(b"///audit\r\nclass C {}\r\n"), + owned( + comment(0..8, "audit", [(0..5, Copied(3..8))]), + "class_declaration", + 10..20 + ) + ); + assert_eq!( + view(b"/**a\r\n * b*/\r\nclass C {}"), + owned( + comment( + 0..12, + "a\nb", + [ + (0..1, Copied(3..4)), + (1..2, Decoded(4..6)), + (2..3, Copied(9..10)), + ] + ), + "class_declaration", + 14..24 + ) + ); + let tail = b"///audit\nclass C {}\n/// tail"; + let leading = || { + owned( + comment(0..8, "audit", [(0..5, Copied(3..8))]), + "class_declaration", + 9..19, + ) + }; + // The line at 20..28 has no declaration after it and is in no document. + assert_eq!(view(tail), leading()); + assert_eq!( + retained(tail), + View { + evidence: vec![(CandidateDisposition::Unattached, 20..28)], + ..leading() + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_grammar_shapes_the_unit_relies_on() { + // Attributes and modifiers are inside the declaration, which starts at the attribute. + let parser = clean(b"[System.Obsolete] public class C {}"); + let top = named_children(parser.ts_tree().root_node()); + assert_eq!(shapes(&top), [("class_declaration", 0..35)]); + assert_eq!( + shapes(&named_children(top[0])), + [ + ("attribute_list", 0..17), + ("modifier", 18..24), + ("identifier", 31..32), + ("declaration_list", 33..35), + ] + ); + + // A directive that wraps no code is an extra sibling of the declarations. + let parser = clean( + b"#define X\n#undef X\n#region R\n#endregion\n#line 1\n#pragma warning disable\n\ + #nullable enable\n#error e\n#warning w\nclass C {}", + ); + let top = named_children(parser.ts_tree().root_node()); + assert_eq!( + shapes(&top), + [ + ("preproc_define", 0..10), + ("preproc_undef", 10..19), + ("preproc_region", 19..29), + ("preproc_endregion", 29..40), + ("preproc_line", 40..48), + ("preproc_pragma", 48..72), + ("preproc_nullable", 72..89), + ("preproc_error", 89..98), + ("preproc_warning", 98..109), + ("class_declaration", 109..119), + ] + ); + assert!(top[..9].iter().all(tree_sitter::Node::is_extra)); + assert!(!top[9].is_extra()); + + // `#if` around members is a node of the body that holds them. + let parser = clean(b"class C {\n#if A\nvoid F() {}\n#endif\n}"); + let top = named_children(parser.ts_tree().root_node()); + assert_eq!(shapes(&top), [("class_declaration", 0..36)]); + let class = named_children(top[0]); + assert_eq!( + shapes(&class), + [("identifier", 6..7), ("declaration_list", 8..36)] + ); + let body = named_children(class[1]); + assert_eq!(shapes(&body), [("preproc_if", 10..34)]); + assert_eq!( + shapes(&named_children(body[0])), + [("identifier", 14..15), ("method_declaration", 16..27)] + ); + + // `#if` around an attribute is inside the declaration, which starts at the `#if`. + let parser = clean(b"#if A\n[System.Obsolete]\n#endif\nclass C {}"); + let top = named_children(parser.ts_tree().root_node()); + assert_eq!(shapes(&top), [("class_declaration", 0..41)]); + assert_eq!( + shapes(&named_children(top[0])), + [ + ("preproc_if_in_attribute_list", 0..30), + ("identifier", 37..38), + ("declaration_list", 39..41), + ] + ); + + // A primary constructor is a parameter list directly under the type. + let parser = clean(b"class C(int x) {}"); + let top = named_children(parser.ts_tree().root_node()); + assert_eq!(shapes(&top), [("class_declaration", 0..17)]); + assert_eq!( + shapes(&named_children(top[0])), + [ + ("identifier", 6..7), + ("parameter_list", 7..14), + ("declaration_list", 15..17), + ] + ); + + // A line comment ends before its line ending, whichever it is. + let endings: [(&[u8], &[u8], Range); 2] = [ + (b"///audit\r\nclass C {}\r\n", b"\r\n", 10..20), + (b"///audit\nclass C {}", b"\n", 9..19), + ]; + for (source, ending, class) in endings { + let parser = clean(source); + let top = named_children(parser.ts_tree().root_node()); + assert_eq!( + shapes(&top), + [("comment", 0..8), ("class_declaration", class.clone())] + ); + assert!(top[0].is_extra()); + assert_eq!(&source[8..class.start], ending); + } +} diff --git a/utils/documentation-csharp-unit1-perturb.json b/utils/documentation-csharp-unit1-perturb.json new file mode 100644 index 000000000..6790e34a8 --- /dev/null +++ b/utils/documentation-csharp-unit1-perturb.json @@ -0,0 +1,63 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "csharp-run-join-dropped", + "file": "big-code-analysis-ast/src/checker/csharp.rs", + "old": "joins: |_, _, _| true,", + "new": "joins: |_, _, _| false,", + "expect": ["documentation::collector::csharp_tests::csharp_adjacent_documentation_lines_join_into_one_run", "documentation::collector::csharp_tests::csharp_plain_comment_ends_the_run_and_older_lines_are_superseded", "documentation::collector::csharp_tests::csharp_xml_markup_stays_verbatim"] + }, + { + "name": "csharp-plain-comment-not-hidden", + "file": "big-code-analysis-ast/src/checker/csharp.rs", + "old": "hidden: |node, code| !Self::is_doc_comment(node, code),", + "new": "hidden: |_, _| false,", + "expect": ["documentation::collector::csharp_tests::csharp_plain_comments_and_directives_do_not_detach_documentation"] + }, + { + "name": "csharp-directive-not-skipped", + "file": "big-code-analysis-ast/src/checker/csharp.rs", + "old": "skips: |node, _| csharp_directive(node),", + "new": "skips: |_, _| false,", + "expect": ["documentation::collector::csharp_tests::csharp_plain_comments_and_directives_do_not_detach_documentation"] + }, + { + "name": "csharp-after-code-dropped", + "file": "big-code-analysis-ast/src/checker/csharp.rs", + "old": "after_code: |_| true,", + "new": "after_code: |_| false,", + "expect": ["documentation::collector::csharp_tests::csharp_documentation_on_a_code_row_attaches_to_the_next_declaration"] + }, + { + "name": "csharp-region-not-a-directive", + "file": "big-code-analysis-ast/src/checker/csharp.rs", + "old": "Csharp::PreprocRegion\n | Csharp::PreprocEndregion", + "new": "Csharp::PreprocEndregion", + "expect": ["documentation::collector::csharp_tests::csharp_plain_comments_and_directives_do_not_detach_documentation"] + }, + { + "name": "csharp-property-not-a-target", + "file": "big-code-analysis-ast/src/roles/csharp.rs", + "old": " PropertyDeclaration,\n", + "new": "", + "expect": ["documentation::collector::csharp_tests::csharp_declaration_kinds_own_their_leading_xml_documentation", "documentation::collector::csharp_tests::csharp_expression_bodied_property_and_indexer_own_their_documentation"] + }, + { + "name": "line-comment-prefix-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "(if profile == Profile::GoDoc { 2 } else { 3 }, 0, false)", + "new": "(if profile == Profile::GoDoc { 2 } else { 2 }, 0, false)", + "expect": ["documentation::collector::csharp_tests::csharp_declaration_kinds_own_their_leading_xml_documentation", "documentation::collector::csharp_tests::csharp_expression_bodied_property_and_indexer_own_their_documentation", "documentation::collector::csharp_tests::csharp_adjacent_documentation_lines_join_into_one_run", "documentation::collector::csharp_tests::csharp_plain_comments_and_directives_do_not_detach_documentation", "documentation::collector::csharp_tests::csharp_xml_markup_stays_verbatim", "documentation::collector::csharp_tests::csharp_bare_documentation_line_is_a_present_empty_document", "documentation::collector::csharp_tests::csharp_line_endings_and_trailing_documentation"] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": ["documentation::collector::csharp_tests::csharp_plain_comments_and_directives_do_not_detach_documentation", "documentation::collector::csharp_tests::csharp_block_documentation_is_cleaned_as_a_block_comment", "documentation::collector::csharp_tests::csharp_xml_markup_stays_verbatim"] + } + ] +} From 3730a588b10085ac32800002a1a27616d9656373 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:27:37 -0800 Subject: [PATCH 071/221] test(loc): guard C# documentation rows before conditional compilation work For nine C# sources, among them the `#if` shapes and a field with two declarators, collect documentation once and then assert the exact LOC tuple and DLOC rows of `analyze`. Also assert that `analyze` builds no source evidence: the marker stream's `evidence_built` counter and the collector's `renders` and `visits` do not move across the call. Refs #1667 --- src/metrics/loc/documentation_tests.rs | 94 ++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index f269fade0..743fe2d8b 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -494,3 +494,97 @@ fn documentation_optional_rows_follow_anchors_not_filenames() { .is_err() ); } + +#[cfg(feature = "csharp")] +#[test] +fn documentation_csharp_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + let fixture = documentation::source("csharp-primary.cs"); + let sources: [(&[u8], [u64; 6], &[usize]); 9] = [ + ( + b"/// d\n#if FLAG\nclass C { }\n#endif\n", + [4, 3, 0, 1, 0, 0], + &[], + ), + ( + b"#if FLAG\n/// d\nclass G { }\n#endif\n", + [4, 3, 0, 1, 0, 1], + &[1], + ), + ( + b"/// x\n#if FLAG\n#endif\nclass H { }\n", + [4, 3, 0, 1, 0, 0], + &[], + ), + ( + b"/// d\n#if NET5_0\n[System.Obsolete]\n#endif\npublic class C { }\n", + [5, 4, 0, 1, 0, 1], + &[0], + ), + ( + b"class C {\n /// ab\n int a, b;\n}\n", + [4, 3, 0, 1, 0, 1], + &[1], + ), + ( + b"class C {\n /// d\n#if A\n void F() { }\n#else\n void G() { }\n#endif\n}\n", + [8, 7, 0, 1, 0, 0], + &[], + ), + (b"///a\n///b\nclass C {}\n", [3, 1, 0, 2, 0, 2], &[0, 1]), + ( + b"///audit\n[System.Obsolete] class C {}\n", + [2, 1, 0, 1, 0, 1], + &[0], + ), + (&fixture, [2, 1, 1, 1, 0, 1], &[0]), + ]; + for (source, tuple, rows) in sources { + let name = source.escape_ascii(); + let parser = + crate::langs::AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); + let idle = observations(); + parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let before = observations(); + // The collection is counted on this thread, so a zero across `analyze` is a reading. + assert_ne!(before.visits - idle.visits, 0, "{name}"); + let built = evidence_built::observed(); + let space = analyze( + Source::new(LANG::Csharp, source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let after = observations(); + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + assert_eq!(after.renders - before.renders, 0, "{name}"); + assert_eq!(after.visits - before.visits, 0, "{name}"); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + tuple, + "{name}" + ); + assert_eq!( + (0..source.len()) + .filter(|row| loc.dloc.lines.contains(*row)) + .collect::>(), + rows, + "{name}" + ); + } +} From b204df9426c064ed7573a05a240f69c6f7f91166 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:50:05 -0800 Subject: [PATCH 072/221] test(documentation): strengthen the C# source-view assertions and their defects The compared view now also holds the document role and the number of pending assessments, and every association is checked against the tree: its binding is the owner node and its lexical scope is the parent of the first comment. The two region sources end with a line feed and parse cleanly, so all four rows of that group use the clean-parse helper. The five default-only excluded placements also assert their unattached candidate on request. The zero-counter assertions get controls: the callable test of the documented member moves the accessor-search counter by one, and the collection moves `visits`, `renders` and `evidence_built` before `analyze` is measured. The line-ending assertion of the grammar test reads the tree. Four deliberate defects join the manifest, and a second manifest holds one defect for the root-crate test, which the first one's command does not run. Refs #1667 --- .../documentation/collector/csharp_tests.rs | 178 ++++++++++-------- src/metrics/loc/documentation_tests.rs | 8 +- ...mentation-csharp-unit1-legacy-perturb.json | 24 +++ utils/documentation-csharp-unit1-perturb.json | 28 +++ 4 files changed, 155 insertions(+), 83 deletions(-) create mode 100644 utils/documentation-csharp-unit1-legacy-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs b/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs index 17987e12b..fabd9876b 100644 --- a/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs @@ -1,11 +1,14 @@ //! C# XML documentation in the source view: which declaration owns a comment, the text //! of the document and where each part of that text comes from. Every source is collected -//! through both entry points. +//! through both entry points, except in the last test, which pins the parse-tree shapes +//! the other tests rely on. #[cfg(feature = "csharp")] use crate::documentation::*; #[cfg(feature = "csharp")] -use crate::{AnyParser, LANG}; +use crate::test_support::for_each_node_with_chain; +#[cfg(feature = "csharp")] +use crate::{Ancestors, AnyParser, Checker, CsharpCode, LANG}; #[cfg(feature = "csharp")] use std::ops::Range; @@ -22,11 +25,12 @@ enum Run { Synthetic, } -/// One document: its fragments as source byte ranges, its text, and each run of the -/// text as an output range with its origin. +/// One document: its role, its fragments as source byte ranges, its text, and each run +/// of the text as an output range with its origin. #[cfg(feature = "csharp")] #[derive(Debug, PartialEq, Eq)] struct Doc { + role: DocumentRole, composition: Composition, fragments: Vec>, text: String, @@ -34,14 +38,16 @@ struct Doc { } /// What one collection published: the documents, the owner of each association as -/// resolution, node kind and byte range, and each retained candidate as disposition and -/// byte range. The default value is an index that holds none of them. +/// resolution, node kind and byte range, each retained candidate as disposition and byte +/// range, and the number of pending assessments. The default value is an index that +/// holds none of them. #[cfg(feature = "csharp")] #[derive(Debug, Default, PartialEq, Eq)] struct View { documents: Vec, owners: Vec<(Resolution, &'static str, Range)>, evidence: Vec<(CandidateDisposition, Range)>, + assessments: usize, } /// The expected document of one comment. @@ -52,6 +58,7 @@ fn comment( map: [(Range, Run); N], ) -> Doc { Doc { + role: DocumentRole::Primary, composition: Composition::Single, fragments: vec![fragment], text: text.to_owned(), @@ -67,6 +74,7 @@ fn comment_run( map: [(Range, Run); N], ) -> Doc { Doc { + role: DocumentRole::Primary, composition: Composition::CommentRun, fragments: fragments.into(), text: text.to_owned(), @@ -75,13 +83,14 @@ fn comment_run( } /// The expected view of one document that one resolved node owns, with no retained -/// candidate. +/// candidate and no pending assessment. #[cfg(feature = "csharp")] fn owned(document: Doc, kind: &'static str, owner: Range) -> View { View { documents: vec![document], owners: vec![(Resolution::Resolved, kind, owner)], evidence: Vec::new(), + assessments: 0, } } @@ -112,6 +121,7 @@ fn published(index: &DocumentationIndex<'_>) -> View { .map(|document| { let complete = index.complete_text(document).unwrap().unwrap(); Doc { + role: document.get().role(), composition: document.get().composition(), fragments: (0..document.get().fragment_count()) .map(|at| { @@ -131,14 +141,28 @@ fn published(index: &DocumentationIndex<'_>) -> View { let owners = index .associations() .map(|association| { - assert_eq!(association.get().owner_count(), 1); + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); let owner = facts.associated_owner(association, 0).unwrap(); let Owner::Node(declared) = owner.get() else { panic!("a node owner, found {:?}", owner.get()) }; let declaration = declared.node(); + // Both follow from the tree: the binding is the owner itself, and the lexical + // scope is the parent of the first comment of the document. + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declaration) + ); + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let first_comment = first.get().node().unwrap().node(); + assert_eq!( + Some(attachment.lexical_scope.node()), + first_comment.parent() + ); ( - association.get().resolution, + attachment.resolution, declaration.kind(), declaration.byte_range(), ) @@ -155,18 +179,14 @@ fn published(index: &DocumentationIndex<'_>) -> View { documents, owners, evidence, + assessments: index.assessments().len(), } } -#[cfg(feature = "csharp")] -fn parse(source: &[u8]) -> AnyParser { - AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap() -} - /// A parse whose tree holds no syntax error. #[cfg(feature = "csharp")] fn clean(source: &[u8]) -> AnyParser { - let parser = parse(source); + let parser = AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); assert!(!parser.root_node().has_error(), "{}", source.escape_ascii()); parser } @@ -214,12 +234,12 @@ fn retained(source: &[u8]) -> View { /// The one node of that kind and byte range. #[cfg(feature = "csharp")] -fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: &Range) -> tree_sitter::Node<'a> { +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { let found: Vec<_> = parser .root_node() .preorder() .map(|candidate| candidate.as_tree_sitter()) - .filter(|candidate| candidate.kind() == kind && candidate.byte_range() == *range) + .filter(|candidate| candidate.kind() == kind && candidate.byte_range() == range) .collect(); let [found] = found[..] else { panic!("one {kind} at {range:?}, found {found:?}") @@ -342,6 +362,27 @@ fn csharp_expression_bodied_property_and_indexer_own_their_documentation() { 0, "{kind}" ); + // The control. expected: one accessor search per callable test of a property or + // an indexer. + let mut asked = 0; + for_each_node_with_chain::(source, |member, chain| { + if member.kind() != kind || (member.start_byte()..member.end_byte()) != owner { + return; + } + let searches = crate::checker::csharp_accessor_searches::observed(); + assert!(CsharpCode::is_func_with_code( + member, + source, + Ancestors::known(chain) + )); + assert_eq!( + crate::checker::csharp_accessor_searches::observed() - searches, + 1, + "{kind}" + ); + asked += 1; + }); + assert_eq!(asked, 1, "{kind}"); assert_eq!( agreed(&both), owned( @@ -396,7 +437,7 @@ fn csharp_adjacent_documentation_lines_join_into_one_run() { #[test] fn csharp_plain_comment_ends_the_run_and_older_lines_are_superseded() { let source = b"///old\n// plain\n///a\n///b\nclass C {}"; - let joined = || { + let mut expected = owned( comment_run( [16..20, 21..25], "a\nb", @@ -405,61 +446,46 @@ fn csharp_plain_comment_ends_the_run_and_older_lines_are_superseded() { (1..2, Synthetic), (2..3, Copied(24..25)), ], - ) - }; - // The line at 0..6 is in no document. It is kept as superseded only on request. - assert_eq!(view(source), owned(joined(), "class_declaration", 26..36)); - assert_eq!( - retained(source), - View { - evidence: vec![(CandidateDisposition::Superseded, 0..6)], - ..owned(joined(), "class_declaration", 26..36) - } + ), + "class_declaration", + 26..36, ); + // The line at 0..6 is in no document. It is kept as superseded only on request. + assert_eq!(view(source), expected); + expected + .evidence + .push((CandidateDisposition::Superseded, 0..6)); + assert_eq!(retained(source), expected); } #[cfg(feature = "csharp")] #[test] fn csharp_plain_comments_and_directives_do_not_detach_documentation() { - // A file that ends at `#endregion` with no line ending leaves a syntax error behind - // the class, so the two region sources do not parse cleanly. - let rows: [(&[u8], bool, Doc, Range); 4] = [ + let rows: [(&[u8], Doc, Range); 4] = [ ( b"/// a\n// p\nclass C {}", - false, comment(0..5, "a", [(0..1, Copied(4..5))]), 11..21, ), ( b"///d\n#nullable enable\nclass C {}", - false, comment(0..4, "d", [(0..1, Copied(3..4))]), 22..32, ), ( - b"///a\n#region R\n///b\nclass C {}\n#endregion", - true, + b"///a\n#region R\n///b\nclass C {}\n#endregion\n", comment(15..19, "b", [(0..1, Copied(18..19))]), 20..30, ), ( - b"///r\n#region R\nclass C {}\n#endregion", - true, + b"///r\n#region R\nclass C {}\n#endregion\n", comment(0..4, "r", [(0..1, Copied(3..4))]), 15..25, ), ]; - for (source, has_error, document, owner) in rows { - let parser = parse(source); - assert_eq!( - parser.root_node().has_error(), - has_error, - "{}", - source.escape_ascii() - ); - assert!(!node_at(&parser, "class_declaration", &owner).has_error()); + for (source, document, owner) in rows { assert_eq!( - agreed(&indexes(&parser, DocumentationOptions::default())), + view(source), owned(document, "class_declaration", owner), "{}", source.escape_ascii() @@ -598,13 +624,13 @@ fn csharp_type_with_primary_constructor_owns_its_documentation() { 28..72 ) ); - let class = node_at(&parser, "class_declaration", &(28..72)); - let parameters = node_at(&parser, "parameter_list", &(35..42)); + let class = node_at(&parser, "class_declaration", 28..72); + let parameters = node_at(&parser, "parameter_list", 35..42); for index in &both { - assert_eq!( - index.node_associations(class).unwrap().associations().len(), - 1 - ); + let query = index.node_associations(class).unwrap(); + assert_eq!(query.associations().len(), 1); + assert!(!query.projection_pending()); + assert_eq!(query.assessments().count(), 0); assert_eq!( index.node_projection(parameters).err(), Some(OwnerError::UnsupportedOwner) @@ -615,10 +641,15 @@ fn csharp_type_with_primary_constructor_owns_its_documentation() { #[cfg(feature = "csharp")] #[test] fn csharp_excluded_placements_give_no_document() { - let kept_on_request: [(&[u8], Range); 3] = [ + let kept_on_request: [(&[u8], Range); 8] = [ (b"class C { int P { /**audit*/ get; } }", 18..28), (b"class C(/**audit*/ int x) {}", 8..18), (b"class C { void F() { ///audit\nint x = 1; } }", 21..29), + (b"///audit\nnamespace N { }", 0..8), + (b"///audit\nnamespace N;", 0..8), + (b"///audit\nusing System;", 0..8), + (b"class C {\n///audit\n}", 10..18), + (b"class C {}\n///audit", 11..19), ]; for (source, unattached) in kept_on_request { assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); @@ -632,16 +663,6 @@ fn csharp_excluded_placements_give_no_document() { source.escape_ascii() ); } - let sources: [&[u8]; 5] = [ - b"///audit\nnamespace N { }", - b"///audit\nnamespace N;", - b"///audit\nusing System;", - b"class C {\n///audit\n}", - b"class C {}\n///audit", - ]; - for source in sources { - assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); - } } #[cfg(feature = "csharp")] @@ -693,22 +714,17 @@ fn csharp_line_endings_and_trailing_documentation() { ) ); let tail = b"///audit\nclass C {}\n/// tail"; - let leading = || { - owned( - comment(0..8, "audit", [(0..5, Copied(3..8))]), - "class_declaration", - 9..19, - ) - }; - // The line at 20..28 has no declaration after it and is in no document. - assert_eq!(view(tail), leading()); - assert_eq!( - retained(tail), - View { - evidence: vec![(CandidateDisposition::Unattached, 20..28)], - ..leading() - } + let mut expected = owned( + comment(0..8, "audit", [(0..5, Copied(3..8))]), + "class_declaration", + 9..19, ); + // The line at 20..28 has no declaration after it and is in no document. + assert_eq!(view(tail), expected); + expected + .evidence + .push((CandidateDisposition::Unattached, 20..28)); + assert_eq!(retained(tail), expected); } #[cfg(feature = "csharp")] @@ -804,9 +820,9 @@ fn csharp_grammar_shapes_the_unit_relies_on() { let top = named_children(parser.ts_tree().root_node()); assert_eq!( shapes(&top), - [("comment", 0..8), ("class_declaration", class.clone())] + [("comment", 0..8), ("class_declaration", class)] ); assert!(top[0].is_extra()); - assert_eq!(&source[8..class.start], ending); + assert_eq!(&source[top[0].end_byte()..top[1].start_byte()], ending); } } diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 743fe2d8b..fe2373794 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -547,6 +547,7 @@ fn documentation_csharp_source_and_legacy_views_are_independent() { let parser = crate::langs::AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); let idle = observations(); + let unbuilt = evidence_built::observed(); parser .documentation( &DocumentationContext::default(), @@ -554,9 +555,12 @@ fn documentation_csharp_source_and_legacy_views_are_independent() { ) .unwrap(); let before = observations(); - // The collection is counted on this thread, so a zero across `analyze` is a reading. - assert_ne!(before.visits - idle.visits, 0, "{name}"); let built = evidence_built::observed(); + // The collection moves each counter on this thread, so a zero across `analyze` is + // a reading. + assert_ne!(before.visits - idle.visits, 0, "{name}"); + assert_ne!(before.renders - idle.renders, 0, "{name}"); + assert_ne!(built - unbuilt, 0, "{name}"); let space = analyze( Source::new(LANG::Csharp, source), MetricsOptions::default().with_only(&[Metric::Loc]), diff --git a/utils/documentation-csharp-unit1-legacy-perturb.json b/utils/documentation-csharp-unit1-legacy-perturb.json new file mode 100644 index 000000000..adadcd895 --- /dev/null +++ b/utils/documentation-csharp-unit1-legacy-perturb.json @@ -0,0 +1,24 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis", + "--all-features", + "--lib", + "documentation_csharp" + ], + "cases": [ + { + "name": "csharp-conditional-is-a-doc-target", + "file": "big-code-analysis-ast/src/roles/csharp.rs", + "old": " IndexerDeclaration,\n EnumMemberDeclaration,\n", + "new": " IndexerDeclaration,\n EnumMemberDeclaration,\n PreprocIf,\n PreprocIf2,\n PreprocIf3,\n PreprocIf4,\n", + "expect": [ + "metrics::loc::documentation_tests::documentation_csharp_source_and_legacy_views_are_independent" + ] + } + ] +} diff --git a/utils/documentation-csharp-unit1-perturb.json b/utils/documentation-csharp-unit1-perturb.json index 6790e34a8..d475d4602 100644 --- a/utils/documentation-csharp-unit1-perturb.json +++ b/utils/documentation-csharp-unit1-perturb.json @@ -58,6 +58,34 @@ "old": " lines[0].content.start += 1;\n", "new": " lines[0].content.start += 0;\n", "expect": ["documentation::collector::csharp_tests::csharp_plain_comments_and_directives_do_not_detach_documentation", "documentation::collector::csharp_tests::csharp_block_documentation_is_cleaned_as_a_block_comment", "documentation::collector::csharp_tests::csharp_xml_markup_stays_verbatim"] + }, + { + "name": "csharp-enum-member-not-a-target", + "file": "big-code-analysis-ast/src/roles/csharp.rs", + "old": " EnumMemberDeclaration,\n", + "new": "", + "expect": ["documentation::collector::csharp_tests::csharp_enum_member_owns_its_documentation"] + }, + { + "name": "csharp-namespace-is-a-target", + "file": "big-code-analysis-ast/src/roles/csharp.rs", + "old": " IndexerDeclaration,\n EnumMemberDeclaration,\n", + "new": " IndexerDeclaration,\n EnumMemberDeclaration,\n NamespaceDeclaration,\n", + "expect": ["documentation::collector::csharp_tests::csharp_excluded_placements_give_no_document"] + }, + { + "name": "block-continuation-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "line.content.start = star + 1;", + "new": "line.content.start = star;", + "expect": ["documentation::collector::csharp_tests::csharp_block_documentation_is_cleaned_as_a_block_comment", "documentation::collector::csharp_tests::csharp_line_endings_and_trailing_documentation"] + }, + { + "name": "unbound-dispositions-swapped", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "disposition: if member.selection == markers::MarkerSelection::Superseded {", + "new": "disposition: if member.selection != markers::MarkerSelection::Superseded {", + "expect": ["documentation::collector::csharp_tests::csharp_plain_comment_ends_the_run_and_older_lines_are_superseded", "documentation::collector::csharp_tests::csharp_documentation_attaches_before_an_attribute_and_not_after_it", "documentation::collector::csharp_tests::csharp_excluded_placements_give_no_document", "documentation::collector::csharp_tests::csharp_line_endings_and_trailing_documentation"] } ] } From d71bbc75f9d1586b6e09d8f1b8f19759e7aa0025 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:19:45 -0800 Subject: [PATCH 073/221] test(documentation): pin Go documentation owners, runs and text in the source view Collect 49 Go sources, in 67 cases, through AnyParser::documentation and documentation::collect and compare the whole published view of both: documents with composition, fragments, text and mapping runs, the owner of each association, the retained candidates and the number of pending assessments. The binding and the lexical scope of every association are asserted from the tree. The role of a package document is undecided and is left out of the view. The groups are declaration kinds, a group and its specs, comment runs, an empty comment row, a blank source row, directive rows, trailing comments, local declarations, imports, several documents in one file, the fixture, line endings and the end of the file, and text cleanup. Every case that expects no document runs again with a retention option and must publish the exact candidate. One test collects nothing and pins the parse-tree shapes of 14 sources that these cases depend on. Add the perturbation manifest with the 16 deliberate defects that the tests must catch. No production code changes. Refs #1672 --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/go_tests.rs | 1152 +++++++++++++++++ utils/documentation-go-unit1-perturb.json | 119 ++ 3 files changed, 1273 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/go_tests.rs create mode 100644 utils/documentation-go-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 751305a78..f81ed7122 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1010,6 +1010,8 @@ mod csharp_tests; #[cfg(test)] mod form_tests; #[cfg(test)] +mod go_tests; +#[cfg(test)] mod named_tests; #[cfg(test)] mod projection_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/go_tests.rs b/big-code-analysis-ast/src/documentation/collector/go_tests.rs new file mode 100644 index 000000000..af9f8b2db --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/go_tests.rs @@ -0,0 +1,1152 @@ +//! Go documentation in the source view: which declaration owns a comment, the text of +//! the document and where each part of that text comes from. Every source is collected +//! through both entry points, except in the last test, which collects nothing and pins +//! the parse-tree shapes the other tests rely on. + +#[cfg(feature = "go")] +use crate::documentation::*; +#[cfg(feature = "go")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "go")] +use std::ops::Range; + +#[cfg(feature = "go")] +use Run::{Copied, Decoded, Synthetic}; + +/// The origin of one run of a document's text, with the source byte range it reads. +#[cfg(feature = "go")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +/// One document: its role, its fragments as source byte ranges, its text, and each run +/// of the text as an output range with its origin. A package document has no role here. +#[cfg(feature = "go")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: Option, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +/// What one collection published: the documents, the owner of each association as +/// resolution, node kind and byte range, each retained candidate as disposition and byte +/// range, and the number of pending assessments. The default value is an index that +/// holds none of them. +#[cfg(feature = "go")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + owners: Vec<(Resolution, &'static str, Range)>, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: usize, +} + +/// The candidates a collection keeps beside its documents. +#[cfg(feature = "go")] +#[derive(Clone, Copy)] +enum Retain { + Unbound, + Directives, + Both, +} + +/// The expected document of one comment above a declaration other than the package +/// clause. +#[cfg(feature = "go")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: Some(DocumentRole::Primary), + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +/// The expected document of one comment above the package clause. +#[cfg(feature = "go")] +fn package_comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: None, + ..comment(fragment, text, map) + } +} + +/// The expected document of adjacent comments that join. +#[cfg(feature = "go")] +fn comment_run( + fragments: [Range; F], + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: Some(DocumentRole::Primary), + composition: Composition::CommentRun, + fragments: fragments.into(), + text: text.to_owned(), + map: map.into(), + } +} + +/// The expected view of documents in index order, each owned by the resolved node at +/// its position, with no retained candidate and no pending assessment. +#[cfg(feature = "go")] +fn owned_in_order( + documents: [Doc; N], + owners: [(&'static str, Range); N], +) -> View { + View { + documents: documents.into(), + owners: owners + .into_iter() + .map(|(kind, owner)| (Resolution::Resolved, kind, owner)) + .collect(), + ..View::default() + } +} + +#[cfg(feature = "go")] +fn owned(document: Doc, kind: &'static str, owner: Range) -> View { + owned_in_order([document], [(kind, owner)]) +} + +/// The byte range of a spelling that is one included piece, as every spelling here is. +#[cfg(feature = "go")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "go")] +fn run_of(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +/// The node that alone owns the association, as every owner here is. +#[cfg(feature = "go")] +fn owner_node<'s>( + facts: &Facts<'s>, + association: FactRef<'_, Association<'s>>, +) -> tree_sitter::Node<'s> { + assert_eq!(association.get().owner_count(), 1); + let owner = facts.associated_owner(association, 0).unwrap(); + let Owner::Node(declared) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + declared.node() +} + +#[cfg(feature = "go")] +fn published(index: &DocumentationIndex<'_>) -> View { + // bca: suppress(halstead) -- one flat reading of everything the index publishes, in the order of the view's fields. + let facts = index.facts(); + let documents = index + .documents() + .map(|document| { + let complete = index.complete_text(document).unwrap().unwrap(); + let owner_kind = index + .associations() + .find(|association| facts.associated_document(*association).unwrap() == document) + .map(|association| owner_node(facts, association).kind()); + Doc { + // The role of a package document is undecided, so the view holds none for it. + role: (owner_kind != Some("package_clause")).then(|| document.get().role()), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| { + let fragment = facts.document_fragment(document, at).unwrap(); + span(fragment.get().source()) + }) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|run| (run.output.range(), run_of(&run.origin))) + .collect(), + } + }) + .collect(); + let owners = index + .associations() + .map(|association| { + let attachment = association.get(); + let declaration = owner_node(facts, association); + // Both follow from the tree: the binding is the owner itself, and the lexical + // scope is the parent of the first comment of the document. + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declaration) + ); + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let first_comment = first.get().node().unwrap().node(); + assert_eq!( + Some(attachment.lexical_scope.node()), + first_comment.parent() + ); + ( + attachment.resolution, + declaration.kind(), + declaration.byte_range(), + ) + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, span(fragment.get().source())) + }) + .collect(); + View { + documents, + owners, + evidence, + assessments: index.assessments().len(), + } +} + +/// A parse in which no node below the root holds a syntax error, is an error node or is +/// missing. Whether the root holds an error is for the caller to assert. +#[cfg(feature = "go")] +fn parsed(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Go, source.to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + let flagged: Vec<_> = parser + .root_node() + .preorder() + .map(|found| found.as_tree_sitter()) + .filter(|found| { + *found != root && (found.has_error() || found.is_error() || found.is_missing()) + }) + .collect(); + assert!( + flagged.is_empty(), + "{flagged:?} in {}", + source.escape_ascii() + ); + parser +} + +/// A parse whose tree holds no syntax error. +#[cfg(feature = "go")] +fn clean(source: &[u8]) -> AnyParser { + let parser = parsed(source); + assert!(!parser.root_node().has_error(), "{}", source.escape_ascii()); + parser +} + +/// Both entry points over one parse: the typed parser's method, then `collect`. +#[cfg(feature = "go")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Go, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +/// The view that both entry points publish. +#[cfg(feature = "go")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2]) -> View { + let [typed, raw] = indexes.each_ref().map(published); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +/// The view of an error-free parse under the default options. +#[cfg(feature = "go")] +fn view(source: &[u8]) -> View { + agreed(&indexes(&clean(source), DocumentationOptions::default())) +} + +/// The view of an error-free parse that also keeps those candidates. +#[cfg(feature = "go")] +fn retained(source: &[u8], retain: Retain) -> View { + let options = DocumentationOptions { + retain_unbound: matches!(retain, Retain::Unbound | Retain::Both), + retain_directives: matches!(retain, Retain::Directives | Retain::Both), + ..DocumentationOptions::default() + }; + agreed(&indexes(&clean(source), options)) +} + +/// Asserts the view under the default options, and that the retention adds exactly that +/// candidate to it. For an empty default view, the candidate shows that the collector +/// saw the comment. +#[cfg(feature = "go")] +fn assert_default_then_retained( + source: &[u8], + mut expected: View, + retain: Retain, + candidate: (CandidateDisposition, Range), +) { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + expected.evidence.push(candidate); + assert_eq!( + retained(source, retain), + expected, + "{}", + source.escape_ascii() + ); +} + +/// The one node of that kind and byte range. +#[cfg(feature = "go")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|candidate| candidate.as_tree_sitter()) + .filter(|candidate| candidate.kind() == kind && candidate.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "go")] +fn named_in(parent: tree_sitter::Node<'_>) -> Vec> { + parent.named_children(&mut parent.walk()).collect() +} + +#[cfg(feature = "go")] +fn shapes(nodes: &[tree_sitter::Node<'_>]) -> Vec<(&'static str, Range)> { + nodes + .iter() + .map(|found| (found.kind(), found.byte_range())) + .collect() +} + +#[cfg(feature = "go")] +#[test] +fn go_declaration_kinds_own_the_comment_above_them() { + assert_eq!( + view(b"// audit\npackage p"), + owned( + package_comment(0..8, "audit", [(0..5, Copied(3..8))]), + "package_clause", + 9..18 + ) + ); + let declarations: [(&[u8], Doc, &str, Range); 5] = [ + ( + b"package p\n/* audit */\nfunc F() {}", + comment(10..21, "audit", [(0..5, Copied(13..18))]), + "function_declaration", + 22..33, + ), + ( + b"package p\ntype T int\n// audit\nfunc (t T) M() {}", + comment(21..29, "audit", [(0..5, Copied(24..29))]), + "method_declaration", + 30..47, + ), + ( + b"package p\n// audit\nconst C = 1", + comment(10..18, "audit", [(0..5, Copied(13..18))]), + "const_declaration", + 19..30, + ), + ( + b"package p\n// audit\ntype T struct{}\n", + comment(10..18, "audit", [(0..5, Copied(13..18))]), + "type_declaration", + 19..34, + ), + ( + b"package p\n// audit\ntype A = int\n", + comment(10..18, "audit", [(0..5, Copied(13..18))]), + "type_declaration", + 19..31, + ), + ]; + for (source, document, kind, owner) in declarations { + assert_eq!( + view(source), + owned(document, kind, owner), + "{}", + source.escape_ascii() + ); + } + + let parser = clean(b"package p\n// audit\nvar x, y int\n"); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both), + owned( + comment(10..18, "audit", [(0..5, Copied(13..18))]), + "var_declaration", + 19..31 + ) + ); + let declaration = node_at(&parser, "var_declaration", 19..31); + let spec = node_at(&parser, "var_spec", 23..31); + for index in &both { + for declared in [declaration, spec] { + let projection = index.node_projection(declared).unwrap(); + assert!(!projection.pending()); + let owners: Vec<_> = projection.owners().collect(); + let [owner] = owners[..] else { + panic!("one owner, found {owners:?}") + }; + let Owner::Node(itself) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + assert_eq!(itself.node(), declared); + } + let query = index.node_associations(declaration).unwrap(); + assert_eq!(query.associations().len(), 1); + assert!(!query.projection_pending()); + assert_eq!(query.assessments().count(), 0); + // The spec is an owner as well, and the comment above the declaration is not + // its document. + let query = index.node_associations(spec).unwrap(); + assert_eq!(query.associations().len(), 0); + assert_eq!(query.assessments().count(), 0); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_group_and_its_specs_have_separate_documents() { + assert_eq!( + view(b"package p\n// group\nvar (\n// member\nX int\n)\n"), + owned_in_order( + [ + comment(10..18, "group", [(0..5, Copied(13..18))]), + comment(25..34, "member", [(0..6, Copied(28..34))]), + ], + [("var_declaration", 19..42), ("var_spec", 35..40)] + ) + ); + assert_eq!( + view(b"package p\n// g\nconst (\n// m\nC, D = 1, 2\n)\n"), + owned_in_order( + [ + comment(10..14, "g", [(0..1, Copied(13..14))]), + comment(23..27, "m", [(0..1, Copied(26..27))]), + ], + [("const_declaration", 15..41), ("const_spec", 28..39)] + ) + ); + assert_eq!( + view(b"package p\n// h\ntype (\n// n\nT int\n// o\nU = int\n)\n"), + owned_in_order( + [ + comment(10..14, "h", [(0..1, Copied(13..14))]), + comment(22..26, "n", [(0..1, Copied(25..26))]), + comment(33..37, "o", [(0..1, Copied(36..37))]), + ], + [ + ("type_declaration", 15..47), + ("type_spec", 27..32), + ("type_alias", 38..45), + ] + ) + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_adjacent_comments_join_into_one_run() { + let runs: [(&[u8], Doc, Range); 3] = [ + ( + b"package p\n// a\n// b\nfunc F() {}", + comment_run( + [10..14, 15..19], + "a\nb", + [ + (0..1, Copied(13..14)), + (1..2, Synthetic), + (2..3, Copied(18..19)), + ], + ), + 20..31, + ), + ( + b"package p\n// a\n/* b */\n// c\nfunc F() {}", + comment_run( + [10..14, 15..22, 23..27], + "a\nb\nc", + [ + (0..1, Copied(13..14)), + (1..2, Synthetic), + (2..3, Copied(18..19)), + (3..4, Synthetic), + (4..5, Copied(26..27)), + ], + ), + 28..39, + ), + ( + b"package p\n/* a */ /* b */\nfunc F() {}", + comment_run( + [10..17, 18..25], + "a\nb", + [ + (0..1, Copied(13..14)), + (1..2, Synthetic), + (2..3, Copied(21..22)), + ], + ), + 26..37, + ), + ]; + for (source, document, owner) in runs { + assert_eq!( + view(source), + owned(document, "function_declaration", owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_empty_comment_row_stays_inside_the_run() { + assert_eq!( + view(b"package p\n// a\n//\n// c\nfunc F() {}"), + owned( + comment_run( + [10..14, 15..17, 18..22], + "a\n\nc", + [ + (0..1, Copied(13..14)), + (1..2, Synthetic), + (2..3, Synthetic), + (3..4, Copied(21..22)), + ] + ), + "function_declaration", + 23..34 + ) + ); + // At the start and at the end of a run, an empty row is a fragment that adds no text. + assert_eq!( + view(b"package p\n//\n// a\n//\nfunc F() {}"), + owned( + comment_run([10..12, 13..17, 18..20], "a", [(0..1, Copied(16..17))]), + "function_declaration", + 21..32 + ) + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_blank_source_row_detaches_a_run() { + // The comment at 10..14 is above a blank row and is in no document. + assert_default_then_retained( + b"package p\n// a\n\n// b\nfunc F() {}", + owned( + comment(16..20, "b", [(0..1, Copied(19..20))]), + "function_declaration", + 21..32, + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 10..14), + ); + assert_default_then_retained( + b"package p\n// a\n\nfunc F() {}", + View::default(), + Retain::Unbound, + (CandidateDisposition::Unattached, 10..14), + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_directive_rows_are_evidence_and_not_prose() { + // The directive at 19..37 is in no document. + assert_default_then_retained( + b"package p\n// audit\n//go:generate tool\nfunc F() {}", + owned( + comment(10..18, "audit", [(0..5, Copied(13..18))]), + "function_declaration", + 38..49, + ), + Retain::Directives, + (CandidateDisposition::Directive, 19..37), + ); + // A directive before, inside and after the prose, and a comment that only looks + // like one: `// go:generate` has a space after the marker. + let prose: [(&[u8], Doc, Range); 4] = [ + ( + b"package p\n//go:noinline\n// audit\nfunc F() {}", + comment(24..32, "audit", [(0..5, Copied(27..32))]), + 33..44, + ), + ( + b"package p\n// a\n//go:generate tool\n// b\nfunc F() {}", + comment_run( + [10..14, 34..38], + "a\nb", + [ + (0..1, Copied(13..14)), + (1..2, Synthetic), + (2..3, Copied(37..38)), + ], + ), + 39..50, + ), + ( + b"package p\n// audit\n//export F\nfunc F() {}", + comment(10..18, "audit", [(0..5, Copied(13..18))]), + 30..41, + ), + ( + b"package p\n// go:generate tool\nfunc F() {}", + comment(10..29, "go:generate tool", [(0..16, Copied(13..29))]), + 30..41, + ), + ]; + for (source, document, owner) in prose { + assert_eq!( + view(source), + owned(document, "function_declaration", owner), + "{}", + source.escape_ascii() + ); + } + // In the first source a blank row also separates the run from the package clause; + // its control sets both options. + let directives_alone: [(&[u8], Retain, Range); 3] = [ + (b"//go:build linux\n\npackage p", Retain::Both, 0..16), + (b"//go:generate tool\npackage p", Retain::Directives, 0..18), + ( + b"package p\n//go:noinline\nfunc F() {}", + Retain::Directives, + 10..23, + ), + ]; + for (source, retain, directive) in directives_alone { + assert_default_then_retained( + source, + View::default(), + retain, + (CandidateDisposition::Directive, directive), + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_trailing_comment_documents_nothing() { + // The comment at 20..24 follows code on its row and is in no document. + assert_default_then_retained( + b"package p\nvar x = 1 // t\nfunc F() {}", + View::default(), + Retain::Unbound, + (CandidateDisposition::Unattached, 20..24), + ); + assert_default_then_retained( + b"package p\nvar x = 1 // t\n// d\nfunc F() {}", + owned( + comment(25..29, "d", [(0..1, Copied(28..29))]), + "function_declaration", + 30..41, + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 20..24), + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_local_declaration_has_no_document_and_no_owner() { + let first_in_body = b"package p\nfunc F() {\n// local\nvar x = 1\n}"; + let parser = clean(first_in_body); + let both = indexes(&parser, DocumentationOptions::default()); + let mut expected = View::default(); + assert_eq!(agreed(&both), expected); + let locals = [ + node_at(&parser, "var_declaration", 30..39), + node_at(&parser, "var_spec", 34..39), + ]; + for index in &both { + for local in locals { + assert_eq!( + index.node_projection(local).err(), + Some(OwnerError::UnsupportedOwner), + "{}", + local.kind() + ); + } + } + expected + .evidence + .push((CandidateDisposition::Unattached, 21..29)); + assert_eq!(retained(first_in_body, Retain::Unbound), expected); + + let after_a_statement: [(&[u8], Range); 2] = [ + ( + b"package p\nfunc F() {\nx := 1\n// local\nvar y = x\n_ = y\n}", + 28..36, + ), + ( + b"package p\nfunc F() {\n_ = 0\n// local\ntype T int\n}", + 27..35, + ), + ]; + for (source, unattached) in after_a_statement { + assert_default_then_retained( + source, + View::default(), + Retain::Unbound, + (CandidateDisposition::Unattached, unattached), + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_import_has_no_document_and_no_owner() { + let single = b"package p\n// not doc\nimport \"fmt\""; + let parser = clean(single); + let both = indexes(&parser, DocumentationOptions::default()); + let mut expected = View::default(); + assert_eq!(agreed(&both), expected); + let imports = [ + node_at(&parser, "import_declaration", 21..33), + node_at(&parser, "import_spec", 28..33), + ]; + for index in &both { + for import in imports { + assert_eq!( + index.node_projection(import).err(), + Some(OwnerError::UnsupportedOwner), + "{}", + import.kind() + ); + } + } + expected + .evidence + .push((CandidateDisposition::Unattached, 10..20)); + assert_eq!(retained(single, Retain::Unbound), expected); + + assert_default_then_retained( + b"package p\nimport (\n// c\n\"fmt\"\n)", + View::default(), + Retain::Unbound, + (CandidateDisposition::Unattached, 19..23), + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_documents_of_one_file_stay_separate_and_in_source_order() { + assert_eq!( + view(b"// pkg\npackage p\n// fn\nfunc F() {}"), + owned_in_order( + [ + package_comment(0..6, "pkg", [(0..3, Copied(3..6))]), + comment(17..22, "fn", [(0..2, Copied(20..22))]), + ], + [("package_clause", 7..16), ("function_declaration", 23..34)] + ) + ); + assert_eq!( + view(b"package p\n// same\nfunc A() {}\n// same\nfunc B() {}"), + owned_in_order( + [ + comment(10..17, "same", [(0..4, Copied(13..17))]), + comment(30..37, "same", [(0..4, Copied(33..37))]), + ], + [ + ("function_declaration", 18..29), + ("function_declaration", 38..49), + ] + ) + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_fixture_function_owns_its_comment() { + let source = crate::test_support::documentation::source("primary.go"); + assert_eq!(source, b"package p\n// audit\nfunc F() {}"); + assert_eq!( + view(&source), + owned( + comment(10..18, "audit", [(0..5, Copied(13..18))]), + "function_declaration", + 19..30 + ) + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_line_endings_and_the_end_of_the_file() { + let documented: [(&[u8], Doc, Range); 4] = [ + ( + b"package p\r\n// a\r\n// b\r\nfunc F() {}\r\n", + comment_run( + [11..15, 17..21], + "a\nb", + [ + (0..1, Copied(14..15)), + (1..2, Synthetic), + (2..3, Copied(20..21)), + ], + ), + 23..34, + ), + ( + b"package p\r\n/* a\r\n b */\r\nfunc F() {}\r\n", + comment( + 11..24, + "a\n b", + [ + (0..1, Copied(14..15)), + (1..2, Decoded(15..17)), + (2..6, Copied(17..21)), + ], + ), + 26..37, + ), + ( + b"package p\r\n// a\r\n//\r\n// c\r\nfunc F() {}", + comment_run( + [11..15, 17..19, 21..25], + "a\n\nc", + [ + (0..1, Copied(14..15)), + (1..2, Synthetic), + (2..3, Synthetic), + (3..4, Copied(24..25)), + ], + ), + 27..38, + ), + ( + b"package p\r\n// audit\r\n//go:generate tool\r\nfunc F() {}", + comment(11..19, "audit", [(0..5, Copied(14..19))]), + 41..52, + ), + ]; + for (source, document, owner) in documented { + assert_eq!( + view(source), + owned(document, "function_declaration", owner), + "{}", + source.escape_ascii() + ); + } + assert_eq!( + view(b"// audit\npackage p\n"), + owned( + package_comment(0..8, "audit", [(0..5, Copied(3..8))]), + "package_clause", + 9..18 + ) + ); + // A CRLF blank row detaches the comment, and a comment at the end of the file has + // no declaration after it. + let undocumented: [(&[u8], Range); 2] = [ + (b"package p\r\n// a\r\n\r\nfunc F() {}", 11..15), + (b"package p\nfunc F() {}\n// tail", 22..29), + ]; + for (source, unattached) in undocumented { + assert_default_then_retained( + source, + View::default(), + Retain::Unbound, + (CandidateDisposition::Unattached, unattached), + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_text_cleanup_removes_only_the_markers_and_one_space() { + let comments: [(&[u8], Doc, Range); 7] = [ + ( + b"package p\n//audit\nfunc F() {}", + comment(10..17, "audit", [(0..5, Copied(12..17))]), + 18..29, + ), + ( + b"package p\n// audit\nfunc F() {}", + comment(10..19, " audit", [(0..6, Copied(13..19))]), + 20..31, + ), + ( + b"package p\n// audit \nfunc F() {}", + comment(10..20, "audit ", [(0..7, Copied(13..20))]), + 21..32, + ), + ( + b"package p\n/*audit*/\nfunc F() {}", + comment(10..19, "audit", [(0..5, Copied(12..17))]), + 20..31, + ), + ( + b"package p\n/* audit */\nfunc F() {}", + comment(10..23, " audit ", [(0..7, Copied(13..20))]), + 24..35, + ), + ( + b"package p\n/* a\n * b */\nfunc F() {}", + comment( + 10..22, + "a\n * b", + [ + (0..1, Copied(13..14)), + (1..2, Copied(14..15)), + (2..6, Copied(15..19)), + ], + ), + 23..34, + ), + ( + b"package p\n/*\naudit\n*/\nfunc F() {}", + comment(10..21, "audit", [(0..5, Copied(13..18))]), + 22..33, + ), + ]; + for (source, document, owner) in comments { + assert_eq!( + view(source), + owned(document, "function_declaration", owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_grammar_shapes_the_unit_relies_on() { + // A comment above a declaration is an extra child of the file, and the declaration + // is its next sibling. + let parser = clean(b"package p\n// audit\nfunc F() {}"); + let top = named_in(parser.ts_tree().root_node()); + assert_eq!( + shapes(&top), + [ + ("package_clause", 0..9), + ("comment", 10..18), + ("function_declaration", 19..30), + ] + ); + assert!(top[1].is_extra()); + assert_eq!(top[1].next_sibling(), Some(top[2])); + + // The specs of a `var` group and their comments are in a list node. + let parser = clean(b"package p\n// group\nvar (\n// member\nX int\n)\n"); + let group = named_in(node_at(&parser, "var_declaration", 19..42)); + assert_eq!(shapes(&group), [("var_spec_list", 23..42)]); + assert_eq!( + shapes(&named_in(group[0])), + [("comment", 25..34), ("var_spec", 35..40)] + ); + + // The specs of a `const` group and of a `type` group are directly under the + // declaration; there is no list node. + let parser = clean(b"package p\n// g\nconst (\n// m\nC, D = 1, 2\n)\n"); + assert_eq!( + shapes(&named_in(node_at(&parser, "const_declaration", 15..41))), + [("comment", 23..27), ("const_spec", 28..39)] + ); + let parser = clean(b"package p\n// h\ntype (\n// n\nT int\n// o\nU = int\n)\n"); + assert_eq!( + shapes(&named_in(node_at(&parser, "type_declaration", 15..47))), + [ + ("comment", 22..26), + ("type_spec", 27..32), + ("comment", 33..37), + ("type_alias", 38..45), + ] + ); + + // An ungrouped declaration holds its spec directly. + let parser = clean( + b"package p\n// t\ntype T struct{}\n// c\nconst C = 1\n// a\ntype A = int\n// v\nvar x, y int\n", + ); + let ungrouped: [(&str, Range, &str, Range); 4] = [ + ("type_declaration", 15..30, "type_spec", 20..30), + ("const_declaration", 36..47, "const_spec", 42..47), + ("type_declaration", 53..65, "type_alias", 58..65), + ("var_declaration", 71..83, "var_spec", 75..83), + ]; + for (kind, declaration, spec_kind, spec) in ungrouped { + assert_eq!( + shapes(&named_in(node_at(&parser, kind, declaration))), + [(spec_kind, spec)] + ); + } + + // The fields of a struct and their comments are in one list. A field with two + // names has two name nodes, and an embedded field has none. + let parser = clean(b"package p\ntype S struct {\n// both\nX, Y int\n// e\nio.Reader\n}\n"); + let fields = named_in(node_at(&parser, "field_declaration_list", 24..59)); + assert_eq!( + shapes(&fields), + [ + ("comment", 26..33), + ("field_declaration", 34..42), + ("comment", 43..47), + ("field_declaration", 48..57), + ] + ); + assert_eq!( + shapes(&named_in(fields[1])), + [ + ("field_identifier", 34..35), + ("field_identifier", 37..38), + ("type_identifier", 39..42), + ] + ); + assert_eq!(shapes(&named_in(fields[3])), [("qualified_type", 48..57)]); + + // The elements of an interface and their comments are directly under the interface + // type. An embedded name and a `~` element are both type elements. + let parser = + clean(b"package p\ntype I interface {\n// m\nM()\n// e\nio.Reader\n// u\n~int\n}\n"); + let elements = named_in(node_at(&parser, "interface_type", 17..64)); + assert_eq!( + shapes(&elements), + [ + ("comment", 29..33), + ("method_elem", 34..37), + ("comment", 38..42), + ("type_elem", 43..52), + ("comment", 53..57), + ("type_elem", 58..62), + ] + ); + assert_eq!(shapes(&named_in(elements[3])), [("qualified_type", 43..52)]); + assert_eq!(shapes(&named_in(elements[5])), [("negated_type", 58..62)]); + + // The first comment of a body is outside the statement list; a later one is inside. + let parser = clean(b"package p\nfunc F() {\n// first\nx := 1\n// local\nvar y = x\n_ = y\n}"); + let body = named_in(node_at(&parser, "block", 19..63)); + assert_eq!( + shapes(&body), + [("comment", 21..29), ("statement_list", 30..62)] + ); + assert_eq!( + shapes(&named_in(body[1])), + [ + ("short_var_declaration", 30..36), + ("comment", 37..45), + ("var_declaration", 46..55), + ("assignment_statement", 56..61), + ] + ); + + // A trailing comment, an empty comment row and the comment above a method are all + // children of the file, in source order. + let parser = clean(b"package p\nvar x = 1 // t\n//\n// d\nfunc (t T) M() {}"); + assert_eq!( + shapes(&named_in(parser.ts_tree().root_node())), + [ + ("package_clause", 0..9), + ("var_declaration", 10..19), + ("comment", 20..24), + ("comment", 25..27), + ("comment", 28..32), + ("method_declaration", 33..50), + ] + ); + + // The specs of an import group and their comments are in a list node. + let parser = clean(b"package p\nimport (\n// c\n\"fmt\"\n)"); + let imports = named_in(node_at(&parser, "import_declaration", 10..31)); + assert_eq!(shapes(&imports), [("import_spec_list", 17..31)]); + assert_eq!( + shapes(&named_in(imports[0])), + [("comment", 19..23), ("import_spec", 24..29)] + ); + + // With CRLF a line comment node includes the CR, and a block comment node ends at + // its `*/`. + let crlf = b"package p\r\n// a\r\n/* b\r\n c */\r\nfunc F() {}\r\n"; + let parser = clean(crlf); + let top = named_in(parser.ts_tree().root_node()); + assert_eq!( + shapes(&top), + [ + ("package_clause", 0..9), + ("comment", 11..16), + ("comment", 17..28), + ("function_declaration", 30..41), + ] + ); + assert_eq!(&crlf[top[1].byte_range()], b"// a\r"); + assert_eq!(&crlf[top[1].end_byte()..top[2].start_byte()], b"\n"); + assert_eq!(&crlf[top[2].end_byte()..top[3].start_byte()], b"\r\n"); + + // With LF a line comment node ends before the LF, and the root spans the final LF. + let lf = b"package p\n// a\n/* b\n c */\nfunc F() {}\n"; + let parser = clean(lf); + let root = parser.ts_tree().root_node(); + let top = named_in(root); + assert_eq!( + shapes(&top), + [ + ("package_clause", 0..9), + ("comment", 10..14), + ("comment", 15..25), + ("function_declaration", 26..37), + ] + ); + assert_eq!(&lf[top[1].end_byte()..top[2].start_byte()], b"\n"); + assert_eq!(&lf[top[2].end_byte()..top[3].start_byte()], b"\n"); + assert_eq!(root.byte_range(), 0..38); + assert_eq!(&lf[top[3].end_byte()..root.end_byte()], b"\n"); + + // A file that ends in a `type` declaration without a line ending has the same nodes + // as the file with one, and its root alone holds an error. + let ends: [(&[u8], bool); 2] = [ + (b"package p\ntype T int", true), + (b"package p\ntype T int\n", false), + ]; + for (source, root_error) in ends { + let parser = parsed(source); + let root = parser.ts_tree().root_node(); + assert_eq!(root.has_error(), root_error, "{}", source.escape_ascii()); + assert_eq!( + shapes(&named_in(root)), + [("package_clause", 0..9), ("type_declaration", 10..20)], + "{}", + source.escape_ascii() + ); + } +} diff --git a/utils/documentation-go-unit1-perturb.json b/utils/documentation-go-unit1-perturb.json new file mode 100644 index 000000000..73c2b0219 --- /dev/null +++ b/utils/documentation-go-unit1-perturb.json @@ -0,0 +1,119 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "go-positional-docs-off", + "file": "big-code-analysis-ast/src/checker/go.rs", + "old": "const SOURCE_POSITIONAL_DOCS: bool = true;", + "new": "const SOURCE_POSITIONAL_DOCS: bool = false;", + "expect": ["documentation::collector::go_tests::go_declaration_kinds_own_the_comment_above_them", "documentation::collector::go_tests::go_group_and_its_specs_have_separate_documents", "documentation::collector::go_tests::go_adjacent_comments_join_into_one_run", "documentation::collector::go_tests::go_empty_comment_row_stays_inside_the_run", "documentation::collector::go_tests::go_blank_source_row_detaches_a_run", "documentation::collector::go_tests::go_directive_rows_are_evidence_and_not_prose", "documentation::collector::go_tests::go_trailing_comment_documents_nothing", "documentation::collector::go_tests::go_local_declaration_has_no_document_and_no_owner", "documentation::collector::go_tests::go_import_has_no_document_and_no_owner", "documentation::collector::go_tests::go_documents_of_one_file_stay_separate_and_in_source_order", "documentation::collector::go_tests::go_fixture_function_owns_its_comment", "documentation::collector::go_tests::go_line_endings_and_the_end_of_the_file", "documentation::collector::go_tests::go_text_cleanup_removes_only_the_markers_and_one_space"] + }, + { + "name": "go-gated-kinds-not-targets", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " _ => outside_function_body_with_budget(node, ancestors, budget),", + "new": " _ => Ok(false),", + "expect": ["documentation::collector::go_tests::go_declaration_kinds_own_the_comment_above_them", "documentation::collector::go_tests::go_group_and_its_specs_have_separate_documents"] + }, + { + "name": "go-function-body-gate-open", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " Go::StatementList | Go::Block => 0,", + "new": " Go::StatementList | Go::Block => 1,", + "expect": ["documentation::collector::go_tests::go_local_declaration_has_no_document_and_no_owner"] + }, + { + "name": "go-empty-comment-row-ends-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " Ok(R::Checker::is_comment(next)\n && (next.start_row() <= comment.end_row()", + "new": " Ok(R::Checker::is_comment(next)\n && node_bytes(comment, code) != b\"//\"\n && (next.start_row() <= comment.end_row()", + "expect": ["documentation::collector::go_tests::go_empty_comment_row_stays_inside_the_run"] + }, + { + "name": "blank-row-keeps-target-below", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " && R::start_row(&next, budget)? == comment.end_row().saturating_add(1)", + "new": " && R::start_row(&next, budget)? >= comment.end_row().saturating_add(1)", + "expect": ["documentation::collector::go_tests::go_blank_source_row_detaches_a_run", "documentation::collector::go_tests::go_line_endings_and_the_end_of_the_file"] + }, + { + "name": "blank-row-continues-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " || (next.start_row() == comment.end_row().saturating_add(1)", + "new": " || (next.start_row() >= comment.end_row().saturating_add(1)", + "expect": ["documentation::collector::go_tests::go_blank_source_row_detaches_a_run"] + }, + { + "name": "go-colon-directive-not-recognized", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " && rest.get(word) == Some(&b':')", + "new": " && rest.get(word) == Some(&b';')", + "expect": ["documentation::collector::go_tests::go_directive_rows_are_evidence_and_not_prose", "documentation::collector::go_tests::go_line_endings_and_the_end_of_the_file"] + }, + { + "name": "trailing-comment-seeds-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " if prev.end_row() >= row_first.start_row() {", + "new": " if prev.end_row() > row_first.start_row() {", + "expect": ["documentation::collector::go_tests::go_trailing_comment_documents_nothing"] + }, + { + "name": "go-line-marker-three-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "(if profile == Profile::GoDoc { 2 } else { 3 }, 0, false)", + "new": "(if profile == Profile::GoDoc { 3 } else { 3 }, 0, false)", + "expect": ["documentation::collector::go_tests::go_text_cleanup_removes_only_the_markers_and_one_space"] + }, + { + "name": "go-block-marker-three-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "let prefix = if profile == Profile::GoDoc { 2 } else { 3 };", + "new": "let prefix = if profile == Profile::GoDoc { 3 } else { 3 };", + "expect": ["documentation::collector::go_tests::go_text_cleanup_removes_only_the_markers_and_one_space"] + }, + { + "name": "go-block-star-decoration-removed", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "if c_block && profile != Profile::GoDoc {", + "new": "if c_block {", + "expect": ["documentation::collector::go_tests::go_text_cleanup_removes_only_the_markers_and_one_space"] + }, + { + "name": "line-fragment-keeps-terminator", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": " if bytes.starts_with(b\"//\")\n || bytes.starts_with(b\"#\")", + "new": " if bytes.starts_with(b\"#\")", + "expect": ["documentation::collector::go_tests::go_line_endings_and_the_end_of_the_file"] + }, + { + "name": "go-import-is-a-target", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " PackageClause,\n", + "new": " PackageClause,\n ImportDeclaration,\n ImportSpec,\n", + "expect": ["documentation::collector::go_tests::go_import_has_no_document_and_no_owner"] + }, + { + "name": "same-row-comment-leaves-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " && (next.start_row() <= comment.end_row()", + "new": " && (next.start_row() < comment.end_row()", + "expect": ["documentation::collector::go_tests::go_adjacent_comments_join_into_one_run"] + }, + { + "name": "go-package-clause-not-a-target", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " PackageClause,\n", + "new": "", + "expect": ["documentation::collector::go_tests::go_declaration_kinds_own_the_comment_above_them", "documentation::collector::go_tests::go_directive_rows_are_evidence_and_not_prose", "documentation::collector::go_tests::go_documents_of_one_file_stay_separate_and_in_source_order", "documentation::collector::go_tests::go_line_endings_and_the_end_of_the_file"] + }, + { + "name": "go-function-not-a-target", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " FunctionDeclaration,\n", + "new": "", + "expect": ["documentation::collector::go_tests::go_declaration_kinds_own_the_comment_above_them", "documentation::collector::go_tests::go_adjacent_comments_join_into_one_run", "documentation::collector::go_tests::go_empty_comment_row_stays_inside_the_run", "documentation::collector::go_tests::go_blank_source_row_detaches_a_run", "documentation::collector::go_tests::go_directive_rows_are_evidence_and_not_prose", "documentation::collector::go_tests::go_trailing_comment_documents_nothing", "documentation::collector::go_tests::go_documents_of_one_file_stay_separate_and_in_source_order", "documentation::collector::go_tests::go_fixture_function_owns_its_comment", "documentation::collector::go_tests::go_line_endings_and_the_end_of_the_file", "documentation::collector::go_tests::go_text_cleanup_removes_only_the_markers_and_one_space"] + } + ] +} From 557d60b2cde0cc0d2c7e8fc43c83afd1e7457d2c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:11:56 -0800 Subject: [PATCH 074/221] test(documentation): pin Doxygen owners and text for the four C-family variants Add source-view tests for C, C++, Mozcpp and Objective-C. Each of the 38 sources is collected through `AnyParser::documentation` and through `documentation::collect`, and the test compares everything the index publishes: documents with their fragments, text and mappings, associations with their owners and binding, retained evidence and pending assessments. Four grammar tests pin the parse-tree shapes these cases rely on. No production code changes. `utils/documentation-c-family-unit1-perturb.json` holds 22 deliberate defects for `utils/perturb.py`. Every source-view test is named by at least one of them. Refs #1671 --- .../src/documentation/collector.rs | 2 + .../documentation/collector/c_family_tests.rs | 1246 +++++++++++++++++ .../documentation-c-family-unit1-perturb.json | 391 ++++++ 3 files changed, 1639 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/c_family_tests.rs create mode 100644 utils/documentation-c-family-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 751305a78..bffd70c16 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1002,6 +1002,8 @@ crate::observation::counter!(field_requests, cfg(any(test, feature = "test-suppo #[cfg(test)] mod assessment_tests; #[cfg(test)] +mod c_family_tests; +#[cfg(test)] mod cancellation_tests; #[cfg(test)] mod cost_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs b/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs new file mode 100644 index 000000000..df7390842 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs @@ -0,0 +1,1246 @@ +//! Doxygen documentation of C, C++, Mozcpp and Objective-C in the source view: what owns a +//! comment, the text of the document and where each part of that text comes from. The +//! source-view tests collect every source through both entry points and compare everything +//! the index publishes. The grammar tests collect nothing: they pin the parse-tree shapes +//! the source-view tests rely on. + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +use crate::documentation::*; +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +use crate::{AnyParser, LANG}; +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +use std::ops::Range; + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +use Run::{Copied, Synthetic}; + +/// The origin of one run of a document's text, with the source byte range it reads. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +/// One document: its fragments as source byte ranges, and each run of its text as an +/// output range with its origin. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +/// A node of the parse tree as its kind and byte range. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +type Site = (&'static str, Range); + +/// One owner of an association. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[derive(Debug, PartialEq, Eq)] +enum Holder { + Node(Site), + /// The byte range of the slot's name, and the node owner that encloses the slot. + Slot { + role: SlotRole, + ordinal: usize, + source: Range, + enclosing: Site, + }, + /// The byte range of the root. + File(Range), +} + +/// One association: the position of its document in the published order, its owners in +/// order, and the node it is bound to. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[derive(Debug, PartialEq, Eq)] +struct Link { + document: usize, + resolution: Resolution, + owners: Vec, + binding: Option, +} + +/// One pending assessment, with the position of its linked document in the published +/// order. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option, + document: Option, +} + +/// Everything one collection published. Documents, associations and retained candidates +/// are in published order, and a retained candidate is its disposition and byte range. +/// Pending assessments are in the order of `unordered`. The default value is an index +/// that published nothing and holds nothing pending. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +const NEEDS_PROJECTION: &str = "Recognized declaration requires a semantic projection"; +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +const AWAITS_OWNER: &str = "Selected local or wrapper form awaits owner projection"; + +/// The expected primary document of one comment. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +/// The expected `Field` slot of the declarator whose name is at `source`. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn field_slot(ordinal: usize, source: Range, enclosing: &Site) -> Holder { + Holder::Slot { + role: SlotRole::Field, + ordinal, + source, + enclosing: enclosing.clone(), + } +} + +/// The expected association of a document whose binding follows from its owners: the +/// node owner itself, or the node that encloses its slot owners. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn bound(document: usize, resolution: Resolution, owners: Vec) -> Link { + let binding = match owners.first() { + Some(Holder::Node(declared)) => declared.clone(), + Some(Holder::Slot { enclosing, .. }) => enclosing.clone(), + other => panic!("a node or slot owner, found {other:?}"), + }; + Link { + document, + resolution, + owners, + binding: Some(binding), + } +} + +/// The expected view of one document that `owners` own through one resolved association +/// bound as in `bound`, with no retained candidate and no pending assessment. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn owned(document: Doc, owners: Vec) -> View { + View { + documents: vec![document], + associations: vec![bound(0, Resolution::Resolved, owners)], + ..View::default() + } +} + +/// The expected pending assessment on the owner axis, the only axis these cases hold. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn pending(reason: &'static str, node: Option, document: Option) -> Pending { + Pending { + axis: AssessmentAxis::Owner, + reason, + node, + document, + } +} + +/// The pending assessments of a view, published or expected. The contract states no +/// order for assessments, so they are sorted by their debug text, and a comparison does +/// not depend on the order in which the index publishes them. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn unordered(assessments: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = assessments.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +/// The byte range of a spelling that is one included piece, as every spelling here is. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn run_of(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn site(found: tree_sitter::Node<'_>) -> Site { + (found.kind(), found.byte_range()) +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn holder<'s>( + facts: &Facts<'s>, + owner: FactRef<'_, Owner<'s>>, + root: tree_sitter::Node<'_>, +) -> Holder { + match owner.get() { + Owner::Node(declared) => Holder::Node(site(declared.node())), + Owner::Slot(slot) => { + let enclosing = facts.slot_enclosing(owner).unwrap(); + let Owner::Node(declared) = enclosing.get() else { + panic!("a slot inside a node owner, found {:?}", enclosing.get()) + }; + Holder::Slot { + role: slot.role, + ordinal: slot.ordinal, + source: span(&slot.source), + enclosing: site(declared.node()), + } + } + Owner::File(file) => { + assert_eq!(file.node(), root); + Holder::File(file.node().byte_range()) + } + other => panic!("a node, slot or file owner, found {other:?}"), + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let position = |document: FactRef<'_, Document<'_>>| { + ordered.iter().position(|known| *known == document).unwrap() + }; + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| { + let fragment = facts.document_fragment(document, at).unwrap().get(); + let range = span(fragment.source()); + // The same for every fragment here, so no expected view states it: + // the spelling is one whole comment node. + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|carrier| site(carrier.node())), + Some(("comment", range.clone())) + ); + range + }) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|run| (run.output.range(), run_of(&run.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .map(|association| { + let attachment = association.get(); + // The same for every association here, so no expected view states them. + assert_eq!(attachment.convention.name(), "Doxygen"); + assert_eq!(attachment.publication, Publication::Unknown); + // The lexical scope follows from the tree: it is the parent of the first + // comment of the document. + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let first_comment = first.get().node().unwrap().node(); + assert_eq!( + Some(attachment.lexical_scope.node()), + first_comment.parent() + ); + Link { + document: position(document), + resolution: attachment.resolution, + owners: (0..attachment.owner_count()) + .map(|at| { + let owner = facts.associated_owner(association, at).unwrap(); + holder(facts, owner, root) + }) + .collect(), + binding: attachment.binding.map(|wrapper| site(wrapper.node())), + } + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, span(fragment.get().source())) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|about| site(about.node())), + document: index.assessed_document(assessment).unwrap().map(position), + })); + View { + documents, + associations, + evidence, + assessments, + } +} + +/// A parse whose tree holds no syntax error. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn clean(language: LANG, source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!( + !parser.root_node().has_error(), + "{language:?}: {}", + source.escape_ascii() + ); + parser +} + +/// The view that both entry points publish for an error-free parse under the default +/// options: the typed parser's method, then `collect`. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn view(language: LANG, source: &[u8]) -> View { + let parser = clean(language, source); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let root = parser.ts_tree().root_node(); + let typed = published(&parser.documentation(&context, &options).unwrap(), root); + let raw = published( + &collect( + language, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + root, + ); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +/// The one node of that kind and byte range. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|candidate| candidate.as_tree_sitter()) + .filter(|candidate| candidate.kind() == kind && candidate.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +/// Every child of `parent` in order, named or not: its field name, kind and byte range. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static str, Range)> { + let mut cursor = parent.walk(); + let mut found = Vec::new(); + if cursor.goto_first_child() { + loop { + let child = cursor.node(); + found.push((cursor.field_name(), child.kind(), child.byte_range())); + if !cursor.goto_next_sibling() { + break; + } + } + } + found +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn named_parts(parent: tree_sitter::Node<'_>) -> Vec { + parent + .named_children(&mut parent.walk()) + .map(site) + .collect() +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn leading_block_documents_the_declaration_after_it(language: LANG) { + let rows: [(&[u8], Site); 7] = [ + ( + b"/** d */\nint f(void) { return 0; }\n", + ("function_definition", 9..34), + ), + (b"/** d */\nint f(void);\n", ("declaration", 9..21)), + (b"/** d */\ntypedef int T;\n", ("type_definition", 9..23)), + ( + b"/** d */\nstruct S { int a; };\n", + ("struct_specifier", 9..28), + ), + ( + b"/** d */\nunion U { int a; };\n", + ("union_specifier", 9..27), + ), + (b"/** d */\nenum E { A };\n", ("enum_specifier", 9..21)), + (b"/** d */\n#define M 1\n", ("preproc_def", 9..21)), + ]; + for (source, owner) in rows { + assert_eq!( + view(language, source), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + vec![Holder::Node(owner)] + ), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Objc); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn each_variable_declarator_owns_one_slot(language: LANG) { + let one = ("declaration", 9..15); + assert_eq!( + view(language, b"/** d */\nint x;\n"), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + vec![field_slot(0, 13..14, &one)] + ) + ); + let two = ("declaration", 11..20); + assert_eq!( + view(language, b"/**audit*/\nint a, b;\n"), + owned( + comment(0..10, "audit", [(0..5, Copied(3..8))]), + vec![field_slot(0, 15..16, &two), field_slot(1, 18..19, &two)] + ) + ); +} + +#[cfg(feature = "c")] +#[test] +fn c_each_variable_declarator_owns_one_slot() { + each_variable_declarator_owns_one_slot(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_each_variable_declarator_owns_one_slot() { + each_variable_declarator_owns_one_slot(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_each_variable_declarator_owns_one_slot() { + each_variable_declarator_owns_one_slot(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_each_variable_declarator_owns_one_slot() { + each_variable_declarator_owns_one_slot(LANG::Objc); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn enumerator_and_field_own_their_leading_block(language: LANG) { + assert_eq!( + view(language, b"enum E { /** la */ A, /** lb */ B };\n"), + View { + documents: vec![ + comment(9..18, "la", [(0..2, Copied(13..15))]), + comment(22..31, "lb", [(0..2, Copied(26..28))]), + ], + associations: vec![ + bound( + 0, + Resolution::Resolved, + vec![Holder::Node(("enumerator", 19..20))] + ), + bound( + 1, + Resolution::Resolved, + vec![Holder::Node(("enumerator", 32..33))] + ), + ], + ..View::default() + } + ); + let field = ("field_declaration", 24..30); + assert_eq!( + view(language, b"struct S {\n /** d */\n int x;\n};\n"), + owned( + comment(13..21, "d", [(0..1, Copied(17..18))]), + vec![field_slot(0, 28..29, &field)] + ) + ); +} + +#[cfg(feature = "c")] +#[test] +fn c_enumerator_and_field_own_their_leading_block() { + enumerator_and_field_own_their_leading_block(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_enumerator_and_field_own_their_leading_block() { + enumerator_and_field_own_their_leading_block(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_enumerator_and_field_own_their_leading_block() { + enumerator_and_field_own_their_leading_block(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_enumerator_and_field_own_their_leading_block() { + enumerator_and_field_own_their_leading_block(LANG::Objc); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn trailing_block_documents_the_member_before_it(language: LANG) { + let field = ("field_declaration", 11..17); + assert_eq!( + view(language, b"struct S { int x; ///, Vec); 2] = [ + (b"/** @file */\nint x;\n", 0..20, vec![]), + ( + b"/** @file */\n#ifndef G_H\n#define G_H\nint x;\n#endif\n", + 0..51, + // The assessment on the include guard is pending work, pinned as it is today. + vec![pending( + NEEDS_PROJECTION, + Some(("preproc_ifdef", 13..50)), + None, + )], + ), + ]; + for (source, file, assessments) in rows { + assert_eq!( + view(language, source), + View { + documents: vec![Doc { + role: DocumentRole::FilePackage, + ..comment(0..12, "@file", [(0..5, Copied(4..9))]) + }], + // The file owns the document, and no node binds it. + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::File(file)], + binding: None, + }], + assessments: unordered(assessments), + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_file_command_documents_the_file() { + file_command_documents_the_file(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_file_command_documents_the_file() { + file_command_documents_the_file(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_file_command_documents_the_file() { + file_command_documents_the_file(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_file_command_documents_the_file() { + file_command_documents_the_file(LANG::Objc); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn fn_command_resolves_by_signature(language: LANG) { + // The prototype that the signature names owns the document, and no node binds it. + assert_eq!( + view( + language, + b"/**@fn void f(void)\n * audit*/\nvoid f(void);\n" + ), + View { + documents: vec![comment( + 0..30, + "@fn void f(void)\naudit", + [ + (0..16, Copied(3..19)), + (16..17, Copied(19..20)), + (17..22, Copied(23..28)), + ] + )], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::Node(("declaration", 31..44))], + binding: None, + }], + ..View::default() + } + ); + // No declaration has the name, so the association lists no owner. + assert_eq!( + view( + language, + b"/**@fn void missing(void)\n * audit*/\nvoid f(void);\n" + ), + View { + documents: vec![comment( + 0..36, + "@fn void missing(void)\naudit", + [ + (0..22, Copied(3..25)), + (22..23, Copied(25..26)), + (23..28, Copied(29..34)), + ] + )], + associations: vec![Link { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::MissingName), + owners: vec![], + binding: None, + }], + ..View::default() + } + ); +} + +#[cfg(feature = "c")] +#[test] +fn c_fn_command_resolves_by_signature() { + fn_command_resolves_by_signature(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_fn_command_resolves_by_signature() { + fn_command_resolves_by_signature(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_fn_command_resolves_by_signature() { + fn_command_resolves_by_signature(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_fn_command_resolves_by_signature() { + fn_command_resolves_by_signature(LANG::Objc); +} + +#[cfg(any(feature = "cpp", feature = "mozcpp"))] +fn class_member_function_namespace_and_alias_own_their_block(language: LANG) { + let rows: [(&[u8], Doc, Site); 5] = [ + ( + b"/** c */\nclass C { };\n", + comment(0..8, "c", [(0..1, Copied(4..5))]), + ("class_specifier", 9..20), + ), + ( + b"class C {\n /** m */\n void m();\n};\n", + comment(12..20, "m", [(0..1, Copied(16..17))]), + ("field_declaration", 23..32), + ), + ( + b"class C {\n /** m */\n void m() { }\n};\n", + comment(12..20, "m", [(0..1, Copied(16..17))]), + ("function_definition", 23..35), + ), + ( + b"/** n */\nnamespace N { }\n", + comment(0..8, "n", [(0..1, Copied(4..5))]), + ("namespace_definition", 9..24), + ), + ( + b"/** a */\nusing T = int;\n", + comment(0..8, "a", [(0..1, Copied(4..5))]), + ("alias_declaration", 9..23), + ), + ]; + for (source, document, owner) in rows { + assert_eq!( + view(language, source), + owned(document, vec![Holder::Node(owner)]), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "cpp")] +#[test] +fn cpp_class_member_function_namespace_and_alias_own_their_block() { + class_member_function_namespace_and_alias_own_their_block(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_class_member_function_namespace_and_alias_own_their_block() { + class_member_function_namespace_and_alias_own_their_block(LANG::Mozcpp); +} + +#[cfg(feature = "objc")] +#[test] +fn objc_interface_property_method_and_instance_variable_own_their_block() { + let rows: [(&[u8], Doc, Site); 4] = [ + ( + b"/** i */\n@interface C\n@end\n", + comment(0..8, "i", [(0..1, Copied(4..5))]), + ("class_interface", 9..26), + ), + ( + b"@interface C\n/** p */\n@property int p;\n@end\n", + comment(13..21, "p", [(0..1, Copied(17..18))]), + ("property_declaration", 22..38), + ), + ( + b"@interface C\n/**audit*/\n- (void)f;\n@end\n", + comment(13..23, "audit", [(0..5, Copied(16..21))]), + ("method_declaration", 24..34), + ), + ( + b"@interface C {\n /** v */\n int v;\n}\n@end\n", + comment(17..25, "v", [(0..1, Copied(21..22))]), + ("instance_variable", 28..34), + ), + ]; + for (source, document, owner) in rows { + assert_eq!( + view(LANG::Objc, source), + owned(document, vec![Holder::Node(owner)]), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn comment_forms_are_cleaned_to_their_text(language: LANG) { + let rows: [(&[u8], Doc, Site); 5] = [ + ( + b"/*! d */\nint f(void);\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("declaration", 9..21), + ), + ( + b"/// d\nint f(void);\n", + comment(0..5, "d", [(0..1, Copied(4..5))]), + ("declaration", 6..18), + ), + ( + b"//! d\nint f(void);\n", + comment(0..5, "d", [(0..1, Copied(4..5))]), + ("declaration", 6..18), + ), + ( + b"/// a\n/// b\nint f(void);\n", + Doc { + role: DocumentRole::Primary, + composition: Composition::CommentRun, + fragments: vec![0..5, 6..11], + text: "a\nb".to_owned(), + map: vec![ + (0..1, Copied(4..5)), + (1..2, Synthetic), + (2..3, Copied(10..11)), + ], + }, + ("declaration", 12..24), + ), + ( + b"/**\n * a\n * b\n */\nint f(void);\n", + comment( + 0..17, + "a\nb", + [ + (0..1, Copied(7..8)), + (1..2, Copied(8..9)), + (2..3, Copied(12..13)), + ], + ), + ("declaration", 18..30), + ), + ]; + for (source, document, owner) in rows { + assert_eq!( + view(language, source), + owned(document, vec![Holder::Node(owner)]), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_comment_forms_are_cleaned_to_their_text() { + comment_forms_are_cleaned_to_their_text(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_comment_forms_are_cleaned_to_their_text() { + comment_forms_are_cleaned_to_their_text(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_comment_forms_are_cleaned_to_their_text() { + comment_forms_are_cleaned_to_their_text(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_comment_forms_are_cleaned_to_their_text() { + comment_forms_are_cleaned_to_their_text(LANG::Objc); +} + +// These outcomes are pinned as they are today. Later units of issue 1671 change them on +// purpose, so this test is expected to move with them. +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn positions_without_a_resolved_owner_keep_their_outcome(language: LANG) { + let conditional = ("preproc_if", 9..55); + assert_eq!( + view( + language, + b"/** d */\n#if A\nvoid f(void);\n#else\nvoid g(void);\n#endif\n" + ), + View { + documents: vec![comment(0..8, "d", [(0..1, Copied(4..5))])], + // Today no branch declaration is listed as an owner, and the conditional is the + // binding. + associations: vec![Link { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::Conditional), + owners: vec![], + binding: Some(conditional.clone()), + }], + assessments: unordered([ + pending(AWAITS_OWNER, Some(conditional.clone()), Some(0)), + pending(NEEDS_PROJECTION, Some(conditional), None), + pending(NEEDS_PROJECTION, Some(("preproc_else", 29..48)), None), + ]), + ..View::default() + } + ); + assert_eq!( + view(language, b"int f(void) {\n /** note */\n return 0;\n}\n"), + View { + documents: vec![comment(16..27, "note", [(0..4, Copied(20..24))])], + assessments: unordered([pending( + "Exact named matching awaits supported signature grammar", + None, + Some(0) + )]), + ..View::default() + } + ); + assert_eq!( + view(language, b"int a, /**< ta */ b;\n"), + View { + documents: vec![comment(7..17, "ta", [(0..2, Copied(12..14))])], + assessments: unordered([pending(AWAITS_OWNER, Some((",", 5..6)), Some(0))]), + ..View::default() + } + ); + // Today the candidate inside an include guard is listed, as an uncertain one. + assert_eq!( + view( + language, + b"#ifndef G_H\n#define G_H\n/** d */\nint f(void);\n#endif\n" + ), + View { + documents: vec![comment(24..32, "d", [(0..1, Copied(28..29))])], + associations: vec![bound( + 0, + Resolution::Unresolved(UnresolvedReason::Conditional), + vec![Holder::Node(("declaration", 33..45))] + )], + assessments: unordered([pending( + NEEDS_PROJECTION, + Some(("preproc_ifdef", 0..52)), + None + )]), + ..View::default() + } + ); + let variable = ("declaration", 33..39); + assert_eq!( + view( + language, + b"#ifndef G_H\n#define G_H\n/** d */\nint x;\n#endif\n" + ), + View { + documents: vec![comment(24..32, "d", [(0..1, Copied(28..29))])], + associations: vec![bound( + 0, + Resolution::Unresolved(UnresolvedReason::Conditional), + vec![field_slot(0, 37..38, &variable)] + )], + assessments: unordered([pending( + NEEDS_PROJECTION, + Some(("preproc_ifdef", 0..46)), + None + )]), + ..View::default() + } + ); +} + +#[cfg(feature = "c")] +#[test] +fn c_positions_without_a_resolved_owner_keep_their_outcome() { + positions_without_a_resolved_owner_keep_their_outcome(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_positions_without_a_resolved_owner_keep_their_outcome() { + positions_without_a_resolved_owner_keep_their_outcome(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_positions_without_a_resolved_owner_keep_their_outcome() { + positions_without_a_resolved_owner_keep_their_outcome(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_positions_without_a_resolved_owner_keep_their_outcome() { + positions_without_a_resolved_owner_keep_their_outcome(LANG::Objc); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[allow(clippy::too_many_lines)] +fn grammar_shapes_the_unit_relies_on(language: LANG) { + // Each declarator name is a `declarator` child of the declaration, and the comma + // between two names is an unnamed child. + let parser = clean(language, b"int a, b;\n"); + let declaration = node_at(&parser, "declaration", 0..9); + assert_eq!( + parts(declaration), + [ + (Some("type"), "primitive_type", 0..3), + (Some("declarator"), "identifier", 4..5), + (None, ",", 5..6), + (Some("declarator"), "identifier", 7..8), + (None, ";", 8..9), + ] + ); + let comma = node_at(&parser, "identifier", 4..5).next_sibling().unwrap(); + assert_eq!(site(comma), (",", 5..6)); + assert!(!comma.is_named()); + + // A prototype is a declaration whose declarator is a function declarator. + let parser = clean(language, b"int f(void);\n"); + let declaration = node_at(&parser, "declaration", 0..12); + let function = declaration.child_by_field_name("declarator").unwrap(); + assert_eq!(site(function), ("function_declarator", 4..11)); + assert_eq!( + function.child_by_field_name("declarator").map(site), + Some(("identifier", 4..5)) + ); + + // A struct ends before its `;`. A field holds its `;`, and a comment after the field + // is its next sibling and ends before the line feed. + let source = b"struct S { int x; /// 1;", + "new": " let signatures = false;", + "expect": [ + "documentation::collector::c_family_tests::c_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::cpp_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::mozcpp_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::objc_fn_command_resolves_by_signature" + ] + }, + { + "name": "fn-command-not-resolved", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " if command != b\"fn\" {", + "new": " if command == b\"fn\" {", + "expect": [ + "documentation::collector::c_family_tests::c_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::cpp_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::mozcpp_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::objc_fn_command_resolves_by_signature" + ] + }, + { + "name": "inherited-conditional-qualification-dropped", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " if conditional_kind(node.kind()) {\n record.qualification.insert(UnresolvedReason::Conditional);", + "new": " if false {\n record.qualification.insert(UnresolvedReason::Conditional);", + "expect": [ + "documentation::collector::c_family_tests::c_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::cpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::mozcpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::objc_positions_without_a_resolved_owner_keep_their_outcome" + ] + }, + { + "name": "conditional-target-uncertainty-dropped", + "file": "big-code-analysis-ast/src/checker/doxygen_doc_binding.rs", + "old": " Some(UnresolvedReason::Conditional)", + "new": " None", + "expect": [ + "documentation::collector::c_family_tests::c_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::cpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::mozcpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::objc_positions_without_a_resolved_owner_keep_their_outcome" + ] + }, + { + "name": "conditional-is-not-a-doc-target", + "file": "big-code-analysis-ast/src/lang_helpers/doxygen.rs", + "old": " if preproc_conditional::(node) {\n return conditional_declares_with_budget::(node, ancestors, budget);\n }", + "new": " if preproc_conditional::(node) {\n return Ok(false);\n }", + "expect": [ + "documentation::collector::c_family_tests::c_file_command_documents_the_file", + "documentation::collector::c_family_tests::cpp_file_command_documents_the_file", + "documentation::collector::c_family_tests::mozcpp_file_command_documents_the_file", + "documentation::collector::c_family_tests::objc_file_command_documents_the_file", + "documentation::collector::c_family_tests::c_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::cpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::mozcpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::objc_positions_without_a_resolved_owner_keep_their_outcome" + ] + }, + { + "name": "conditional-pending-assessment-dropped", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " if matches!(\n self.index.canonical.nodes[id].projection,\n Projection::Pending\n ) {", + "new": " if matches!(\n self.index.canonical.nodes[id].projection,\n Projection::Pending\n ) && !conditional_kind(self.index.canonical.nodes[id].evidence.node().kind())\n {", + "expect": [ + "documentation::collector::c_family_tests::c_file_command_documents_the_file", + "documentation::collector::c_family_tests::cpp_file_command_documents_the_file", + "documentation::collector::c_family_tests::mozcpp_file_command_documents_the_file", + "documentation::collector::c_family_tests::objc_file_command_documents_the_file", + "documentation::collector::c_family_tests::c_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::cpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::mozcpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::objc_positions_without_a_resolved_owner_keep_their_outcome" + ] + }, + { + "name": "block-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start = star + 1;", + "new": " line.content.start = star;", + "expect": [ + "documentation::collector::c_family_tests::c_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::cpp_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::mozcpp_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::objc_fn_command_resolves_by_signature", + "documentation::collector::c_family_tests::c_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::cpp_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::mozcpp_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::objc_comment_forms_are_cleaned_to_their_text" + ] + }, + { + "name": "line-comment-prefix-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "(if profile == Profile::GoDoc { 2 } else { 3 }, 0, false)", + "new": "(if profile == Profile::GoDoc { 2 } else { 2 }, 0, false)", + "expect": [ + "documentation::collector::c_family_tests::c_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::cpp_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::mozcpp_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::objc_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::c_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::cpp_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::mozcpp_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::objc_comment_forms_are_cleaned_to_their_text" + ] + }, + { + "name": "local-block-targets-its-scope", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " _ => draft.pending = true,", + "new": " _ => draft.target = Some(draft.scope),", + "expect": [ + "documentation::collector::c_family_tests::c_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::cpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::mozcpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::objc_positions_without_a_resolved_owner_keep_their_outcome" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::c_family_tests::c_leading_block_documents_the_declaration_after_it", + "documentation::collector::c_family_tests::cpp_leading_block_documents_the_declaration_after_it", + "documentation::collector::c_family_tests::mozcpp_leading_block_documents_the_declaration_after_it", + "documentation::collector::c_family_tests::objc_leading_block_documents_the_declaration_after_it", + "documentation::collector::c_family_tests::c_each_variable_declarator_owns_one_slot", + "documentation::collector::c_family_tests::cpp_each_variable_declarator_owns_one_slot", + "documentation::collector::c_family_tests::mozcpp_each_variable_declarator_owns_one_slot", + "documentation::collector::c_family_tests::objc_each_variable_declarator_owns_one_slot", + "documentation::collector::c_family_tests::c_enumerator_and_field_own_their_leading_block", + "documentation::collector::c_family_tests::cpp_enumerator_and_field_own_their_leading_block", + "documentation::collector::c_family_tests::mozcpp_enumerator_and_field_own_their_leading_block", + "documentation::collector::c_family_tests::objc_enumerator_and_field_own_their_leading_block", + "documentation::collector::c_family_tests::c_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::cpp_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::mozcpp_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::objc_trailing_block_documents_the_member_before_it", + "documentation::collector::c_family_tests::c_file_command_documents_the_file", + "documentation::collector::c_family_tests::cpp_file_command_documents_the_file", + "documentation::collector::c_family_tests::mozcpp_file_command_documents_the_file", + "documentation::collector::c_family_tests::objc_file_command_documents_the_file", + "documentation::collector::c_family_tests::cpp_class_member_function_namespace_and_alias_own_their_block", + "documentation::collector::c_family_tests::mozcpp_class_member_function_namespace_and_alias_own_their_block", + "documentation::collector::c_family_tests::objc_interface_property_method_and_instance_variable_own_their_block", + "documentation::collector::c_family_tests::c_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::cpp_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::mozcpp_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::objc_comment_forms_are_cleaned_to_their_text", + "documentation::collector::c_family_tests::c_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::cpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::mozcpp_positions_without_a_resolved_owner_keep_their_outcome", + "documentation::collector::c_family_tests::objc_positions_without_a_resolved_owner_keep_their_outcome" + ] + } + ] +} \ No newline at end of file From 11f301ab53837d652cdce0c129300e5c9711ae6a Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:23:14 -0800 Subject: [PATCH 075/221] test(loc): guard C-family documentation rows before owner and conditional work Add one root-crate test over 15 sources in the C, C++, Mozcpp and Objective-C variants they parse in, 47 rows. It pins the LOC tuple and the DLOC rows of each row and asserts that `analyze` moves none of the collector's visit, render and evidence counters. A collection on the same thread first moves each counter by an exact amount, so the zero is a reading. No production code changes. `utils/documentation-c-family-unit1-legacy-perturb.json` holds two deliberate defects that change a pinned row. Refs #1671 --- src/metrics/loc/documentation_tests.rs | 166 ++++++++++++++++++ ...ntation-c-family-unit1-legacy-perturb.json | 33 ++++ 2 files changed, 199 insertions(+) create mode 100644 utils/documentation-c-family-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index fe2373794..4dc3d22a9 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -592,3 +592,169 @@ fn documentation_csharp_source_and_legacy_views_are_independent() { ); } } + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_c_family_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + /// One source: the variants it runs in, its bytes, its LOC tuple and its DLOC rows. + type Case<'a> = (&'a [LANG], &'a [u8], [u64; 6], &'a [usize]); + const ALL: &[LANG] = &[LANG::C, LANG::Cpp, LANG::Mozcpp, LANG::Objc]; + const CXX: &[LANG] = &[LANG::Cpp, LANG::Mozcpp]; + let primary_c = documentation::source("primary.c"); + let primary_cpp = documentation::source("primary.cpp"); + let primary_m = documentation::source("primary.m"); + let sources: [Case<'_>; 15] = [ + (ALL, b"/**audit*/\nint a, b;\n", [2, 1, 1, 1, 0, 1], &[0]), + ( + ALL, + b"#ifndef G_H\n#define G_H\n/** d */\nint f(void);\n#endif\n", + [5, 4, 1, 1, 0, 1], + &[2], + ), + ( + ALL, + b"/** d */\n#if A\nvoid f(void);\n#else\nvoid g(void);\n#endif\n", + [6, 5, 2, 1, 0, 1], + &[0], + ), + ( + ALL, + b"enum E {\n A, /**< ta */\n B /**< tb */\n};\n", + [4, 4, 0, 2, 0, 2], + &[1, 2], + ), + ( + ALL, + b"/** d */\nextern \"C\" {\nint f(void);\n}\n", + [4, 3, 1, 1, 0, 1], + &[0], + ), + ( + CXX, + b"/** d */\ntemplate class X {};\n", + [2, 1, 0, 1, 0, 1], + &[0], + ), + ( + ALL, + b"int f(void) {\n /** note */\n return 0;\n}\n", + [4, 3, 1, 1, 0, 1], + &[1], + ), + (ALL, b"int a, /**< ta */ b;\n", [1, 1, 1, 1, 0, 1], &[0]), + (ALL, b"/** @file */\nint x;\n", [2, 1, 1, 1, 0, 1], &[0]), + ( + ALL, + b"struct S { int x; ///(), + "{name}" + ); + // The collection moves each counter on this thread, so a zero across `analyze` + // is a reading. + assert_ne!(visited, 0, "{name}"); + assert_ne!(rendered, 0, "{name}"); + assert_ne!(members, 0, "{name}"); + let space = analyze( + Source::new(lang, source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let after = observations(); + // expected: 0 for each. `analyze` takes its documentation rows from the legacy + // scan and does not run the collector. + assert_eq!(after.visits - before.visits, 0, "{name}"); + assert_eq!(after.renders - before.renders, 0, "{name}"); + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + tuple, + "{name}" + ); + assert_eq!( + (0..source.len()) + .filter(|row| loc.dloc.lines.contains(*row)) + .collect::>(), + rows, + "{name}" + ); + } + } + assert!(ran > 0); +} diff --git a/utils/documentation-c-family-unit1-legacy-perturb.json b/utils/documentation-c-family-unit1-legacy-perturb.json new file mode 100644 index 000000000..761dcfcb5 --- /dev/null +++ b/utils/documentation-c-family-unit1-legacy-perturb.json @@ -0,0 +1,33 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis", + "--all-features", + "--lib", + "documentation_c_family_source_and_legacy_views_are_independent" + ], + "cases": [ + { + "name": "objc-method-declaration-not-a-target", + "file": "big-code-analysis-ast/src/roles/objc.rs", + "old": " MethodDeclaration,\n MethodDefinition,", + "new": " MethodDefinition,", + "expect": [ + "metrics::loc::documentation_tests::documentation_c_family_source_and_legacy_views_are_independent" + ] + }, + { + "name": "conditional-is-not-a-doc-target", + "file": "big-code-analysis-ast/src/lang_helpers/doxygen.rs", + "old": " if preproc_conditional::(node) {\n return conditional_declares_with_budget::(node, ancestors, budget);\n }", + "new": " if preproc_conditional::(node) {\n return Ok(false);\n }", + "expect": [ + "metrics::loc::documentation_tests::documentation_c_family_source_and_legacy_views_are_independent" + ] + } + ] +} \ No newline at end of file From dccae50ee21e7b1ab4865100adc9db51e4d75bd8 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:27:27 -0800 Subject: [PATCH 076/221] test(loc): guard Go documentation rows before field and group owner work For twelve Go sources, among them struct fields, interface elements, a group with a member comment, directive rows, a trailing block comment and the fixture, collect documentation once and then assert the exact LOC tuple and DLOC rows of `analyze`. Six counters are read around both steps. During the collection, visits, renders, built evidence and materialized members are compared with values read from the tree and the index, and the scanned comment runs with the number pinned for the source; the count of included-range questions is only required to move. Across `analyze` none of them moves except the scan of the comment runs, which the legacy view repeats once per run. Add a second perturbation manifest for this test, because the first one's command runs the AST crate only: three deliberate defects that each change a pinned tuple and DLOC row. No production code changes. Refs #1672 --- src/metrics/loc/documentation_tests.rs | 203 ++++++++++++++++++ ...documentation-go-unit1-legacy-perturb.json | 28 +++ 2 files changed, 231 insertions(+) create mode 100644 utils/documentation-go-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index fe2373794..013418867 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -592,3 +592,206 @@ fn documentation_csharp_source_and_legacy_views_are_independent() { ); } } + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_go_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::positional::{ + evidence_built, members_materialized, positional_runs_collected, + }; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, included_range_visits, observations, + }; + struct Row<'a> { + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + // A run is a maximal sequence of comments in which each one starts on the row + // where the one before it ends, or on the next row. + comment_runs: usize, + } + let counters = || { + [ + observations().visits, + observations().renders, + evidence_built::observed(), + members_materialized::observed(), + positional_runs_collected::observed(), + included_range_visits::observed(), + ] + }; + let fixture = documentation::source("primary.go"); + let sources = [ + Row { + source: b"package p\ntype S struct {\n// both\nX, Y int\n}\n", + loc: [5, 4, 0, 1, 0, 1], + dloc_rows: &[2], + comment_runs: 1, + }, + // Code separates the three comments. + Row { + source: b"package p\ntype I interface {\n// m\nM()\n// e\nio.Reader\n// u\n~int\n}\n", + loc: [9, 6, 0, 3, 0, 2], + dloc_rows: &[2, 4], + comment_runs: 3, + }, + // `var (` separates the two comments. + Row { + source: b"package p\n// group\nvar (\n// member\nX int\n)\n", + loc: [6, 4, 1, 2, 0, 2], + dloc_rows: &[1, 3], + comment_runs: 2, + }, + Row { + source: b"package p\n// audit\n//go:generate tool\nfunc F() {}\n", + loc: [4, 2, 0, 2, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + Row { + source: b"package p\ntype S struct {\n//go:notinheap\n// audit\nX int\n}\n", + loc: [6, 4, 0, 2, 0, 1], + dloc_rows: &[3], + comment_runs: 1, + }, + // Three comments on rows 1 to 3: the second starts where the first ends. + Row { + source: b"package p\nvar y = 0 /* t1\nt2 */ /* t3 */\n// doc\nvar z = 1\n", + loc: [5, 3, 2, 3, 0, 1], + dloc_rows: &[3], + comment_runs: 1, + }, + // A blank row separates the first comment from the other three. + Row { + source: b"package p\n// a\n\n// b\n//\n// c\nfunc F() {}\n", + loc: [7, 2, 0, 4, 1, 3], + dloc_rows: &[3, 4, 5], + comment_runs: 2, + }, + // `N struct {` separates the two comments. + Row { + source: b"package p\ntype S struct {\n// same\nN struct {\n// same\nX, Y int\n}\n}\n", + loc: [8, 6, 0, 2, 0, 2], + dloc_rows: &[2, 4], + comment_runs: 2, + }, + Row { + source: b"package p\ntype S struct { // t\n// d\nX int\n}\n", + loc: [5, 4, 0, 2, 0, 1], + dloc_rows: &[2], + comment_runs: 1, + }, + Row { + source: b"package p\nfunc F() {\nx := 1\n// local\nvar y = x\n_ = y\n}\n", + loc: [7, 6, 3, 1, 0, 0], + dloc_rows: &[], + comment_runs: 1, + }, + Row { + source: b"package p\n// not doc\nimport \"fmt\"\n", + loc: [3, 2, 0, 1, 0, 0], + dloc_rows: &[], + comment_runs: 1, + }, + Row { + source: &fixture, + loc: [3, 2, 0, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + ]; + for row in sources { + let name = row.source.escape_ascii(); + let parser = + crate::langs::AnyParser::parse(LANG::Go, row.source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error(), "{name}"); + let idle = counters(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let collected = counters(); + let space = analyze( + Source::new(LANG::Go, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = counters(); + + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + + // The collection moves each counter on this thread, so a zero across `analyze` is + // a reading. + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| collected[at] - idle[at]); + // expected: the walk enters every node of the tree once. + assert_eq!(visits, parser.root_node().preorder().count(), "{name}"); + // expected: one render per published document. + assert_eq!(renders, index.documents().len(), "{name}"); + // expected: under default options the positional stream builds one member for + // each fragment of a selected run, and none for a directive or a trailing member. + let fragments: usize = index + .documents() + .map(|document| document.get().fragment_count()) + .sum(); + assert_eq!(built, fragments, "{name}"); + // expected: every comment is a member of exactly one run, and the source view + // materializes each run once. + let comments = parser + .root_node() + .preorder() + .filter(|node| node.kind() == "comment") + .count(); + assert_eq!(materialized, comments, "{name}"); + // expected: the source view scans every run once, at its last comment. + assert_eq!(scanned, row.comment_runs, "{name}"); + // Not exact: the number of included-range questions is the collector's own + // accounting and follows from no fact of the tree. + assert_ne!(covered, 0, "{name}"); + // A source without a document moves neither `renders` nor `evidence_built`. + // expected: in these sources a document is published exactly where the legacy + // view counts a row. + assert_eq!( + index.documents().len() == 0, + row.dloc_rows.is_empty(), + "{name}" + ); + + // The same six counters across `analyze`. + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| analyzed[at] - collected[at]); + // expected: 0 and 0, because `analyze` builds no documentation index. + assert_eq!(visits, 0, "{name}"); + assert_eq!(renders, 0, "{name}"); + // expected: 0, because the legacy view builds no source evidence. + assert_eq!(built, 0, "{name}"); + // expected: 0, because the legacy view walks members without a buffer. + assert_eq!(materialized, 0, "{name}"); + // expected: the legacy view scans every run once as well, at its last comment. + assert_eq!(scanned, row.comment_runs, "{name}"); + // expected: 0, because the legacy view has no source context to ask. + assert_eq!(covered, 0, "{name}"); + } +} diff --git a/utils/documentation-go-unit1-legacy-perturb.json b/utils/documentation-go-unit1-legacy-perturb.json new file mode 100644 index 000000000..66a34841d --- /dev/null +++ b/utils/documentation-go-unit1-legacy-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_go_source_and_legacy_views_are_independent"], + "cases": [ + { + "name": "go-function-body-gate-open", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " Go::StatementList | Go::Block => 0,", + "new": " Go::StatementList | Go::Block => 1,", + "expect": ["metrics::loc::documentation_tests::documentation_go_source_and_legacy_views_are_independent"] + }, + { + "name": "go-colon-directive-not-recognized", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " && rest.get(word) == Some(&b':')", + "new": " && rest.get(word) == Some(&b';')", + "expect": ["metrics::loc::documentation_tests::documentation_go_source_and_legacy_views_are_independent"] + }, + { + "name": "trailing-comment-seeds-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " if prev.end_row() >= row_first.start_row() {", + "new": " if prev.end_row() > row_first.start_row() {", + "expect": ["metrics::loc::documentation_tests::documentation_go_source_and_legacy_views_are_independent"] + } + ] +} From 4df9d1c0acf61f0a6b65e97e8c3363bf92dcfa5d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:28:48 -0800 Subject: [PATCH 077/221] test(documentation): assert what every Go source has in common An audit of the Go source-view tests found values the index publishes that the compared view did not read. A defect in each passed all 14 tests: every association given the first document; a fragment that reports the declaration as its node; another convention name or publication; a pending query for an owner without a document; one retention option that also keeps the other option's candidates. The helper that builds the published view now asserts what is the same for every source: an association belongs to the document at its own position, each fragment is a comment whose node starts with it, the convention is GoDoc, the publication is unknown, the adapter is partial and the index holds no qualification record. Two assertions show that the retention options are independent, and one covers the query of the var spec that owns nothing. No expected value changes and no production code changes. --- .../src/documentation/collector/go_tests.rs | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/go_tests.rs b/big-code-analysis-ast/src/documentation/collector/go_tests.rs index af9f8b2db..4184edc07 100644 --- a/big-code-analysis-ast/src/documentation/collector/go_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/go_tests.rs @@ -38,7 +38,8 @@ struct Doc { /// What one collection published: the documents, the owner of each association as /// resolution, node kind and byte range, each retained candidate as disposition and byte /// range, and the number of pending assessments. The default value is an index that -/// holds none of them. +/// holds none of them. What is the same for every source here is asserted by +/// `published` and is in no expected value. Node queries are not part of it. #[cfg(feature = "go")] #[derive(Debug, Default, PartialEq, Eq)] struct View { @@ -144,6 +145,21 @@ fn run_of(origin: &Origin<'_>) -> Run { } } +/// The byte range of a fragment. The same holds for every fragment here, so no expected +/// view states it: the spelling is a comment, and its node is the `comment` node that +/// starts with it. The node may end one byte later, where it holds the CR of a CRLF. +#[cfg(feature = "go")] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + let carrier = fragment.node().unwrap().node(); + assert_eq!( + (carrier.kind(), carrier.start_byte()), + ("comment", range.start) + ); + range +} + /// The node that alone owns the association, as every owner here is. #[cfg(feature = "go")] fn owner_node<'s>( @@ -175,10 +191,7 @@ fn published(index: &DocumentationIndex<'_>) -> View { role: (owner_kind != Some("package_clause")).then(|| document.get().role()), composition: document.get().composition(), fragments: (0..document.get().fragment_count()) - .map(|at| { - let fragment = facts.document_fragment(document, at).unwrap(); - span(fragment.get().source()) - }) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) .collect(), text: complete.text().to_owned(), map: complete @@ -191,16 +204,22 @@ fn published(index: &DocumentationIndex<'_>) -> View { .collect(); let owners = index .associations() - .map(|association| { + .enumerate() + .map(|(position, association)| { let attachment = association.get(); let declaration = owner_node(facts, association); + // The same for every association here, so no expected view states them. Each + // document has one association, at the document's own position. + assert_eq!(attachment.convention.name(), "GoDoc"); + assert_eq!(attachment.publication, Publication::Unknown); + let document = facts.associated_document(association).unwrap(); + assert_eq!(index.documents().nth(position), Some(document)); // Both follow from the tree: the binding is the owner itself, and the lexical // scope is the parent of the first comment of the document. assert_eq!( attachment.binding.map(NodeEvidence::node), Some(declaration) ); - let document = facts.associated_document(association).unwrap(); let first = facts.document_fragment(document, 0).unwrap(); let first_comment = first.get().node().unwrap().node(); assert_eq!( @@ -218,9 +237,14 @@ fn published(index: &DocumentationIndex<'_>) -> View { .evidence() .map(|candidate| { let fragment = index.evidence_fragment(candidate).unwrap(); - (candidate.get().disposition, span(fragment.get().source())) + (candidate.get().disposition, fragment_span(fragment.get())) }) .collect(); + // The same for every source here: the Go adapter is partial, and a qualification + // record belongs to a documentation command that names its declaration, which Go + // does not have. + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); View { documents, owners, @@ -434,6 +458,7 @@ fn go_declaration_kinds_own_the_comment_above_them() { // its document. let query = index.node_associations(spec).unwrap(); assert_eq!(query.associations().len(), 0); + assert!(!query.projection_pending()); assert_eq!(query.assessments().count(), 0); } } @@ -585,6 +610,9 @@ fn go_blank_source_row_detaches_a_run() { Retain::Unbound, (CandidateDisposition::Unattached, 10..14), ); + // Keeping directives does not keep the detached comment. + let detached: &[u8] = b"package p\n// a\n\n// b\nfunc F() {}"; + assert_eq!(retained(detached, Retain::Directives), view(detached)); } #[cfg(feature = "go")] @@ -601,6 +629,9 @@ fn go_directive_rows_are_evidence_and_not_prose() { Retain::Directives, (CandidateDisposition::Directive, 19..37), ); + // Keeping unbound candidates does not keep the directive of a selected run. + let selected: &[u8] = b"package p\n// audit\n//go:generate tool\nfunc F() {}"; + assert_eq!(retained(selected, Retain::Unbound), view(selected)); // A directive before, inside and after the prose, and a comment that only looks // like one: `// go:generate` has a space after the marker. let prose: [(&[u8], Doc, Range); 4] = [ @@ -641,6 +672,8 @@ fn go_directive_rows_are_evidence_and_not_prose() { source.escape_ascii() ); } + // A run that holds only directives documents nothing. That is the collector's answer + // today, pinned as it is; whether such a run should be a document is not decided. // In the first source a blank row also separates the run from the package clause; // its control sets both options. let directives_alone: [(&[u8], Retain, Range); 3] = [ From 7967cca17fe15194ed3f5d86d59ed6047dabe7f9 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:36:33 -0800 Subject: [PATCH 078/221] test(documentation): assert the capability and the absent qualifications An audit of the C-family source-view tests found that the compared view read neither the qualification records nor the capability of the index, while two comments said the tests compare everything the index publishes. A defect that gave every `@fn` document a wrong reference record passed all 39 tests, and so did a wrong capability. The helper that builds the published view now asserts both: the Doxygen adapter is partial, and no source has a qualification record. The two comments name what the view holds. No expected value changes and no production code changes. --- .../documentation/collector/c_family_tests.rs | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs b/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs index df7390842..d1c57b9a7 100644 --- a/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs @@ -1,8 +1,9 @@ //! Doxygen documentation of C, C++, Mozcpp and Objective-C in the source view: what owns a //! comment, the text of the document and where each part of that text comes from. The -//! source-view tests collect every source through both entry points and compare everything -//! the index publishes. The grammar tests collect nothing: they pin the parse-tree shapes -//! the source-view tests rely on. +//! source-view tests collect every source through both entry points and compare the +//! documents, associations, retained candidates and pending assessments the index +//! publishes. The grammar tests collect nothing: they pin the parse-tree shapes the +//! source-view tests rely on. #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] use crate::documentation::*; @@ -78,10 +79,11 @@ struct Pending { document: Option, } -/// Everything one collection published. Documents, associations and retained candidates -/// are in published order, and a retained candidate is its disposition and byte range. -/// Pending assessments are in the order of `unordered`. The default value is an index -/// that published nothing and holds nothing pending. +/// What one collection published. Documents, associations and retained candidates are in +/// published order, and a retained candidate is its disposition and byte range. Pending +/// assessments are in the order of `unordered`. The default value is an index that +/// published nothing and holds nothing pending. What is the same for every source here is +/// asserted by `published` and is in no expected view. Node queries are not part of it. #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] #[derive(Debug, Default, PartialEq, Eq)] struct View { @@ -303,6 +305,11 @@ fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> Vie node: assessment.get().node.map(|about| site(about.node())), document: index.assessed_document(assessment).unwrap().map(position), })); + // The same for every source here: the Doxygen adapter is partial. A qualification + // record states that a command which names its declaration, or the declaration it + // names, lies inside a conditional or a recovery region; no source has that. + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); View { documents, associations, From 1678ce83d689930347c85e47795a6f0dbce8fc86 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:09:56 -0800 Subject: [PATCH 079/221] test(documentation): pin Lua LDoc owners, the first-file rule and text in the source view --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/lua_tests.rs | 970 ++++++++++++++++++ utils/documentation-lua-unit1-perturb.json | 260 +++++ 3 files changed, 1232 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/lua_tests.rs create mode 100644 utils/documentation-lua-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index ba61b15fd..fb0b6ec58 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1014,6 +1014,8 @@ mod form_tests; #[cfg(test)] mod go_tests; #[cfg(test)] +mod lua_tests; +#[cfg(test)] mod named_tests; #[cfg(test)] mod projection_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/lua_tests.rs b/big-code-analysis-ast/src/documentation/collector/lua_tests.rs new file mode 100644 index 000000000..00c4999cb --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/lua_tests.rs @@ -0,0 +1,970 @@ +//! Lua LDoc source-view tests compare documents, associations, retained candidates and +//! pending assessments through both entry points. The grammar test collects nothing and +//! pins the parse-tree shapes on which the source-view tests rely. Node queries are not +//! part of the compared view. + +#[cfg(feature = "lua")] +use crate::documentation::*; +#[cfg(feature = "lua")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "lua")] +use std::ops::Range; + +#[cfg(feature = "lua")] +use Run::{Copied, Decoded, Synthetic}; + +#[cfg(feature = "lua")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "lua")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(feature = "lua")] +#[derive(Debug, PartialEq, Eq)] +enum Holder { + Node(&'static str, Range), + File(Range), +} + +#[cfg(feature = "lua")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +} + +/// Documents, associations, retained candidates and pending assessments published by +/// one collection. Assessments have no defined order. Node queries are not part of this +/// view; values shared by every case are asserted by `published`. +#[cfg(feature = "lua")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec<(Resolution, Holder)>, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(feature = "lua")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "lua")] +fn run( + fragments: [Range; F], + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::CommentRun, + fragments: fragments.into(), + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "lua")] +fn file(document: Doc) -> Doc { + Doc { + role: DocumentRole::FilePackage, + ..document + } +} + +#[cfg(feature = "lua")] +fn owned(document: Doc, holder: Holder) -> View { + View { + documents: vec![document], + associations: vec![(Resolution::Resolved, holder)], + ..View::default() + } +} + +#[cfg(feature = "lua")] +fn function(document: Doc, range: Range) -> View { + owned(document, Holder::Node("function_declaration", range)) +} + +#[cfg(feature = "lua")] +fn pending(reason: &'static str, range: Range, document: Option) -> Pending { + Pending { + axis: AssessmentAxis::Owner, + reason, + node: Some(("assignment_statement", range)), + document, + } +} + +#[cfg(feature = "lua")] +fn unordered(assessments: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = assessments.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +#[cfg(feature = "lua")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "lua")] +fn origin_run(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "lua")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "lua")] +fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + // bca: suppress(halstead) -- one cohesive reading of the four published lists and their shared invariants. + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| { + let fragment = facts.document_fragment(document, at).unwrap().get(); + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("comment", range.clone())) + ); + range + }) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|entry| (entry.output.range(), origin_run(&entry.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .enumerate() + .map(|(at, association)| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "LDoc"); + assert_eq!(attachment.publication, Publication::Unknown); + let document = facts.associated_document(association).unwrap(); + assert_eq!(ordered.get(at), Some(&document)); + let first = facts.document_fragment(document, 0).unwrap(); + let comment = first.get().node().unwrap().node(); + assert_eq!(Some(attachment.lexical_scope.node()), comment.parent()); + let owner = facts.associated_owner(association, 0).unwrap(); + let holder = match owner.get() { + Owner::Node(declared) => { + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declared.node()) + ); + let (kind, range) = site(declared.node()); + Holder::Node(kind, range) + } + Owner::File(file) => { + assert_eq!(file.node(), root); + assert!(attachment.binding.is_none()); + Holder::File(file.node().byte_range()) + } + other => panic!("a node or file owner, found {other:?}"), + }; + (attachment.resolution, holder) + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, span(fragment.get().source())) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| { + Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| site(node.node())), + document: index + .assessed_document(assessment) + .unwrap() + .map(|document| ordered.iter().position(|known| *known == document).unwrap()), + } + })); + // The Lua LDoc adapter is partial for every source here. + assert_eq!(index.capability(), Capability::Partial); + // A qualification record belongs to a documentation command that names its declaration + // (the Doxygen named-reference path), which LDoc does not have here. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + associations, + evidence, + assessments, + } +} + +#[cfg(feature = "lua")] +fn clean(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Lua, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{}", + source.escape_ascii() + ); + parser +} + +#[cfg(feature = "lua")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Lua, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(feature = "lua")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2], root: tree_sitter::Node<'_>) -> View { + let [typed, raw] = indexes.each_ref().map(|index| published(index, root)); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "lua")] +fn view(source: &[u8]) -> View { + let parser = clean(source); + agreed( + &indexes(&parser, DocumentationOptions::default()), + parser.ts_tree().root_node(), + ) +} + +#[cfg(feature = "lua")] +fn retained(source: &[u8]) -> View { + let parser = clean(source); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + agreed(&indexes(&parser, options), parser.ts_tree().root_node()) +} + +#[cfg(feature = "lua")] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static str, Range)> { + let mut cursor = parent.walk(); + let mut result = Vec::new(); + if cursor.goto_first_child() { + loop { + let child = cursor.node(); + result.push((cursor.field_name(), child.kind(), child.byte_range())); + if !cursor.goto_next_sibling() { + break; + } + } + } + result +} + +#[cfg(feature = "lua")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|node| node.as_tree_sitter()) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "lua")] +#[test] +fn lua_marked_block_above_a_function_documents_the_function() { + let sources: [(&[u8], Range); 4] = [ + (b"module(\"m\")\n---audit\nfunction f() end\n", 21..37), + (b"module(\"m\")\n---audit\nlocal function f() end\n", 21..43), + (b"module(\"m\")\n---audit\nfunction M.f() end\n", 21..39), + (b"module(\"m\")\n---audit\nfunction M:m() end\n", 21..39), + ]; + for (source, owner) in sources { + assert_eq!( + view(source), + function(comment(12..20, "audit", [(0..5, Copied(15..20))]), owner), + "{}", + source.escape_ascii() + ); + } +} + +/// The four assignment forms pin today's pending outcome; a later unit changes it on purpose. +#[cfg(feature = "lua")] +#[test] +fn lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet() { + let sources: [(&[u8], Range); 4] = [ + (b"module(\"m\")\n---audit\nf = function() end\n", 21..39), + (b"module(\"m\")\n---audit\nM.f = function() end\n", 21..41), + (b"module(\"m\")\n---audit\nt = {}\n", 21..27), + (b"module(\"m\")\n---audit\nM.t = {}\n", 21..29), + ]; + for (source, owner) in sources { + assert_eq!( + view(source), + View { + documents: vec![comment(12..20, "audit", [(0..5, Copied(15..20))])], + assessments: unordered([ + pending( + "Selected local or wrapper form awaits owner projection", + owner.clone(), + Some(0) + ), + pending( + "Recognized declaration requires a semantic projection", + owner, + None + ), + ]), + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "lua")] +#[test] +fn lua_long_bracket_block_is_one_fragment_and_ends_its_run() { + let sources: [(&[u8], Doc, Range); 3] = [ + ( + b"module(\"m\")\n--[[-- audit ]]\nfunction f() end\n", + comment(12..27, " audit ", [(0..7, Copied(18..25))]), + 28..44, + ), + ( + b"module(\"m\")\n--[==[-- audit ]==]\nfunction f() end\n", + comment(12..31, " audit ", [(0..7, Copied(20..27))]), + 32..48, + ), + ( + b"module(\"m\")\n--[[--\naudit\nsecond\n]]\nfunction f() end\n", + comment( + 12..34, + "audit\nsecond", + [ + (0..5, Copied(19..24)), + (5..6, Copied(24..25)), + (6..12, Copied(25..31)), + ], + ), + 35..51, + ), + ]; + for (source, document, owner) in sources { + assert_eq!( + view(source), + function(document, owner), + "{}", + source.escape_ascii() + ); + } + assert_eq!( + view(b"--[[-- audit ]]\n-- note\nfunction f() end\n"), + owned( + file(comment(0..15, " audit ", [(0..7, Copied(6..13))])), + Holder::File(0..41) + ) + ); + let source = b"module(\"m\")\n--[[-- audit ]]\n-- note\nfunction f() end\n"; + let mut expected = View::default(); + assert_eq!(view(source), expected); + expected.evidence.extend([ + (CandidateDisposition::Unattached, 12..27), + (CandidateDisposition::Unattached, 28..35), + ]); + assert_eq!(retained(source), expected); +} + +#[cfg(feature = "lua")] +#[test] +#[allow(clippy::single_range_in_vec_init)] +fn lua_plain_comments_give_no_document() { + let sources: [(&[u8], Vec>); 5] = [ + (b"module(\"m\")\n-- audit\nfunction f() end\n", vec![12..20]), + ( + b"module(\"m\")\n-- a\n-- b\nfunction f() end\n", + vec![12..16, 17..21], + ), + ( + b"module(\"m\")\n--[[ audit ]]\nfunction f() end\n", + vec![12..25], + ), + (b"-- audit\nfunction f() end\n", vec![0..8]), + ( + b"module(\"m\")\n-- plain\n---audit\nfunction f() end\n", + vec![12..20, 21..29], + ), + ]; + for (source, candidates) in sources { + let mut expected = View::default(); + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + expected.evidence.extend( + candidates + .into_iter() + .map(|range| (CandidateDisposition::Unattached, range)), + ); + assert_eq!(retained(source), expected, "{}", source.escape_ascii()); + } +} + +#[cfg(feature = "lua")] +#[test] +#[allow(clippy::type_complexity)] +fn lua_first_block_of_a_file_documents_the_file() { + let sources: [(&[u8], Range, Range, Range); 7] = [ + (b"---audit\nfunction f() end\n", 0..8, 3..8, 0..26), + (b"---audit\n\nfunction f() end\n", 0..8, 3..8, 0..27), + (b"---audit\n", 0..8, 3..8, 0..9), + ( + b"#!/usr/bin/env lua\n---audit\nfunction f() end\n", + 19..27, + 22..27, + 0..45, + ), + ( + b"-- plain\n\n---audit\nfunction f() end\n", + 10..18, + 13..18, + 0..36, + ), + ( + b"--[[ plain ]]\n---audit\nfunction f() end\n", + 14..22, + 17..22, + 0..40, + ), + ( + b"---audit\nmodule(\"m\")\nfunction f() end\n", + 0..8, + 3..8, + 0..38, + ), + ]; + for (source, fragment, text, root) in sources { + assert_eq!( + view(source), + owned( + file(comment(fragment, "audit", [(0..5, Copied(text))])), + Holder::File(root) + ), + "{}", + source.escape_ascii() + ); + } + assert_eq!( + view(b"---audit\nfunction f() end\n---second\nfunction g() end\n"), + View { + documents: vec![ + file(comment(0..8, "audit", [(0..5, Copied(3..8))])), + comment(26..35, "second", [(0..6, Copied(29..35))]) + ], + associations: vec![ + (Resolution::Resolved, Holder::File(0..53)), + ( + Resolution::Resolved, + Holder::Node("function_declaration", 36..52) + ) + ], + ..View::default() + } + ); + assert_eq!( + view(b"--- Module.\n-- @module m\nfunction f() end\n"), + owned( + file(run( + [0..11, 12..24], + "Module.\n@module m", + [ + (0..7, Copied(4..11)), + (7..8, Synthetic), + (8..17, Copied(15..24)) + ] + )), + Holder::File(0..42) + ) + ); + let source = b"-- plain\n---audit\nfunction f() end\n"; + let mut expected = View::default(); + assert_eq!(view(source), expected); + expected.evidence.extend([ + (CandidateDisposition::Unattached, 0..8), + (CandidateDisposition::Unattached, 9..17), + ]); + assert_eq!(retained(source), expected); +} + +#[cfg(feature = "lua")] +#[test] +fn lua_blank_row_separates_two_blocks() { + let source = b"module(\"m\")\n---first\n\n---audit\nfunction f() end\n"; + let mut expected = function(comment(22..30, "audit", [(0..5, Copied(25..30))]), 31..47); + assert_eq!(view(source), expected); + expected + .evidence + .push((CandidateDisposition::Unattached, 12..20)); + assert_eq!(retained(source), expected); +} + +#[cfg(feature = "lua")] +#[test] +fn lua_rows_of_a_run_compose_one_document() { + let sources: [(&[u8], Doc, Range); 4] = [ + ( + b"module(\"m\")\n--- first\n-- second\nfunction f() end\n", + run( + [12..21, 22..31], + "first\nsecond", + [ + (0..5, Copied(16..21)), + (5..6, Synthetic), + (6..12, Copied(25..31)), + ], + ), + 32..48, + ), + ( + b"module(\"m\")\n--- a\n--\n-- b\nfunction f() end\n", + run( + [12..17, 18..20, 21..25], + "a\n\nb", + [ + (0..1, Copied(16..17)), + (1..2, Synthetic), + (2..3, Synthetic), + (3..4, Copied(24..25)), + ], + ), + 26..42, + ), + ( + b"module(\"m\")\n---\n-- audit\nfunction f() end\n", + run([12..15, 16..24], "audit", [(0..5, Copied(19..24))]), + 25..41, + ), + ( + b"module(\"m\")\n---a\n---b\nfunction f() end\n", + run( + [12..16, 17..21], + "a\nb", + [ + (0..1, Copied(15..16)), + (1..2, Synthetic), + (2..3, Copied(20..21)), + ], + ), + 22..38, + ), + ]; + for (source, document, owner) in sources { + assert_eq!( + view(source), + function(document, owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "lua")] +#[test] +fn lua_text_cleanup_removes_the_marker_and_at_most_one_space() { + let sources: [(&[u8], Doc, Range); 7] = [ + ( + b"module(\"m\")\n--- audit\nfunction f() end\n", + comment(12..21, "audit", [(0..5, Copied(16..21))]), + 22..38, + ), + ( + b"module(\"m\")\n--- audit\nfunction f() end\n", + comment(12..22, " audit", [(0..6, Copied(16..22))]), + 23..39, + ), + ( + b"module(\"m\")\n--- a \nfunction f() end\n", + comment(12..19, "a ", [(0..3, Copied(16..19))]), + 20..36, + ), + ( + b"module(\"m\")\n--- a\n--b\n-- c\nfunction f() end\n", + run( + [12..17, 18..21, 22..27], + "a\nb\n c", + [ + (0..1, Copied(16..17)), + (1..2, Synthetic), + (2..3, Copied(20..21)), + (3..4, Synthetic), + (4..6, Copied(25..27)), + ], + ), + 28..44, + ), + ( + b"module(\"m\")\n--[[-audit]]\nfunction f() end\n", + comment(12..24, "audit", [(0..5, Copied(17..22))]), + 25..41, + ), + ( + b"module(\"m\")\n--[=[-audit]=]\nfunction f() end\n", + comment(12..26, "audit", [(0..5, Copied(18..23))]), + 27..43, + ), + ( + b"module(\"m\")\n--[==[-audit]==]\nfunction f() end\n", + comment(12..28, "audit", [(0..5, Copied(19..24))]), + 29..45, + ), + ]; + for (source, document, owner) in sources { + assert_eq!( + view(source), + function(document, owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "lua")] +#[test] +fn lua_crlf_rows_keep_owners_fragments_and_text() { + assert_eq!( + view(b"module(\"m\")\r\n---audit\r\nfunction f() end\r\n"), + function(comment(13..21, "audit", [(0..5, Copied(16..21))]), 23..39) + ); + assert_eq!( + view(b"module(\"m\")\r\n--- a\r\n-- b\r\nfunction f() end\r\n"), + function( + run( + [13..18, 20..24], + "a\nb", + [ + (0..1, Copied(17..18)), + (1..2, Synthetic), + (2..3, Copied(23..24)) + ] + ), + 26..42 + ) + ); + assert_eq!( + view(b"module(\"m\")\r\n--[[--\r\naudit\r\nsecond\r\n]]\r\nfunction f() end\r\n"), + function( + comment( + 13..38, + "audit\nsecond", + [ + (0..5, Copied(21..26)), + (5..6, Decoded(26..28)), + (6..12, Copied(28..34)) + ] + ), + 40..56 + ) + ); + assert_eq!( + view(b"---audit\r\nfunction f() end\r\n"), + owned( + file(comment(0..8, "audit", [(0..5, Copied(3..8))])), + Holder::File(0..28) + ) + ); +} + +#[cfg(feature = "lua")] +#[test] +#[allow(clippy::too_many_lines)] +fn lua_grammar_shapes_the_unit_relies_on() { + let lf = b"module(\"m\")\n---audit\nfunction f() end\n"; + let parser = clean(lf); + let root = parser.ts_tree().root_node(); + let line = node_at(&parser, "comment", 12..20); + let function = line.next_sibling().unwrap(); + assert_eq!(site(root), ("chunk", 0..38)); + assert_eq!(line.parent(), Some(root)); + assert!(line.is_extra()); + assert_eq!(site(function), ("function_declaration", 21..37)); + assert_eq!( + parts(line), + [ + (Some("start"), "--", 12..14), + (Some("content"), "comment_content", 14..20) + ] + ); + assert_eq!(&lf[line.end_byte()..function.start_byte()], b"\n"); + assert_eq!(&lf[function.end_byte()..root.end_byte()], b"\n"); + + let parser = clean( + b"function f() end\nlocal function g() end\nfunction M.f() end\nfunction M:m() end\n", + ); + let root = parser.ts_tree().root_node(); + assert_eq!( + parts(root), + [ + (None, "function_declaration", 0..16), + (Some("local_declaration"), "function_declaration", 17..39), + (None, "function_declaration", 40..58), + (None, "function_declaration", 59..77), + ] + ); + for (range, kind, name) in [ + (0..16, "identifier", 9..10), + (17..39, "identifier", 32..33), + (40..58, "dot_index_expression", 49..52), + (59..77, "method_index_expression", 68..71), + ] { + let function = node_at(&parser, "function_declaration", range); + assert_eq!( + function.child_by_field_name("name").map(site), + Some((kind, name)) + ); + assert!(function.child_by_field_name("block").is_none()); + } + assert_eq!( + site( + node_at(&parser, "function_declaration", 17..39) + .child(0) + .unwrap() + ), + ("local", 17..22) + ); + + let parser = clean(b"f = function() end\nM.f = function() end\nt = {}\nM.t = {}\n"); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "assignment_statement", 0..18), + (None, "assignment_statement", 19..39), + (None, "assignment_statement", 40..46), + (None, "assignment_statement", 47..55), + ] + ); + for (range, variable, expression, value_kind, value, target) in [ + (0..18, 0..1, 4..18, "function_definition", 4..18, None), + ( + 19..39, + 19..22, + 25..39, + "function_definition", + 25..39, + Some(19..22), + ), + (40..46, 40..41, 44..46, "table_constructor", 44..46, None), + ( + 47..55, + 47..50, + 53..55, + "table_constructor", + 53..55, + Some(47..50), + ), + ] { + let assignment = node_at(&parser, "assignment_statement", range); + assert_eq!( + parts(assignment) + .iter() + .filter(|(_, kind, _)| *kind != "=") + .cloned() + .collect::>(), + [ + (None, "variable_list", variable), + (None, "expression_list", expression), + ] + ); + let expression = assignment.named_child(1).unwrap(); + assert_eq!( + expression.named_child(0).map(site), + Some((value_kind, value)) + ); + if let Some(target) = target { + assert_eq!( + assignment.named_child(0).unwrap().named_child(0).map(site), + Some(("dot_index_expression", target)) + ); + } + } + + let parser = + clean(b"--[[-- audit ]]\n--[==[-audit]==]\n--[[--\naudit\nsecond\n]]\nfunction f() end\n"); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "comment", 0..15), + (None, "comment", 16..32), + (None, "comment", 33..55), + (None, "function_declaration", 56..72), + ] + ); + for (comment, opener, content, closer) in [ + (0..15, 0..4, 4..13, 13..15), + (16..32, 16..22, 22..28, 28..32), + (33..55, 33..37, 37..53, 53..55), + ] { + assert_eq!( + parts(node_at(&parser, "comment", comment)), + [ + (Some("start"), "[[", opener), + (Some("content"), "comment_content", content), + (Some("end"), "]]", closer), + ] + ); + } + + let parser = clean(b"#!/usr/bin/env lua\n---audit\nfunction f() end\n"); + assert_eq!( + parts(parser.ts_tree().root_node())[0..2], + [(None, "hash_bang_line", 0..18), (None, "comment", 19..27)] + ); + assert!(node_at(&parser, "hash_bang_line", 0..18).is_named()); + + let crlf = b"module(\"m\")\r\n---audit\r\nfunction f() end\r\n"; + let parser = clean(crlf); + let root = parser.ts_tree().root_node(); + let comment = node_at(&parser, "comment", 13..21); + let function = node_at(&parser, "function_declaration", 23..39); + assert_eq!(site(root), ("chunk", 0..41)); + assert_eq!(&crlf[comment.end_byte()..function.start_byte()], b"\r\n"); + assert_eq!(&crlf[function.end_byte()..root.end_byte()], b"\r\n"); + + let crlf = b"module(\"m\")\r\n--[[--\r\naudit\r\nsecond\r\n]]\r\nfunction f() end\r\n"; + let parser = clean(crlf); + let comment = node_at(&parser, "comment", 13..38); + assert_eq!( + comment.child_by_field_name("content").map(site), + Some(("comment_content", 17..36)) + ); + assert!(crlf[comment.byte_range()].contains(&b'\r')); + let function = node_at(&parser, "function_declaration", 40..56); + assert_eq!(&crlf[comment.end_byte()..function.start_byte()], b"\r\n"); + + let source = b"---audit\n\nfunction f() end\n"; + let parser = clean(source); + let comment = node_at(&parser, "comment", 0..8); + let function = comment.next_sibling().unwrap(); + assert_eq!(site(function), ("function_declaration", 10..26)); + assert_eq!(comment.parent(), function.parent()); + assert_eq!( + function.start_position().row, + comment.end_position().row + 2 + ); + assert_eq!(&source[comment.end_byte()..function.start_byte()], b"\n\n"); + + let parser = clean(b"---audit\n"); + assert_eq!(site(parser.ts_tree().root_node()), ("chunk", 0..9)); + assert_eq!( + parts(parser.ts_tree().root_node()), + [(None, "comment", 0..8)] + ); + + let parser = clean(b"module(\"m\")\n--- a\n--\n-- b\nfunction f() end\n"); + let root = parser.ts_tree().root_node(); + assert_eq!( + parts(root)[1..4], + [ + (None, "comment", 12..17), + (None, "comment", 18..20), + (None, "comment", 21..25) + ] + ); + let empty = node_at(&parser, "comment_content", 20..20); + assert!(!empty.is_missing()); + assert_eq!(empty.parent().map(site), Some(("comment", 18..20))); + + let parser = clean(b"local t = {}\nreturn {}\n"); + let local = node_at(&parser, "variable_declaration", 0..12); + assert_eq!( + local.named_child(0).map(site), + Some(("assignment_statement", 6..12)) + ); + let returning = node_at(&parser, "return_statement", 13..22); + let expressions = node_at(&parser, "expression_list", 20..22); + assert_eq!(expressions.parent(), Some(returning)); + assert_eq!( + expressions.named_child(0).map(site), + Some(("table_constructor", 20..22)) + ); + + let parser = clean(b"module(\"m\")\n---audit\nfunction f(\nx -- input\n) end\n"); + let function = node_at(&parser, "function_declaration", 21..49); + let parameters = node_at(&parser, "parameters", 31..45); + assert_eq!(parameters.parent(), Some(function)); + let comment = node_at(&parser, "comment", 35..43); + assert_eq!(comment.parent(), Some(parameters)); + assert_eq!( + comment.prev_sibling().map(site), + Some(("identifier", 33..34)) + ); + + let parser = clean(b"module(\"m\")\n--- settings\n-- @table options\noptions = {\nalpha = 1, -- correction\n}\n"); + let table = node_at(&parser, "table_constructor", 53..81); + let comment = node_at(&parser, "comment", 66..79); + assert_eq!(comment.parent(), Some(table)); + let comma = comment.prev_sibling().unwrap(); + assert_eq!(site(comma), (",", 64..65)); + assert!(!comma.is_named()); + assert_eq!(comma.prev_sibling().map(site), Some(("field", 55..64))); +} diff --git a/utils/documentation-lua-unit1-perturb.json b/utils/documentation-lua-unit1-perturb.json new file mode 100644 index 000000000..f0effa959 --- /dev/null +++ b/utils/documentation-lua-unit1-perturb.json @@ -0,0 +1,260 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis-ast", + "--all-features", + "--lib", + "documentation::" + ], + "cases": [ + { + "name": "lua-positional-docs-off", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": " const SOURCE_POSITIONAL_DOCS: bool = true;", + "new": " const SOURCE_POSITIONAL_DOCS: bool = false;", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_a_function_documents_the_function", + "documentation::collector::lua_tests::lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet", + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_plain_comments_give_no_document", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_blank_row_separates_two_blocks", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-function-not-a-source-item", + "file": "big-code-analysis-ast/src/roles/lua.rs", + "old": " _ => Ok(true),", + "new": " _ => Ok(false),", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_a_function_documents_the_function", + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_blank_row_separates_two_blocks", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-assignment-not-a-source-item", + "file": "big-code-analysis-ast/src/roles/lua.rs", + "old": " Lua::AssignmentStatement | Lua::AssignmentStatement2 => {\n assigns_one_name_with_budget(node, budget)\n }", + "new": " Lua::AssignmentStatement | Lua::AssignmentStatement2 => {\n assigns_one_name_with_budget(node, budget).map(|_| false)\n }", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet" + ] + }, + { + "name": "lua-assignment-owner-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"assignment_statement\" | \"variable_declaration\" | \"return_statement\" | \"field\"", + "new": " \"variable_declaration\" | \"return_statement\" | \"field\"", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet" + ] + }, + { + "name": "ldoc-two-dashes-open-a-block", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " Ok(s.starts_with(b\"---\") && !ldoc_end_marker(s, budget)?)", + "new": " Ok(s.starts_with(b\"--\") && !ldoc_end_marker(s, budget)?)", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_plain_comments_give_no_document", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file" + ] + }, + { + "name": "ldoc-plain-long-comment-opens-a-block", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " return Ok(body.first() == Some(&b'-'));", + "new": " return Ok(body.first() != Some(&b'+'));", + "expect": [ + "documentation::collector::lua_tests::lua_plain_comments_give_no_document", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file" + ] + }, + { + "name": "ldoc-long-doc-comment-opens-no-block", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " return Ok(body.first() == Some(&b'-'));", + "new": " return Ok(body.first() == Some(&b'+'));", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-first-file-rule-off", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": " Ok(true) => return Ok(Ok(Some(OpenerReason::FirstFile))),", + "new": " Ok(true) => {}", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-file-opening-with-a-call-has-a-first-block", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": " Lua::Comment | Lua::HashBangLine\n", + "new": " Lua::Comment | Lua::HashBangLine | Lua::FunctionCall\n", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_a_function_documents_the_function", + "documentation::collector::lua_tests::lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet", + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_blank_row_separates_two_blocks", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-shebang-is-code", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": " Lua::Comment | Lua::HashBangLine\n", + "new": " Lua::Comment\n", + "expect": [ + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file" + ] + }, + { + "name": "lua-file-document-keeps-the-item-below", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " draft.target = Some(NodeId(0));\n draft.role = DocumentRole::FilePackage;\n draft.binding = None;", + "new": " draft.role = DocumentRole::FilePackage;\n draft.binding = None;", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-file-document-has-primary-role", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " draft.role = DocumentRole::FilePackage;\n draft.binding = None;", + "new": " draft.binding = None;", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "blank-row-continues-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " || (next.start_row() == comment.end_row().saturating_add(1)", + "new": " || (next.start_row() >= comment.end_row().saturating_add(1)", + "expect": [ + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_blank_row_separates_two_blocks" + ] + }, + { + "name": "lua-long-comment-does-not-end-run", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": " budget,\n )\n } else {\n PublicRules::::ends(node, code, budget)", + "new": " budget,\n )\n .map(|_| false)\n } else {\n PublicRules::::ends(node, code, budget)", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file" + ] + }, + { + "name": "ldoc-line-marker-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let mut prefix = 2;\n while raw.get(prefix) == Some(&b'-') {", + "new": " let mut prefix = 2;\n while raw.get(prefix) == Some(&b'+') {", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_a_function_documents_the_function", + "documentation::collector::lua_tests::lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_blank_row_separates_two_blocks", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "ldoc-long-level-ignored", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let close = equals - 1;", + "new": " let close = 2;", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space" + ] + }, + { + "name": "ldoc-long-dashes-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let mut prefix = equals + 1;\n while raw.get(prefix) == Some(&b'-') {", + "new": " let mut prefix = equals + 1;\n while raw.get(prefix) == Some(&b'+') {", + "expect": [ + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "crlf-in-block-copied-raw", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.ending.len() == 2 {", + "new": " if line.ending.len() == 3 {", + "expect": [ + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "lua-every-block-is-tagged", + "file": "big-code-analysis-ast/src/checker/lua.rs", + "old": " if text.tag {\n return Ok(Ok(Some(OpenerReason::Tagged)));", + "new": " if text.text {\n return Ok(Ok(Some(OpenerReason::Tagged)));", + "expect": [ + "documentation::collector::lua_tests::lua_marked_block_above_a_function_documents_the_function", + "documentation::collector::lua_tests::lua_marked_block_above_an_assignment_has_a_document_and_no_owner_yet", + "documentation::collector::lua_tests::lua_long_bracket_block_is_one_fragment_and_ends_its_run", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_blank_row_separates_two_blocks", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + }, + { + "name": "next-row-comment-leaves-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " || (next.start_row() == comment.end_row().saturating_add(1)", + "new": " || (next.start_row() == comment.end_row()", + "expect": [ + "documentation::collector::lua_tests::lua_plain_comments_give_no_document", + "documentation::collector::lua_tests::lua_first_block_of_a_file_documents_the_file", + "documentation::collector::lua_tests::lua_rows_of_a_run_compose_one_document", + "documentation::collector::lua_tests::lua_text_cleanup_removes_the_marker_and_at_most_one_space", + "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" + ] + } + ] +} From c8cd930b0c88023e89a63722d5ce0c76c7c3d29a Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:10:11 -0800 Subject: [PATCH 080/221] test(loc): guard Lua documentation rows before tagged-block and owner work --- src/metrics/loc/documentation_tests.rs | 164 ++++++++++++++++++ ...ocumentation-lua-unit1-legacy-perturb.json | 28 +++ 2 files changed, 192 insertions(+) create mode 100644 utils/documentation-lua-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 8934d7ed5..19f3fba53 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -961,3 +961,167 @@ fn documentation_c_family_source_and_legacy_views_are_independent() { } assert!(ran > 0); } + +#[cfg(feature = "lua")] +struct LuaLegacyRow<'a> { + name: &'static str, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + // A run is a maximal sequence of comments whose next comment starts on the same row + // where the previous one ends, or on the next row. + comment_runs: usize, +} + +#[cfg(feature = "lua")] +fn lua_documentation_counters() -> [usize; 6] { + use big_code_analysis_ast::documentation::streaming::positional::{ + evidence_built, members_materialized, positional_runs_collected, + }; + use big_code_analysis_ast::documentation::{included_range_visits, observations}; + [ + observations().visits, + observations().renders, + evidence_built::observed(), + members_materialized::observed(), + positional_runs_collected::observed(), + included_range_visits::observed(), + ] +} + +#[cfg(feature = "lua")] +#[allow(clippy::too_many_lines, clippy::arithmetic_side_effects)] +fn check_lua_legacy_row(row: &LuaLegacyRow<'_>) -> usize { + use big_code_analysis_ast::documentation::{DocumentationContext, DocumentationOptions}; + let parser = + crate::langs::AnyParser::parse(LANG::Lua, row.source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error(), "{}", row.name); + let idle = lua_documentation_counters(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let collected = lua_documentation_counters(); + let space = analyze( + Source::new(LANG::Lua, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = lua_documentation_counters(); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + row.loc, + "{}", + row.name + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{}", + row.name + ); + + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| collected[at] - idle[at]); + // expected: the collector's walk enters every node exactly once. + assert_eq!( + visits, + parser.root_node().preorder().count(), + "{}", + row.name + ); + // expected: one render per document published by the collection. + assert_eq!(renders, index.documents().len(), "{}", row.name); + // expected: default options build one member for every selected fragment and none + // for comments outside documents. + assert_eq!( + built, + index + .documents() + .map(|document| document.get().fragment_count()) + .sum::(), + "{}", + row.name + ); + // expected: each comment is a member of one run, materialized once by the source view. + assert_eq!( + materialized, + parser + .root_node() + .preorder() + .filter(|node| node.kind() == "comment") + .count(), + "{}", + row.name + ); + // expected: the source view scans every run once, at its final comment. + assert_eq!(scanned, row.comment_runs, "{}", row.name); + // The coverage counter counts the collector's questions, with no tree-derived + // closed form; the collection must move it on this thread. + assert_ne!(covered, 0, "{}", row.name); + + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| analyzed[at] - collected[at]); + // expected: analyze never builds or renders a documentation index. + assert_eq!(visits, 0, "{}", row.name); + assert_eq!(renders, 0, "{}", row.name); + // expected: the legacy view builds no source evidence or buffered members. + assert_eq!(built, 0, "{}", row.name); + assert_eq!(materialized, 0, "{}", row.name); + // expected: the legacy view also scans every run once, at its final comment. + assert_eq!(scanned, row.comment_runs, "{}", row.name); + // expected: the legacy view has no source context in which to ask a coverage question. + assert_eq!(covered, 0, "{}", row.name); + index.documents().len() +} + +#[cfg(feature = "lua")] +#[test] +fn documentation_lua_source_and_legacy_views_are_independent() { + let first_file = documentation::source("lua-first-file.lua"); + let primary = documentation::source("primary.lua"); + let rows = [ + LuaLegacyRow { name: "l01_tagged_block_above_function", source: b"module(\"m\")\n--- audit\n-- @param x thing\nfunction f(x) end\n", loc: [4, 2, 1, 2, 0, 2], dloc_rows: &[1, 2], comment_runs: 1 }, + LuaLegacyRow { name: "l02_luals_tag_above_function", source: b"module(\"m\")\n---@param x integer\nfunction f(x) end\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + // The trailing `-- correction` on a code row starts a second run. + LuaLegacyRow { name: "l03_table_field_row", source: b"module(\"m\")\n--- settings\n-- @table options\noptions = {\nalpha = 1, -- correction\n}\n", loc: [6, 4, 1, 3, 0, 2], dloc_rows: &[1, 2], comment_runs: 2 }, + // The trailing `-- input` on a parameter row starts a second run. + LuaLegacyRow { name: "l04_parameter_row", source: b"module(\"m\")\n---audit\nfunction f(\nx -- input\n) end\n", loc: [5, 4, 1, 2, 0, 1], dloc_rows: &[1], comment_runs: 2 }, + LuaLegacyRow { name: "l05_explicit_virtual_row", source: b"module(\"m\")\n---audit\n-- @function ghost\n", loc: [3, 1, 0, 2, 0, 2], dloc_rows: &[1, 2], comment_runs: 1 }, + LuaLegacyRow { name: "l06_function_assigned_to_field", source: b"module(\"m\")\n---audit\nM.f = function() end\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + LuaLegacyRow { name: "l07_local_table", source: b"module(\"m\")\n---audit\nlocal t = {}\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + LuaLegacyRow { name: "l08_return_table", source: b"module(\"m\")\n---audit\nreturn {}\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + LuaLegacyRow { name: "l10_long_block_several_rows", source: b"module(\"m\")\n--[[--\naudit\nsecond\n]]\nfunction f() end\n", loc: [6, 2, 1, 4, 0, 4], dloc_rows: &[1, 2, 3, 4], comment_runs: 1 }, + LuaLegacyRow { name: "l11_first_block_with_module_tag", source: b"--- Module.\n-- @module m\nlocal M = {}\n", loc: [3, 1, 1, 2, 0, 2], dloc_rows: &[0, 1], comment_runs: 1 }, + LuaLegacyRow { name: "l12_fixture_first_file", source: &first_file, loc: [2, 1, 1, 1, 0, 1], dloc_rows: &[0], comment_runs: 1 }, + LuaLegacyRow { name: "l13_fixture_primary", source: &primary, loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + // The code between `-- plain` and the marked block separates their runs. + LuaLegacyRow { name: "l14_plain_comment_module_block", source: b"-- plain\nmodule(\"m\")\n---audit\nfunction f() end\n", loc: [4, 2, 1, 2, 0, 1], dloc_rows: &[2], comment_runs: 2 }, + LuaLegacyRow { name: "l15_shebang_module_block", source: b"#!/usr/bin/env lua\nmodule(\"m\")\n---audit\nfunction f() end\n", loc: [4, 3, 1, 1, 0, 1], dloc_rows: &[2], comment_runs: 1 }, + ]; + for row in rows { + let name = row.name; + assert_ne!(check_lua_legacy_row(&row), 0, "{name}"); + } + // Whether a block publishes a document after code other than `module()` is open; + // the other fourteen rows provide the positive controls for render and evidence. + check_lua_legacy_row(&LuaLegacyRow { + name: "l09_code_first_no_module", + source: b"require(\"m\")\n---audit\nfunction f() end\n", + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }); +} diff --git a/utils/documentation-lua-unit1-legacy-perturb.json b/utils/documentation-lua-unit1-legacy-perturb.json new file mode 100644 index 000000000..ee06592f7 --- /dev/null +++ b/utils/documentation-lua-unit1-legacy-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_lua_source_and_legacy_views_are_independent"], + "cases": [ + { + "name": "next-row-comment-leaves-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " || (next.start_row() == comment.end_row().saturating_add(1)", + "new": " || (next.start_row() == comment.end_row()", + "expect": ["metrics::loc::documentation_tests::documentation_lua_source_and_legacy_views_are_independent"] + }, + { + "name": "ldoc-two-dashes-open-a-block", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " Ok(s.starts_with(b\"---\") && !ldoc_end_marker(s, budget)?)", + "new": " Ok(s.starts_with(b\"--\") && !ldoc_end_marker(s, budget)?)", + "expect": ["metrics::loc::documentation_tests::documentation_lua_source_and_legacy_views_are_independent"] + }, + { + "name": "ldoc-long-doc-comment-opens-no-block", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " return Ok(body.first() == Some(&b'-'));", + "new": " return Ok(body.first() == Some(&b'+'));", + "expect": ["metrics::loc::documentation_tests::documentation_lua_source_and_legacy_views_are_independent"] + } + ] +} From 91dd0a5e263e0f7f47cc83b935725ae136dcdc8b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:50:31 -0800 Subject: [PATCH 081/221] test(documentation): tighten the Lua grammar and fragment assertions Assert grammar children by kind and validate retained fragment form and node. Format legacy rows without changing expected values or production code. --- .../src/documentation/collector/lua_tests.rs | 53 +++--- src/metrics/loc/documentation_tests.rs | 157 +++++++++++++----- 2 files changed, 147 insertions(+), 63 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/lua_tests.rs b/big-code-analysis-ast/src/documentation/collector/lua_tests.rs index 00c4999cb..1d59caf1e 100644 --- a/big-code-analysis-ast/src/documentation/collector/lua_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/lua_tests.rs @@ -152,9 +152,20 @@ fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { (node.kind(), node.byte_range()) } +#[cfg(feature = "lua")] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("comment", range.clone())) + ); + range +} + #[cfg(feature = "lua")] fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { - // bca: suppress(halstead) -- one cohesive reading of the four published lists and their shared invariants. + // bca: suppress(halstead) -- one reading of the four published lists and the rules they share. let facts = index.facts(); let ordered: Vec<_> = index.documents().collect(); let documents = ordered @@ -165,16 +176,7 @@ fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> Vie role: document.get().role(), composition: document.get().composition(), fragments: (0..document.get().fragment_count()) - .map(|at| { - let fragment = facts.document_fragment(document, at).unwrap().get(); - let range = span(fragment.source()); - assert_eq!(fragment.form(), FragmentForm::Comment); - assert_eq!( - fragment.node().map(|node| site(node.node())), - Some(("comment", range.clone())) - ); - range - }) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) .collect(), text: complete.text().to_owned(), map: complete @@ -222,7 +224,7 @@ fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> Vie .evidence() .map(|candidate| { let fragment = index.evidence_fragment(candidate).unwrap(); - (candidate.get().disposition, span(fragment.get().source())) + (candidate.get().disposition, fragment_span(fragment.get())) }) .collect(); let assessments = unordered(index.assessments().map(|assessment| { @@ -441,8 +443,8 @@ fn lua_long_bracket_block_is_one_fragment_and_ends_its_run() { #[cfg(feature = "lua")] #[test] -#[allow(clippy::single_range_in_vec_init)] fn lua_plain_comments_give_no_document() { + #[allow(clippy::single_range_in_vec_init)] let sources: [(&[u8], Vec>); 5] = [ (b"module(\"m\")\n-- audit\nfunction f() end\n", vec![12..20]), ( @@ -473,8 +475,8 @@ fn lua_plain_comments_give_no_document() { #[cfg(feature = "lua")] #[test] -#[allow(clippy::type_complexity)] fn lua_first_block_of_a_file_documents_the_file() { + #[allow(clippy::type_complexity)] let sources: [(&[u8], Range, Range, Range); 7] = [ (b"---audit\nfunction f() end\n", 0..8, 3..8, 0..26), (b"---audit\n\nfunction f() end\n", 0..8, 3..8, 0..27), @@ -755,6 +757,7 @@ fn lua_grammar_shapes_the_unit_relies_on() { (Some("content"), "comment_content", 14..20) ] ); + assert!(!line.child(0).unwrap().is_named()); assert_eq!(&lf[line.end_byte()..function.start_byte()], b"\n"); assert_eq!(&lf[function.end_byte()..root.end_byte()], b"\n"); @@ -782,16 +785,13 @@ fn lua_grammar_shapes_the_unit_relies_on() { function.child_by_field_name("name").map(site), Some((kind, name)) ); - assert!(function.child_by_field_name("block").is_none()); + assert!(parts(function).iter().all(|(_, kind, _)| *kind != "block")); } - assert_eq!( - site( - node_at(&parser, "function_declaration", 17..39) - .child(0) - .unwrap() - ), - ("local", 17..22) - ); + let local = node_at(&parser, "function_declaration", 17..39) + .child(0) + .unwrap(); + assert_eq!(site(local), ("local", 17..22)); + assert!(!local.is_named()); let parser = clean(b"f = function() end\nM.f = function() end\nt = {}\nM.t = {}\n"); assert_eq!( @@ -873,6 +873,8 @@ fn lua_grammar_shapes_the_unit_relies_on() { ] ); } + let rows = node_at(&parser, "comment", 33..55); + assert_eq!(rows.end_position().row, rows.start_position().row + 3); let parser = clean(b"#!/usr/bin/env lua\n---audit\nfunction f() end\n"); assert_eq!( @@ -959,7 +961,10 @@ fn lua_grammar_shapes_the_unit_relies_on() { Some(("identifier", 33..34)) ); - let parser = clean(b"module(\"m\")\n--- settings\n-- @table options\noptions = {\nalpha = 1, -- correction\n}\n"); + let parser = clean( + b"module(\"m\")\n--- settings\n-- @table options\noptions = {\n\ + alpha = 1, -- correction\n}\n", + ); let table = node_at(&parser, "table_constructor", 53..81); let comment = node_at(&parser, "comment", 66..79); assert_eq!(comment.parent(), Some(table)); diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 19f3fba53..2ff9b61cc 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -990,12 +990,14 @@ fn lua_documentation_counters() -> [usize; 6] { } #[cfg(feature = "lua")] -#[allow(clippy::too_many_lines, clippy::arithmetic_side_effects)] +/// Checks one row and returns the number of documents its collection published. +#[allow(clippy::arithmetic_side_effects)] fn check_lua_legacy_row(row: &LuaLegacyRow<'_>) -> usize { use big_code_analysis_ast::documentation::{DocumentationContext, DocumentationOptions}; + let name = row.name; let parser = crate::langs::AnyParser::parse(LANG::Lua, row.source.to_vec(), None, None).unwrap(); - assert!(!parser.ts_tree().root_node().has_error(), "{}", row.name); + assert!(!parser.ts_tree().root_node().has_error(), "{name}"); let idle = lua_documentation_counters(); let index = parser .documentation( @@ -1021,29 +1023,22 @@ fn check_lua_legacy_row(row: &LuaLegacyRow<'_>) -> usize { loc.dloc() ], row.loc, - "{}", - row.name + "{name}" ); assert_eq!( (0..row.source.len()) .filter(|at| loc.dloc.lines.contains(*at)) .collect::>(), row.dloc_rows, - "{}", - row.name + "{name}" ); let [visits, renders, built, materialized, scanned, covered] = std::array::from_fn(|at| collected[at] - idle[at]); // expected: the collector's walk enters every node exactly once. - assert_eq!( - visits, - parser.root_node().preorder().count(), - "{}", - row.name - ); + assert_eq!(visits, parser.root_node().preorder().count(), "{name}"); // expected: one render per document published by the collection. - assert_eq!(renders, index.documents().len(), "{}", row.name); + assert_eq!(renders, index.documents().len(), "{name}"); // expected: default options build one member for every selected fragment and none // for comments outside documents. assert_eq!( @@ -1052,8 +1047,7 @@ fn check_lua_legacy_row(row: &LuaLegacyRow<'_>) -> usize { .documents() .map(|document| document.get().fragment_count()) .sum::(), - "{}", - row.name + "{name}" ); // expected: each comment is a member of one run, materialized once by the source view. assert_eq!( @@ -1063,53 +1057,138 @@ fn check_lua_legacy_row(row: &LuaLegacyRow<'_>) -> usize { .preorder() .filter(|node| node.kind() == "comment") .count(), - "{}", - row.name + "{name}" ); // expected: the source view scans every run once, at its final comment. - assert_eq!(scanned, row.comment_runs, "{}", row.name); + assert_eq!(scanned, row.comment_runs, "{name}"); // The coverage counter counts the collector's questions, with no tree-derived // closed form; the collection must move it on this thread. - assert_ne!(covered, 0, "{}", row.name); + assert_ne!(covered, 0, "{name}"); let [visits, renders, built, materialized, scanned, covered] = std::array::from_fn(|at| analyzed[at] - collected[at]); // expected: analyze never builds or renders a documentation index. - assert_eq!(visits, 0, "{}", row.name); - assert_eq!(renders, 0, "{}", row.name); + assert_eq!(visits, 0, "{name}"); + assert_eq!(renders, 0, "{name}"); // expected: the legacy view builds no source evidence or buffered members. - assert_eq!(built, 0, "{}", row.name); - assert_eq!(materialized, 0, "{}", row.name); + assert_eq!(built, 0, "{name}"); + assert_eq!(materialized, 0, "{name}"); // expected: the legacy view also scans every run once, at its final comment. - assert_eq!(scanned, row.comment_runs, "{}", row.name); + assert_eq!(scanned, row.comment_runs, "{name}"); // expected: the legacy view has no source context in which to ask a coverage question. - assert_eq!(covered, 0, "{}", row.name); + assert_eq!(covered, 0, "{name}"); index.documents().len() } #[cfg(feature = "lua")] #[test] +#[allow(clippy::too_many_lines)] fn documentation_lua_source_and_legacy_views_are_independent() { let first_file = documentation::source("lua-first-file.lua"); let primary = documentation::source("primary.lua"); let rows = [ - LuaLegacyRow { name: "l01_tagged_block_above_function", source: b"module(\"m\")\n--- audit\n-- @param x thing\nfunction f(x) end\n", loc: [4, 2, 1, 2, 0, 2], dloc_rows: &[1, 2], comment_runs: 1 }, - LuaLegacyRow { name: "l02_luals_tag_above_function", source: b"module(\"m\")\n---@param x integer\nfunction f(x) end\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + LuaLegacyRow { + name: "l01_tagged_block_above_function", + source: b"module(\"m\")\n--- audit\n-- @param x thing\nfunction f(x) end\n", + loc: [4, 2, 1, 2, 0, 2], + dloc_rows: &[1, 2], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l02_luals_tag_above_function", + source: b"module(\"m\")\n---@param x integer\nfunction f(x) end\n", + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, // The trailing `-- correction` on a code row starts a second run. - LuaLegacyRow { name: "l03_table_field_row", source: b"module(\"m\")\n--- settings\n-- @table options\noptions = {\nalpha = 1, -- correction\n}\n", loc: [6, 4, 1, 3, 0, 2], dloc_rows: &[1, 2], comment_runs: 2 }, + LuaLegacyRow { + name: "l03_table_field_row", + source: b"module(\"m\")\n--- settings\n-- @table options\noptions = {\n\ + alpha = 1, -- correction\n}\n", + loc: [6, 4, 1, 3, 0, 2], + dloc_rows: &[1, 2], + comment_runs: 2, + }, // The trailing `-- input` on a parameter row starts a second run. - LuaLegacyRow { name: "l04_parameter_row", source: b"module(\"m\")\n---audit\nfunction f(\nx -- input\n) end\n", loc: [5, 4, 1, 2, 0, 1], dloc_rows: &[1], comment_runs: 2 }, - LuaLegacyRow { name: "l05_explicit_virtual_row", source: b"module(\"m\")\n---audit\n-- @function ghost\n", loc: [3, 1, 0, 2, 0, 2], dloc_rows: &[1, 2], comment_runs: 1 }, - LuaLegacyRow { name: "l06_function_assigned_to_field", source: b"module(\"m\")\n---audit\nM.f = function() end\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, - LuaLegacyRow { name: "l07_local_table", source: b"module(\"m\")\n---audit\nlocal t = {}\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, - LuaLegacyRow { name: "l08_return_table", source: b"module(\"m\")\n---audit\nreturn {}\n", loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, - LuaLegacyRow { name: "l10_long_block_several_rows", source: b"module(\"m\")\n--[[--\naudit\nsecond\n]]\nfunction f() end\n", loc: [6, 2, 1, 4, 0, 4], dloc_rows: &[1, 2, 3, 4], comment_runs: 1 }, - LuaLegacyRow { name: "l11_first_block_with_module_tag", source: b"--- Module.\n-- @module m\nlocal M = {}\n", loc: [3, 1, 1, 2, 0, 2], dloc_rows: &[0, 1], comment_runs: 1 }, - LuaLegacyRow { name: "l12_fixture_first_file", source: &first_file, loc: [2, 1, 1, 1, 0, 1], dloc_rows: &[0], comment_runs: 1 }, - LuaLegacyRow { name: "l13_fixture_primary", source: &primary, loc: [3, 2, 1, 1, 0, 1], dloc_rows: &[1], comment_runs: 1 }, + LuaLegacyRow { + name: "l04_parameter_row", + source: b"module(\"m\")\n---audit\nfunction f(\nx -- input\n) end\n", + loc: [5, 4, 1, 2, 0, 1], + dloc_rows: &[1], + comment_runs: 2, + }, + LuaLegacyRow { + name: "l05_explicit_virtual_row", + source: b"module(\"m\")\n---audit\n-- @function ghost\n", + loc: [3, 1, 0, 2, 0, 2], + dloc_rows: &[1, 2], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l06_function_assigned_to_field", + source: b"module(\"m\")\n---audit\nM.f = function() end\n", + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l07_local_table", + source: b"module(\"m\")\n---audit\nlocal t = {}\n", + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l08_return_table", + source: b"module(\"m\")\n---audit\nreturn {}\n", + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l10_long_block_several_rows", + source: b"module(\"m\")\n--[[--\naudit\nsecond\n]]\nfunction f() end\n", + loc: [6, 2, 1, 4, 0, 4], + dloc_rows: &[1, 2, 3, 4], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l11_first_block_with_module_tag", + source: b"--- Module.\n-- @module m\nlocal M = {}\n", + loc: [3, 1, 1, 2, 0, 2], + dloc_rows: &[0, 1], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l12_fixture_first_file", + source: &first_file, + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + comment_runs: 1, + }, + LuaLegacyRow { + name: "l13_fixture_primary", + source: &primary, + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, // The code between `-- plain` and the marked block separates their runs. - LuaLegacyRow { name: "l14_plain_comment_module_block", source: b"-- plain\nmodule(\"m\")\n---audit\nfunction f() end\n", loc: [4, 2, 1, 2, 0, 1], dloc_rows: &[2], comment_runs: 2 }, - LuaLegacyRow { name: "l15_shebang_module_block", source: b"#!/usr/bin/env lua\nmodule(\"m\")\n---audit\nfunction f() end\n", loc: [4, 3, 1, 1, 0, 1], dloc_rows: &[2], comment_runs: 1 }, + LuaLegacyRow { + name: "l14_plain_comment_module_block", + source: b"-- plain\nmodule(\"m\")\n---audit\nfunction f() end\n", + loc: [4, 2, 1, 2, 0, 1], + dloc_rows: &[2], + comment_runs: 2, + }, + LuaLegacyRow { + name: "l15_shebang_module_block", + source: b"#!/usr/bin/env lua\nmodule(\"m\")\n---audit\nfunction f() end\n", + loc: [4, 3, 1, 1, 0, 1], + dloc_rows: &[2], + comment_runs: 1, + }, ]; for row in rows { let name = row.name; From 6cb7be795f2ca1d4f2e9f43f07d7cccc9ec35ad1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:42:46 -0800 Subject: [PATCH 082/221] test(documentation): pin PHP DocBlock owners, file documents and text in the source view --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/php_tests.rs | 1029 +++++++++++++++++ utils/documentation-php-unit1-perturb.json | 401 +++++++ 3 files changed, 1432 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/php_tests.rs create mode 100644 utils/documentation-php-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index fb0b6ec58..3e44727da 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1018,6 +1018,8 @@ mod lua_tests; #[cfg(test)] mod named_tests; #[cfg(test)] +mod php_tests; +#[cfg(test)] mod projection_tests; #[cfg(test)] mod remediation_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/php_tests.rs b/big-code-analysis-ast/src/documentation/collector/php_tests.rs new file mode 100644 index 000000000..d53f7a2a4 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/php_tests.rs @@ -0,0 +1,1029 @@ +//! PHP DocBlock source-view tests compare documents, associations, retained candidates and +//! pending assessments through both entry points. The grammar test collects nothing and +//! pins the parse-tree shapes the source-view tests rely on. Node queries are not in the view. + +#[cfg(feature = "php")] +use crate::documentation::*; +#[cfg(feature = "php")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "php")] +use std::ops::Range; + +#[cfg(feature = "php")] +use Run::{Copied, Decoded}; + +#[cfg(feature = "php")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "php")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(feature = "php")] +#[derive(Debug, PartialEq, Eq)] +enum Holder { + Node(&'static str, Range), + File(Range), +} + +#[cfg(feature = "php")] +#[derive(Debug, PartialEq, Eq)] +struct Link { + document: usize, + resolution: Resolution, + owner: Holder, +} + +#[cfg(feature = "php")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +} + +/// Documents, associations, retained candidates and pending assessments from a collection. +/// Assessment order is unspecified; shared values are asserted in `published`. Node queries +/// are not included. An empty view has nothing published and nothing pending. +#[cfg(feature = "php")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(feature = "php")] +const AWAITS_OWNER: &str = "Selected local or wrapper form awaits owner projection"; +#[cfg(feature = "php")] +const NEEDS_PROJECTION: &str = "Recognized declaration requires a semantic projection"; + +#[cfg(feature = "php")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "php")] +fn file(document: Doc) -> Doc { + Doc { + role: DocumentRole::FilePackage, + ..document + } +} + +#[cfg(feature = "php")] +fn owned(document: Doc, owner: Holder) -> View { + View { + documents: vec![document], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owner, + }], + ..View::default() + } +} + +#[cfg(feature = "php")] +fn node_owner(document: Doc, kind: &'static str, range: Range) -> View { + owned(document, Holder::Node(kind, range)) +} + +#[cfg(feature = "php")] +fn pending( + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +) -> Pending { + Pending { + axis, + reason, + node, + document, + } +} + +#[cfg(feature = "php")] +fn owner_pending(kind: &'static str, range: Range) -> Vec { + unordered([ + pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + Some((kind, range.clone())), + Some(0), + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some((kind, range)), + None, + ), + ]) +} + +#[cfg(feature = "php")] +fn unordered(entries: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = entries.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +#[cfg(feature = "php")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "php")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "php")] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("comment", range.clone())) + ); + range +} + +#[cfg(feature = "php")] +fn origin_run(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "php")] +fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|entry| (entry.output.range(), origin_run(&entry.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .map(|association| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "BcaPhpSource"); + assert_eq!(attachment.publication, Publication::Unknown); + assert_eq!(attachment.resolution, Resolution::Resolved); + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let comment = first.get().node().unwrap().node(); + assert_eq!(Some(attachment.lexical_scope.node()), comment.parent()); + let owner = facts.associated_owner(association, 0).unwrap(); + let holder = match owner.get() { + Owner::Node(declared) => { + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declared.node()) + ); + let (kind, range) = site(declared.node()); + Holder::Node(kind, range) + } + Owner::File(file) => { + assert_eq!(file.node(), root); + assert!(attachment.binding.is_none()); + Holder::File(file.node().byte_range()) + } + other => panic!("a node or file owner, found {other:?}"), + }; + Link { + document: ordered.iter().position(|known| *known == document).unwrap(), + resolution: attachment.resolution, + owner: holder, + } + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| { + Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| site(node.node())), + document: index + .assessed_document(assessment) + .unwrap() + .map(|document| ordered.iter().position(|known| *known == document).unwrap()), + } + })); + // The PHP source adapter is partial for all these cases. + assert_eq!(index.capability(), Capability::Partial); + // Qualifications belong to named-reference commands (the Doxygen path), absent here. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + associations, + evidence, + assessments, + } +} + +#[cfg(feature = "php")] +fn clean(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Php, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{}", + source.escape_ascii() + ); + parser +} + +#[cfg(feature = "php")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Php, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(feature = "php")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2], root: tree_sitter::Node<'_>) -> View { + let [typed, raw] = indexes.each_ref().map(|index| published(index, root)); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "php")] +fn view(source: &[u8]) -> View { + let parser = clean(source); + agreed( + &indexes(&parser, DocumentationOptions::default()), + parser.ts_tree().root_node(), + ) +} + +#[cfg(feature = "php")] +fn retained(source: &[u8]) -> View { + let parser = clean(source); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + agreed(&indexes(&parser, options), parser.ts_tree().root_node()) +} + +#[cfg(feature = "php")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|node| node.as_tree_sitter()) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "php")] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static str, Range)> { + let mut cursor = parent.walk(); + let mut result = Vec::new(); + if cursor.goto_first_child() { + loop { + let child = cursor.node(); + result.push((cursor.field_name(), child.kind(), child.byte_range())); + if !cursor.goto_next_sibling() { + break; + } + } + } + result +} + +#[cfg(feature = "php")] +#[test] +fn php_leading_docblock_documents_the_declaration_after_it() { + let declarations: [(&[u8], &str, Range); 5] = [ + ( + b"); 2] = [ + ( + b"); 2] = [ + ( + b"); 4] = [ + ( + b"\n\n); 2] = [ + ( + b"\n\n

\n node_bytes(&callee, code) == b\"define\",", + "new": " Php::Name => node_bytes(&callee, code) == b\"defined\",", + "expect": [ + "documentation::collector::php_tests::php_one_docblock_before_a_first_enum_or_define_goes_to_the_declaration" + ] + }, + { + "name": "php-attribute-detaches-the-block", + "file": "big-code-analysis-ast/src/roles/php.rs", + "old": " Ok(doc_target::owns(node, code, ancestors))\n", + "new": " Ok(doc_target::owns(node, code, ancestors)\n && !node.children().any(|child| child.kind() == \"attribute_list\"))\n", + "expect": [ + "documentation::collector::php_tests::php_attribute_between_docblock_and_declaration_does_not_detach" + ] + }, + { + "name": "php-file-rule-counts-three-blocks", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " docs == 2\n", + "new": " docs == 3\n", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble" + ] + }, + { + "name": "php-first-function-is-not-restricted", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " | Php::FunctionDefinition\n", + "new": "", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble" + ] + }, + { + "name": "php-first-class-is-not-restricted", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " Php::ClassDeclaration\n | Php::FunctionDefinition\n", + "new": " Php::FunctionDefinition\n", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace" + ] + }, + { + "name": "php-first-namespace-is-restricted", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " node.kind_id().into(),\n Php::ClassDeclaration\n", + "new": " node.kind_id().into(),\n Php::NamespaceDefinition\n | Php::ClassDeclaration\n", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace" + ] + }, + { + "name": "php-inline-html-is-not-preamble", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": "Php::PhpTag | Php::Text | Php::TextInterpolation | Php::DeclareStatement", + "new": "Php::PhpTag | Php::TextInterpolation | Php::DeclareStatement", + "expect": [ + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble" + ] + }, + { + "name": "php-no-block-is-the-files", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " .map(|file| !file))", + "new": " .map(|_| true))", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble" + ] + }, + { + "name": "php-every-block-is-the-files", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " .map(|file| !file))", + "new": " .map(|_| false))", + "expect": [ + "documentation::collector::php_tests::php_leading_docblock_documents_the_declaration_after_it", + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_attribute_between_docblock_and_declaration_does_not_detach", + "documentation::collector::php_tests::php_docblock_in_a_function_body", + "documentation::collector::php_tests::php_docblock_text_over_several_lines", + "documentation::collector::php_tests::php_docblock_with_crlf_line_endings", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble", + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "php-enum-block-stays-with-the-file", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "if matches!(kind, \"enum_declaration\" | \"expression_statement\") {", + "new": "if matches!(kind, \"expression_statement\") {", + "expect": [ + "documentation::collector::php_tests::php_one_docblock_before_a_first_enum_or_define_goes_to_the_declaration" + ] + }, + { + "name": "php-define-block-stays-with-the-file", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "if matches!(kind, \"enum_declaration\" | \"expression_statement\") {", + "new": "if matches!(kind, \"enum_declaration\") {", + "expect": [ + "documentation::collector::php_tests::php_one_docblock_before_a_first_enum_or_define_goes_to_the_declaration" + ] + }, + { + "name": "php-file-block-follows-every-declaration", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "if matches!(kind, \"enum_declaration\" | \"expression_statement\") {", + "new": "if !kind.is_empty() {", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble" + ] + }, + { + "name": "php-root-block-is-not-the-file", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " Profile::BcaPhpSource if draft.scope.0 == 0 => {", + "new": " Profile::BcaPhpSource if draft.scope.0 == usize::MAX => {", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_one_docblock_before_a_first_enum_or_define_goes_to_the_declaration", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble" + ] + }, + { + "name": "php-every-local-block-is-the-files", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " Profile::BcaPhpSource if draft.scope.0 == 0 => {", + "new": " Profile::BcaPhpSource if draft.scope.0 != usize::MAX => {", + "expect": [ + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "php-parameter-list-block-binds-forward", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " | Php::FormalParameters\n", + "new": "", + "expect": [ + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "php-local-blocks-are-not-collected", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " const SOURCE_LOCAL_DOCS: bool = true;", + "new": " const SOURCE_LOCAL_DOCS: bool = false;", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "superseded-block-is-unattached", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " MarkerSelection::Superseded\n } else {", + "new": " MarkerSelection::Unattached\n } else {", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace" + ] + }, + { + "name": "php-adjacent-blocks-join", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " joins: never_joins,", + "new": " joins: |a, b, c| !never_joins(a, b, c),", + "expect": [ + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace" + ] + }, + { + "name": "target-less-block-is-selected", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " MarkerSelection::Unattached\n };\n", + "new": " MarkerSelection::Selected\n };\n", + "expect": [ + "documentation::collector::php_tests::php_docblock_in_a_function_body" + ] + }, + { + "name": "php-every-comment-is-a-docblock", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " s.starts_with(b\"/**\") && s.get(3).is_some_and(u8::is_ascii_whitespace)", + "new": " s.starts_with(b\"/\") || s.starts_with(b\"#\")", + "expect": [ + "documentation::collector::php_tests::php_plain_comments_are_no_documentation" + ] + }, + { + "name": "php-define-statement-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " | \"expression_statement\"\n | \"property_declaration\"\n", + "new": " | \"property_declaration\"\n", + "expect": [ + "documentation::collector::php_tests::php_one_docblock_before_a_first_enum_or_define_goes_to_the_declaration" + ] + }, + { + "name": "php-property-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " | \"expression_statement\"\n | \"property_declaration\"\n", + "new": " | \"expression_statement\"\n", + "expect": [ + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "php-constant-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " | \"property_declaration\"\n | \"const_declaration\"\n", + "new": " | \"property_declaration\"\n", + "expect": [ + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "php-promoted-parameter-is-no-slot-candidate", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"property_promotion_parameter\" | \"simple_parameter\" | \"variadic_parameter\"", + "new": " \"simple_parameter\" | \"variadic_parameter\"", + "expect": [ + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "php-parameter-list-block-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"formal_parameters\"\n | \"property_promotion_parameter\"\n", + "new": " \"property_promotion_parameter\"\n", + "expect": [ + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + }, + { + "name": "block-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start = star + 1;", + "new": " line.content.start = star;", + "expect": [ + "documentation::collector::php_tests::php_docblock_text_over_several_lines", + "documentation::collector::php_tests::php_docblock_with_crlf_line_endings" + ] + }, + { + "name": "space-after-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "bytes[line.content.start] == b' ' {\n line.content.start += 1;", + "new": "bytes[line.content.start] == b' ' {\n line.content.start += 0;", + "expect": [ + "documentation::collector::php_tests::php_docblock_text_over_several_lines", + "documentation::collector::php_tests::php_docblock_with_crlf_line_endings" + ] + }, + { + "name": "empty-first-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while first < end && block.lines[first].content.is_empty() {", + "new": " while first > end && block.lines[first].content.is_empty() {", + "expect": [ + "documentation::collector::php_tests::php_docblock_text_over_several_lines", + "documentation::collector::php_tests::php_docblock_with_crlf_line_endings" + ] + }, + { + "name": "crlf-inside-block-is-copied", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.ending.len() == 2 {", + "new": " if line.ending.len() == 3 {", + "expect": [ + "documentation::collector::php_tests::php_docblock_with_crlf_line_endings" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::php_tests::php_leading_docblock_documents_the_declaration_after_it", + "documentation::collector::php_tests::php_first_file_rule_before_a_class_a_function_and_a_namespace", + "documentation::collector::php_tests::php_one_docblock_before_a_first_enum_or_define_goes_to_the_declaration", + "documentation::collector::php_tests::php_attribute_between_docblock_and_declaration_does_not_detach", + "documentation::collector::php_tests::php_docblock_in_a_function_body", + "documentation::collector::php_tests::php_docblock_text_over_several_lines", + "documentation::collector::php_tests::php_docblock_with_crlf_line_endings", + "documentation::collector::php_tests::php_inline_html_before_the_opening_tag_is_preamble", + "documentation::collector::php_tests::php_property_constant_and_promoted_parameter_keep_a_document_without_an_owner" + ] + } + ] +} From 133cd655579f83683ff0dc98fe0a9ebfe6b62a1c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:44:12 -0800 Subject: [PATCH 083/221] test(documentation): pin Ruby YARD owners and text in the source view --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/ruby_tests.rs | 849 ++++++++++++++++++ utils/documentation-ruby-unit1-perturb.json | 368 ++++++++ 3 files changed, 1219 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/ruby_tests.rs create mode 100644 utils/documentation-ruby-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index fb0b6ec58..9ab3bb820 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1022,4 +1022,6 @@ mod projection_tests; #[cfg(test)] mod remediation_tests; #[cfg(test)] +mod ruby_tests; +#[cfg(test)] mod tests; diff --git a/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs b/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs new file mode 100644 index 000000000..d3c76d646 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs @@ -0,0 +1,849 @@ +//! Ruby YARD source-view tests compare documents, associations, retained candidates and +//! pending assessments through both entry points. The grammar test collects nothing and +//! pins the tree shapes the source-view tests rely on. Node queries are not part of the view. + +#[cfg(feature = "ruby")] +use crate::documentation::*; +#[cfg(feature = "ruby")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "ruby")] +use std::ops::Range; + +#[cfg(feature = "ruby")] +use Run::{Copied, Synthetic}; + +#[cfg(feature = "ruby")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "ruby")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(feature = "ruby")] +#[derive(Debug, PartialEq, Eq)] +struct Link { + document: usize, + resolution: Resolution, + owner: (&'static str, Range), +} + +#[cfg(feature = "ruby")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +} + +/// Documents, associations, retained candidates and order-independent pending assessments +/// of a collection. Shared values are asserted by `published`; node queries are not included. +#[cfg(feature = "ruby")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(feature = "ruby")] +#[derive(Clone, Copy)] +enum Retain { + Unbound, + Directives, +} + +#[cfg(feature = "ruby")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "ruby")] +fn run( + fragments: [Range; F], + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::CommentRun, + fragments: fragments.into(), + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "ruby")] +fn owned(document: Doc, kind: &'static str, range: Range) -> View { + View { + documents: vec![document], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owner: (kind, range), + }], + ..View::default() + } +} + +#[cfg(feature = "ruby")] +fn pending( + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +) -> Pending { + Pending { + axis: AssessmentAxis::Owner, + reason, + node, + document, + } +} + +#[cfg(feature = "ruby")] +fn unordered(assessments: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = assessments.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +#[cfg(feature = "ruby")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "ruby")] +fn origin_run(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "ruby")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "ruby")] +fn fragment_span(fragment: &Fragment<'_>, source: &[u8]) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + let node = fragment.node().unwrap().node(); + assert_eq!((node.kind(), node.start_byte()), ("comment", range.start)); + // LF comments end with the spelling; on CRLF the tree node alone includes the CR. + assert!(matches!(&source[range.end..node.end_byte()], b"" | b"\r")); + range +} + +#[cfg(feature = "ruby")] +fn published(index: &DocumentationIndex<'_>, source: &[u8]) -> View { + // bca: suppress(halstead) -- one reading of the four published lists and their shared rules. + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let position = |document| ordered.iter().position(|known| *known == document).unwrap(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| { + fragment_span(facts.document_fragment(document, at).unwrap().get(), source) + }) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|entry| (entry.output.range(), origin_run(&entry.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .map(|association| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "YARD"); + assert_eq!(attachment.publication, Publication::Unknown); + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let first_comment = first.get().node().unwrap().node(); + let last = facts + .document_fragment(document, document.get().fragment_count() - 1) + .unwrap(); + let last_comment = last.get().node().unwrap().node(); + // Both the binding and scope follow from the comment nodes in the parse tree. + assert_eq!( + attachment.binding.map(NodeEvidence::node), + last_comment.next_sibling() + ); + assert_eq!( + Some(attachment.lexical_scope.node()), + first_comment.parent() + ); + let binding = attachment.binding.unwrap().node(); + let expected_owner = if binding.kind() == "body_statement" { + binding.child(0).unwrap() + } else { + binding + }; + let owner = facts.associated_owner(association, 0).unwrap(); + let Owner::Node(declared) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + assert_eq!(declared.node(), expected_owner); + Link { + document: position(document), + resolution: attachment.resolution, + owner: site(declared.node()), + } + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + ( + candidate.get().disposition, + fragment_span(fragment.get(), source), + ) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| site(node.node())), + document: index.assessed_document(assessment).unwrap().map(position), + })); + assert_eq!(index.capability(), Capability::Partial); + // Qualifications belong to named-reference commands, which none of these YARD cases has. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + associations, + evidence, + assessments, + } +} + +#[cfg(feature = "ruby")] +fn clean(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Ruby, source.to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error(), "{}", source.escape_ascii()); + parser +} + +#[cfg(feature = "ruby")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Ruby, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(feature = "ruby")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2], source: &[u8]) -> View { + let [typed, raw] = indexes.each_ref().map(|index| published(index, source)); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "ruby")] +fn view(source: &[u8]) -> View { + let parser = clean(source); + agreed(&indexes(&parser, DocumentationOptions::default()), source) +} + +#[cfg(feature = "ruby")] +fn retained(source: &[u8], retain: Retain) -> View { + let parser = clean(source); + let options = DocumentationOptions { + retain_unbound: matches!(retain, Retain::Unbound), + retain_directives: matches!(retain, Retain::Directives), + ..DocumentationOptions::default() + }; + agreed(&indexes(&parser, options), source) +} + +#[cfg(feature = "ruby")] +fn assert_default_then_retained( + source: &[u8], + mut expected: View, + retain: Retain, + candidates: &[(CandidateDisposition, Range)], +) { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + expected.evidence.extend_from_slice(candidates); + assert_eq!( + retained(source, retain), + expected, + "{}", + source.escape_ascii() + ); +} + +#[cfg(feature = "ruby")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|node| node.as_tree_sitter()) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "ruby")] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static str, Range)> { + let mut cursor = parent.walk(); + let mut result = Vec::new(); + if cursor.goto_first_child() { + loop { + let child = cursor.node(); + result.push((cursor.field_name(), child.kind(), child.byte_range())); + if !cursor.goto_next_sibling() { + break; + } + } + } + result +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_hash_run_documents_the_declaration_below_it() { + let sources: [(&[u8], &str, Range); 4] = [ + (b"# audit\ndef f\nend\n", "method", 8..17), + (b"# audit\ndef self.f; end\n", "singleton_method", 8..23), + (b"# audit\nclass C\nend\n", "class", 8..19), + (b"# audit\nmodule M\nend\n", "module", 8..20), + ]; + for (source, kind, owner) in sources { + assert_eq!( + view(source), + owned(comment(0..7, "audit", [(0..5, Copied(2..7))]), kind, owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_hash_rows_on_consecutive_rows_join_into_one_run() { + let sources: [(&[u8], Doc, Range); 3] = [ + ( + b"# a\n# b\ndef f; end\n", + run( + [0..3, 4..7], + "a\nb", + [ + (0..1, Copied(2..3)), + (1..2, Synthetic), + (2..3, Copied(6..7)), + ], + ), + 8..18, + ), + ( + b"# a\n#\n# b\ndef f; end\n", + run( + [0..3, 4..5, 6..9], + "a\n\nb", + [ + (0..1, Copied(2..3)), + (1..2, Synthetic), + (2..3, Synthetic), + (3..4, Copied(8..9)), + ], + ), + 10..20, + ), + ( + b"#\n# audit\n#\ndef f; end\n", + run([0..1, 2..9, 10..11], "audit", [(0..5, Copied(4..9))]), + 12..22, + ), + ]; + for (source, document, owner) in sources { + assert_eq!(view(source), owned(document, "method", owner)); + } +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_begin_block_alone_documents_the_method_below_it() { + assert_eq!( + view(b"=begin\naudit\n=end\ndef f\nend\n"), + owned( + comment(0..17, "audit", [(0..5, Copied(7..12))]), + "method", + 18..27 + ) + ); + assert_eq!( + view(b"=begin\na\n b\n=end\ndef f; end\n"), + owned( + comment( + 0..17, + "a\n b", + [ + (0..1, Copied(7..8)), + (1..2, Copied(8..9)), + (2..5, Copied(9..12)), + ] + ), + "method", + 18..28 + ) + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_blank_row_splits_a_run() { + // Only the lower run documents the method; the upper row is retained on request. + assert_default_then_retained( + b"# a\n\n# b\ndef f; end\n", + owned(comment(5..8, "b", [(0..1, Copied(7..8))]), "method", 9..19), + Retain::Unbound, + &[(CandidateDisposition::Unattached, 0..3)], + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_shebang_and_magic_comment_are_no_text() { + assert_default_then_retained( + b"#!/usr/bin/env ruby\n# frozen_string_literal: true\n# audit\ndef f; end\n", + owned( + comment(50..57, "audit", [(0..5, Copied(52..57))]), + "method", + 58..68, + ), + Retain::Directives, + &[ + (CandidateDisposition::Directive, 0..19), + (CandidateDisposition::Directive, 20..49), + ], + ); + let alone = b"#!/usr/bin/env ruby\ndef f; end\n"; + assert_default_then_retained( + alone, + View::default(), + Retain::Directives, + &[(CandidateDisposition::Directive, 0..19)], + ); + // Keeping unbound comments alone does not retain a directive. + assert_eq!(retained(alone, Retain::Unbound), View::default()); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_comment_on_a_code_row_is_no_document() { + let alone = b"x = 1 # t\ndef f; end\n"; + assert_default_then_retained( + alone, + View::default(), + Retain::Unbound, + &[(CandidateDisposition::Unattached, 6..9)], + ); + // Keeping directives alone does not retain the comment after code. + assert_eq!(retained(alone, Retain::Directives), View::default()); + assert_default_then_retained( + b"x = 1 # t\n# d\ndef f; end\n", + owned( + comment(10..13, "d", [(0..1, Copied(12..13))]), + "method", + 14..24, + ), + Retain::Unbound, + &[(CandidateDisposition::Unattached, 6..9)], + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_run_inside_a_class_body_documents_the_method_below_it() { + assert_eq!( + view(b"class C\n# audit\ndef f; end\nend\n"), + owned( + comment(8..15, "audit", [(0..5, Copied(10..15))]), + "method", + 16..26 + ) + ); + assert_eq!( + view(b"class C\ndef a; end\n# audit\ndef f; end\nend\n"), + owned( + comment(19..26, "audit", [(0..5, Copied(21..26))]), + "method", + 27..37 + ) + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_run_documents_a_method_inside_a_singleton_class() { + assert_eq!( + view(b"class C\nclass << self\n# audit\ndef f; end\nend\nend\n"), + owned( + comment(22..29, "audit", [(0..5, Copied(24..29))]), + "method", + 30..40 + ) + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_hash_marker_and_one_space_are_removed() { + let sources: [(&[u8], Doc, Range); 4] = [ + ( + b"#audit\ndef f; end\n", + comment(0..6, "audit", [(0..5, Copied(1..6))]), + 7..17, + ), + ( + b"# audit\ndef f; end\n", + comment(0..8, " audit", [(0..6, Copied(2..8))]), + 9..19, + ), + ( + b"#\taudit\ndef f; end\n", + comment(0..7, "\taudit", [(0..6, Copied(1..7))]), + 8..18, + ), + ( + b"# audit \ndef f; end\n", + comment(0..9, "audit ", [(0..7, Copied(2..9))]), + 10..20, + ), + ]; + for (source, document, owner) in sources { + assert_eq!(view(source), owned(document, "method", owner)); + } +} + +/// Pins today's double-hash outcome; a later unit changes it on purpose. +#[cfg(feature = "ruby")] +#[test] +fn ruby_double_hash_rows_keep_their_outcome() { + let awaiting = "Selected local or wrapper form awaits owner projection"; + assert_eq!( + view(b"##\n# audit\ndef f; end\n"), + View { + documents: vec![run([0..2, 3..10], "audit", [(0..5, Copied(5..10))])], + assessments: unordered([pending(awaiting, None, Some(0))]), + ..View::default() + } + ); + assert_eq!( + view(b"## audit\ndef f; end\n"), + View { + documents: vec![comment(0..8, "audit", [(0..5, Copied(3..8))])], + assessments: unordered([pending(awaiting, None, Some(0))]), + ..View::default() + } + ); + assert_eq!( + view(b"# a\n## b\ndef f; end\n"), + owned( + run( + [0..3, 4..8], + "a\nb", + [ + (0..1, Copied(2..3)), + (1..2, Synthetic), + (2..3, Copied(7..8)), + ] + ), + "method", + 9..19 + ) + ); +} + +#[cfg(feature = "ruby")] +#[test] +fn ruby_crlf_line_endings_stay_out_of_fragments_and_text() { + assert_eq!( + view(b"# audit\r\ndef f\r\nend\r\n"), + owned( + comment(0..7, "audit", [(0..5, Copied(2..7))]), + "method", + 9..19 + ) + ); + assert_eq!( + view(b"# a\r\n# b\r\ndef f; end\r\n"), + owned( + run( + [0..3, 5..8], + "a\nb", + [ + (0..1, Copied(2..3)), + (1..2, Synthetic), + (2..3, Copied(7..8)), + ] + ), + "method", + 10..20 + ) + ); +} + +/// Pins today's pending forms; a later unit changes their owner projections on purpose. +#[cfg(feature = "ruby")] +#[test] +fn ruby_pending_forms_keep_their_outcome() { + let awaiting = "Selected local or wrapper form awaits owner projection"; + let projection = "Recognized declaration requires a semantic projection"; + assert_eq!( + view(b"class C\n# audit\nprivate def f; end\nend\n"), + View { + documents: vec![comment(8..15, "audit", [(0..5, Copied(10..15))])], + assessments: unordered([ + pending(awaiting, Some(("body_statement", 16..34)), Some(0)), + pending(projection, Some(("body_statement", 16..34)), None), + pending(projection, Some(("call", 16..34)), None), + ]), + ..View::default() + } + ); + for (source, kind, range) in [ + (b"# audit\nattr_reader :x\n".as_slice(), "call", 8..22), + (b"# audit\nX = 1\n".as_slice(), "assignment", 8..13), + ] { + assert_eq!( + view(source), + View { + documents: vec![comment(0..7, "audit", [(0..5, Copied(2..7))])], + assessments: unordered([ + pending(awaiting, Some((kind, range.clone())), Some(0)), + pending(projection, Some((kind, range)), None), + ]), + ..View::default() + } + ); + } +} + +#[cfg(feature = "ruby")] +#[test] +#[allow(clippy::too_many_lines)] +fn ruby_grammar_shapes_the_unit_relies_on() { + let source = b"# a\n# b\ndef f\nend\n"; + let parser = clean(source); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("program", 0..18)); + assert_eq!( + parts(root), + [ + (None, "comment", 0..3), + (None, "comment", 4..7), + (None, "method", 8..17), + ] + ); + for range in [0..3, 4..7] { + let comment = node_at(&parser, "comment", range.clone()); + assert!(comment.is_extra()); + assert_eq!(comment.parent(), Some(root)); + assert_eq!(source[range.end], b'\n'); + } + let method = node_at(&parser, "method", 8..17); + assert_eq!( + method.child_by_field_name("name").map(site), + Some(("identifier", 12..13)) + ); + + let source = b"=begin\naudit\n=end\ndef f\nend\n"; + let parser = clean(source); + let comment = node_at(&parser, "comment", 0..17); + assert_eq!(comment.parent(), Some(parser.ts_tree().root_node())); + assert_eq!(comment.next_sibling().map(site), Some(("method", 18..27))); + assert_eq!(&source[comment.end_byte()..18], b"\n"); + assert_eq!(comment.end_position().row - comment.start_position().row, 2); + + let parser = clean(b"class C\n# a\ndef f; end\n# b\ndef g; end\nend\n"); + let class = node_at(&parser, "class", 0..41); + assert_eq!( + parts(class), + [ + (None, "class", 0..5), + (Some("name"), "constant", 6..7), + (None, "comment", 8..11), + (Some("body"), "body_statement", 12..37), + (None, "end", 38..41), + ] + ); + assert!(node_at(&parser, "comment", 8..11).is_extra()); + assert_eq!( + parts(class.child_by_field_name("body").unwrap()), + [ + (None, "method", 12..22), + (None, "comment", 23..26), + (None, "method", 27..37), + ] + ); + assert!(node_at(&parser, "comment", 23..26).is_extra()); + + let parser = clean(b"class C\nclass << self\n# audit\ndef f; end\nend\nend\n"); + let singleton = node_at(&parser, "singleton_class", 8..44); + assert_eq!( + parts(singleton), + [ + (None, "class", 8..13), + (None, "<<", 14..16), + (Some("value"), "self", 17..21), + (None, "comment", 22..29), + (Some("body"), "body_statement", 30..40), + (None, "end", 41..44), + ] + ); + assert_eq!( + singleton + .child_by_field_name("body") + .unwrap() + .child(0) + .map(site), + Some(("method", 30..40)) + ); + + let parser = clean(b"class C\n# audit\nprivate def f; end\nend\n"); + let class = node_at(&parser, "class", 0..38); + assert_eq!( + parts(class)[2..4], + [ + (None, "comment", 8..15), + (Some("body"), "body_statement", 16..34), + ] + ); + let body = class.child_by_field_name("body").unwrap(); + assert_eq!(parts(body), [(None, "call", 16..34)]); + let call = node_at(&parser, "call", 16..34); + assert_eq!( + parts(call), + [ + (Some("method"), "identifier", 16..23), + (Some("arguments"), "argument_list", 24..34), + ] + ); + assert_eq!( + parts(call.child_by_field_name("arguments").unwrap()), + [(None, "method", 24..34)] + ); + + let parser = clean(b"# audit\nattr_reader :x\n"); + let call = node_at(&parser, "call", 8..22); + assert_eq!( + parts(call), + [ + (Some("method"), "identifier", 8..19), + (Some("arguments"), "argument_list", 20..22), + ] + ); + assert_eq!( + parts(call.child_by_field_name("arguments").unwrap()), + [(None, "simple_symbol", 20..22)] + ); + + let parser = clean(b"# audit\nX = 1\n"); + let assignment = node_at(&parser, "assignment", 8..13); + assert_eq!( + assignment.child_by_field_name("left").map(site), + Some(("constant", 8..9)) + ); + + let parser = clean(b"x = 1 # t\n# d\ndef f; end\n"); + let assignment = node_at(&parser, "assignment", 0..5); + assert_eq!( + assignment.child_by_field_name("left").map(site), + Some(("identifier", 0..1)) + ); + let after_code = assignment.next_sibling().unwrap(); + assert_eq!(site(after_code), ("comment", 6..9)); + assert_eq!( + after_code.start_position().row, + assignment.start_position().row + ); + assert_eq!( + after_code.next_sibling().map(site), + Some(("comment", 10..13)) + ); + assert_eq!( + after_code.next_sibling().unwrap().next_sibling().map(site), + Some(("method", 14..24)) + ); + + let parser = clean(b"def self.f; end\nmodule M\nend\nclass C\nend\n"); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "singleton_method", 0..15), + (None, "module", 16..28), + (None, "class", 29..40), + ] + ); + + let parser = clean(b"#!/usr/bin/env ruby\n##\ndef f; end\n"); + assert_eq!( + parts(parser.ts_tree().root_node())[0..2], + [(None, "comment", 0..19), (None, "comment", 20..22)] + ); + + let source = b"# audit\r\ndef f\r\nend\r\n"; + let parser = clean(source); + let root = parser.ts_tree().root_node(); + let comment = node_at(&parser, "comment", 0..8); + let method = node_at(&parser, "method", 9..19); + assert_eq!(site(root), ("program", 0..21)); + assert_eq!(&source[comment.byte_range()], b"# audit\r"); + assert_eq!(&source[comment.end_byte()..method.start_byte()], b"\n"); + assert_eq!(&source[method.end_byte()..root.end_byte()], b"\r\n"); +} diff --git a/utils/documentation-ruby-unit1-perturb.json b/utils/documentation-ruby-unit1-perturb.json new file mode 100644 index 000000000..be3e06a47 --- /dev/null +++ b/utils/documentation-ruby-unit1-perturb.json @@ -0,0 +1,368 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis-ast", + "--all-features", + "--lib", + "documentation::" + ], + "cases": [ + { + "name": "ruby-positional-docs-off", + "file": "big-code-analysis-ast/src/checker/ruby.rs", + "old": " const SOURCE_POSITIONAL_DOCS: bool = true;", + "new": " const SOURCE_POSITIONAL_DOCS: bool = false;", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it", + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run", + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text", + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document", + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "ruby-positional-targets-off", + "file": "big-code-analysis-ast/src/checker/ruby.rs", + "old": " const SOURCE_POSITIONAL_TARGETS: bool = true;", + "new": " const SOURCE_POSITIONAL_TARGETS: bool = false;", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it", + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run", + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text", + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document", + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "ruby-method-not-a-target", + "file": "big-code-analysis-ast/src/roles/ruby.rs", + "old": " owns [\n Method,\n SingletonMethod,\n Class,\n Module,", + "new": " owns [\n SingletonMethod,\n Class,\n Module,", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it", + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run", + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text", + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document", + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text" + ] + }, + { + "name": "ruby-singleton-method-not-a-target", + "file": "big-code-analysis-ast/src/roles/ruby.rs", + "old": " Method,\n SingletonMethod,\n Class,\n Module,", + "new": " Method,\n Class,\n Module,", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it" + ] + }, + { + "name": "ruby-class-not-a-target", + "file": "big-code-analysis-ast/src/roles/ruby.rs", + "old": " SingletonMethod,\n Class,\n Module,", + "new": " SingletonMethod,\n Module,", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it" + ] + }, + { + "name": "ruby-module-not-a-target", + "file": "big-code-analysis-ast/src/roles/ruby.rs", + "old": " Class,\n Module,\n Alias(gated_by alias_names_a_method no_chain),", + "new": " Class,\n Alias(gated_by alias_names_a_method no_chain),", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it" + ] + }, + { + "name": "positional-run-has-no-target", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " target,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.uncertainty,", + "new": " target: None,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.uncertainty,", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it", + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run", + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text", + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document", + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "positional-run-has-no-binding", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " target,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.uncertainty,", + "new": " target,\n scope,\n binding: None,\n role: DocumentRole::Primary,\n unresolved: run.uncertainty,", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it", + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run", + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text", + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document", + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "positional-scope-is-the-root", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " let scope = self.evidence_id(run.containing)?.unwrap_or(NodeId(0));\n let mut draft = Draft {", + "new": " let scope = NodeId(0);\n let mut draft = Draft {", + "expect": [ + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class" + ] + }, + { + "name": "blank-row-joins-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " || (next.start_row() == comment.end_row().saturating_add(1)", + "new": " || (next.start_row() >= comment.end_row().saturating_add(1)", + "expect": [ + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run" + ] + }, + { + "name": "trailing-comment-is-eligible", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " if prev.end_row() >= row_first.start_row() {\n run.first_eligible = clean_first;", + "new": " if prev.end_row() > row_first.start_row() {\n run.first_eligible = clean_first;", + "expect": [ + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document" + ] + }, + { + "name": "ruby-shebang-is-text", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " if s.starts_with(b\"#!\") {\n return Ok(true);\n }\n let Some(body) = s.strip_prefix(b\"#\") else {\n return Ok(false);\n };\n let body = scan::trim(body, budget)?;", + "new": " if s.starts_with(b\"#!\") {\n return Ok(false);\n }\n let Some(body) = s.strip_prefix(b\"#\") else {\n return Ok(false);\n };\n let body = scan::trim(body, budget)?;", + "expect": [ + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text" + ] + }, + { + "name": "ruby-magic-comment-is-text", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " b\"frozen_string_literal\",\n b\"frozen-string-literal\",", + "new": " b\"frozen-string-literal\",", + "expect": [ + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text" + ] + }, + { + "name": "directive-selected-when-retained", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": " selected: !ineligible && !directive && selection != RunSelection::Unattached,", + "new": " selected: !ineligible && selection != RunSelection::Unattached,", + "expect": [ + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text" + ] + }, + { + "name": "ruby-body-statement-not-descended", + "file": "big-code-analysis-ast/src/checker/ruby.rs", + "old": " Ruby::BodyStatement | Ruby::BodyStatement2 | Ruby::BlockBody => node.child(0),", + "new": " Ruby::BodyStatement2 | Ruby::BlockBody => node.child(0),", + "expect": [ + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "yard-body-statement-not-a-wrapper", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " \"if_modifier\" | \"unless_modifier\" | \"body_statement\" | \"block_body\" | \"then\"", + "new": " \"if_modifier\" | \"unless_modifier\" | \"block_body\" | \"then\"", + "expect": [ + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "ruby-class-body-not-read", + "file": "big-code-analysis-ast/src/lang_helpers/ruby.rs", + "old": " Ruby::Class\n | Ruby::Module\n | Ruby::SingletonClass\n | Ruby::If", + "new": " Ruby::Class => 0,\n Ruby::Module\n | Ruby::SingletonClass\n | Ruby::If", + "expect": [ + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "ruby-singleton-class-body-not-read", + "file": "big-code-analysis-ast/src/lang_helpers/ruby.rs", + "old": " Ruby::Class\n | Ruby::Module\n | Ruby::SingletonClass\n | Ruby::If", + "new": " Ruby::SingletonClass => 0,\n Ruby::Class\n | Ruby::Module\n | Ruby::If", + "expect": [ + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class" + ] + }, + { + "name": "yard-call-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " Profile::Yard => matches!(node.kind(), \"call\" | \"assignment\" | \"alias\"),", + "new": " Profile::Yard => matches!(node.kind(), \"assignment\" | \"alias\"),", + "expect": [ + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "yard-assignment-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " Profile::Yard => matches!(node.kind(), \"call\" | \"assignment\" | \"alias\"),", + "new": " Profile::Yard => matches!(node.kind(), \"call\" | \"alias\"),", + "expect": [ + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "ruby-double-hash-is-no-opener", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " if s.starts_with(b\"##\") && s.get(2) != Some(&b'#') {\n return Ok(true);\n }", + "new": " if s.starts_with(b\"##\") && s.get(2) != Some(&b'#') {\n return Ok(false);\n }", + "expect": [ + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome" + ] + }, + { + "name": "explicit-opener-keeps-target", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " positional::RunSelection::Opener(\n positional::OpenerReason::Explicit | positional::OpenerReason::Tagged,\n ) => {", + "new": " positional::RunSelection::Opener(positional::OpenerReason::Tagged) => {", + "expect": [ + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome" + ] + }, + { + "name": "ruby-hash-marker-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if raw.starts_with(b\"##\") && raw.get(2) != Some(&b'#') {\n 2\n } else {\n 1\n },", + "new": " if raw.starts_with(b\"##\") && raw.get(2) != Some(&b'#') {\n 2\n } else {\n 2\n },", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed" + ] + }, + { + "name": "ruby-double-hash-marker-one-byte", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if raw.starts_with(b\"##\") && raw.get(2) != Some(&b'#') {\n 2\n } else {\n 1\n },", + "new": " if raw.starts_with(b\"##\") && raw.get(2) != Some(&b'#') {\n 1\n } else {\n 1\n },", + "expect": [ + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_run_documents_the_declaration_below_it", + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_blank_row_splits_a_run", + "documentation::collector::ruby_tests::ruby_shebang_and_magic_comment_are_no_text", + "documentation::collector::ruby_tests::ruby_comment_on_a_code_row_is_no_document", + "documentation::collector::ruby_tests::ruby_run_inside_a_class_body_documents_the_method_below_it", + "documentation::collector::ruby_tests::ruby_run_documents_a_method_inside_a_singleton_class", + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text", + "documentation::collector::ruby_tests::ruby_pending_forms_keep_their_outcome" + ] + }, + { + "name": "hash-row-trailing-space-trimmed", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if c_block\n && let Some(last) = lines.last_mut()", + "new": " if (c_block || !block)\n && let Some(last) = lines.last_mut()", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_marker_and_one_space_are_removed" + ] + }, + { + "name": "member-join-is-a-space", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if position != first_block {\n builder.transformed(\"\\n\", Origin::Synthetic, budget)?;", + "new": " if position != first_block {\n builder.transformed(\" \", Origin::Synthetic, budget)?;", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome", + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text" + ] + }, + { + "name": "leading-empty-member-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while first_block < last_block && empty_block(&blocks[first_block], budget)? {", + "new": " while first_block > last_block && empty_block(&blocks[first_block], budget)? {", + "expect": [ + "documentation::collector::ruby_tests::ruby_hash_rows_on_consecutive_rows_join_into_one_run", + "documentation::collector::ruby_tests::ruby_double_hash_rows_keep_their_outcome" + ] + }, + { + "name": "ruby-begin-row-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " range.start + (first + 1).min(raw.len())..range.start + last,", + "new": " range.start..range.start + last,", + "expect": [ + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it" + ] + }, + { + "name": "ruby-end-row-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " range.start + (first + 1).min(raw.len())..range.start + last,", + "new": " range.start + (first + 1).min(raw.len())..range.end,", + "expect": [ + "documentation::collector::ruby_tests::ruby_begin_block_alone_documents_the_method_below_it" + ] + }, + { + "name": "hash-row-terminator-kept", + "file": "big-code-analysis-ast/src/documentation/streaming/positional.rs", + "old": " || bytes.starts_with(b\"#\")\n", + "new": "", + "expect": [ + "documentation::collector::ruby_tests::ruby_crlf_line_endings_stay_out_of_fragments_and_text" + ] + } + ] +} From 9a51cce403f41748da5c470e05657c2a0195df2c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:44:16 -0800 Subject: [PATCH 084/221] test(loc): guard Ruby documentation rows before owner and profile work --- src/metrics/loc/documentation_tests.rs | 215 ++++++++++++++++++ ...cumentation-ruby-unit1-legacy-perturb.json | 28 +++ 2 files changed, 243 insertions(+) create mode 100644 utils/documentation-ruby-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 2ff9b61cc..6af40fab8 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1204,3 +1204,218 @@ fn documentation_lua_source_and_legacy_views_are_independent() { comment_runs: 1, }); } + +#[cfg(feature = "ruby")] +#[test] +#[allow(clippy::too_many_lines, clippy::arithmetic_side_effects)] +fn documentation_ruby_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::positional::{ + evidence_built, members_materialized, positional_runs_collected, + }; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, included_range_visits, observations, + }; + struct Row<'a> { + name: &'static str, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + // A run is a maximal sequence of comments starting on the previous comment's + // final row or the next row. Only l10 has two: code separates its comments. + comment_runs: usize, + } + let counters = || { + [ + observations().visits, + observations().renders, + evidence_built::observed(), + members_materialized::observed(), + positional_runs_collected::observed(), + included_range_visits::observed(), + ] + }; + let fixture = documentation::source("primary.rb"); + let sources = [ + Row { + name: "l01_visibility_wrapped_def", + source: b"class C\n# audit\nprivate def f; end\nend\n", + loc: [4, 3, 2, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + Row { + name: "l02_attribute_call", + source: b"# audit\nattr_reader :x\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + comment_runs: 1, + }, + Row { + name: "l03_attribute_two_names", + source: b"class C\n# audit\nattr_accessor :a, :b\nend\n", + loc: [4, 3, 1, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + Row { + name: "l04_constant", + source: b"# audit\nX = 1\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + comment_runs: 1, + }, + Row { + name: "l05_alias", + source: b"class C\ndef a; end\n# audit\nalias b a\nend\n", + loc: [5, 4, 3, 1, 0, 1], + dloc_rows: &[2], + comment_runs: 1, + }, + Row { + name: "l06_blank_row_before_def", + source: b"# audit\n\ndef f; end\n", + loc: [3, 1, 1, 1, 1, 0], + dloc_rows: &[], + comment_runs: 1, + }, + Row { + name: "l07_double_hash_above_def", + source: b"##\n# audit\ndef f; end\n", + loc: [3, 1, 1, 2, 0, 2], + dloc_rows: &[0, 1], + comment_runs: 1, + }, + Row { + name: "l08_yard_virtual_method", + source: b"# @!method ghost\n# audit\n", + loc: [2, 0, 0, 2, 0, 2], + dloc_rows: &[0, 1], + comment_runs: 1, + }, + Row { + name: "l09_block_then_row", + source: b"=begin\na\n=end\n# b\ndef f; end\n", + loc: [5, 1, 1, 4, 0, 4], + dloc_rows: &[0, 1, 2, 3], + comment_runs: 1, + }, + Row { + name: "l10_nodoc_after_def", + source: b"# audit\ndef f; end # :nodoc:\n", + loc: [2, 1, 1, 2, 0, 1], + dloc_rows: &[0], + comment_runs: 2, + }, + Row { + name: "l11_shebang_and_magic_comment", + source: b"#!/usr/bin/env ruby\n# frozen_string_literal: true\n# audit\ndef f; end\n", + loc: [4, 1, 1, 3, 0, 1], + dloc_rows: &[2], + comment_runs: 1, + }, + Row { + name: "l12_later_visibility_symbol", + source: b"class C\n# audit\ndef f; end\nprivate :f\nend\n", + loc: [5, 4, 2, 1, 0, 1], + dloc_rows: &[1], + comment_runs: 1, + }, + Row { + name: "l13_fixture_primary_rb", + source: &fixture, + loc: [3, 2, 1, 1, 0, 1], + dloc_rows: &[0], + comment_runs: 1, + }, + ]; + let (mut renders_total, mut evidence_total) = (0, 0); + for row in sources { + let name = row.name; + let parser = + crate::langs::AnyParser::parse(LANG::Ruby, row.source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error(), "{name}"); + let idle = counters(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let collected = counters(); + let space = analyze( + Source::new(LANG::Ruby, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = counters(); + + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| collected[at] - idle[at]); + // expected: the walk visits each node exactly once. + assert_eq!(visits, parser.root_node().preorder().count(), "{name}"); + // expected: one render per document published by the collection. + assert_eq!(renders, index.documents().len(), "{name}"); + // expected: the default positional stream builds one member per selected fragment. + assert_eq!( + built, + index + .documents() + .map(|document| document.get().fragment_count()) + .sum::(), + "{name}" + ); + // expected: every comment is materialized once as a member of a run. + assert_eq!( + materialized, + parser + .root_node() + .preorder() + .filter(|node| node.kind() == "comment") + .count(), + "{name}" + ); + // expected: every run is scanned once, at its last comment. + assert_eq!(scanned, row.comment_runs, "{name}"); + // Coverage questions have no tree-derived exact count; collection must ask some. + assert_ne!(covered, 0, "{name}"); + renders_total += renders; + evidence_total += built; + + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| analyzed[at] - collected[at]); + // expected: analyze does not collect or render a source documentation index. + assert_eq!(visits, 0, "{name}"); + assert_eq!(renders, 0, "{name}"); + // expected: the legacy view builds no source evidence or buffered members. + assert_eq!(built, 0, "{name}"); + assert_eq!(materialized, 0, "{name}"); + // expected: the legacy view scans each comment run once too. + assert_eq!(scanned, row.comment_runs, "{name}"); + // expected: the legacy view has no source context to ask coverage questions. + assert_eq!(covered, 0, "{name}"); + } + // One row may publish nothing; the remaining rows control both positive deltas. + assert_ne!(renders_total, 0); + assert_ne!(evidence_total, 0); +} diff --git a/utils/documentation-ruby-unit1-legacy-perturb.json b/utils/documentation-ruby-unit1-legacy-perturb.json new file mode 100644 index 000000000..8babfd2a3 --- /dev/null +++ b/utils/documentation-ruby-unit1-legacy-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_ruby_source_and_legacy_views_are_independent"], + "cases": [ + { + "name": "ruby-magic-comment-is-text", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " b\"frozen_string_literal\",\n b\"frozen-string-literal\",", + "new": " b\"frozen-string-literal\",", + "expect": ["metrics::loc::documentation_tests::documentation_ruby_source_and_legacy_views_are_independent"] + }, + { + "name": "ruby-body-statement-not-descended", + "file": "big-code-analysis-ast/src/checker/ruby.rs", + "old": " Ruby::BodyStatement | Ruby::BodyStatement2 | Ruby::BlockBody => node.child(0),", + "new": " Ruby::BodyStatement2 | Ruby::BlockBody => node.child(0),", + "expect": ["metrics::loc::documentation_tests::documentation_ruby_source_and_legacy_views_are_independent"] + }, + { + "name": "ruby-method-not-a-target", + "file": "big-code-analysis-ast/src/roles/ruby.rs", + "old": " owns [\n Method,\n SingletonMethod,\n Class,\n Module,", + "new": " owns [\n SingletonMethod,\n Class,\n Module,", + "expect": ["metrics::loc::documentation_tests::documentation_ruby_source_and_legacy_views_are_independent"] + } + ] +} From 515f546120ce74a029fec44504c010d839cdd87f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:44:57 -0800 Subject: [PATCH 085/221] test(loc): guard PHP documentation rows before owner and selection work --- src/metrics/loc/documentation_tests.rs | 174 ++++++++++++++++++ ...ocumentation-php-unit1-legacy-perturb.json | 42 +++++ 2 files changed, 216 insertions(+) create mode 100644 utils/documentation-php-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 2ff9b61cc..4c755360e 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1204,3 +1204,177 @@ fn documentation_lua_source_and_legacy_views_are_independent() { comment_runs: 1, }); } + +#[cfg(feature = "php")] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_php_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + struct Row<'a> { + name: &'static str, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + } + let fixture = documentation::source("php-define.php"); + let rows = [ + Row { + name: "l01_property", + source: b"(), + "{name}" + ); + rendered_total += renders; + built_total += members; + + let space = analyze( + Source::new(LANG::Php, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + let analyzed = observations(); + // expected: analyze uses legacy LOC rows and builds no source evidence. + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + assert_eq!(analyzed.renders - collected.renders, 0, "{name}"); + assert_eq!(analyzed.visits - collected.visits, 0, "{name}"); + } + assert_ne!(rendered_total, 0); + assert_ne!(built_total, 0); +} diff --git a/utils/documentation-php-unit1-legacy-perturb.json b/utils/documentation-php-unit1-legacy-perturb.json new file mode 100644 index 000000000..2c253f134 --- /dev/null +++ b/utils/documentation-php-unit1-legacy-perturb.json @@ -0,0 +1,42 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis", + "--all-features", + "--lib", + "documentation_php_source_and_legacy_views_are_independent" + ], + "cases": [ + { + "name": "php-property-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/php.rs", + "old": " PropertyDeclaration,\n", + "new": "", + "expect": [ + "metrics::loc::documentation_tests::documentation_php_source_and_legacy_views_are_independent" + ] + }, + { + "name": "php-define-call-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/php.rs", + "old": " Php::Name => node_bytes(&callee, code) == b\"define\",", + "new": " Php::Name => node_bytes(&callee, code) == b\"defined\",", + "expect": [ + "metrics::loc::documentation_tests::documentation_php_source_and_legacy_views_are_independent" + ] + }, + { + "name": "php-parameter-list-block-binds-forward", + "file": "big-code-analysis-ast/src/checker/php.rs", + "old": " | Php::FormalParameters\n", + "new": "", + "expect": [ + "metrics::loc::documentation_tests::documentation_php_source_and_legacy_views_are_independent" + ] + } + ] +} From 9f051d5c4b5ddbed3f49cc828d895d5d7e2a7bbd Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:31:51 -0800 Subject: [PATCH 086/221] test(documentation): restore a PHP legacy source and mark the view reader Restore the legacy test source to the exact evidence bytes, read the grammar source length from the parse tree, and keep resolved associations out of the view. Mark the cohesive published-view reader for the Halstead advisory. No expected value or production code changed. --- .../src/documentation/collector/php_tests.rs | 19 +++++-------------- src/metrics/loc/documentation_tests.rs | 2 +- 2 files changed, 6 insertions(+), 15 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/php_tests.rs b/big-code-analysis-ast/src/documentation/collector/php_tests.rs index d53f7a2a4..cddcacd78 100644 --- a/big-code-analysis-ast/src/documentation/collector/php_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/php_tests.rs @@ -42,7 +42,6 @@ enum Holder { #[derive(Debug, PartialEq, Eq)] struct Link { document: usize, - resolution: Resolution, owner: Holder, } @@ -99,11 +98,7 @@ fn file(document: Doc) -> Doc { fn owned(document: Doc, owner: Holder) -> View { View { documents: vec![document], - associations: vec![Link { - document: 0, - resolution: Resolution::Resolved, - owner, - }], + associations: vec![Link { document: 0, owner }], ..View::default() } } @@ -189,6 +184,7 @@ fn origin_run(origin: &Origin<'_>) -> Run { #[cfg(feature = "php")] fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + // bca: suppress(halstead) -- one reading of the four published lists and the rules they share. let facts = index.facts(); let ordered: Vec<_> = index.documents().collect(); let documents = ordered @@ -241,7 +237,6 @@ fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> Vie }; Link { document: ordered.iter().position(|known| *known == document).unwrap(), - resolution: attachment.resolution, owner: holder, } }) @@ -465,12 +460,10 @@ fn php_first_file_rule_before_a_class_a_function_and_a_namespace() { associations: vec![ Link { document: 0, - resolution: Resolution::Resolved, - owner: Holder::File(root) + owner: Holder::File(root), }, Link { document: 1, - resolution: Resolution::Resolved, owner: Holder::Node(kind, range), }, ], @@ -726,12 +719,10 @@ fn php_inline_html_before_the_opening_tag_is_preamble() { associations: vec![ Link { document: 0, - resolution: Resolution::Resolved, - owner: Holder::File(0..53) + owner: Holder::File(0..53), }, Link { document: 1, - resolution: Resolution::Resolved, owner: Holder::Node("function_definition", 37..52), }, ], @@ -799,8 +790,8 @@ fn php_grammar_shapes_the_unit_relies_on() { let source = b" Date: Wed, 25 Nov 2026 00:34:14 -0800 Subject: [PATCH 087/221] test(documentation): pin the order of two Ruby documents and read offsets from nodes Add a two-document Ruby source-view case, derive grammar offsets from parsed nodes, and name sources in failing assertions. Remove an unneeded lint allowance; no production code changed. --- .../src/documentation/collector/ruby_tests.rs | 49 ++++++++++++++++--- src/metrics/loc/documentation_tests.rs | 2 +- 2 files changed, 43 insertions(+), 8 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs b/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs index d3c76d646..cc5bde9ba 100644 --- a/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/ruby_tests.rs @@ -410,7 +410,12 @@ fn ruby_hash_rows_on_consecutive_rows_join_into_one_run() { ), ]; for (source, document, owner) in sources { - assert_eq!(view(source), owned(document, "method", owner)); + assert_eq!( + view(source), + owned(document, "method", owner), + "{}", + source.escape_ascii() + ); } } @@ -525,6 +530,28 @@ fn ruby_run_inside_a_class_body_documents_the_method_below_it() { 27..37 ) ); + assert_eq!( + view(b"class C\n# a\ndef f; end\n# b\ndef g; end\nend\n"), + View { + documents: vec![ + comment(8..11, "a", [(0..1, Copied(10..11))]), + comment(23..26, "b", [(0..1, Copied(25..26))]), + ], + associations: vec![ + Link { + document: 0, + resolution: Resolution::Resolved, + owner: ("method", 12..22), + }, + Link { + document: 1, + resolution: Resolution::Resolved, + owner: ("method", 27..37), + }, + ], + ..View::default() + } + ); } #[cfg(feature = "ruby")] @@ -566,7 +593,12 @@ fn ruby_hash_marker_and_one_space_are_removed() { ), ]; for (source, document, owner) in sources { - assert_eq!(view(source), owned(document, "method", owner)); + assert_eq!( + view(source), + owned(document, "method", owner), + "{}", + source.escape_ascii() + ); } } @@ -669,7 +701,9 @@ fn ruby_pending_forms_keep_their_outcome() { pending(projection, Some((kind, range)), None), ]), ..View::default() - } + }, + "{}", + source.escape_ascii() ); } } @@ -691,10 +725,10 @@ fn ruby_grammar_shapes_the_unit_relies_on() { ] ); for range in [0..3, 4..7] { - let comment = node_at(&parser, "comment", range.clone()); + let comment = node_at(&parser, "comment", range); assert!(comment.is_extra()); assert_eq!(comment.parent(), Some(root)); - assert_eq!(source[range.end], b'\n'); + assert_eq!(source[comment.end_byte()], b'\n'); } let method = node_at(&parser, "method", 8..17); assert_eq!( @@ -705,9 +739,10 @@ fn ruby_grammar_shapes_the_unit_relies_on() { let source = b"=begin\naudit\n=end\ndef f\nend\n"; let parser = clean(source); let comment = node_at(&parser, "comment", 0..17); + let method = comment.next_sibling().unwrap(); assert_eq!(comment.parent(), Some(parser.ts_tree().root_node())); - assert_eq!(comment.next_sibling().map(site), Some(("method", 18..27))); - assert_eq!(&source[comment.end_byte()..18], b"\n"); + assert_eq!(site(method), ("method", 18..27)); + assert_eq!(&source[comment.end_byte()..method.start_byte()], b"\n"); assert_eq!(comment.end_position().row - comment.start_position().row, 2); let parser = clean(b"class C\n# a\ndef f; end\n# b\ndef g; end\nend\n"); diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 6af40fab8..27d76ec18 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1207,7 +1207,7 @@ fn documentation_lua_source_and_legacy_views_are_independent() { #[cfg(feature = "ruby")] #[test] -#[allow(clippy::too_many_lines, clippy::arithmetic_side_effects)] +#[allow(clippy::too_many_lines)] fn documentation_ruby_source_and_legacy_views_are_independent() { use big_code_analysis_ast::documentation::streaming::positional::{ evidence_built, members_materialized, positional_runs_collected, From e68cbbe59c23dcda62fa55ad975b312455f4e931 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:59:15 -0800 Subject: [PATCH 088/221] docs(documentation): say that one resolved association lists several field owners --- docs/development/documentation_extraction.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/development/documentation_extraction.md b/docs/development/documentation_extraction.md index 3ffe68c1f..e6e0b7673 100644 --- a/docs/development/documentation_extraction.md +++ b/docs/development/documentation_extraction.md @@ -103,7 +103,7 @@ cache. | --- | --- | | Physical fragment | One source occurrence; ordered included byte ranges; optional exact syntax node | | Logical document | Ordered fragment composition, role and text state; shared by its associations | -| Association | One document, its convention/provenance, binding wrapper and resolved owner or unresolved candidates | +| Association | One document, its convention/provenance, binding wrapper and resolved owners or unresolved candidates | | Owner | Exact node, location-backed slot, file/root, logical declaration group or virtual target | A line-comment fragment excludes its terminating LF/CRLF, even when the grammar @@ -115,7 +115,7 @@ braces or quotes. Included-range intersection applies to each of these spellings An occurrence's identity is not its text. Equal strings at different offsets remain different fragments. A document describing several qualifying fields -is stored once and has several resolved associations. A conditional declaration +is stored once; one resolved association lists them. A conditional declaration with alternative branches has unresolved alternatives, not several claims that all branches are active. From 3854363427ce912cd0013a8450b4b3fd330ff8fd Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:00:55 -0800 Subject: [PATCH 089/221] test(documentation): pin the Java owners and no-document forms the collector already resolves --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/java_tests.rs | 508 ++++++++++++++++++ 2 files changed, 510 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/java_tests.rs diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index fb0b6ec58..760743d06 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1014,6 +1014,8 @@ mod form_tests; #[cfg(test)] mod go_tests; #[cfg(test)] +mod java_tests; +#[cfg(test)] mod lua_tests; #[cfg(test)] mod named_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/java_tests.rs b/big-code-analysis-ast/src/documentation/collector/java_tests.rs new file mode 100644 index 000000000..2280eeeb8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/java_tests.rs @@ -0,0 +1,508 @@ +#![allow(clippy::single_range_in_vec_init)] + +#[cfg(feature = "java")] +use crate::documentation::*; + +#[cfg(feature = "java")] +use crate::{AnyParser, LANG}; + +#[cfg(feature = "java")] +use std::ops::Range; + +#[cfg(feature = "java")] +fn spelled(node: tree_sitter::Node<'_>) -> String { + format!("{} {}..{}", node.kind(), node.start_byte(), node.end_byte()) +} + +#[cfg(feature = "java")] +fn owner_text<'s>(index: &DocumentationIndex<'s>, owner: FactRef<'_, Owner<'s>>) -> String { + match owner.get() { + Owner::Node(node) => format!("Node({})", spelled(node.node())), + Owner::File(node) => format!("File({})", spelled(node.node())), + Owner::Slot(slot) => { + let pieces: Vec<_> = slot + .source + .pieces() + .iter() + .map(|piece| format!("{}..{}", piece.range().start, piece.range().end)) + .collect(); + assert!(!slot.source.has_excluded_gap()); + format!( + "Slot({:?} #{} {} in {})", + slot.role, + slot.ordinal, + pieces.join(","), + owner_text(index, index.facts().slot_enclosing(owner).unwrap()) + ) + } + _ => panic!("unexpected owner variant"), + } +} + +#[cfg(feature = "java")] +type Doc = (Vec>, Option); + +#[cfg(feature = "java")] +fn documents(index: &DocumentationIndex<'_>) -> Vec { + index + .documents() + .map(|document| { + let fragments = (0..document.get().fragment_count()) + .map(|position| { + let fragment = index.facts().document_fragment(document, position).unwrap(); + let pieces = fragment.get().source().pieces(); + assert_eq!(pieces.len(), 1); + pieces[0].range() + }) + .collect(); + let text = index + .complete_text(document) + .unwrap() + .map(|text| text.text().to_owned()); + (fragments, text) + }) + .collect() +} + +#[cfg(feature = "java")] +type Edge = (usize, Resolution, Vec, Option, String); + +#[cfg(feature = "java")] +fn associations(index: &DocumentationIndex<'_>) -> Vec { + index + .associations() + .map(|association| { + let document = index.facts().associated_document(association).unwrap(); + let owners = (0..association.get().owner_count()) + .map(|position| { + owner_text( + index, + index + .facts() + .associated_owner(association, position) + .unwrap(), + ) + }) + .collect(); + ( + index + .documents() + .position(|known| known == document) + .unwrap(), + association.get().resolution, + owners, + association.get().binding.map(|node| spelled(node.node())), + spelled(association.get().lexical_scope.node()), + ) + }) + .collect() +} + +#[cfg(feature = "java")] +type Pending = (AssessmentAxis, &'static str, Option, Option); + +#[cfg(feature = "java")] +fn assessments<'i, 's: 'i>( + index: &'i DocumentationIndex<'s>, + found: impl Iterator>>, +) -> Vec { + found + .map(|assessment| { + ( + assessment.get().axis, + assessment.get().reason, + assessment.get().node.map(|node| spelled(node.node())), + index + .assessed_document(assessment) + .unwrap() + .map(|document| { + index + .documents() + .position(|known| known == document) + .unwrap() + }), + ) + }) + .collect() +} + +#[cfg(feature = "java")] +fn evidence(index: &DocumentationIndex<'_>) -> Vec<(CandidateDisposition, Range)> { + index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + let pieces = fragment.get().source().pieces(); + assert_eq!(pieces.len(), 1); + (candidate.get().disposition, pieces[0].range()) + }) + .collect() +} + +#[cfg(feature = "java")] +fn node<'t>(root: tree_sitter::Node<'t>, kind: &str, range: Range) -> tree_sitter::Node<'t> { + let mut found = Vec::new(); + let mut stack = vec![root]; + while let Some(current) = stack.pop() { + if current.kind() == kind && current.byte_range() == range { + found.push(current); + } + let mut cursor = current.walk(); + stack.extend(current.children(&mut cursor)); + } + assert_eq!(found.len(), 1, "{kind} {range:?}"); + found[0] +} + +#[cfg(feature = "java")] +fn both( + source: &str, + options: DocumentationOptions, + check: impl Fn(tree_sitter::Node<'_>, &DocumentationIndex<'_>), +) { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Java, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + check(parser.ts_tree().root_node(), &index); + } +} + +#[cfg(feature = "java")] +fn unbound() -> DocumentationOptions { + DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + } +} + +#[cfg(feature = "java")] +#[test] +#[allow(clippy::too_many_lines)] +fn java_declarations_own_their_leading_documentation() { + for (source, fragment, owner, scope, others) in [ + ( + "/**audit*/\ninterface I {}", + 0..10, + "interface_declaration 11..25", + "program 0..25", + vec![], + ), + ( + "/**audit*/\nenum E { A }", + 0..10, + "enum_declaration 11..23", + "program 0..23", + vec![("enum_constant", 20..21)], + ), + ( + "/**audit*/\nrecord R(int a) {}", + 0..10, + "record_declaration 11..29", + "program 0..29", + vec![], + ), + ( + "/**audit*/\n@interface A {}", + 0..10, + "annotation_type_declaration 11..26", + "program 0..26", + vec![], + ), + ( + "/**audit*/\nmodule m { }", + 0..10, + "module_declaration 11..23", + "program 0..23", + vec![], + ), + ( + "class C { /**audit*/ void f() {} }", + 10..20, + "method_declaration 21..32", + "class_body 8..34", + vec![("class_declaration", 0..34)], + ), + ( + "interface I { /**audit*/ void g(); }", + 14..24, + "method_declaration 25..34", + "interface_body 12..36", + vec![("interface_declaration", 0..36)], + ), + ( + "interface I { /**audit*/ private void h() {} }", + 14..24, + "method_declaration 25..44", + "interface_body 12..46", + vec![("interface_declaration", 0..46)], + ), + ( + "@interface A { /**audit*/ int v() default 1; }", + 15..25, + "annotation_type_element_declaration 26..44", + "annotation_type_body 13..46", + vec![("annotation_type_declaration", 0..46)], + ), + ( + "class C { /**audit*/ C() {} }", + 10..20, + "constructor_declaration 21..27", + "class_body 8..29", + vec![("class_declaration", 0..29)], + ), + ( + "record R(int x) { /**audit*/ R {} }", + 18..28, + "compact_constructor_declaration 29..33", + "class_body 16..35", + vec![("record_declaration", 0..35)], + ), + ( + "enum E { /**audit*/ A }", + 9..19, + "enum_constant 20..21", + "enum_body 7..23", + vec![("enum_declaration", 0..23)], + ), + ( + "interface I { /**audit*/ class N {} }", + 14..24, + "class_declaration 25..35", + "interface_body 12..37", + vec![("interface_declaration", 0..37)], + ), + ( + "class C { void m() { /**audit*/ class L {} } }", + 21..31, + "class_declaration 32..42", + "block 19..44", + vec![("class_declaration", 0..46), ("method_declaration", 10..44)], + ), + ( + "class C { void f() { new Object() { /**audit*/ void m() {} }; } }", + 36..46, + "method_declaration 47..58", + "class_body 34..60", + vec![("class_declaration", 0..65), ("method_declaration", 10..63)], + ), + ] { + both(source, DocumentationOptions::default(), |root, index| { + assert!(!root.has_error(), "{source}"); + assert_eq!( + documents(index), + [(vec![fragment.clone()], Some("audit".to_owned()))], + "{source}" + ); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![format!("Node({owner})")], + Some(owner.to_owned()), + scope.to_owned() + )], + "{source}" + ); + assert_eq!(assessments(index, index.assessments()), [], "{source}"); + let (kind, range) = owner.split_once(' ').unwrap(); + let (start, end) = range.split_once("..").unwrap(); + let target = node(root, kind, start.parse().unwrap()..end.parse().unwrap()); + let query = index.node_associations(target).unwrap(); + assert!(query.associations().eq(index.associations()), "{source}"); + for (kind, range) in &others { + let query = index + .node_associations(node(root, kind, range.clone())) + .unwrap(); + assert!(!query.projection_pending(), "{source}"); + assert_eq!(query.associations().len(), 0, "{source}"); + } + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_record_documentation_belongs_to_the_type() { + for (source, record, constructor) in [ + ( + "/** Record doc */\nrecord R(int a) {}\n", + "record_declaration 18..36", + None, + ), + ( + "/** Record doc */\nrecord R(int a) { R {} }\n", + "record_declaration 18..42", + Some(36..40), + ), + ] { + both(source, DocumentationOptions::default(), |root, index| { + assert_eq!( + documents(index), + [(vec![0..17], Some("Record doc".to_owned()))] + ); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![format!("Node({record})")], + Some(record.to_owned()), + format!("program 0..{}", source.len()) + )] + ); + assert!(matches!( + index.node_associations(node(root, "formal_parameters", 26..33)), + Err(OwnerError::UnsupportedOwner) + )); + if let Some(range) = constructor.clone() { + let query = index + .node_associations(node(root, "compact_constructor_declaration", range)) + .unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 0); + } + assert_eq!(assessments(index, index.assessments()), []); + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_comments_without_a_declaration_produce_no_document() { + for (source, kept, dropped) in [ + ( + "/**a*/\npublic /**b*/ static class C {}", + vec![(vec![0..6], Some("a".to_owned()))], + vec![14..20], + ), + ("class C { void f(/**p*/ int x) {} }", vec![], vec![17..23]), + ( + "/** r */\nrecord R(/** a */ int a) { }\n", + vec![(vec![0..8], Some("r".to_owned()))], + vec![18..26], + ), + ( + "class C { void f() {} }", + vec![], + vec![8..14, 21..27], + ), + ( + "class C { /**i*/ static {} /**j*/ {} }", + vec![], + vec![10..16, 27..33], + ), + ( + "class C { void f() { /**v*/ int x; } }", + vec![], + vec![21..27], + ), + ( + "class C { void f() {}\n /**d*/\n ;\n void g() {} }", + vec![], + vec![24..30], + ), + ] { + both(source, DocumentationOptions::default(), |root, index| { + assert!(!root.has_error(), "{source}"); + assert_eq!(documents(index), kept, "{source}"); + assert_eq!(index.associations().len(), kept.len(), "{source}"); + assert_eq!(evidence(index), [], "{source}"); + assert_eq!(assessments(index, index.assessments()), [], "{source}"); + }); + both(source, unbound(), |_, index| { + assert_eq!(documents(index), kept, "{source}"); + assert_eq!( + evidence(index), + dropped + .iter() + .map(|range| (CandidateDisposition::Unattached, range.clone())) + .collect::>(), + "{source}" + ); + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_field_grammar_names_declarators_by_kind_and_first_child() { + let mut declarations = 0; + let mut declarators = 0; + for source in [ + "class C { /**audit*/ int a = 1, b[] = {2}, c; }", + "class C {\n /** a */\n int x,\n /** b */\n y;\n}\n", + "class C { /**audit*/ @Deprecated int x; }", + "class C { /**audit*/ int x /*c*/ = 1; }", + "class C { /**audit*/ int /*c*/ x, /*d*/ y; }", + "class C { /**audit*/ java.util.Map m, n[]; }", + "class C { /**audit*/ int record, open; }", + "class C { /**audit*/ int a, _; }", + "interface I { /**audit*/ int K = 1; }", + "@interface A { /**audit*/ int K = 1; }", + "enum E { /**a*/ A, /**b*/ B; /**f*/ int x; }", + "class C { Object o = new Object() { /**audit*/ int x; }; }", + ] { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + assert!(!root.has_error(), "{source}"); + let mut stack = vec![root]; + while let Some(current) = stack.pop() { + let mut cursor = current.walk(); + stack.extend(current.children(&mut cursor)); + if !matches!(current.kind(), "field_declaration" | "constant_declaration") { + continue; + } + declarations += 1; + let mut by_field = Vec::new(); + let mut by_kind = Vec::new(); + let mut cursor = current.walk(); + assert!(cursor.goto_first_child()); + loop { + if cursor.field_name() == Some("declarator") { + by_field.push(cursor.node().id()); + } + if cursor.node().kind() == "variable_declarator" { + by_kind.push(cursor.node().id()); + } + if !cursor.goto_next_sibling() { + break; + } + } + assert!(!by_field.is_empty(), "{source}"); + assert_eq!(by_field, by_kind, "{source}"); + let mut cursor = current.walk(); + for child in current.children(&mut cursor) { + if child.kind() != "variable_declarator" { + continue; + } + declarators += 1; + let name = child.child_by_field_name("name").unwrap(); + assert_eq!(child.child(0).unwrap().id(), name.id(), "{source}"); + assert!( + matches!(name.kind(), "identifier" | "underscore_pattern"), + "{source}" + ); + assert_eq!( + name.kind() == "underscore_pattern", + &source.as_bytes()[name.byte_range()] == b"_", + "{source}" + ); + } + } + } + // expected: one declaration per source, two in the anonymous-class source. + assert_eq!(declarations, 13); + // expected: 3 + 2 + 1 + 1 + 2 + 2 + 2 + 2 + 1 + 1 + 1 + 2. + assert_eq!(declarators, 20); +} From c5913aad392a126c8b91f40d7fe9cf7da52f1d10 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:04:09 -0800 Subject: [PATCH 090/221] feat(documentation): give Java fields and constants field-slot owners --- .bca-baseline.toml | 12 +- CHANGELOG.md | 8 + .../src/documentation/collector/form_tests.rs | 4 +- .../src/documentation/collector/java_tests.rs | 1105 ++++++++++++++++- .../documentation/collector/projections.rs | 71 ++ src/metrics/loc/documentation_tests.rs | 98 ++ .../documentation/java-unit1-provenance.json | 23 + utils/documentation-audit-perturb.json | 2 +- utils/documentation-form-matrix.json | 4 +- utils/documentation-java-unit1-perturb.json | 161 +++ 10 files changed, 1476 insertions(+), 12 deletions(-) create mode 100644 tests/fixtures/documentation/java-unit1-provenance.json create mode 100644 utils/documentation-java-unit1-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index f4c449f99..c74105c26 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -665,7 +665,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>" metric = "wmc" -value = 67.0 +value = 73.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" @@ -695,31 +695,31 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "abc" -value = 44.15880433163923 +value = 46.75467891024384 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cognitive" -value = 27.0 +value = 29.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cyclomatic" -value = 29.0 +value = 32.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "halstead.effort" -value = 191098.72458144272 +value = 223608.98282915083 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "nexits" -value = 11.0 +value = 12.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index ea48a4e28..79e40afe2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,14 @@ for historical reference. Marker and positional runs retain excluded-prefix and suffix composition metadata. Legacy positional coverage streams without buffering members. (#1659) +- The unstable AST documentation collector now gives Java field declarations and + interface or annotation-type constant declarations owners: the declaration + and one field slot per declarator, spelled by the declarator's name. A + documentation comment before such a declaration is one document associated + with every slot, as JDK 25 attaches it. A declaration that holds a syntax + error, excluded bytes or an unnamed (`_`) declarator stays a pending owner. + Legacy documentation rows are unchanged. (#1666) + - Added unstable AST-crate source-marker `Checker` hooks and streaming requests that retain selection, source pieces and attachment uncertainty. The separate legacy event stream preserves existing metric behavior. (#1658) diff --git a/big-code-analysis-ast/src/documentation/collector/form_tests.rs b/big-code-analysis-ast/src/documentation/collector/form_tests.rs index 4a33038f8..ac5842cb5 100644 --- a/big-code-analysis-ast/src/documentation/collector/form_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/form_tests.rs @@ -49,10 +49,10 @@ fn assert_pending_form(language: LANG, source: &str, owner_kind: &str) { #[cfg(feature = "java")] #[test] -fn java_field_form_is_pending_in_default_queries() { +fn java_unnamed_field_form_is_pending_in_default_queries() { assert_pending_form( LANG::Java, - "class C { /**audit*/ int x; }", + "class C { /**audit*/ int _; }", "field_declaration", ); } diff --git a/big-code-analysis-ast/src/documentation/collector/java_tests.rs b/big-code-analysis-ast/src/documentation/collector/java_tests.rs index 2280eeeb8..e0db79e03 100644 --- a/big-code-analysis-ast/src/documentation/collector/java_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/java_tests.rs @@ -1,14 +1,26 @@ -#![allow(clippy::single_range_in_vec_init)] +#![allow(clippy::single_range_in_vec_init, clippy::naive_bytecount)] #[cfg(feature = "java")] use crate::documentation::*; +#[cfg(feature = "java")] +use crate::documentation::budget::WorkBudget; + #[cfg(feature = "java")] use crate::{AnyParser, LANG}; #[cfg(feature = "java")] use std::ops::Range; +#[cfg(feature = "java")] +use std::cell::Cell; + +#[cfg(feature = "java")] +const PENDING_DOCUMENT: &str = "Selected local or wrapper form awaits owner projection"; + +#[cfg(feature = "java")] +const PENDING_OWNER: &str = "Recognized declaration requires a semantic projection"; + #[cfg(feature = "java")] fn spelled(node: tree_sitter::Node<'_>) -> String { format!("{} {}..{}", node.kind(), node.start_byte(), node.end_byte()) @@ -177,6 +189,36 @@ fn both( } } +#[cfg(feature = "java")] +fn restricted(source: &str, included: &[Range]) -> tree_sitter::Tree { + let point = |offset: usize| { + let before = &source.as_bytes()[..offset]; + tree_sitter::Point::new( + before.iter().filter(|byte| **byte == b'\n').count(), + before + .iter() + .rev() + .take_while(|byte| **byte != b'\n') + .count(), + ) + }; + let ranges: Vec<_> = included + .iter() + .map(|range| tree_sitter::Range { + start_byte: range.start, + end_byte: range.end, + start_point: point(range.start), + end_point: point(range.end), + }) + .collect(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Java.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + parser.parse(source, None).unwrap() +} + #[cfg(feature = "java")] fn unbound() -> DocumentationOptions { DocumentationOptions { @@ -185,6 +227,14 @@ fn unbound() -> DocumentationOptions { } } +#[cfg(feature = "java")] +fn slot(ordinal: usize, name: Range, declaration: &str) -> String { + format!( + "Slot(Field #{ordinal} {}..{} in Node({declaration}))", + name.start, name.end + ) +} + #[cfg(feature = "java")] #[test] #[allow(clippy::too_many_lines)] @@ -506,3 +556,1056 @@ fn java_field_grammar_names_declarators_by_kind_and_first_child() { // expected: 3 + 2 + 1 + 1 + 2 + 2 + 2 + 2 + 1 + 1 + 1 + 2. assert_eq!(declarators, 20); } + +#[cfg(feature = "java")] +#[test] +fn java_field_declarators_each_own_a_field_slot() { + for (source, fragment, declaration, names) in [ + ( + "class C { /**audit*/ int x; }", + 10..20, + "field_declaration 21..27", + vec![25..26], + ), + ( + "class C { /**audit*/ int a, b; }", + 10..20, + "field_declaration 21..30", + vec![25..26, 28..29], + ), + ( + "class C { /**audit*/ int a[], b; }", + 10..20, + "field_declaration 21..32", + vec![25..26, 30..31], + ), + ( + "class C { /**audit*/ int a = 1, b[] = {2}, c; }", + 10..20, + "field_declaration 21..45", + vec![25..26, 32..33, 43..44], + ), + ( + "class C { /**audit*/ @Deprecated int x; }", + 10..20, + "field_declaration 21..39", + vec![37..38], + ), + ( + "class C { /**audit*/ public static final int X = 1; }", + 10..20, + "field_declaration 21..51", + vec![45..46], + ), + ] { + both(source, DocumentationOptions::default(), |_, index| { + assert_eq!( + documents(index), + [(vec![fragment.clone()], Some("audit".to_owned()))], + "{source}" + ); + let owners: Vec<_> = names + .iter() + .enumerate() + .map(|(ordinal, name)| slot(ordinal, name.clone(), declaration)) + .collect(); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + owners, + Some(declaration.to_owned()), + format!("class_body 8..{}", source.len()) + )], + "{source}" + ); + assert_eq!(assessments(index, index.assessments()), [], "{source}"); + // expected: file, class, declaration, one slot per declarator. + assert_eq!(index.facts().owners().len(), 3 + names.len(), "{source}"); + for (ordinal, name) in names.iter().enumerate() { + let owner = index + .facts() + .associated_owner(index.associations().next().unwrap(), ordinal) + .unwrap(); + let Owner::Slot(found) = owner.get() else { + panic!("field slot") + }; + assert_eq!( + found.source.pieces()[0].bytes(), + &source.as_bytes()[name.clone()] + ); + } + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_field_queries_answer_per_slot_and_per_declaration() { + both( + "class C { /**audit*/ int x; }", + DocumentationOptions::default(), + |root, index| { + let field = node(root, "field_declaration", 21..27); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let projection = index.node_projection(field).unwrap(); + assert!(!projection.pending()); + assert!(projection.owners().eq([owner])); + assert!(index.node_owners(field).unwrap().eq([owner])); + let query = index.node_associations(field).unwrap(); + assert!(!query.projection_pending()); + assert!(query.associations().eq([association])); + assert_eq!(query.assessments().count(), 0); + assert!( + index + .owner_associations(owner) + .unwrap() + .associations() + .eq([association]) + ); + let enclosing = index.facts().slot_enclosing(owner).unwrap(); + assert_eq!( + owner_text(index, enclosing), + "Node(field_declaration 21..27)" + ); + let declaration = index.owner_associations(enclosing).unwrap(); + assert_eq!(declaration.associations().len(), 0); + assert_eq!(declaration.assessments().count(), 0); + for (kind, range) in [("variable_declarator", 25..26), ("identifier", 25..26)] { + assert!(matches!( + index.node_associations(node(root, kind, range.clone())), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_projection(node(root, kind, range)), + Err(OwnerError::UnsupportedOwner) + )); + } + }, + ); + both( + "class C { /**audit*/ int a, b; }", + DocumentationOptions::default(), + |root, index| { + let field = node(root, "field_declaration", 21..30); + let association = index.associations().next().unwrap(); + let owners = [ + index.facts().associated_owner(association, 0).unwrap(), + index.facts().associated_owner(association, 1).unwrap(), + ]; + assert!(matches!( + index.node_associations(field), + Err(OwnerError::MultipleOwners) + )); + assert!(index.node_owners(field).unwrap().eq(owners)); + let projection = index.node_projection(field).unwrap(); + assert!(!projection.pending()); + assert!(projection.owners().eq(owners)); + assert_eq!(projection.assessments().count(), 0); + for owner in owners { + let query = index.owner_associations(owner).unwrap(); + assert!(query.associations().eq([association])); + assert_eq!(query.assessments().count(), 0); + assert_eq!( + owner_text(index, index.facts().slot_enclosing(owner).unwrap()), + "Node(field_declaration 21..30)" + ); + } + assert_ne!(owners[0], owners[1]); + }, + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_constants_own_field_slots() { + for (source, fragment, declaration, name, scope) in [ + ( + "interface I { /**audit*/ int K = 1; }", + 14..24, + "constant_declaration 25..35", + 29..30, + "interface_body 12..37", + ), + ( + "@interface A { /**audit*/ int K = 1; }", + 15..25, + "constant_declaration 26..36", + 30..31, + "annotation_type_body 13..38", + ), + ] { + both(source, DocumentationOptions::default(), |_, index| { + assert_eq!( + documents(index), + [(vec![fragment.clone()], Some("audit".to_owned()))] + ); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![slot(0, name.clone(), declaration)], + Some(declaration.to_owned()), + scope.to_owned() + )] + ); + assert_eq!(assessments(index, index.assessments()), []); + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_enum_constants_and_enum_field_have_their_own_owners() { + both( + "enum E { /**a*/ A, /**b*/ B; /**f*/ int x; }", + DocumentationOptions::default(), + |_, index| { + assert_eq!( + documents(index), + [ + (vec![9..15], Some("a".to_owned())), + (vec![19..25], Some("b".to_owned())), + (vec![29..35], Some("f".to_owned())), + ] + ); + assert_eq!( + associations(index), + [ + ( + 0, + Resolution::Resolved, + vec!["Node(enum_constant 16..17)".to_owned()], + Some("enum_constant 16..17".to_owned()), + "enum_body 7..44".to_owned() + ), + ( + 1, + Resolution::Resolved, + vec!["Node(enum_constant 26..27)".to_owned()], + Some("enum_constant 26..27".to_owned()), + "enum_body 7..44".to_owned() + ), + ( + 2, + Resolution::Resolved, + vec![slot(0, 40..41, "field_declaration 36..42")], + Some("field_declaration 36..42".to_owned()), + "enum_body_declarations 27..42".to_owned() + ), + ] + ); + assert_eq!(assessments(index, index.assessments()), []); + // expected: file, enum, two constants, declaration, slot. + assert_eq!(index.facts().owners().len(), 6); + }, + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_fields_of_records_anonymous_and_local_classes_own_field_slots() { + for (source, fragment, declaration, name, scope, owners) in [ + ( + "record R(int a) { /**audit*/ static int x; }", + 18..28, + "field_declaration 29..42", + 40..41, + "class_body 16..44", + // expected: file, record, declaration, slot. + 4, + ), + ( + "class C { Object o = new Object() { /**audit*/ int x; }; }", + 36..46, + "field_declaration 47..53", + 51..52, + "class_body 34..55", + // expected: file, class, inner declaration and slot, outer declaration and slot. + 6, + ), + ( + "class C { void f() { class L { /**audit*/ int x; } } }", + 31..41, + "field_declaration 42..48", + 46..47, + "class_body 29..50", + // expected: file, class C, method, class L, declaration, slot. + 6, + ), + ] { + both(source, DocumentationOptions::default(), |_, index| { + assert_eq!( + documents(index), + [(vec![fragment.clone()], Some("audit".to_owned()))] + ); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![slot(0, name.clone(), declaration)], + Some(declaration.to_owned()), + scope.to_owned() + )] + ); + assert_eq!(assessments(index, index.assessments()), []); + assert_eq!(index.facts().owners().len(), owners); + }); + } + both( + "class C { Object o = new Object() { /**audit*/ int x; }; }", + DocumentationOptions::default(), + |root, index| { + let outer = index + .node_owners(node(root, "field_declaration", 10..56)) + .unwrap() + .map(|owner| owner_text(index, owner)) + .collect::>(); + assert_eq!(outer, [slot(0, 17..18, "field_declaration 10..56")]); + }, + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_second_comment_inside_a_field_declaration_is_not_documentation() { + let source = "class C {\n /** a */\n int x,\n /** b */\n y;\n}\n"; + assert_eq!(source.len(), 48); + for (options, kept) in [ + (DocumentationOptions::default(), vec![]), + (unbound(), vec![(CandidateDisposition::Unattached, 32..40)]), + ] { + both(source, options, |_, index| { + assert_eq!(documents(index), [(vec![12..20], Some("a".to_owned()))]); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![ + slot(0, 27..28, "field_declaration 23..45"), + slot(1, 43..44, "field_declaration 23..45") + ], + Some("field_declaration 23..45".to_owned()), + "class_body 8..47".to_owned() + )] + ); + assert_eq!(evidence(index), kept); + assert_eq!(assessments(index, index.assessments()), []); + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_undocumented_fields_have_slots_and_no_assessment() { + both("class C { int x; int a, b; }", unbound(), |root, index| { + assert_eq!(documents(index), []); + assert_eq!(associations(index), []); + assert_eq!(assessments(index, index.assessments()), []); + assert_eq!(evidence(index), []); + let owners: Vec<_> = index + .facts() + .owners() + .map(|owner| owner_text(index, owner)) + .collect(); + assert_eq!( + owners, + [ + "File(program 0..28)".to_owned(), + "Node(class_declaration 0..28)".to_owned(), + "Node(field_declaration 10..16)".to_owned(), + slot(0, 14..15, "field_declaration 10..16"), + "Node(field_declaration 17..26)".to_owned(), + slot(0, 21..22, "field_declaration 17..26"), + slot(1, 24..25, "field_declaration 17..26"), + ] + ); + let single = index + .node_associations(node(root, "field_declaration", 10..16)) + .unwrap(); + assert!(!single.projection_pending()); + assert_eq!(single.associations().len(), 0); + assert_eq!(single.assessments().count(), 0); + for owner in index.facts().owners() { + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.associations().len(), 0); + assert_eq!(query.assessments().count(), 0); + } + }); +} + +#[cfg(feature = "java")] +#[test] +fn java_comment_inside_a_field_declaration_does_not_document_it() { + for (source, declaration, name, dropped) in [ + ( + "class C { @Deprecated /**audit*/ int x; }", + "field_declaration 10..39", + 37..38, + 22..32, + ), + ( + "class C { public /**audit*/ int x; }", + "field_declaration 10..34", + 32..33, + 17..27, + ), + ( + "class C {\n int x;\n /**d*/\n ;\n void f() {}\n}\n", + "field_declaration 12..18", + 16..17, + 21..27, + ), + ] { + both(source, unbound(), |root, index| { + assert_eq!(documents(index), []); + assert_eq!(associations(index), []); + assert_eq!( + evidence(index), + [(CandidateDisposition::Unattached, dropped.clone())] + ); + assert_eq!(assessments(index, index.assessments()), []); + let (kind, range) = declaration.split_once(' ').unwrap(); + let (start, end) = range.split_once("..").unwrap(); + let field = node(root, kind, start.parse().unwrap()..end.parse().unwrap()); + let owners: Vec<_> = index + .node_owners(field) + .unwrap() + .map(|owner| owner_text(index, owner)) + .collect(); + assert_eq!(owners, [slot(0, name.clone(), declaration)]); + let query = index.node_associations(field).unwrap(); + assert_eq!(query.associations().len(), 0); + assert_eq!(query.assessments().count(), 0); + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_field_with_a_syntax_error_stays_pending() { + // javac recovers from the missing `;` and attaches `d` to `x` and `e` to `y`. + // The pinned grammar leaves an error in the first declaration, which stays pending. + let source = "class C {\n/** d */\nint x\n/** e */\nint y;\n}\n"; + assert_eq!(source.len(), 43); + both(source, unbound(), |root, index| { + assert!(node(root, "field_declaration", 19..33).has_error()); + assert_eq!(documents(index), [(vec![10..18], Some("d".to_owned()))]); + assert_eq!(associations(index), []); + assert_eq!( + assessments(index, index.assessments()), + [ + ( + AssessmentAxis::Owner, + PENDING_DOCUMENT, + Some("field_declaration 19..33".to_owned()), + Some(0) + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("class_declaration 0..42".to_owned()), + None + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("field_declaration 19..33".to_owned()), + None + ), + ] + ); + assert_eq!( + evidence(index), + [(CandidateDisposition::Unattached, 25..33)] + ); + let broken = node(root, "field_declaration", 19..33); + assert!(index.node_projection(broken).unwrap().pending()); + assert!(matches!( + index.node_owners(broken), + Err(OwnerError::PendingOwner) + )); + let clean = index + .node_owners(node(root, "field_declaration", 34..40)) + .unwrap() + .map(|owner| owner_text(index, owner)) + .collect::>(); + assert_eq!(clean, [slot(0, 38..39, "field_declaration 34..40")]); + // expected: file, the clean declaration and its slot; + // the class and first field are pending. + assert_eq!(index.facts().owners().len(), 3); + }); + let source = "class C { /**audit*/ int x = ; }"; + both(source, DocumentationOptions::default(), |root, index| { + let field = node(root, "field_declaration", 21..30); + assert!(field.has_error()); + assert_eq!(node(root, "ERROR", 27..28).parent().unwrap(), field); + assert_eq!(documents(index), [(vec![10..20], Some("audit".to_owned()))]); + assert_eq!(associations(index), []); + assert!(index.node_projection(field).unwrap().pending()); + // expected: the file only. + assert_eq!(index.facts().owners().len(), 1); + }); +} + +#[cfg(feature = "java")] +#[test] +fn java_field_with_an_unnamed_declarator_stays_pending_as_a_whole() { + // javac rejects `_` as a field name and still attaches the comment to every + // declarator. Here the declaration has no plain name for one slot and stays pending. + for (source, field) in [ + ("class C { /**audit*/ int a, _; }", 21..30), + ("class C { /**audit*/ int _, a; }", 21..30), + ] { + both(source, DocumentationOptions::default(), |root, index| { + assert!(!root.has_error()); + let declaration = node(root, "field_declaration", field.clone()); + assert_eq!(documents(index), [(vec![10..20], Some("audit".to_owned()))]); + assert_eq!(associations(index), []); + assert_eq!( + assessments(index, index.assessments()), + [ + ( + AssessmentAxis::Owner, + PENDING_DOCUMENT, + Some("field_declaration 21..30".to_owned()), + Some(0) + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("field_declaration 21..30".to_owned()), + None + ), + ] + ); + assert!(index.node_projection(declaration).unwrap().pending()); + assert!(matches!( + index.node_owners(declaration), + Err(OwnerError::PendingOwner) + )); + // expected: file and class; no declaration owner and no slot. + assert_eq!(index.facts().owners().len(), 2); + }); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_field_beside_recovery_keeps_its_slots() { + let source = "class C { /**audit*/ int x; static {"; + both(source, DocumentationOptions::default(), |root, index| { + assert!(root.is_error()); + assert!(!node(root, "field_declaration", 21..27).has_error()); + assert_eq!(documents(index), [(vec![10..20], Some("audit".to_owned()))]); + assert_eq!( + associations(index), + [( + 0, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + vec![slot(0, 25..26, "field_declaration 21..27")], + Some("field_declaration 21..27".to_owned()), + "ERROR 0..36".to_owned() + )] + ); + assert_eq!(assessments(index, index.assessments()), []); + }); + let source = "class C { /**audit*/ int x; "; + both(source, DocumentationOptions::default(), |root, index| { + assert!(!root.is_error()); + assert!(node(root, "class_declaration", 0..27).has_error()); + assert!(!node(root, "field_declaration", 21..27).has_error()); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![slot(0, 25..26, "field_declaration 21..27")], + Some("field_declaration 21..27".to_owned()), + "class_body 8..27".to_owned() + )] + ); + let pending = [( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("class_declaration 0..27".to_owned()), + None, + )]; + assert_eq!(assessments(index, index.assessments()), pending); + let query = index + .node_associations(node(root, "field_declaration", 21..27)) + .unwrap(); + assert_eq!(assessments(index, query.assessments()), pending); + }); +} + +#[cfg(feature = "java")] +#[test] +#[allow(clippy::too_many_lines)] +fn java_field_and_excluded_ranges() { + let source = "class C { /**audit*/ int a, b; }"; + let context = DocumentationContext::default(); + // A gap inside the declaration: the space at 27..28. + let tree = restricted(source, &[0..27, 28..32]); + let index = collect(LANG::Java, &tree, source.as_bytes(), &context, &unbound()).unwrap(); + let root = tree.root_node(); + assert!(!root.has_error()); + let field = node(root, "field_declaration", 21..30); + assert_eq!(documents(&index), []); + assert_eq!(associations(&index), []); + assert_eq!( + evidence(&index), + [(CandidateDisposition::Unattached, 10..20)] + ); + assert!(index.node_projection(field).unwrap().pending()); + assert!(matches!( + index.node_owners(field), + Err(OwnerError::PendingOwner) + )); + // expected: the file only; class, body and field hold the gap. + assert_eq!(index.facts().owners().len(), 1); + assert_eq!( + assessments(&index, index.assessments()), + [ + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("class_declaration 0..32".to_owned()), + None + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("class_body 8..32".to_owned()), + None + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("field_declaration 21..30".to_owned()), + None + ), + ] + ); + // A gap between the comment and the declaration: the space at 20..21. + let tree = restricted(source, &[0..20, 21..32]); + let index = collect(LANG::Java, &tree, source.as_bytes(), &context, &unbound()).unwrap(); + let root = tree.root_node(); + assert!(!root.has_error()); + let field = node(root, "field_declaration", 21..30); + assert_eq!(documents(&index), []); + assert_eq!(associations(&index), []); + assert_eq!( + evidence(&index), + [(CandidateDisposition::Unattached, 10..20)] + ); + let owners: Vec<_> = index + .node_owners(field) + .unwrap() + .map(|owner| owner_text(&index, owner)) + .collect(); + assert_eq!( + owners, + [ + slot(0, 25..26, "field_declaration 21..30"), + slot(1, 28..29, "field_declaration 21..30") + ] + ); + for owner in index.node_owners(field).unwrap() { + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .len(), + 0 + ); + } + assert_eq!( + assessments(&index, index.assessments()), + [ + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("class_declaration 0..32".to_owned()), + None + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("class_body 8..32".to_owned()), + None + ), + ] + ); + // No gap: two adjacent included ranges meet inside the name, after `al`. + let source = "class C { /**audit*/ int alpha; }"; + assert_eq!(source.len(), 33); + let tree = restricted(source, &[0..27, 27..33]); + let index = collect(LANG::Java, &tree, source.as_bytes(), &context, &unbound()).unwrap(); + assert!(!tree.root_node().has_error()); + assert_eq!( + documents(&index), + [(vec![10..20], Some("audit".to_owned()))] + ); + assert_eq!( + associations(&index), + [( + 0, + Resolution::Resolved, + vec!["Slot(Field #0 25..27,27..30 in Node(field_declaration 21..31))".to_owned()], + Some("field_declaration 21..31".to_owned()), + "class_body 8..33".to_owned() + )] + ); + assert_eq!(assessments(&index, index.assessments()), []); + assert_eq!(evidence(&index), []); + // expected: file, class, declaration, slot. + assert_eq!(index.facts().owners().len(), 4); + let owner = index + .facts() + .associated_owner(index.associations().next().unwrap(), 0) + .unwrap(); + let Owner::Slot(found) = owner.get() else { + panic!("field slot") + }; + assert_eq!(found.source.pieces()[0].bytes(), b"al"); + assert_eq!(found.source.pieces()[1].bytes(), b"pha"); +} + +#[cfg(feature = "java")] +#[test] +fn java_field_comment_with_a_raw_unicode_escape_lists_its_slot_unresolved() { + // javac translates the escape first and attaches `@audit ` to `x`. + let source = r"class C { /** \u0040audit */ int x; }"; + assert_eq!(source.len(), 37); + both(source, DocumentationOptions::default(), |root, index| { + assert!(!root.has_error()); + assert_eq!(documents(index), [(vec![10..28], None)]); + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::UnsupportedDecoding) + )); + assert_eq!( + associations(index), + [( + 0, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + vec![slot(0, 33..34, "field_declaration 29..35")], + Some("field_declaration 29..35".to_owned()), + "class_body 8..37".to_owned() + )] + ); + assert_eq!(assessments(index, index.assessments()), []); + let field = node(root, "field_declaration", 29..35); + let query = index.node_associations(field).unwrap(); + assert!(!query.projection_pending()); + assert!(query.associations().eq(index.associations())); + assert_eq!(query.assessments().count(), 0); + // expected: file, class, declaration, slot. + assert_eq!(index.facts().owners().len(), 4); + }); +} + +#[cfg(feature = "java")] +#[test] +fn java_pending_field_comment_with_a_raw_unicode_escape_keeps_an_ownerless_association() { + // The unnamed declarator keeps the declaration pending; the escape alone makes the + // association unresolved, so it exists without an owner. + let source = r"class C { /** \u0040audit */ int a, _; }"; + assert_eq!(source.len(), 40); + both(source, DocumentationOptions::default(), |root, index| { + assert!(!root.has_error()); + assert_eq!(documents(index), [(vec![10..28], None)]); + assert!(matches!( + index.documents().next().unwrap().get().content(), + Content::Unavailable(UnavailableReason::UnsupportedDecoding) + )); + assert_eq!( + associations(index), + [( + 0, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + vec![], + Some("field_declaration 29..38".to_owned()), + "class_body 8..40".to_owned() + )] + ); + assert_eq!( + assessments(index, index.assessments()), + [ + ( + AssessmentAxis::Owner, + PENDING_DOCUMENT, + Some("field_declaration 29..38".to_owned()), + Some(0) + ), + ( + AssessmentAxis::Owner, + PENDING_OWNER, + Some("field_declaration 29..38".to_owned()), + None + ), + ] + ); + let field = node(root, "field_declaration", 29..38); + assert!(index.node_projection(field).unwrap().pending()); + assert!(matches!( + index.node_owners(field), + Err(OwnerError::PendingOwner) + )); + // expected: file and class; no declaration owner and no slot. + assert_eq!(index.facts().owners().len(), 2); + }); +} + +#[cfg(feature = "java")] +#[derive(Default)] +struct Counting { + steps: Cell, + bytes: Cell, + fail_at: Option, +} + +#[cfg(feature = "java")] +impl WorkBudget for Counting { + type Error = SourceError; + #[cfg(feature = "java")] + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + fn step(&self) -> Result<(), SourceError> { + self.steps.set(self.steps.get() + 1); + if self.fail_at == Some(self.steps.get()) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + #[cfg(feature = "java")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + Ok(()) + } +} + +#[cfg(feature = "java")] +fn wide(width: usize) -> String { + let names: Vec<_> = (0..width).map(|at| format!("v{at}")).collect(); + format!("class C {{ /**audit*/ int {}; }}", names.join(", ")) +} + +#[cfg(feature = "java")] +#[test] +#[allow(clippy::too_many_lines)] +fn java_declarator_scan_charges_one_step_per_child() { + let wide_source = wide(300); + for (source, kind, steps, names) in [ + ( + "class C { /**audit*/ int x; }", + "field_declaration", + 3, + Some(vec![25..26]), + ), + ( + "class C { /**audit*/ int a, b; }", + "field_declaration", + 5, + Some(vec![25..26, 28..29]), + ), + ( + "class C { /**audit*/ int a = 1, b[] = {2}, c; }", + "field_declaration", + 7, + Some(vec![25..26, 32..33, 43..44]), + ), + ( + "class C {\n /** a */\n int x,\n /** b */\n y;\n}\n", + "field_declaration", + 6, + Some(vec![27..28, 43..44]), + ), + ( + "class C { /**audit*/ @Deprecated int x; }", + "field_declaration", + 4, + Some(vec![37..38]), + ), + ( + "interface I { /**audit*/ int K = 1; }", + "constant_declaration", + 3, + Some(vec![29..30]), + ), + ( + "class C { /**audit*/ int a, _; }", + "field_declaration", + 4, + None, + ), + ( + "class C { /**audit*/ int _, a; }", + "field_declaration", + 2, + None, + ), + ( + wide_source.as_str(), + "field_declaration", + 601, + None::>>, + ), + ] { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let declaration = parser + .root_node() + .preorder() + .find(|node| node.kind() == kind) + .unwrap(); + let id = index + .canonical + .lookup(declaration.as_tree_sitter()) + .unwrap(); + let budget = Counting::default(); + let found = + super::projections::java_declarator_names(&index.canonical, id, &budget).unwrap(); + assert_eq!(budget.steps.get(), steps, "{source}"); + assert_eq!(budget.bytes.get(), 0, "{source}"); + let found = found.map(|names| { + names + .iter() + .map(|name| index.canonical.nodes[name.0].evidence.node().byte_range()) + .collect::>() + }); + if source.len() < 100 { + assert_eq!(found, names, "{source}"); + } else { + let found = found.unwrap(); + assert_eq!(found.len(), 300); + assert_eq!(found[0], 25..27); + assert_eq!(found[299], 1709..1713); + } + if source.len() >= 100 || source == "class C { /**audit*/ int a, b; }" { + for fail_at in 1..=steps { + let budget = Counting { + fail_at: Some(fail_at), + ..Counting::default() + }; + assert!(matches!( + super::projections::java_declarator_names(&index.canonical, id, &budget), + Err(SourceError::Cancelled) + )); + assert_eq!(budget.steps.get(), fail_at); + } + let budget = Counting { + fail_at: Some(steps + 1), + ..Counting::default() + }; + assert!( + super::projections::java_declarator_names(&index.canonical, id, &budget) + .unwrap() + .is_some() + ); + } + } +} + +#[cfg(feature = "java")] +#[test] +fn java_field_width_costs_linear_work() { + for width in [64, 512, 2048] { + let source = wide(width); + let parser = AnyParser::parse(LANG::Java, source.clone().into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + let index = parser.documentation(&context, &options).unwrap(); + let after = observations(); + assert_eq!(parser.root_node().preorder().count(), 3 * width + 11); + assert_eq!(after.visits - before.visits, 3 * width + 11); + assert_eq!(after.child_batches - before.child_batches, 3 * width + 11); + assert_eq!( + after.target_classifications - before.target_classifications, + 3 * width + 10 + ); + assert_eq!(after.owner_projections - before.owner_projections, 3); + assert_eq!( + after.intersection_searches - before.intersection_searches, + width + 1 + ); + assert_eq!(after.field_requests - before.field_requests, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + assert_eq!(after.renders - before.renders, 1); + assert_eq!(index.facts().owners().len(), width + 3); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().owner_count(), width); + for position in [0, width - 1] { + let owner = index + .facts() + .associated_owner(association, position) + .unwrap(); + let Owner::Slot(found) = owner.get() else { + panic!("field slot") + }; + assert_eq!(found.ordinal, position); + assert_eq!( + found.source.pieces()[0].bytes(), + format!("v{position}").as_bytes() + ); + } + } +} + +#[cfg(feature = "java")] +#[test] +fn java_field_width_collection_observes_cancellation_in_the_slot_loop() { + let width = 2048; + let parser = AnyParser::parse(LANG::Java, wide(width).into_bytes(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + parser.documentation(&context, &options).unwrap(); + let polls = observations().polls - before.polls; + let mut inside = 0; + for checkpoint in 1..=polls { + let before = observations(); + let result = crate::documentation::budget::cancel_after(checkpoint, || { + parser.documentation(&context, &options) + }); + let after = observations(); + assert!( + matches!(result, Err(CollectionError::Cancelled)), + "{checkpoint}" + ); + let owners = after.owner_projections - before.owner_projections; + let searches = after.intersection_searches - before.intersection_searches; + if owners == 3 && searches < width + 1 { + inside += 1; + } + } + // expected: 6 checkpoints fall in the 6144 step charges of the slot loop + // (3 per slot, one checkpoint per 1024); the last may follow the last search. + assert!(inside >= 5, "{inside}"); + let index = crate::documentation::budget::cancel_after(polls + 1, || { + parser.documentation(&context, &options) + }) + .unwrap(); + assert_eq!( + index.associations().next().unwrap().get().owner_count(), + width + ); +} diff --git a/big-code-analysis-ast/src/documentation/collector/projections.rs b/big-code-analysis-ast/src/documentation/collector/projections.rs index 0f688acb0..10ea5a9fa 100644 --- a/big-code-analysis-ast/src/documentation/collector/projections.rs +++ b/big-code-analysis-ast/src/documentation/collector/projections.rs @@ -40,6 +40,15 @@ impl Builder<'_> { { return self.c_slots(id, budget); } + if self.index.profile == Profile::Javadoc + && matches!(node.kind(), "field_declaration" | "constant_declaration") + && matches!( + self.index.canonical.nodes[id.0].projection, + Projection::Pending + ) + { + return self.java_field_slots(id, budget); + } if !is_wrapper(self.index.profile, node.kind()) || !matches!( self.index.canonical.nodes[id.0].projection, @@ -208,6 +217,41 @@ impl Builder<'_> { Ok(()) } + fn java_field_slots( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let Some(names) = java_declarator_names(&self.index.canonical, id, budget)? else { + return Ok(()); + }; + let declaration = OwnerId(self.index.facts.owners.len()); + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + let mut fields = Vec::new(); + for name in names { + budget.step()?; + let spelling = self.index.canonical.nodes[name.0] + .evidence + .node() + .byte_range(); + let source = self.index.source.pieces_with_budget(spelling, budget)?; + let field = OwnerId(self.index.facts.owners.len()); + self.index.facts.owners.push(Owner::Slot(Slot { + enclosing: declaration, + role: SlotRole::Field, + ordinal: fields.len(), + source, + })); + self.index.associations_by_owner.push(Vec::new()); + self.index.assessments_by_owner.push(Vec::new()); + self.index.qualifications_by_owner.push(Vec::new()); + self.index.owner_nodes.push(id); + fields.push(field); + } + self.index.canonical.nodes[id.0].projection = Projection::Ready(fields); + Ok(()) + } + fn index_function_definition( &mut self, id: NodeId, @@ -326,3 +370,30 @@ impl Builder<'_> { Ok(()) } } + +// Field names are not requested for this profile (`fields_needed`), so a +// declarator is told by its kind and its name by position. +pub(super) fn java_declarator_names( + canonical: &CanonicalNodes<'_>, + declaration: NodeId, + budget: &B, +) -> Result>, B::Error> { + let mut names = Vec::new(); + for &child in &canonical.children[canonical.nodes[declaration.0].children.clone()] { + budget.step()?; + let declarator = &canonical.nodes[child.0]; + if declarator.evidence.node().kind() != "variable_declarator" { + continue; + } + match canonical.children[declarator.children.clone()].first() { + Some(&name) if canonical.nodes[name.0].evidence.node().kind() == "identifier" => { + names.push(name); + } + // An unnamed variable (`_`) has no name to own documentation. A + // declarator without a child is not reachable from an error-free parse. + _ => return Ok(None), + } + } + // The grammar requires one declarator; an empty list is not reachable either. + Ok((!names.is_empty()).then_some(names)) +} diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 2ff9b61cc..abf1dfc1c 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1204,3 +1204,101 @@ fn documentation_lua_source_and_legacy_views_are_independent() { comment_runs: 1, }); } + +#[cfg(feature = "java")] +#[test] +fn documentation_java_field_owners_leave_legacy_rows_unchanged() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::{AnyParser, documentation::*}; + for (source, documents, owners, loc) in [ + ( + "class C { /**audit*/ int x; }\n", + 1, + vec![1], + [1, 1, 0, 1, 0, 1], + ), + ( + "class C { /**audit*/ int a, b; }\n", + 1, + vec![2], + [1, 1, 0, 1, 0, 1], + ), + ( + "interface I { /**audit*/ int K = 1; }\n", + 1, + vec![1], + [1, 1, 0, 1, 0, 1], + ), + ( + "enum E { /**a*/ A, /**b*/ B; /**f*/ int x; }\n", + 3, + vec![1, 1, 1], + [1, 1, 0, 1, 0, 1], + ), + ( + "class C {\n /** a */\n int x,\n /** b */\n y;\n}\n", + 1, + vec![2], + [6, 4, 0, 2, 0, 1], + ), + ( + "class C {\n/** d */\nint x\n/** e */\nint y;\n}\n", + 1, + vec![], + [6, 5, 0, 2, 0, 1], + ), + ( + "class C {\n int x;\n /**d*/\n ;\n void f() {}\n}\n", + 0, + vec![], + [6, 5, 0, 1, 0, 0], + ), + ] { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), documents, "{source}"); + assert_eq!( + index + .associations() + .map(|association| association.get().owner_count()) + .collect::>(), + owners, + "{source}" + ); + let before = observations(); + let built = evidence_built::observed(); + let space = analyze( + Source::new(LANG::Java, source.as_bytes()), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let stats = &space.metrics.loc; + assert_eq!( + [ + stats.sloc(), + stats.ploc(), + stats.lloc(), + stats.cloc(), + stats.blank(), + stats.dloc() + ], + loc, + "{source}" + ); + let after = observations(); + assert_eq!(evidence_built::observed() - built, 0, "{source}"); + assert_eq!(after.renders - before.renders, 0, "{source}"); + assert_eq!(after.visits - before.visits, 0, "{source}"); + assert_eq!( + after.owner_projections - before.owner_projections, + 0, + "{source}" + ); + assert_eq!(after.polls - before.polls, 0, "{source}"); + } +} diff --git a/tests/fixtures/documentation/java-unit1-provenance.json b/tests/fixtures/documentation/java-unit1-provenance.json new file mode 100644 index 000000000..a7930230f --- /dev/null +++ b/tests/fixtures/documentation/java-unit1-provenance.json @@ -0,0 +1,23 @@ +{ + "scope": "Java field and constant declaration owners as field slots; pins of the Java declaration owners that already resolve; Unit 1 of #1666", + "base": "3924d45adf9716ec5d64381849b671b298b8b5fe", + "grammar": {"runtime": "0.26.13", "java": "0.23.5"}, + "production_oracles": "big-code-analysis-ast/src/documentation/collector/java_tests.rs", + "legacy_oracles": "src/metrics/loc/documentation_tests.rs", + "mutation_manifest": "utils/documentation-java-unit1-perturb.json", + "reference": {"tool": "Zulu OpenJDK", "version": "25.0.5.0.3", "configuration": "JavacTask.parse on in-memory sources named C.java (module-info.java for the module source), options -proc:none -Xlint:dangling-doc-comments --release 25; DocTrees.getDocComment and getDocCommentTree per class, method, variable and module tree; javac diagnostics retained", "evidence": "Executed on 2026-11-24 for every source of the production oracles; the attachment of each documentation comment and each dangling-comment warning were compared with the expected owners", "qualification": "Source attachment only. No javadoc run; publication is not claimed."}, + "legacy_measurement": {"binary": "bca 2.6.1, git 3924d45adf9716ec5d64381849b671b298b8b5fe, debug profile", "command": "bca metrics --no-config --no-ignore --no-skip-generated --language java --format json --metrics loc ", "qualification": "Each measured file holds exactly the bytes of one legacy oracle source: no CR and one final LF, so file normalization changes nothing."}, + "known_differences": [ + "A field declaration with a missing semicolon has a syntax error in the pinned grammar and stays a pending owner; javac recovers and attaches both comments.", + "A declaration with an unnamed (_) declarator stays a pending owner as a whole; javac reports an error for the name and still attaches the comment to every declarator.", + "The local text of /** a */ is a; DocTrees.getDocComment returns the raw text with its trailing space.", + "A documentation comment that holds a raw \\u escape has no text and an unresolved association, which lists the field slots of a resolvable declaration as candidates; javac translates the escape and attaches the comment." + ], + "pending": [ + "Package and module role and filename-dependent publication", + "Java text edges /****/ and /** x **/", + "Parameter and record-component documentation", + "Kotlin and Groovy owners", + "Benchmark workloads and fuzz seeds for field slots" + ] +} diff --git a/utils/documentation-audit-perturb.json b/utils/documentation-audit-perturb.json index 7975a58d0..72d9b5fb3 100644 --- a/utils/documentation-audit-perturb.json +++ b/utils/documentation-audit-perturb.json @@ -22,7 +22,7 @@ "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", "old": " let (content, attribute) = self.render_draft(&mut draft, budget)?;", "new": " if draft.target.is_some_and(|target| matches!(self.index.canonical.nodes[target.0].projection, Projection::Pending)) { return Ok(()); }\n let (content, attribute) = self.render_draft(&mut draft, budget)?;", - "expect": ["documentation::collector::form_tests::java_field_form_is_pending_in_default_queries", "documentation::collector::form_tests::javascript_binding_form_is_pending_in_default_queries"] + "expect": ["documentation::collector::form_tests::java_unnamed_field_form_is_pending_in_default_queries", "documentation::collector::form_tests::javascript_binding_form_is_pending_in_default_queries"] }, { "name": "deferred-perl-is-empty-success", diff --git a/utils/documentation-form-matrix.json b/utils/documentation-form-matrix.json index d1c93d9d6..6a78afc8c 100644 --- a/utils/documentation-form-matrix.json +++ b/utils/documentation-form-matrix.json @@ -8,9 +8,9 @@ "pending": ["doc assignment/raw/cooked/metadata attributes", "cfg_attr", "mixed comment/attribute composition", "field/variant/tuple slots", "other local contexts"] }, "Java": { - "implemented": ["traditional/Markdown basic declaration", "empty block", "four-slash Markdown", "last selection", "annotation-bearing declaration", "prelex unavailable plus source-cleaned evidence"], + "implemented": ["traditional/Markdown basic declaration", "empty block", "four-slash Markdown", "last selection", "annotation-bearing declaration", "prelex unavailable plus source-cleaned evidence", "field/constant declarator slots"], "ineligible": ["ordinary comments", "signature/accessor trivia without a target", "body working notes"], - "pending": ["filename publication", "field/constant slot projections", "semantic Unicode prelexing"] + "pending": ["filename publication", "unnamed-declarator and recovered field declarations", "semantic Unicode prelexing"] }, "Kotlin": { "implemented": ["basic KDoc function", "last selection across plain comments", "annotation-bearing function", "selected Local raw/text/maps"], diff --git a/utils/documentation-java-unit1-perturb.json b/utils/documentation-java-unit1-perturb.json new file mode 100644 index 000000000..026d2c3f6 --- /dev/null +++ b/utils/documentation-java-unit1-perturb.json @@ -0,0 +1,161 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "java-field-projection-disabled", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "new": " if false\n && self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot", "documentation::collector::java_tests::java_undocumented_fields_have_slots_and_no_assessment", "documentation::collector::java_tests::java_field_comment_with_a_raw_unicode_escape_lists_its_slot_unresolved"] + }, + { + "name": "java-field-projection-reaches-groovy", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "new": " if matches!(self.index.profile, Profile::Javadoc | Profile::Groovydoc)\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "expect": ["documentation::collector::form_tests::groovy_field_form_is_pending_in_default_queries"] + }, + { + "name": "java-constant-declaration-not-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "new": " && matches!(node.kind(), \"field_declaration\")", + "expect": ["documentation::collector::java_tests::java_constants_own_field_slots"] + }, + { + "name": "java-error-field-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if node.has_error()\n || node.is_missing()\n || !self", + "new": " if (node.has_error() && self.index.profile != Profile::Javadoc)\n || node.is_missing()\n || !self", + "expect": ["documentation::collector::java_tests::java_field_with_a_syntax_error_stays_pending"] + }, + { + "name": "java-uncovered-field-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " .covers_with_budget(node.byte_range(), budget)?\n {\n return Ok(());", + "new": " .covers_with_budget(node.byte_range(), budget)?\n && self.index.profile != Profile::Javadoc\n {\n return Ok(());", + "expect": ["documentation::collector::java_tests::java_field_and_excluded_ranges"] + }, + { + "name": "java-later-declarators-dropped", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " names.push(name);\n }", + "new": " names.push(name);\n break;\n }", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot", "documentation::collector::java_tests::java_declarator_scan_charges_one_step_per_child", "documentation::collector::java_tests::java_field_width_costs_linear_work"] + }, + { + "name": "java-slot-source-is-the-declarator", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " names.push(name);", + "new": " names.push(child);", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot", "documentation::collector::java_tests::java_constants_own_field_slots", "documentation::collector::java_tests::java_declarator_scan_charges_one_step_per_child"] + }, + { + "name": "java-unnamed-declarator-skipped", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " _ => return Ok(None),", + "new": " _ => continue,", + "expect": ["documentation::collector::java_tests::java_field_with_an_unnamed_declarator_stays_pending_as_a_whole", "documentation::collector::java_tests::java_declarator_scan_charges_one_step_per_child", "documentation::collector::java_tests::java_pending_field_comment_with_a_raw_unicode_escape_keeps_an_ownerless_association"] + }, + { + "name": "java-any-first-child-is-a-name", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " Some(&name) if canonical.nodes[name.0].evidence.node().kind() == \"identifier\" => {", + "new": " Some(&name) => {", + "expect": ["documentation::collector::form_tests::java_unnamed_field_form_is_pending_in_default_queries", "documentation::collector::java_tests::java_field_with_an_unnamed_declarator_stays_pending_as_a_whole", "documentation::collector::java_tests::java_declarator_scan_charges_one_step_per_child"] + }, + { + "name": "java-slot-ordinal-off-by-one", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " ordinal: fields.len(),", + "new": " ordinal: fields.len() + 1,", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot", "documentation::collector::java_tests::java_field_width_costs_linear_work"] + }, + { + "name": "java-slot-role-is-binding", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " enclosing: declaration,\n role: SlotRole::Field,", + "new": " enclosing: declaration,\n role: SlotRole::Binding,", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot"] + }, + { + "name": "java-slot-enclosing-is-the-file", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let declaration = OwnerId(self.index.facts.owners.len());", + "new": " let declaration = OwnerId(0);", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot", "documentation::collector::java_tests::java_field_queries_answer_per_slot_and_per_declaration"] + }, + { + "name": "java-declaration-node-stays-the-owner", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " self.index.canonical.nodes[id.0].projection = Projection::Ready(fields);", + "new": " let _ = fields;", + "expect": ["documentation::collector::java_tests::java_field_declarators_each_own_a_field_slot", "documentation::collector::java_tests::java_field_queries_answer_per_slot_and_per_declaration"] + }, + { + "name": "java-slot-owner-node-is-the-root", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " self.index.owner_nodes.push(id);\n fields.push(field);", + "new": " self.index.owner_nodes.push(NodeId(0));\n fields.push(field);", + "expect": ["documentation::collector::java_tests::java_field_beside_recovery_keeps_its_slots"] + }, + { + "name": "java-declarator-scan-unbudgeted", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " for &child in &canonical.children[canonical.nodes[declaration.0].children.clone()] {\n budget.step()?;", + "new": " for &child in &canonical.children[canonical.nodes[declaration.0].children.clone()] {\n let _ = budget;", + "expect": ["documentation::collector::java_tests::java_declarator_scan_charges_one_step_per_child"] + }, + { + "name": "java-slot-loop-unbudgeted", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " for name in names {\n budget.step()?;", + "new": " for name in names {", + "expect": ["documentation::collector::java_tests::java_field_width_collection_observes_cancellation_in_the_slot_loop"] + }, + { + "name": "java-slot-pieces-ignore-the-collection-budget", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let source = self.index.source.pieces_with_budget(spelling, budget)?;", + "new": " let source = self\n .index\n .source\n .pieces_with_budget(spelling, &crate::documentation::budget::NoBudget)?;", + "expect": ["documentation::collector::java_tests::java_field_width_collection_observes_cancellation_in_the_slot_loop"] + }, + { + "name": "java-field-names-requested-from-the-cursor", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " || (profile == Profile::Yard && matches!(kind, \"if_modifier\" | \"unless_modifier\"))", + "new": " || (profile == Profile::Yard && matches!(kind, \"if_modifier\" | \"unless_modifier\"))\n || (profile == Profile::Javadoc && kind == \"field_declaration\")", + "expect": ["documentation::collector::java_tests::java_field_width_costs_linear_work"] + }, + { + "name": "java-every-declaration-is-a-pending-owner", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " Profile::Javadoc => matches!(node.kind(), \"field_declaration\" | \"constant_declaration\"),", + "new": " Profile::Javadoc => true,", + "expect": ["documentation::collector::java_tests::java_declarations_own_their_leading_documentation", "documentation::collector::java_tests::java_record_documentation_belongs_to_the_type"] + }, + { + "name": "java-forward-scan-reads-past-unnamed-tokens", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " || (!skips(&n, ancestors)?\n && !read_past_error_with_budget::(&n, code, ancestors, view, budget)?)", + "new": " || (n.is_named()\n && !skips(&n, ancestors)?\n && !read_past_error_with_budget::(&n, code, ancestors, view, budget)?)", + "expect": ["documentation::collector::java_tests::java_comments_without_a_declaration_produce_no_document", "documentation::collector::java_tests::java_comment_inside_a_field_declaration_does_not_document_it"] + }, + { + "name": "java-name-across-adjacent-ranges-is-not-a-slot", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let source = self.index.source.pieces_with_budget(spelling, budget)?;", + "new": " let source = self.index.source.pieces_with_budget(spelling, budget)?;\n if source.pieces().len() != 1 {\n return Ok(());\n }", + "expect": ["documentation::collector::java_tests::java_field_and_excluded_ranges"] + }, + { + "name": "java-raw-unicode-escape-leaves-the-association-resolved", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " if prelex {\n draft.unresolved = Some(UnresolvedReason::GrammarBoundary);\n }", + "new": " if prelex {\n draft.unresolved = None;\n }", + "expect": ["documentation::collector::java_tests::java_field_comment_with_a_raw_unicode_escape_lists_its_slot_unresolved", "documentation::collector::java_tests::java_pending_field_comment_with_a_raw_unicode_escape_keeps_an_ownerless_association"] + } + ] +} From df8a1e214d5423c74353043fb2a6e76fe8c88e3a Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:13:12 -0800 Subject: [PATCH 091/221] test(loc): state the Ruby comment-run rule as the code has it The comment that derives `comment_runs` in the Ruby legacy guard said a run is a sequence of comments that each start on the previous comment's final row or on the next row. By that wording the two comments of row l10 would be one run. The rule of `leading_doc_run` is narrower: the rows of a run hold nothing but comments, so a comment after code on its row is no member. The comment now says so. No assertion, expected value or source changes. --- src/metrics/loc/documentation_tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 84ffbb184..abba1b07c 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1394,8 +1394,9 @@ fn documentation_ruby_source_and_legacy_views_are_independent() { source: &'a [u8], loc: [u64; 6], dloc_rows: &'a [usize], - // A run is a maximal sequence of comments starting on the previous comment's - // final row or the next row. Only l10 has two: code separates its comments. + // A run is a maximal sequence of comments on consecutive rows that hold nothing but + // comments. Only l10 has two: `# :nodoc:` follows code on its row, so it does not join + // the run of `# audit` and counts on its own. comment_runs: usize, } let counters = || { From 5adadb6bd5e47ed23be242d0d97186ba83a69375 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:20:17 -0800 Subject: [PATCH 092/221] test(documentation): pin JSDoc owners and text for JavaScript and Mozjs --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/js_tests.rs | 1283 +++++++++++++++++ utils/documentation-js-unit1-perturb.json | 561 +++++++ 3 files changed, 1846 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/js_tests.rs create mode 100644 utils/documentation-js-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 3e44727da..1a4629e09 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1014,6 +1014,8 @@ mod form_tests; #[cfg(test)] mod go_tests; #[cfg(test)] +mod js_tests; +#[cfg(test)] mod lua_tests; #[cfg(test)] mod named_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/js_tests.rs b/big-code-analysis-ast/src/documentation/collector/js_tests.rs new file mode 100644 index 000000000..6adb5cf41 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/js_tests.rs @@ -0,0 +1,1283 @@ +//! JavaScript and Mozjs JSDoc source-view tests compare documents, associations, retained +//! candidates and pending assessments through both entry points. Node queries are asserted +//! separately where a case names them. The grammar tests collect nothing and pin tree shapes. + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +use crate::documentation::*; +#[cfg(any(feature = "javascript", feature = "mozjs"))] +use crate::{AnyParser, LANG}; +#[cfg(any(feature = "javascript", feature = "mozjs"))] +use std::ops::Range; + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +use Run::{Copied, Decoded}; + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[derive(Debug, PartialEq, Eq)] +enum Holder { + Node(&'static str, Range), + File(Range), +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +} + +/// Documents, ordered associations, retained candidates and unordered pending assessments. +/// Shared values are asserted by `published`. Node queries are asserted separately. +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +const AWAITS_OWNER: &str = "Selected local or wrapper form awaits owner projection"; +#[cfg(any(feature = "javascript", feature = "mozjs"))] +const NEEDS_PROJECTION: &str = "Recognized declaration requires a semantic projection"; + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn file(document: Doc) -> Doc { + Doc { + role: DocumentRole::FilePackage, + ..document + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn owned(document: Doc, owner: Holder) -> View { + View { + documents: vec![document], + associations: vec![owner], + ..View::default() + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn node_owner(document: Doc, kind: &'static str, range: Range) -> View { + owned(document, Holder::Node(kind, range)) +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn pending( + reason: &'static str, + kind: &'static str, + range: Range, + doc: Option, +) -> Pending { + Pending { + axis: AssessmentAxis::Owner, + reason, + node: Some((kind, range)), + document: doc, + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn unordered(entries: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = entries.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("comment", range.clone())) + ); + range +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn origin_run(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + // bca: suppress(halstead) -- one reading of the four published lists and their shared rules. + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|entry| (entry.output.range(), origin_run(&entry.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .enumerate() + .map(|(at, association)| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "JSDoc"); + assert_eq!(attachment.publication, Publication::Unknown); + assert_eq!(attachment.resolution, Resolution::Resolved); + let document = facts.associated_document(association).unwrap(); + assert_eq!(ordered.get(at), Some(&document)); + let first = facts.document_fragment(document, 0).unwrap(); + let comment_node = first.get().node().unwrap().node(); + assert_eq!(Some(attachment.lexical_scope.node()), comment_node.parent()); + let owner = facts.associated_owner(association, 0).unwrap(); + match owner.get() { + Owner::Node(declared) => { + let node = declared.node(); + let binding = if node + .parent() + .is_some_and(|parent| parent.kind() == "export_statement") + { + node.parent() + } else { + Some(node) + }; + assert_eq!(attachment.binding.map(NodeEvidence::node), binding); + let (kind, range) = site(node); + Holder::Node(kind, range) + } + Owner::File(file) => { + assert_eq!(file.node(), root); + assert!(file.node().parent().is_none()); + assert!(attachment.binding.is_none()); + Holder::File(file.node().byte_range()) + } + other => panic!("a node or file owner, found {other:?}"), + } + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| { + Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| site(node.node())), + document: index + .assessed_document(assessment) + .unwrap() + .map(|document| ordered.iter().position(|known| *known == document).unwrap()), + } + })); + // This adapter is partial in every case; none has a named-reference command. + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); + View { + documents, + associations, + evidence, + assessments, + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn clean(language: LANG, source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{}", + source.escape_ascii() + ); + parser +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + parser.language(), + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn agreed(indexes: &[DocumentationIndex<'_>; 2], root: tree_sitter::Node<'_>) -> View { + let [typed, raw] = indexes.each_ref().map(|index| published(index, root)); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn view(language: LANG, source: &[u8]) -> View { + let parser = clean(language, source); + agreed( + &indexes(&parser, DocumentationOptions::default()), + parser.ts_tree().root_node(), + ) +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn retained(language: LANG, source: &[u8]) -> View { + let parser = clean(language, source); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + agreed(&indexes(&parser, options), parser.ts_tree().root_node()) +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|node| node.as_tree_sitter()) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static str, Range)> { + let mut cursor = parent.walk(); + let mut result = Vec::new(); + if cursor.goto_first_child() { + loop { + let child = cursor.node(); + result.push((cursor.field_name(), child.kind(), child.byte_range())); + if !cursor.goto_next_sibling() { + break; + } + } + } + result +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn pending_query(indexes: &[DocumentationIndex<'_>; 2], node: tree_sitter::Node<'_>) { + for index in indexes { + let projection = index.node_projection(node).unwrap(); + assert!(projection.pending()); + let owners: Vec<_> = projection.owners().collect(); + assert_eq!(owners.len(), 0, "{owners:?}"); + let query = index.node_associations(node).unwrap(); + assert_eq!(query.associations().len(), 0); + assert!(query.projection_pending()); + } +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn leading_block_documents_the_declaration_after_it(language: LANG) { + let rows: [(&[u8], Doc, &str, Range); 3] = [ + ( + b"/**audit*/\nfunction f() {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + "function_declaration", + 11..26, + ), + ( + b"/** d */\nfunction* g() {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "generator_function_declaration", + 9..25, + ), + ( + b"/** d */\nclass C {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 9..19, + ), + ]; + for (source, document, kind, range) in rows { + assert_eq!( + view(language, source), + node_owner(document, kind, range), + "{}", + source.escape_ascii() + ); + } + let source = b"/** a */\nfunction f() {}\n/** b */\nfunction g() {}\n"; + assert_eq!( + view(language, source), + View { + documents: vec![ + comment(0..8, "a", [(0..1, Copied(4..5))]), + comment(25..33, "b", [(0..1, Copied(29..30))]), + ], + associations: vec![ + Holder::Node("function_declaration", 9..24), + Holder::Node("function_declaration", 34..49), + ], + ..View::default() + } + ); +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[allow(clippy::type_complexity)] +fn class_and_object_members_own_their_leading_block(language: LANG) { + let rows: [(&[u8], Range, &str, Range, &str); 5] = [ + ( + b"class C {\n /** m */\n m() {}\n}\n", + 12..20, + "method_definition", + 23..29, + "m", + ), + ( + b"class C {\n /** x */\n x = 1;\n}\n", + 12..20, + "field_definition", + 23..28, + "x", + ), + ( + b"use({\n /** p */\n p: 1,\n});\n", + 8..16, + "pair", + 19..23, + "p", + ), + ( + b"use({\n /** q */\n q,\n});\n", + 8..16, + "shorthand_property_identifier", + 19..20, + "q", + ), + ( + b"use({\n /** m */\n m() {},\n});\n", + 8..16, + "method_definition", + 19..25, + "m", + ), + ]; + for (source, fragment, kind, owner, text) in rows { + let offset = fragment.start + 4; + assert_eq!( + view(language, source), + node_owner( + comment(fragment, text, [(0..1, Copied(offset..offset + 1))]), + kind, + owner + ), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_class_and_object_members_own_their_leading_block() { + class_and_object_members_own_their_leading_block(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_class_and_object_members_own_their_leading_block() { + class_and_object_members_own_their_leading_block(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[allow(clippy::type_complexity)] +fn exported_declaration_owns_the_block_and_the_export_is_the_binding(language: LANG) { + let rows: [( + &[u8], + Range, + Range, + Range, + &str, + Range, + &str, + ); 5] = [ + ( + b"/**audit*/\nexport function f() {}\n", + 0..10, + 3..8, + 11..33, + "function_declaration", + 18..33, + "audit", + ), + ( + b"/** d */\nexport function* g() {}\n", + 0..8, + 4..5, + 9..32, + "generator_function_declaration", + 16..32, + "d", + ), + ( + b"/** d */\nexport class C {}\n", + 0..8, + 4..5, + 9..26, + "class_declaration", + 16..26, + "d", + ), + ( + b"/** d */\nexport default function f() {}\n", + 0..8, + 4..5, + 9..39, + "function_declaration", + 24..39, + "d", + ), + ( + b"export class C {\n /** m */\n m() {}\n}\n", + 19..27, + 23..24, + 0..38, + "method_definition", + 30..36, + "m", + ), + ]; + for (source, fragment, copied, export, kind, owner, text) in rows { + let parser = clean(language, source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both, parser.ts_tree().root_node()), + node_owner( + comment( + fragment.clone(), + text, + [(0..copied.len(), Copied(copied.clone()))] + ), + kind, + owner.clone() + ), + "{}", + source.escape_ascii() + ); + if fragment.start == 0 { + let wrapper = node_at(&parser, "export_statement", export); + for index in &both { + let projection = index.node_projection(wrapper).unwrap(); + assert!(!projection.pending()); + let owners: Vec<_> = projection.owners().collect(); + let [found] = owners[..] else { + panic!("one projected owner, found {owners:?}") + }; + let Owner::Node(declared) = found.get() else { + panic!("node owner: {found:?}") + }; + assert_eq!(site(declared.node()), (kind, owner.clone())); + let query = index.node_associations(wrapper).unwrap(); + assert_eq!(query.associations().len(), 1); + assert!(!query.projection_pending()); + } + } + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding() { + exported_declaration_owns_the_block_and_the_export_is_the_binding(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding() { + exported_declaration_owns_the_block_and_the_export_is_the_binding(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn nearest_block_comment_before_a_declaration_decides(language: LANG) { + assert_eq!( + view(language, b"/** d */\n// plain\nfunction f() {}\n"), + node_owner( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "function_declaration", + 18..33 + ) + ); + let superseded = b"function z() {}\n/**old*/\n/**new*/\nfunction f() {}\n"; + let mut expected = node_owner( + comment(25..33, "new", [(0..3, Copied(28..31))]), + "function_declaration", + 34..49, + ); + assert_eq!(view(language, superseded), expected); + expected + .evidence + .push((CandidateDisposition::Superseded, 16..24)); + assert_eq!(retained(language, superseded), expected); + let detached = b"function z() {}\n/** d */\n/* plain */\nfunction f() {}\n"; + let mut expected = View::default(); + assert_eq!(view(language, detached), expected); + expected + .evidence + .push((CandidateDisposition::Unattached, 16..24)); + assert_eq!(retained(language, detached), expected); +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_nearest_block_comment_before_a_declaration_decides() { + nearest_block_comment_before_a_declaration_decides(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_nearest_block_comment_before_a_declaration_decides() { + nearest_block_comment_before_a_declaration_decides(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[allow(clippy::type_complexity)] +fn file_tag_documents_the_file(language: LANG) { + let rows: [(&[u8], Range, &str, Range, Range); 5] = [ + ( + b"/**@file audit*/\nfunction f() {}\n", + 0..16, + "@file audit", + 3..14, + 0..33, + ), + ( + b"/** @fileoverview audit */\nfunction f() {}\n", + 0..26, + "@fileoverview audit", + 4..23, + 0..43, + ), + ( + b"/** @overview audit */\nfunction f() {}\n", + 0..22, + "@overview audit", + 4..19, + 0..39, + ), + ( + b"/** @module m */\nfunction f() {}\n", + 0..16, + "@module m", + 4..13, + 0..33, + ), + ( + b"/** @file audit */\n\"use strict\";\n", + 0..18, + "@file audit", + 4..15, + 0..33, + ), + ]; + for (source, fragment, text, copied, root) in rows { + assert_eq!( + view(language, source), + owned( + file(comment(fragment, text, [(0..text.len(), Copied(copied))])), + Holder::File(root) + ), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_file_tag_documents_the_file() { + file_tag_documents_the_file(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_file_tag_documents_the_file() { + file_tag_documents_the_file(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn block_in_a_body_documents_a_nested_declaration_and_no_statement(language: LANG) { + assert_eq!( + view( + language, + b"function outer() { /**audit*/ function inner() {} }\n" + ), + node_owner( + comment(19..29, "audit", [(0..5, Copied(22..27))]), + "function_declaration", + 30..49 + ) + ); + assert_eq!( + view( + language, + b"class C {\n m() {\n /** d */\n function inner() {}\n }\n}\n" + ), + node_owner( + comment(22..30, "d", [(0..1, Copied(26..27))]), + "function_declaration", + 35..54 + ) + ); + let without_owner = [ + ( + &b"function f() {\n /** note */\n return 1;\n}\n"[..], + 19..30, + ), + (&b"function f() {\n /** note */\n g();\n}\n"[..], 17..28), + ]; + for (source, fragment) in without_owner { + let mut expected = View::default(); + assert_eq!(view(language, source), expected); + expected + .evidence + .push((CandidateDisposition::Unattached, fragment)); + assert_eq!(retained(language, source), expected); + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement() { + block_in_a_body_documents_a_nested_declaration_and_no_statement(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement() { + block_in_a_body_documents_a_nested_declaration_and_no_statement(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn comment_that_is_no_jsdoc_block_gives_no_document(language: LANG) { + let sources: [&[u8]; 3] = [ + b"/* plain */\nfunction f() {}\n", + b"// plain\nfunction f() {}\n", + b"/*** banner */\nfunction f() {}\n", + ]; + for source in sources { + assert_eq!( + view(language, source), + View::default(), + "{}", + source.escape_ascii() + ); + assert_eq!( + retained(language, source), + View::default(), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_comment_that_is_no_jsdoc_block_gives_no_document() { + comment_that_is_no_jsdoc_block_gives_no_document(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_comment_that_is_no_jsdoc_block_gives_no_document() { + comment_that_is_no_jsdoc_block_gives_no_document(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn block_text_loses_its_delimiters_and_one_star_per_line(language: LANG) { + let rows: [(&[u8], Doc, Range); 5] = [ + ( + b"/**\n * a\n * b\n */\nfunction f() {}\n", + comment( + 0..17, + "a\nb", + [ + (0..1, Copied(7..8)), + (1..2, Copied(8..9)), + (2..3, Copied(12..13)), + ], + ), + 18..33, + ), + ( + b"/**\n * a \n * b\n */\nfunction f() {}\n", + comment( + 0..21, + "a \n b", + [ + (0..3, Copied(7..10)), + (3..4, Copied(10..11)), + (4..7, Copied(14..17)), + ], + ), + 22..37, + ), + ( + b"/**\n * a\n *\n * b\n */\nfunction f() {}\n", + comment( + 0..20, + "a\n\nb", + [ + (0..1, Copied(7..8)), + (1..2, Copied(8..9)), + (2..3, Copied(11..12)), + (3..4, Copied(15..16)), + ], + ), + 21..36, + ), + ( + b"/** a\n * b */\nfunction f() {}\n", + comment( + 0..13, + "a\nb", + [ + (0..1, Copied(4..5)), + (1..2, Copied(5..6)), + (2..3, Copied(9..10)), + ], + ), + 14..29, + ), + ( + b"/**\n * @param {number} x the x\n * @returns {number}\n */\n\ + function f(x) { return x; }\n", + comment( + 0..55, + "@param {number} x the x\n@returns {number}", + [ + (0..23, Copied(7..30)), + (23..24, Copied(30..31)), + (24..41, Copied(34..51)), + ], + ), + 56..83, + ), + ]; + for (source, document, owner) in rows { + assert_eq!( + view(language, source), + node_owner(document, "function_declaration", owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_block_text_loses_its_delimiters_and_one_star_per_line() { + block_text_loses_its_delimiters_and_one_star_per_line(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_block_text_loses_its_delimiters_and_one_star_per_line() { + block_text_loses_its_delimiters_and_one_star_per_line(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn crlf_line_endings_keep_byte_ranges_and_decode_to_lf(language: LANG) { + assert_eq!( + view(language, b"/** d */\r\nfunction f() {}\r\n"), + node_owner( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "function_declaration", + 10..25 + ) + ); + assert_eq!( + view( + language, + b"/**\r\n * a\r\n * b\r\n */\r\nfunction f() {}\r\n" + ), + node_owner( + comment( + 0..20, + "a\nb", + [ + (0..1, Copied(8..9)), + (1..2, Decoded(9..11)), + (2..3, Copied(14..15)), + ] + ), + "function_declaration", + 22..37 + ) + ); +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf() { + crlf_line_endings_keep_byte_ranges_and_decode_to_lf(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf() { + crlf_line_endings_keep_byte_ranges_and_decode_to_lf(LANG::Mozjs); +} + +// The ownerless documents and pending assessments are today's outcome, not the later design. +#[cfg(any(feature = "javascript", feature = "mozjs"))] +fn declarations_awaiting_an_owner_keep_their_pending_outcome(language: LANG) { + let ordinary: [(&[u8], &str, Range); 4] = [ + ( + b"/**audit*/\nconst f = () => 1;\n", + "lexical_declaration", + 11..29, + ), + ( + b"/**audit*/\nconst a = 1, b = 2;\n", + "lexical_declaration", + 11..30, + ), + (b"/**audit*/\nlet u;\n", "lexical_declaration", 11..17), + ( + b"/**audit*/\nvar v = function () {};\n", + "variable_declaration", + 11..34, + ), + ]; + for (source, kind, range) in ordinary { + let parser = clean(language, source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both, parser.ts_tree().root_node()), + View { + documents: vec![comment(0..10, "audit", [(0..5, Copied(3..8))])], + assessments: unordered([ + pending(AWAITS_OWNER, kind, range.clone(), Some(0)), + pending(NEEDS_PROJECTION, kind, range.clone(), None), + ]), + ..View::default() + }, + "{}", + source.escape_ascii() + ); + pending_query(&both, node_at(&parser, kind, range)); + } + let source = b"/**audit*/\nexport const e = 3;\n"; + let parser = clean(language, source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both, parser.ts_tree().root_node()), + View { + documents: vec![comment(0..10, "audit", [(0..5, Copied(3..8))])], + assessments: unordered([ + pending(AWAITS_OWNER, "export_statement", 11..30, Some(0)), + pending(NEEDS_PROJECTION, "export_statement", 11..30, None), + pending(NEEDS_PROJECTION, "lexical_declaration", 18..30, None), + ]), + ..View::default() + } + ); + for (kind, range) in [ + ("export_statement", 11..30), + ("lexical_declaration", 18..30), + ] { + pending_query(&both, node_at(&parser, kind, range)); + } + let anonymous: [(&[u8], Range); 2] = [ + (b"/**audit*/\nexport default function () {}\n", 11..40), + (b"/**audit*/\nexport default class {}\n", 11..34), + ]; + for (source, range) in anonymous { + let parser = clean(language, source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both, parser.ts_tree().root_node()), + View { + documents: vec![comment(0..10, "audit", [(0..5, Copied(3..8))])], + assessments: unordered([pending( + AWAITS_OWNER, + "export_statement", + range.clone(), + Some(0) + )]), + ..View::default() + } + ); + for index in &both { + assert_eq!( + index + .node_projection(node_at(&parser, "export_statement", range.clone())) + .err(), + Some(OwnerError::UnsupportedOwner) + ); + } + } +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_declarations_awaiting_an_owner_keep_their_pending_outcome() { + declarations_awaiting_an_owner_keep_their_pending_outcome(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome() { + declarations_awaiting_an_owner_keep_their_pending_outcome(LANG::Mozjs); +} + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[allow(clippy::too_many_lines)] +fn grammar_shapes_the_unit_relies_on(language: LANG) { + let source = b"function f() {}\nfunction* g() {}\nclass C {}\n"; + let parser = clean(language, source); + let root = parser.ts_tree().root_node(); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, "function_declaration", 0..15), + (None, "generator_function_declaration", 16..32), + (None, "class_declaration", 33..43), + ] + ); + + let parser = clean( + language, + b"class C {\n /** x */\n x = 1;\n /** m */\n m() {}\n}\n", + ); + let body = node_at(&parser, "class_body", 8..51); + assert_eq!( + parts(body), + [ + (None, "{", 8..9), + (None, "comment", 12..20), + (Some("member"), "field_definition", 23..28), + (None, ";", 28..29), + (None, "comment", 32..40), + (Some("member"), "method_definition", 43..49), + (None, "}", 50..51), + ] + ); + assert!(!body.child(3).unwrap().is_named()); + for range in [12..20, 32..40] { + assert!(node_at(&parser, "comment", range).is_extra()); + } + + let parser = clean( + language, + b"use({\n /** p */\n p: 1,\n /** q */\n q,\n /** m */\n m() {},\n});\n", + ); + let statement = node_at(&parser, "expression_statement", 0..65); + let call = node_at(&parser, "call_expression", 0..64); + let arguments = node_at(&parser, "arguments", 3..64); + let object = node_at(&parser, "object", 4..63); + assert_eq!(call.parent(), Some(statement)); + assert_eq!(arguments.parent(), Some(call)); + assert_eq!(object.parent(), Some(arguments)); + assert_eq!( + parts(object), + [ + (None, "{", 4..5), + (None, "comment", 8..16), + (None, "pair", 19..23), + (None, ",", 23..24), + (None, "comment", 27..35), + (None, "shorthand_property_identifier", 38..39), + (None, ",", 39..40), + (None, "comment", 43..51), + (None, "method_definition", 54..60), + (None, ",", 60..61), + (None, "}", 62..63), + ] + ); + for at in [3, 6, 9] { + assert!(!object.child(at).unwrap().is_named()); + } + + let parser = clean(language, b"/**audit*/\nexport function f() {}\n"); + assert_eq!( + parts(parser.ts_tree().root_node()), + [(None, "comment", 0..10), (None, "export_statement", 11..33),] + ); + let wrapper = node_at(&parser, "export_statement", 11..33); + assert_eq!( + parts(wrapper), + [ + (None, "export", 11..17), + (Some("declaration"), "function_declaration", 18..33), + ] + ); + assert!(!wrapper.child(0).unwrap().is_named()); + assert_eq!( + wrapper.child_by_field_name("declaration").map(site), + Some(("function_declaration", 18..33)) + ); + + let parser = clean(language, b"export default function f() {}\n"); + let wrapper = node_at(&parser, "export_statement", 0..30); + assert_eq!( + parts(wrapper), + [ + (None, "export", 0..6), + (None, "default", 7..14), + (Some("declaration"), "function_declaration", 15..30), + ] + ); + for at in [0, 1] { + assert!(!wrapper.child(at).unwrap().is_named()); + } + + let parser = clean(language, b"export default function () {}\n"); + let wrapper = node_at(&parser, "export_statement", 0..29); + assert_eq!( + wrapper.child_by_field_name("value").map(site), + Some(("function_expression", 15..29)) + ); + let parser = clean(language, b"export default class {}\n"); + let wrapper = node_at(&parser, "export_statement", 0..23); + assert_eq!( + wrapper.child_by_field_name("value").map(site), + Some(("class", 15..23)) + ); + assert!(wrapper.child_by_field_name("value").unwrap().is_named()); + + let parser = clean(language, b"export const e = 3;\n"); + let wrapper = node_at(&parser, "export_statement", 0..19); + assert_eq!( + wrapper.child_by_field_name("declaration").map(site), + Some(("lexical_declaration", 7..19)) + ); + assert_eq!( + node_at(&parser, "variable_declarator", 13..18) + .child_by_field_name("name") + .map(site), + Some(("identifier", 13..14)) + ); + + let parser = clean( + language, + b"const f = () => 1;\nlet u;\nvar v = function () {};\n", + ); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "lexical_declaration", 0..18), + (None, "lexical_declaration", 19..25), + (None, "variable_declaration", 26..49), + ] + ); + for (kind, range, declarator, semicolon) in [ + ("lexical_declaration", 0..18, 6..17, 17..18), + ("lexical_declaration", 19..25, 23..24, 24..25), + ("variable_declaration", 26..49, 30..48, 48..49), + ] { + let declaration = node_at(&parser, kind, range); + assert!(parts(declaration).contains(&(None, "variable_declarator", declarator))); + let last = declaration + .child((declaration.child_count() - 1).try_into().unwrap()) + .unwrap(); + assert_eq!(site(last), (";", semicolon)); + assert!(!last.is_named()); + } + + let parser = clean( + language, + b"function outer() { /**audit*/ function inner() {} }\n", + ); + let outer = node_at(&parser, "function_declaration", 0..51); + let body = outer.child_by_field_name("body").unwrap(); + assert_eq!(site(body), ("statement_block", 17..51)); + let comment = node_at(&parser, "comment", 19..29); + assert_eq!(comment.parent(), Some(body)); + assert_eq!( + comment.next_sibling().map(site), + Some(("function_declaration", 30..49)) + ); + + let parser = clean( + language, + b"function f() {\n /** note */\n return 1;\n g();\n}\n", + ); + let body = node_at(&parser, "function_declaration", 0..53) + .child_by_field_name("body") + .unwrap(); + assert_eq!(site(body), ("statement_block", 13..53)); + assert_eq!( + parts(body), + [ + (None, "{", 13..14), + (None, "comment", 19..30), + (None, "return_statement", 35..44), + (None, "expression_statement", 47..51), + (None, "}", 52..53), + ] + ); + assert_eq!( + node_at(&parser, "expression_statement", 47..51) + .child(0) + .map(site), + Some(("call_expression", 47..50)) + ); + + let source = b"/* plain */\n// plain\n/*** banner */\nfunction f() {}\n"; + let parser = clean(language, source); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "comment", 0..11), + (None, "comment", 12..20), + (None, "comment", 21..35), + (None, "function_declaration", 36..51), + ] + ); + for range in [0..11, 12..20, 21..35] { + assert!(node_at(&parser, "comment", range).is_extra()); + } + assert_eq!( + source[node_at(&parser, "comment", 12..20).end_byte()], + b'\n' + ); + + let source = b"/**\r\n * a\r\n * b\r\n */\r\nfunction f() {}\r\n"; + let parser = clean(language, source); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("program", 0..39)); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, "comment", 0..20), + (None, "function_declaration", 22..37), + ] + ); + let comment = node_at(&parser, "comment", 0..20); + assert_eq!(comment.end_position().row - comment.start_position().row, 3); + assert_eq!( + source[comment.byte_range()] + .windows(2) + .filter(|pair| *pair == b"\r\n") + .count(), + 3 + ); + + let source = b"function z() {}\n/**old*/\n/**new*/\nfunction f() {}\n"; + let parser = clean(language, source); + let root = parser.ts_tree().root_node(); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, "function_declaration", 0..15), + (None, "comment", 16..24), + (None, "comment", 25..33), + (None, "function_declaration", 34..49), + ] + ); + + let source = b"/** @file audit */\n\"use strict\";\n"; + let parser = clean(language, source); + let root = parser.ts_tree().root_node(); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, "comment", 0..18), + (None, "expression_statement", 19..32), + ] + ); + assert_eq!( + node_at(&parser, "expression_statement", 19..32) + .child(0) + .map(site), + Some(("string", 19..31)) + ); +} + +#[cfg(feature = "javascript")] +#[test] +fn javascript_grammar_shapes_the_unit_relies_on() { + grammar_shapes_the_unit_relies_on(LANG::Javascript); +} +#[cfg(feature = "mozjs")] +#[test] +fn mozjs_grammar_shapes_the_unit_relies_on() { + grammar_shapes_the_unit_relies_on(LANG::Mozjs); +} diff --git a/utils/documentation-js-unit1-perturb.json b/utils/documentation-js-unit1-perturb.json new file mode 100644 index 000000000..1d319e548 --- /dev/null +++ b/utils/documentation-js-unit1-perturb.json @@ -0,0 +1,561 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis-ast", + "--all-features", + "--lib", + "documentation::" + ], + "cases": [ + { + "name": "js-function-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " FunctionDeclaration,\n GeneratorFunctionDeclaration,", + "new": " GeneratorFunctionDeclaration,", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "js-generator-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " GeneratorFunctionDeclaration,\n ClassDeclaration,", + "new": " ClassDeclaration,", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding" + ] + }, + { + "name": "js-class-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " ClassDeclaration,\n MethodDefinition,", + "new": " MethodDefinition,", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding" + ] + }, + { + "name": "js-method-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " MethodDefinition,\n Pair,", + "new": " Pair,", + "expect": [ + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding" + ] + }, + { + "name": "js-pair-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " Pair,\n ShorthandPropertyIdentifier,", + "new": " ShorthandPropertyIdentifier,", + "expect": [ + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block" + ] + }, + { + "name": "js-shorthand-property-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " ShorthandPropertyIdentifier,\n VariableDeclaration(gated_by first_declarator_binds_a_name no_chain),", + "new": " VariableDeclaration(gated_by first_declarator_binds_a_name no_chain),", + "expect": [ + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block" + ] + }, + { + "name": "javascript-field-not-a-target", + "file": "big-code-analysis-ast/src/roles/javascript.rs", + "old": " FieldDefinition,\n ExportStatement(gated_by export_declares no_chain),", + "new": " ExportStatement(gated_by export_declares no_chain),", + "expect": [ + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block" + ] + }, + { + "name": "mozjs-field-not-a-target", + "file": "big-code-analysis-ast/src/roles/mozjs.rs", + "old": " FieldDefinition,\n ExportStatement(gated_by export_declares no_chain),", + "new": " ExportStatement(gated_by export_declares no_chain),", + "expect": [ + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block" + ] + }, + { + "name": "variable-declaration-is-no-source-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " first_declarator_with_budget(node, budget)\n }\n $lang::ExportStatement", + "new": " first_declarator_with_budget(node, budget).map(|_| false)\n }\n $lang::ExportStatement", + "expect": [ + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "export-statement-is-no-source-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " $lang::ExportStatement => export_with_budget(node, budget),", + "new": " $lang::ExportStatement => export_with_budget(node, budget).map(|_| false),", + "expect": [ + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "call-statement-is-a-source-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " $lang::ExpressionStatement => assignment_with_budget(node, budget),", + "new": " $lang::ExpressionStatement => assignment_with_budget(node, budget).map(|_| true),", + "expect": [ + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement" + ] + }, + { + "name": "variable-declaration-needs-no-slot", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " \"lexical_declaration\"\n | \"variable_declaration\"\n | \"expression_statement\"", + "new": " \"expression_statement\"", + "expect": [ + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "export-statement-is-no-wrapper", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " matches!(kind, \"export_statement\" | \"ambient_declaration\")", + "new": " matches!(kind, \"ambient_declaration\")", + "expect": [ + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "export-wrapper-takes-its-first-child", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " && !matches!(record.field, Some(\"declaration\" | \"value\"))\n {", + "new": " && !matches!(record.field, Some(\"declaration\" | \"value\"))\n && false\n {", + "expect": [ + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "javascript-line-comment-not-read-past", + "file": "big-code-analysis-ast/src/checker/javascript.rs", + "old": "&& !crate::lang_helpers::doc_comment::node_bytes(node, code).starts_with(b\"/*\"),", + "new": "&& !crate::lang_helpers::doc_comment::node_bytes(node, code).starts_with(b\"/\"),", + "expect": [ + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides" + ] + }, + { + "name": "mozjs-line-comment-not-read-past", + "file": "big-code-analysis-ast/src/checker/mozjs.rs", + "old": "&& !crate::lang_helpers::doc_comment::node_bytes(node, code).starts_with(b\"/*\"),", + "new": "&& !crate::lang_helpers::doc_comment::node_bytes(node, code).starts_with(b\"/\"),", + "expect": [ + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides" + ] + }, + { + "name": "older-block-joins-the-nearest", + "file": "big-code-analysis-ast/src/checker/js_doc_binding.rs", + "old": "joins: $crate::lang_helpers::doc_comment::never_joins,", + "new": "joins: |_, _, _| true,", + "expect": [ + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides" + ] + }, + { + "name": "superseded-needs-no-selected-block", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " && !self.kept.is_empty()", + "new": " && self.kept.is_empty()", + "expect": [ + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides" + ] + }, + { + "name": "unbound-candidates-kept-without-the-option", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " if selection != MarkerSelection::Selected && !request.retain_unbound {", + "new": " if selection != MarkerSelection::Selected && request.retain_unbound {", + "expect": [ + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement" + ] + }, + { + "name": "file-tag-binds-forward", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": " !crate::lang_helpers::doc_text::jsdoc_virtual_with_budget(bytes, budget)?,", + "new": " !crate::lang_helpers::doc_text::jsdoc_virtual_with_budget(bytes, budget)? || true,", + "expect": [ + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file" + ] + }, + { + "name": "file-tag-list-lacks-file", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": "&& [b\"file\".as_slice(), b\"fileoverview\", b\"overview\", b\"module\"]", + "new": "&& [b\"fileoverview\".as_slice(), b\"overview\", b\"module\"]", + "expect": [ + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file" + ] + }, + { + "name": "file-tag-list-lacks-fileoverview", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": "&& [b\"file\".as_slice(), b\"fileoverview\", b\"overview\", b\"module\"]", + "new": "&& [b\"file\".as_slice(), b\"overview\", b\"module\"]", + "expect": [ + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file" + ] + }, + { + "name": "file-tag-list-lacks-overview", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": "&& [b\"file\".as_slice(), b\"fileoverview\", b\"overview\", b\"module\"]", + "new": "&& [b\"file\".as_slice(), b\"fileoverview\", b\"module\"]", + "expect": [ + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file" + ] + }, + { + "name": "file-tag-list-lacks-module", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": "&& [b\"file\".as_slice(), b\"fileoverview\", b\"overview\", b\"module\"]", + "new": "&& [b\"file\".as_slice(), b\"fileoverview\", b\"overview\"]", + "expect": [ + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file" + ] + }, + { + "name": "block-in-a-body-does-not-bind-forward", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": " !crate::lang_helpers::doc_text::jsdoc_virtual_with_budget(bytes, budget)?,", + "new": " !crate::lang_helpers::doc_text::jsdoc_virtual_with_budget(bytes, budget)?\n && ancestors.parent(node).is_none_or(|parent| parent.kind() != \"statement_block\"),", + "expect": [ + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement" + ] + }, + { + "name": "javascript-reads-three-star-banners", + "file": "big-code-analysis-ast/src/roles/javascript.rs", + "old": "js_family_doc_gates!(Javascript, javadoc_block);", + "new": "js_family_doc_gates!(Javascript, tsdoc_block);", + "expect": [ + "documentation::collector::js_tests::javascript_comment_that_is_no_jsdoc_block_gives_no_document" + ] + }, + { + "name": "mozjs-reads-three-star-banners", + "file": "big-code-analysis-ast/src/roles/mozjs.rs", + "old": "js_family_doc_gates!(Mozjs, javadoc_block);", + "new": "js_family_doc_gates!(Mozjs, tsdoc_block);", + "expect": [ + "documentation::collector::js_tests::mozjs_comment_that_is_no_jsdoc_block_gives_no_document" + ] + }, + { + "name": "plain-block-is-a-marker", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " matches!(s, [b'/', b'*', b'*', b, ..] if *b != b'*' && *b != b'/')", + "new": " matches!(s, [b'/', b'*', _, b, ..] if *b != b'*' && *b != b'/')", + "expect": [ + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_comment_that_is_no_jsdoc_block_gives_no_document", + "documentation::collector::js_tests::mozjs_comment_that_is_no_jsdoc_block_gives_no_document" + ] + }, + { + "name": "any-comment-is-a-marker", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " matches!(s, [b'/', b'*', b'*', b, ..] if *b != b'*' && *b != b'/')", + "new": " matches!(s, [b'/', ..])", + "expect": [ + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_comment_that_is_no_jsdoc_block_gives_no_document", + "documentation::collector::js_tests::mozjs_comment_that_is_no_jsdoc_block_gives_no_document" + ] + }, + { + "name": "target-node-is-not-an-owner", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence));", + "new": " self.index.canonical.nodes[id.0].projection = Projection::Pending;", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_comment_that_is_no_jsdoc_block_gives_no_document", + "documentation::collector::js_tests::mozjs_comment_that_is_no_jsdoc_block_gives_no_document", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "forward-block-has-no-target", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " target,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "new": " target: None,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "forward-binding-dropped", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "new": " binding: None,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "scope-is-the-root", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " containing: ancestors.parent(comment).map(canonical).transpose()?,", + "new": " containing: None,", + "expect": [ + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement" + ] + }, + { + "name": "file-document-keeps-the-primary-role", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " draft.target = Some(NodeId(0));\n draft.role = DocumentRole::FilePackage;\n } else {\n draft.pending = true;\n }\n }\n _ => draft.pending = true,", + "new": " draft.target = Some(NodeId(0));\n } else {\n draft.pending = true;\n }\n }\n _ => draft.pending = true,", + "expect": [ + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file" + ] + }, + { + "name": "block-opener-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let prefix = if profile == Profile::GoDoc { 2 } else { 3 };", + "new": " let prefix = if profile == Profile::GoDoc { 2 } else { 2 };", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::javascript_declarations_awaiting_an_owner_keep_their_pending_outcome", + "documentation::collector::js_tests::mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "last-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " last.content.end -= 1;\n", + "new": " last.content.end -= 0;\n", + "expect": [ + "documentation::collector::js_tests::javascript_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::mozjs_leading_block_documents_the_declaration_after_it", + "documentation::collector::js_tests::javascript_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::mozjs_class_and_object_members_own_their_leading_block", + "documentation::collector::js_tests::javascript_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::mozjs_exported_declaration_owns_the_block_and_the_export_is_the_binding", + "documentation::collector::js_tests::javascript_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::mozjs_nearest_block_comment_before_a_declaration_decides", + "documentation::collector::js_tests::javascript_file_tag_documents_the_file", + "documentation::collector::js_tests::mozjs_file_tag_documents_the_file", + "documentation::collector::js_tests::javascript_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::mozjs_block_in_a_body_documents_a_nested_declaration_and_no_statement", + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "block-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start = star + 1;", + "new": " line.content.start = star;", + "expect": [ + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "space-after-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start += 1;\n", + "new": " line.content.start += 0;\n", + "expect": [ + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "leading-boundary-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if profile != Profile::Rust && position == first_block {", + "new": " if profile == Profile::Rust && position == first_block {", + "expect": [ + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "trailing-boundary-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if profile != Profile::Rust && position + 1 == last_block {", + "new": " if profile == Profile::Rust && position + 1 == last_block {", + "expect": [ + "documentation::collector::js_tests::javascript_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::mozjs_block_text_loses_its_delimiters_and_one_star_per_line", + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + }, + { + "name": "crlf-copied-not-decoded", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.ending.len() == 2 {", + "new": " if line.ending.len() == 3 {", + "expect": [ + "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", + "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" + ] + } + ] +} From 03db218e7e59506b7600f5e44302352c0062cb42 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:20:27 -0800 Subject: [PATCH 093/221] test(loc): guard JavaScript and Mozjs documentation rows before owner work --- src/metrics/loc/documentation_tests.rs | 188 ++++++++++++++++++ ...documentation-js-unit1-legacy-perturb.json | 42 ++++ 2 files changed, 230 insertions(+) create mode 100644 utils/documentation-js-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index ae9cfacb0..aa2e57df1 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1378,3 +1378,191 @@ fn documentation_php_source_and_legacy_views_are_independent() { assert_ne!(rendered_total, 0); assert_ne!(built_total, 0); } + +#[cfg(any(feature = "javascript", feature = "mozjs"))] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_js_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + struct Row<'a> { + variants: &'a [LANG], + name: &'static str, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + } + const BOTH: &[LANG] = &[LANG::Javascript, LANG::Mozjs]; + let rows = [ + Row { + variants: BOTH, + name: "l01_const_arrow", + source: b"/**audit*/\nconst f = () => 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: BOTH, + name: "l02_const_two_declarators", + source: b"/**audit*/\nconst a = 1, b = 2;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: BOTH, + name: "l03_export_const", + source: b"/**audit*/\nexport const e = 3;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: BOTH, + name: "l04_assignment", + source: b"/**audit*/\nx = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: BOTH, + name: "l05_default_anonymous_function", + source: b"/**audit*/\nexport default function () {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: BOTH, + name: "l06_virtual_name", + source: b"/**@name ghost\n * @function\n * audit*/\n", + loc: [3, 0, 0, 3, 0, 3], + dloc_rows: &[0, 1, 2], + }, + Row { + variants: BOTH, + name: "l07_body_before_return", + source: b"function f() {\n /** note */\n return 1;\n}\n", + loc: [4, 3, 1, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + variants: BOTH, + name: "l08_inner_declaration", + source: b"function outer() { /**audit*/ function inner() {} }\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: BOTH, + name: "l09_two_blocks_at_the_first_statement", + source: b"/**old*/\n// plain\n/**new*/\nfunction f() {}\n", + loc: [4, 1, 0, 3, 0, 1], + dloc_rows: &[2], + }, + Row { + variants: BOTH, + name: "l10_static_on_its_own_row", + source: b"class C {\nstatic\n/** d */\nm() {}\n}\n", + loc: [5, 4, 0, 1, 0, 1], + dloc_rows: &[2], + }, + Row { + variants: BOTH, + name: "l11_using", + source: b"/**audit*/\nusing u = f();\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + variants: &[LANG::Mozjs], + name: "l12_preproc_line_between", + source: b"/** d */\n#ifdef XP_WIN\nfunction f() {}\n#endif\n", + loc: [4, 3, 0, 1, 0, 0], + dloc_rows: &[], + }, + Row { + variants: BOTH, + name: "l13_through_a_decorator", + source: b"/** d */\n@dec\nclass C {}\n", + loc: [3, 2, 0, 1, 0, 1], + dloc_rows: &[0], + }, + ]; + let mut ran = 0; + for row in rows { + for &lang in row.variants { + if !lang.is_enabled() { + continue; + } + ran += 1; + let name = format!("{lang:?}: {}", row.name); + let parser = + crate::langs::AnyParser::parse(lang, row.source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error(), "{name}"); + let nodes = parser.root_node().preorder().count(); + let idle = observations(); + let unbuilt = evidence_built::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ) + .unwrap(); + let collected = observations(); + let built = evidence_built::observed(); + let visits = collected.visits - idle.visits; + let renders = collected.renders - idle.renders; + let members = built - unbuilt; + // expected: the collector visits each node exactly once, including unnamed nodes. + assert_eq!(visits, nodes, "{name}"); + // expected: each published document is rendered once; retained candidates have no text. + assert_eq!(renders, index.documents().len(), "{name}"); + // expected: each document fragment and retained candidate builds one marker member. + assert_eq!( + members, + index + .documents() + .map(|doc| doc.get().fragment_count()) + .sum::() + + index.evidence().len(), + "{name}" + ); + assert_ne!(visits, 0, "{name}"); + assert_ne!(members, 0, "{name}"); + let space = analyze( + Source::new(lang, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = observations(); + // expected: legacy LOC uses no source-view collector or rendered evidence. + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + assert_eq!(analyzed.renders - collected.renders, 0, "{name}"); + assert_eq!(analyzed.visits - collected.visits, 0, "{name}"); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc(), + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}", + ); + } + } + assert!(ran > 0); +} diff --git a/utils/documentation-js-unit1-legacy-perturb.json b/utils/documentation-js-unit1-legacy-perturb.json new file mode 100644 index 000000000..67b3a7b4b --- /dev/null +++ b/utils/documentation-js-unit1-legacy-perturb.json @@ -0,0 +1,42 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis", + "--all-features", + "--lib", + "documentation_js_source_and_legacy_views_are_independent" + ], + "cases": [ + { + "name": "js-function-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " FunctionDeclaration,\n GeneratorFunctionDeclaration,", + "new": " GeneratorFunctionDeclaration,", + "expect": [ + "metrics::loc::documentation_tests::documentation_js_source_and_legacy_views_are_independent" + ] + }, + { + "name": "js-method-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " MethodDefinition,\n Pair,", + "new": " Pair,", + "expect": [ + "metrics::loc::documentation_tests::documentation_js_source_and_legacy_views_are_independent" + ] + }, + { + "name": "js-class-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " ClassDeclaration,\n MethodDefinition,", + "new": " MethodDefinition,", + "expect": [ + "metrics::loc::documentation_tests::documentation_js_source_and_legacy_views_are_independent" + ] + } + ] +} From eb33adaba4ed0d8fd33b717112321b8fc9d2dfae Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:27:26 -0800 Subject: [PATCH 094/221] test(documentation): pin TypeScript and TSX documentation owners and text --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/ts_tests.rs | 1405 +++++++++++++++++ utils/documentation-ts-unit1-perturb.json | 659 ++++++++ 3 files changed, 2066 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/ts_tests.rs create mode 100644 utils/documentation-ts-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 3e44727da..7a3621cea 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1025,3 +1025,5 @@ mod projection_tests; mod remediation_tests; #[cfg(test)] mod tests; +#[cfg(test)] +mod ts_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/ts_tests.rs b/big-code-analysis-ast/src/documentation/collector/ts_tests.rs new file mode 100644 index 000000000..5908b825b --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/ts_tests.rs @@ -0,0 +1,1405 @@ +//! TypeScript and TSX source-view tests compare documents, associations, retained candidates +//! and pending assessments through both entry points. Grammar tests collect nothing and pin +//! parse-tree shapes. Node queries are not part of the view. + +#[cfg(feature = "typescript")] +use crate::documentation::*; +#[cfg(feature = "typescript")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "typescript")] +use std::ops::Range; + +#[cfg(feature = "typescript")] +use Run::{Copied, Decoded}; + +#[cfg(feature = "typescript")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "typescript")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(feature = "typescript")] +type Site = (&'static str, Range); + +#[cfg(feature = "typescript")] +type MemberCase = (&'static [u8], Range, Range, Site); + +#[cfg(feature = "typescript")] +#[derive(Debug, PartialEq, Eq)] +enum Holder { + Node(Site), + File(Range), +} + +#[cfg(feature = "typescript")] +#[derive(Debug, PartialEq, Eq)] +struct Link { + document: usize, + owner: Holder, + binding: Option, +} + +#[cfg(feature = "typescript")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option, + document: Option, +} + +/// Documents, associations, retained candidates and unordered pending assessments from a +/// collection. Shared values are asserted in `published`; node queries are not included. +#[cfg(feature = "typescript")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(feature = "typescript")] +const AWAITS_OWNER: &str = "Selected local or wrapper form awaits owner projection"; +#[cfg(feature = "typescript")] +const NEEDS_PROJECTION: &str = "Recognized declaration requires a semantic projection"; + +#[cfg(feature = "typescript")] +fn comment(range: Range, text: &str, map: [(Range, Run); N]) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![range], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "typescript")] +fn file(document: Doc) -> Doc { + Doc { + role: DocumentRole::FilePackage, + ..document + } +} + +#[cfg(feature = "typescript")] +fn link(document: usize, owner: Site, binding: Site) -> Link { + Link { + document, + owner: Holder::Node(owner), + binding: Some(binding), + } +} + +#[cfg(feature = "typescript")] +fn owned(document: Doc, owner: Site) -> View { + View { + documents: vec![document], + associations: vec![link(0, owner.clone(), owner)], + ..View::default() + } +} + +#[cfg(feature = "typescript")] +fn wrapped(document: Doc, owner: Site, binding: Site) -> View { + View { + documents: vec![document], + associations: vec![link(0, owner, binding)], + ..View::default() + } +} + +#[cfg(feature = "typescript")] +fn file_owned(document: Doc, root: Range) -> View { + View { + documents: vec![file(document)], + associations: vec![Link { + document: 0, + owner: Holder::File(root), + binding: None, + }], + ..View::default() + } +} + +#[cfg(feature = "typescript")] +fn pending(reason: &'static str, node: Site, document: Option) -> Pending { + Pending { + axis: AssessmentAxis::Owner, + reason, + node: Some(node), + document, + } +} + +#[cfg(feature = "typescript")] +fn unordered(entries: impl IntoIterator) -> Vec { + let mut entries: Vec<_> = entries.into_iter().collect(); + entries.sort_by_cached_key(|entry| format!("{entry:?}")); + entries +} + +#[cfg(feature = "typescript")] +fn unowned(document: Doc, bound: Site, extra: &[Site]) -> View { + let mut assessments = vec![pending(AWAITS_OWNER, bound, Some(0))]; + assessments.extend( + extra + .iter() + .cloned() + .map(|site| pending(NEEDS_PROJECTION, site, None)), + ); + View { + documents: vec![document], + assessments: unordered(assessments), + ..View::default() + } +} + +#[cfg(feature = "typescript")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "typescript")] +fn site(node: tree_sitter::Node<'_>) -> Site { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "typescript")] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("comment", range.clone())) + ); + range +} + +#[cfg(feature = "typescript")] +fn run_of(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "typescript")] +fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let position = |document| ordered.iter().position(|known| *known == document).unwrap(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|run| (run.output.range(), run_of(&run.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .map(|association| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "BcaTypescriptSource"); + assert_eq!(attachment.publication, Publication::Unknown); + assert_eq!(attachment.resolution, Resolution::Resolved); + let document = facts.associated_document(association).unwrap(); + let comment = facts + .document_fragment(document, 0) + .unwrap() + .get() + .node() + .unwrap() + .node(); + assert_eq!(Some(attachment.lexical_scope.node()), comment.parent()); + let binding = attachment.binding.map(NodeEvidence::node); + let expected_binding = if document.get().role() == DocumentRole::FilePackage { + None + } else { + let mut sibling = comment.next_sibling(); + while sibling.is_some_and(|node| matches!(node.kind(), "comment" | "decorator")) { + sibling = sibling.unwrap().next_sibling(); + } + sibling + }; + assert_eq!(binding, expected_binding); + let owner = facts.associated_owner(association, 0).unwrap(); + let holder = match owner.get() { + Owner::Node(node) => Holder::Node(site(node.node())), + Owner::File(file) => { + assert_eq!(file.node(), root); + Holder::File(file.node().byte_range()) + } + other => panic!("node or file owner, found {other:?}"), + }; + Link { + document: position(document), + owner: holder, + binding: binding.map(site), + } + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| site(node.node())), + document: index.assessed_document(assessment).unwrap().map(position), + })); + // This source adapter is partial for both variants. + assert_eq!(index.capability(), Capability::Partial); + // Named-reference commands alone produce qualifications; none occurs here. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + associations, + evidence, + assessments, + } +} + +#[cfg(feature = "typescript")] +fn clean(language: LANG, source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{language:?}: {}", + source.escape_ascii() + ); + parser +} + +#[cfg(feature = "typescript")] +fn view(language: LANG, source: &[u8], retain_unbound: bool) -> View { + let parser = clean(language, source); + let options = DocumentationOptions { + retain_unbound, + ..DocumentationOptions::default() + }; + let context = DocumentationContext::default(); + let root = parser.ts_tree().root_node(); + let typed = published(&parser.documentation(&context, &options).unwrap(), root); + let raw = published( + &collect( + language, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + root, + ); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "typescript")] +#[allow(clippy::needless_pass_by_value)] +fn check(language: LANG, source: &[u8], expected: View) { + assert_eq!( + view(language, source, false), + expected, + "{language:?}: {}", + source.escape_ascii() + ); +} + +#[cfg(feature = "typescript")] +fn check_retained( + language: LANG, + source: &[u8], + mut expected: View, + disposition: CandidateDisposition, + range: Range, +) { + assert_eq!( + view(language, source, false), + expected, + "{language:?}: {}", + source.escape_ascii() + ); + expected.evidence.push((disposition, range)); + assert_eq!( + view(language, source, true), + expected, + "{language:?}: {}", + source.escape_ascii() + ); +} + +#[cfg(feature = "typescript")] +fn leading_block_documents_the_declaration_after_it(language: LANG) { + let rows: [(&[u8], Site); 6] = [ + ( + b"/** d */\nfunction f(): void {}\n", + ("function_declaration", 9..30), + ), + (b"/** d */\nclass C {}\n", ("class_declaration", 9..19)), + ( + b"/** d */\nabstract class A {}\n", + ("abstract_class_declaration", 9..28), + ), + ( + b"/** d */\ninterface I {}\n", + ("interface_declaration", 9..23), + ), + ( + b"/** d */\ntype T = number;\n", + ("type_alias_declaration", 9..25), + ), + (b"/** d */\nenum E { A }\n", ("enum_declaration", 9..21)), + ]; + for (source, owner) in rows { + check( + language, + source, + owned(comment(0..8, "d", [(0..1, Copied(4..5))]), owner), + ); + } +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_leading_block_documents_the_declaration_after_it() { + leading_block_documents_the_declaration_after_it(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn class_or_interface_member_owns_its_leading_block(language: LANG) { + let rows: [MemberCase; 6] = [ + ( + b"class C {\n /** d */\n m(): void {}\n}\n", + 12..20, + 16..17, + ("method_definition", 23..35), + ), + ( + b"abstract class A {\n /** d */\n abstract m(): void;\n}\n", + 21..29, + 25..26, + ("abstract_method_signature", 32..50), + ), + ( + b"interface I {\n /** d */\n p: number;\n}\n", + 16..24, + 20..21, + ("property_signature", 27..36), + ), + ( + b"interface I {\n /** d */\n m(): void;\n}\n", + 16..24, + 20..21, + ("method_signature", 27..36), + ), + ( + b"interface I {\n /** d */\n (): void;\n}\n", + 16..24, + 20..21, + ("call_signature", 27..35), + ), + ( + b"interface I {\n /** d */\n [k: string]: number;\n}\n", + 16..24, + 20..21, + ("index_signature", 27..46), + ), + ]; + for (source, fragment, text, owner) in rows { + check( + language, + source, + owned(comment(fragment, "d", [(0..1, Copied(text))]), owner), + ); + } +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_class_or_interface_member_owns_its_leading_block() { + class_or_interface_member_owns_its_leading_block(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_class_or_interface_member_owns_its_leading_block() { + class_or_interface_member_owns_its_leading_block(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn enum_member_owns_its_leading_block(language: LANG) { + check( + language, + b"enum E {\n /** a */\n A,\n /** b */\n B = 1,\n}\n", + View { + documents: vec![ + comment(11..19, "a", [(0..1, Copied(15..16))]), + comment(27..35, "b", [(0..1, Copied(31..32))]), + ], + associations: vec![ + link( + 0, + ("property_identifier", 22..23), + ("property_identifier", 22..23), + ), + link(1, ("enum_assignment", 38..43), ("enum_assignment", 38..43)), + ], + ..View::default() + }, + ); + check( + language, + b"enum E {\n /** s */\n \"s\",\n}\n", + owned( + comment(11..19, "s", [(0..1, Copied(15..16))]), + ("string", 22..25), + ), + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_enum_member_owns_its_leading_block() { + enum_member_owns_its_leading_block(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_enum_member_owns_its_leading_block() { + enum_member_owns_its_leading_block(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn each_overload_signature_and_the_implementation_own_their_block(language: LANG) { + check( + language, + b"/**one*/\nfunction f(x: string): string;\n/**two*/\nfunction f(x: number): number;\n", + View { + documents: vec![ + comment(0..8, "one", [(0..3, Copied(3..6))]), + comment(40..48, "two", [(0..3, Copied(43..46))]), + ], + associations: vec![ + link( + 0, + ("function_signature", 9..39), + ("function_signature", 9..39), + ), + link( + 1, + ("function_signature", 49..79), + ("function_signature", 49..79), + ), + ], + // Parameters are pending semantic projections today. + assessments: unordered([ + pending(NEEDS_PROJECTION, ("required_parameter", 20..29), None), + pending(NEEDS_PROJECTION, ("required_parameter", 60..69), None), + ]), + ..View::default() + }, + ); + check( + language, + b"/** sig */\nfunction f(x: string): string;\nfunction f(x: number): number;\n\ +/** impl */\nfunction f(x: any): any { return x; }\n", + View { + documents: vec![ + comment(0..10, "sig", [(0..3, Copied(4..7))]), + comment(73..84, "impl", [(0..4, Copied(77..81))]), + ], + associations: vec![ + link( + 0, + ("function_signature", 11..41), + ("function_signature", 11..41), + ), + link( + 1, + ("function_declaration", 85..122), + ("function_declaration", 85..122), + ), + ], + assessments: unordered([ + pending(NEEDS_PROJECTION, ("required_parameter", 22..31), None), + pending(NEEDS_PROJECTION, ("required_parameter", 53..62), None), + pending(NEEDS_PROJECTION, ("required_parameter", 96..102), None), + ]), + ..View::default() + }, + ); + check( + language, + b"class C {\n /** one */\n m(x: string): void;\n /** two */\n m(x: number): void;\n \ +/** impl */\n m(x: any): void {}\n}\n", + View { + documents: vec![ + comment(12..22, "one", [(0..3, Copied(16..19))]), + comment(47..57, "two", [(0..3, Copied(51..54))]), + comment(82..93, "impl", [(0..4, Copied(86..90))]), + ], + associations: vec![ + link( + 0, + ("method_signature", 25..43), + ("method_signature", 25..43), + ), + link( + 1, + ("method_signature", 60..78), + ("method_signature", 60..78), + ), + link( + 2, + ("method_definition", 96..114), + ("method_definition", 96..114), + ), + ], + assessments: unordered([ + pending(NEEDS_PROJECTION, ("required_parameter", 27..36), None), + pending(NEEDS_PROJECTION, ("required_parameter", 62..71), None), + pending(NEEDS_PROJECTION, ("required_parameter", 98..104), None), + ]), + ..View::default() + }, + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_each_overload_signature_and_the_implementation_own_their_block() { + each_overload_signature_and_the_implementation_own_their_block(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_each_overload_signature_and_the_implementation_own_their_block() { + each_overload_signature_and_the_implementation_own_their_block(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn block_before_export_or_declare_documents_the_wrapped_declaration(language: LANG) { + let rows: [(&[u8], Site, Site); 6] = [ + ( + b"/** d */\nexport function f(): void {}\n", + ("function_declaration", 16..37), + ("export_statement", 9..37), + ), + ( + b"/** d */\nexport class C {}\n", + ("class_declaration", 16..26), + ("export_statement", 9..26), + ), + ( + b"/** d */\nexport abstract class A {}\n", + ("abstract_class_declaration", 16..35), + ("export_statement", 9..35), + ), + ( + b"/** d */\nexport interface I {}\n", + ("interface_declaration", 16..30), + ("export_statement", 9..30), + ), + ( + b"/** d */\nexport type T = number;\n", + ("type_alias_declaration", 16..32), + ("export_statement", 9..32), + ), + ( + b"/** d */\nexport enum E { A }\n", + ("enum_declaration", 16..28), + ("export_statement", 9..28), + ), + ]; + for (source, owner, binding) in rows { + check( + language, + source, + wrapped(comment(0..8, "d", [(0..1, Copied(4..5))]), owner, binding), + ); + } + check( + language, + b"/**audit*/\ndeclare function f(): void;\n", + wrapped( + comment(0..10, "audit", [(0..5, Copied(3..8))]), + ("function_signature", 19..38), + ("ambient_declaration", 11..38), + ), + ); + let source = b"/** above */\nexport /** inside */ function f(): void {}\n"; + check_retained( + language, + source, + wrapped( + comment(0..12, "above", [(0..5, Copied(4..9))]), + ("function_declaration", 34..55), + ("export_statement", 13..55), + ), + CandidateDisposition::Unattached, + 20..33, + ); + let source = b"/** above */\nexport default\n/** inside */\nfunction f(): void {}\n"; + check_retained( + language, + source, + wrapped( + comment(0..12, "above", [(0..5, Copied(4..9))]), + ("function_declaration", 42..63), + ("export_statement", 13..63), + ), + CandidateDisposition::Unattached, + 28..41, + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_block_before_export_or_declare_documents_the_wrapped_declaration() { + block_before_export_or_declare_documents_the_wrapped_declaration(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_block_before_export_or_declare_documents_the_wrapped_declaration() { + block_before_export_or_declare_documents_the_wrapped_declaration(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn block_before_a_decorator_documents_the_decorated_class_or_member(language: LANG) { + let rows: [MemberCase; 3] = [ + ( + b"/** d */\n@dec\nclass C {}\n", + 0..8, + 4..5, + ("class_declaration", 9..24), + ), + ( + b"class C {\n /** d */\n @dec\n m(): void {}\n}\n", + 12..20, + 16..17, + ("method_definition", 30..42), + ), + ( + b"class C {\n /** d */\n @dec\n x = 1;\n}\n", + 12..20, + 16..17, + ("public_field_definition", 23..35), + ), + ]; + for (source, fragment, text, owner) in rows { + check( + language, + source, + owned(comment(fragment, "d", [(0..1, Copied(text))]), owner), + ); + } + check( + language, + b"/** d */\n@dec\nexport class C {}\n", + wrapped( + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("class_declaration", 21..31), + ("export_statement", 9..31), + ), + ); + let source = b"class C {\n/**a*/\n@dec\n/**b*/\nm() {}\n}\n"; + check_retained( + language, + source, + owned( + comment(10..16, "a", [(0..1, Copied(13..14))]), + ("method_definition", 29..35), + ), + CandidateDisposition::Unattached, + 22..28, + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_block_before_a_decorator_documents_the_decorated_class_or_member() { + block_before_a_decorator_documents_the_decorated_class_or_member(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_block_before_a_decorator_documents_the_decorated_class_or_member() { + block_before_a_decorator_documents_the_decorated_class_or_member(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn nearest_block_before_the_declaration_is_selected(language: LANG) { + let source = b"/** old */\n/** new */\nfunction f(): void {}\n"; + check_retained( + language, + source, + owned( + comment(11..21, "new", [(0..3, Copied(15..18))]), + ("function_declaration", 22..43), + ), + CandidateDisposition::Superseded, + 0..10, + ); + // The plain `//` comment is not a candidate, even with retention enabled. + let source = b"/** d */\n// plain\nfunction f(): void {}\n"; + let expected = owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("function_declaration", 18..39), + ); + assert_eq!(view(language, source, false), expected); + assert_eq!(view(language, source, true), expected); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_nearest_block_before_the_declaration_is_selected() { + nearest_block_before_the_declaration_is_selected(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_nearest_block_before_the_declaration_is_selected() { + nearest_block_before_the_declaration_is_selected(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn module_tag_makes_the_block_a_file_document(language: LANG) { + let mut with_const = file_owned( + comment(0..28, "@packageDocumentation", [(0..21, Copied(4..25))]), + 0..49, + ); + // The const and its export wrapper await projections today, not the file document. + with_const.assessments = unordered([ + pending(NEEDS_PROJECTION, ("export_statement", 29..48), None), + pending(NEEDS_PROJECTION, ("lexical_declaration", 36..48), None), + ]); + check( + language, + b"/** @packageDocumentation */\nexport const x = 1;\n", + with_const, + ); + check( + language, + b"/** @module */\nfunction f(): void {}\n", + file_owned(comment(0..14, "@module", [(0..7, Copied(4..11))]), 0..37), + ); + check( + language, + b"/**\n * @module m\n */\nfunction f(): void {}\n", + file_owned(comment(0..20, "@module m", [(0..9, Copied(7..16))]), 0..43), + ); + check( + language, + b"/** @packageDocumentation */\n/** d */\nfunction f(): void {}\n", + View { + documents: vec![ + file(comment( + 0..28, + "@packageDocumentation", + [(0..21, Copied(4..25))], + )), + comment(29..37, "d", [(0..1, Copied(33..34))]), + ], + associations: vec![ + Link { + document: 0, + owner: Holder::File(0..60), + binding: None, + }, + link( + 1, + ("function_declaration", 38..59), + ("function_declaration", 38..59), + ), + ], + ..View::default() + }, + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_module_tag_makes_the_block_a_file_document() { + module_tag_makes_the_block_a_file_document(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_module_tag_makes_the_block_a_file_document() { + module_tag_makes_the_block_a_file_document(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn block_text_is_cleaned_and_mapped_to_its_source(language: LANG) { + check( + language, + b"/**audit*/\nfunction f(): void {}\n", + owned( + comment(0..10, "audit", [(0..5, Copied(3..8))]), + ("function_declaration", 11..32), + ), + ); + check( + language, + b"/**\n * a \n * b\n */\nfunction f(): void {}\n", + owned( + comment( + 0..21, + "a \n b", + [ + (0..3, Copied(7..10)), + (3..4, Copied(10..11)), + (4..7, Copied(14..17)), + ], + ), + ("function_declaration", 22..43), + ), + ); + check( + language, + b"/**\r\n * a\r\n * b\r\n */\r\nfunction f(): void {}\r\n", + owned( + comment( + 0..20, + "a\nb", + [ + (0..1, Copied(8..9)), + (1..2, Decoded(9..11)), + (2..3, Copied(14..15)), + ], + ), + ("function_declaration", 22..43), + ), + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_block_text_is_cleaned_and_mapped_to_its_source() { + block_text_is_cleaned_and_mapped_to_its_source(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_block_text_is_cleaned_and_mapped_to_its_source() { + block_text_is_cleaned_and_mapped_to_its_source(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +#[test] +fn tsx_function_with_a_jsx_element_owns_its_leading_block() { + check( + LANG::Tsx, + b"/**audit*/\nfunction f() { return

; }\n", + owned( + comment(0..10, "audit", [(0..5, Copied(3..8))]), + ("function_declaration", 11..42), + ), + ); + check( + LANG::Tsx, + b"/** d */\nexport default function App() { return
; }\n", + wrapped( + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("function_declaration", 24..57), + ("export_statement", 9..57), + ), + ); +} + +// Today's pending forms intentionally move when anonymous default exports, namespaces, +// const bindings and the child of a declare wrapper gain owner projections. +#[cfg(feature = "typescript")] +fn forms_without_an_owner_keep_their_document_and_no_association(language: LANG) { + let source = b"/** above */\ndeclare /** inside */ function f(): void;\n"; + check_retained( + language, + source, + unowned( + comment(0..12, "above", [(0..5, Copied(4..9))]), + ("ambient_declaration", 13..54), + &[], + ), + CandidateDisposition::Unattached, + 21..34, + ); + let rows: [(&[u8], Doc, Site, &[Site]); 8] = [ + ( + b"/**audit*/\nexport default function() {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + ("export_statement", 11..39), + &[], + ), + ( + b"/**audit*/\nexport default class {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + ("export_statement", 11..34), + &[], + ), + ( + b"/** d */\nnamespace N {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("expression_statement", 9..23), + &[("expression_statement", 9..23)], + ), + ( + b"/** d */\nexport namespace N {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("export_statement", 9..30), + &[], + ), + ( + b"/** d */\ndeclare namespace N {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("ambient_declaration", 9..31), + &[], + ), + ( + b"/**audit*/\nconst x = 1;\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + ("lexical_declaration", 11..23), + &[("lexical_declaration", 11..23)], + ), + ( + b"/** d */\nexport const x = 1;\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("export_statement", 9..28), + &[("export_statement", 9..28), ("lexical_declaration", 16..28)], + ), + ( + b"/** d */\ndeclare const x: number;\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + ("ambient_declaration", 9..33), + &[ + ("ambient_declaration", 9..33), + ("lexical_declaration", 17..33), + ], + ), + ]; + for (source, document, bound, extra) in rows { + check(language, source, unowned(document, bound, extra)); + } +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_forms_without_an_owner_keep_their_document_and_no_association() { + forms_without_an_owner_keep_their_document_and_no_association(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_forms_without_an_owner_keep_their_document_and_no_association() { + forms_without_an_owner_keep_their_document_and_no_association(LANG::Tsx); +} + +#[cfg(feature = "typescript")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|node| node.as_tree_sitter()) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + let [node] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + node +} + +#[cfg(feature = "typescript")] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, Site)> { + let mut cursor = parent.walk(); + let mut found = Vec::new(); + if cursor.goto_first_child() { + loop { + found.push((cursor.field_name(), site(cursor.node()))); + if !cursor.goto_next_sibling() { + break; + } + } + } + found +} + +#[cfg(feature = "typescript")] +fn field(parent: tree_sitter::Node<'_>, name: &str, expected: Site) { + assert_eq!(parent.child_by_field_name(name).map(site), Some(expected)); +} + +#[cfg(feature = "typescript")] +fn unnamed(parser: &AnyParser, kind: &str, range: Range) { + assert!(!node_at(parser, kind, range).is_named()); +} + +#[cfg(feature = "typescript")] +#[allow(clippy::too_many_lines)] +fn grammar_shapes_the_unit_relies_on(language: LANG) { + let parser = clean( + language, + b"export function f(): void {}\nexport default function g(): void {}\n", + ); + for (export, declaration) in [(0..28, 7..28), (29..65, 44..65)] { + field( + node_at(&parser, "export_statement", export), + "declaration", + ("function_declaration", declaration), + ); + } + unnamed(&parser, "export", 0..6); + unnamed(&parser, "export", 29..35); + unnamed(&parser, "default", 36..43); + + let parser = clean(language, b"export /** inside */ function f(): void {}\n"); + let export = node_at(&parser, "export_statement", 0..42); + assert_eq!( + parts(export), + [ + (None, ("export", 0..6)), + (None, ("comment", 7..20)), + (Some("declaration"), ("function_declaration", 21..42)), + ] + ); + assert!(node_at(&parser, "comment", 7..20).is_extra()); + unnamed(&parser, "export", 0..6); + field(export, "declaration", ("function_declaration", 21..42)); + + let parser = clean(language, b"@dec\nexport class C {}\n"); + let export = node_at(&parser, "export_statement", 0..22); + assert_eq!( + parts(export), + [ + (Some("decorator"), ("decorator", 0..4)), + (None, ("export", 5..11)), + (Some("declaration"), ("class_declaration", 12..22)), + ] + ); + field(export, "decorator", ("decorator", 0..4)); + field(export, "declaration", ("class_declaration", 12..22)); + unnamed(&parser, "export", 5..11); + + let parser = clean(language, b"export default function() {}\n"); + let export = node_at(&parser, "export_statement", 0..28); + field(export, "value", ("function_expression", 15..28)); + assert!(export.child_by_field_name("declaration").is_none()); + let parser = clean(language, b"export default class {}\n"); + field( + node_at(&parser, "export_statement", 0..23), + "value", + ("class", 15..23), + ); + assert!(node_at(&parser, "class", 15..23).is_named()); + + let parser = clean(language, b"declare /** inside */ function f(): void;\n"); + let ambient = node_at(&parser, "ambient_declaration", 0..41); + assert_eq!( + parts(ambient), + [ + (None, ("declare", 0..7)), + (None, ("comment", 8..21)), + (None, ("function_signature", 22..41)), + ] + ); + unnamed(&parser, "declare", 0..7); + assert!(node_at(&parser, "comment", 8..21).is_extra()); + assert_eq!(ambient.named_child(0).map(site), Some(("comment", 8..21))); + assert_eq!(ambient.child_count(), 3); + let signature = node_at(&parser, "function_signature", 22..41); + assert_eq!( + signature.children(&mut signature.walk()).last().map(site), + Some((";", 40..41)) + ); + unnamed(&parser, ";", 40..41); + + let parser = clean( + language, + b"class C {\n @dec\n m(): void {}\n @dec\n x = 1;\n n(x: string): void;\n}\n", + ); + let body = node_at(&parser, "class_body", 8..71); + assert_eq!( + parts(body), + [ + (None, ("{", 8..9)), + (Some("decorator"), ("decorator", 12..16)), + (None, ("method_definition", 19..31)), + (None, ("public_field_definition", 34..46)), + (None, (";", 46..47)), + (None, ("method_signature", 50..68)), + (None, (";", 68..69)), + (None, ("}", 70..71)), + ] + ); + field(body, "decorator", ("decorator", 12..16)); + field( + node_at(&parser, "public_field_definition", 34..46), + "decorator", + ("decorator", 34..38), + ); + assert_eq!( + node_at(&parser, "method_signature", 50..68) + .child_by_field_name("parameters") + .unwrap() + .named_child(0) + .map(site), + Some(("required_parameter", 52..61)) + ); + for range in [46..47, 68..69] { + unnamed(&parser, ";", range); + } + + let parser = clean(language, b"@dec\nclass C {}\n"); + field( + node_at(&parser, "class_declaration", 0..15), + "decorator", + ("decorator", 0..4), + ); + + let parser = clean(language, b"abstract class A {\n abstract m(): void;\n}\n"); + assert_eq!( + parser.ts_tree().root_node().child(0).map(site), + Some(("abstract_class_declaration", 0..42)) + ); + let body = node_at(&parser, "class_body", 17..42); + assert_eq!( + parts(body)[1..3], + [ + (None, ("abstract_method_signature", 21..39)), + (None, (";", 39..40)), + ] + ); + assert_eq!( + node_at(&parser, "abstract_method_signature", 21..39) + .child(0) + .map(site), + Some(("abstract", 21..29)) + ); + unnamed(&parser, "abstract", 21..29); + unnamed(&parser, ";", 39..40); + + let parser = clean( + language, + b"interface I {\n p: number;\n m(): void;\n (): void;\n \ +[k: string]: number;\n}\n", + ); + let body = node_at(&parser, "interface_body", 12..76); + assert_eq!( + parts(body), + [ + (None, ("{", 12..13)), + (None, ("property_signature", 16..25)), + (None, (";", 25..26)), + (None, ("method_signature", 29..38)), + (None, (";", 38..39)), + (None, ("call_signature", 42..50)), + (None, (";", 50..51)), + (None, ("index_signature", 54..73)), + (None, (";", 73..74)), + (None, ("}", 75..76)), + ] + ); + for range in [25..26, 38..39, 50..51, 73..74] { + unnamed(&parser, ";", range); + } + + let parser = clean(language, b"enum E {\n A,\n B = 1,\n \"s\",\n}\n"); + let body = node_at(&parser, "enum_body", 7..31); + assert_eq!( + parts(body), + [ + (None, ("{", 7..8)), + (Some("name"), ("property_identifier", 11..12)), + (None, (",", 12..13)), + (None, ("enum_assignment", 16..21)), + (None, (",", 21..22)), + (Some("name"), ("string", 25..28)), + (None, (",", 28..29)), + (None, ("}", 30..31)), + ] + ); + field(body, "name", ("property_identifier", 11..12)); + for range in [12..13, 21..22, 28..29] { + unnamed(&parser, ",", range); + } + + let parser = clean( + language, + b"function f(x: string): string;\nfunction f(x: any): any { return x; }\n", + ); + let signature = node_at(&parser, "function_signature", 0..30); + let function = node_at(&parser, "function_declaration", 31..68); + assert_eq!( + signature + .child_by_field_name("parameters") + .unwrap() + .named_child(0) + .map(site), + Some(("required_parameter", 11..20)) + ); + assert_eq!( + signature.children(&mut signature.walk()).last().map(site), + Some((";", 29..30)) + ); + unnamed(&parser, ";", 29..30); + assert_eq!( + function + .child_by_field_name("parameters") + .unwrap() + .named_child(0) + .map(site), + Some(("required_parameter", 42..48)) + ); + + let parser = clean( + language, + b"namespace N {}\nexport namespace M {}\ndeclare namespace O {}\n", + ); + let root = parser.ts_tree().root_node(); + assert_eq!( + parts(root), + [ + (None, ("expression_statement", 0..14)), + (None, ("export_statement", 15..36)), + (None, ("ambient_declaration", 37..59)), + ] + ); + assert_eq!( + parts(node_at(&parser, "expression_statement", 0..14)), + [(None, ("internal_module", 0..14))] + ); + field( + node_at(&parser, "export_statement", 15..36), + "declaration", + ("internal_module", 22..36), + ); + assert_eq!( + node_at(&parser, "ambient_declaration", 37..59) + .named_child(0) + .map(site), + Some(("internal_module", 45..59)) + ); + + let parser = clean( + language, + b"const x = 1;\nexport const y = 1;\ndeclare const z: number;\n", + ); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, ("lexical_declaration", 0..12)), + (None, ("export_statement", 13..32)), + (None, ("ambient_declaration", 33..57)), + ] + ); + field( + node_at(&parser, "export_statement", 13..32), + "declaration", + ("lexical_declaration", 20..32), + ); + assert_eq!( + node_at(&parser, "ambient_declaration", 33..57) + .named_child(0) + .map(site), + Some(("lexical_declaration", 41..57)) + ); + for range in [6..11, 26..31, 47..56] { + field( + node_at(&parser, "variable_declarator", range.clone()), + "name", + ("identifier", range.start..range.start + 1), + ); + } + + let parser = clean( + language, + b"type T = number;\ninterface I {}\nenum E { A }\nfunction f(): void {}\n", + ); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, ("type_alias_declaration", 0..16)), + (None, ("interface_declaration", 17..31)), + (None, ("enum_declaration", 32..44)), + (None, ("function_declaration", 45..66)), + ] + ); + + let source = b"/**\r\n * a\r\n */\r\nfunction f(): void {}\r\n"; + let parser = clean(language, source); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("program", 0..39)); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, ("comment", 0..14)), + (None, ("function_declaration", 16..37)), + ] + ); + let comment = node_at(&parser, "comment", 0..14); + assert_eq!(comment.end_position().row - comment.start_position().row, 2); + assert_eq!(&source[comment.end_byte()..16], b"\r\n"); +} + +#[cfg(feature = "typescript")] +fn tsx_element_shape() { + let source = b"function f() { return
; }\n"; + let parser = clean(LANG::Tsx, source); + let function = node_at(&parser, "function_declaration", 0..31); + field(function, "body", ("statement_block", 13..31)); + let statement = node_at(&parser, "return_statement", 15..29); + assert_eq!( + statement.parent().map(site), + Some(("statement_block", 13..31)) + ); + assert_eq!( + parts(statement)[1], + (None, ("jsx_self_closing_element", 22..28)) + ); +} + +#[cfg(feature = "typescript")] +#[test] +fn typescript_grammar_shapes_the_unit_relies_on() { + grammar_shapes_the_unit_relies_on(LANG::Typescript); +} +#[cfg(feature = "typescript")] +#[test] +fn tsx_grammar_shapes_the_unit_relies_on() { + grammar_shapes_the_unit_relies_on(LANG::Tsx); + tsx_element_shape(); +} diff --git a/utils/documentation-ts-unit1-perturb.json b/utils/documentation-ts-unit1-perturb.json new file mode 100644 index 000000000..1fb7f2349 --- /dev/null +++ b/utils/documentation-ts-unit1-perturb.json @@ -0,0 +1,659 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis-ast", + "--all-features", + "--lib", + "documentation::" + ], + "cases": [ + { + "name": "interface-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " AbstractClassDeclaration,\n InterfaceDeclaration,", + "new": " AbstractClassDeclaration,", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration" + ] + }, + { + "name": "type-alias-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " TypeAliasDeclaration,\n EnumDeclaration,", + "new": " EnumDeclaration,", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration" + ] + }, + { + "name": "enum-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " EnumDeclaration,\n Module,", + "new": " Module,", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration" + ] + }, + { + "name": "abstract-class-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " AbstractClassDeclaration,\n InterfaceDeclaration,", + "new": " InterfaceDeclaration,", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration" + ] + }, + { + "name": "bare-enum-member-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " PropertyIdentifier(under [EnumBody]),\n", + "new": "", + "expect": [ + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block" + ] + }, + { + "name": "assigned-enum-member-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " EnumAssignment,\n RequiredParameter,", + "new": " RequiredParameter,", + "expect": [ + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block" + ] + }, + { + "name": "string-enum-member-not-a-target-typescript", + "file": "big-code-analysis-ast/src/roles/typescript.rs", + "old": " String(under [EnumBody]),\n", + "new": "", + "expect": [ + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block" + ] + }, + { + "name": "string-enum-member-not-a-target-tsx", + "file": "big-code-analysis-ast/src/roles/tsx.rs", + "old": " String2(under [EnumBody]),\n", + "new": "", + "expect": [ + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block" + ] + }, + { + "name": "function-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " FunctionSignature,\n MethodSignature,", + "new": " MethodSignature,", + "expect": [ + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration" + ] + }, + { + "name": "method-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " MethodSignature,\n AbstractMethodSignature,", + "new": " AbstractMethodSignature,", + "expect": [ + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block" + ] + }, + { + "name": "abstract-method-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " AbstractMethodSignature,\n PublicFieldDefinition,", + "new": " PublicFieldDefinition,", + "expect": [ + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block" + ] + }, + { + "name": "public-field-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " PublicFieldDefinition,\n PropertySignature,", + "new": " PropertySignature,", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member" + ] + }, + { + "name": "property-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " PropertySignature,\n IndexSignature,", + "new": " IndexSignature,", + "expect": [ + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block" + ] + }, + { + "name": "index-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " IndexSignature,\n CallSignature,", + "new": " CallSignature,", + "expect": [ + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block" + ] + }, + { + "name": "call-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " CallSignature,\n ConstructSignature,", + "new": " ConstructSignature,", + "expect": [ + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block" + ] + }, + { + "name": "export-wrapper-takes-first-named-child", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " && !matches!(record.field, Some(\"declaration\" | \"value\"))", + "new": " && !record.evidence.node().is_named()", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member" + ] + }, + { + "name": "export-wrapper-ignores-the-declaration-field", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "Some(\"declaration\" | \"value\")", + "new": "Some(\"value\")", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "export-statement-is-not-a-wrapper", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "matches!(kind, \"export_statement\" | \"ambient_declaration\")", + "new": "matches!(kind, \"ambient_declaration\")", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "ambient-declaration-is-not-a-wrapper", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "matches!(kind, \"export_statement\" | \"ambient_declaration\")", + "new": "matches!(kind, \"export_statement\")", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "declaration-under-export-is-a-target", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": "matches!(parent.kind(), \"export_statement\" | \"ambient_declaration\")", + "new": "matches!(parent.kind(), \"ambient_declaration\")", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration" + ] + }, + { + "name": "wrapper-child-is-no-owner-candidate-typescript", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " crate::roles::typescript::doc_target_with_budget(node, code, ancestors, budget)", + "new": " NativeRules::::target(node, code, ancestors, budget)", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "wrapper-child-is-no-owner-candidate-tsx", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " crate::roles::tsx::doc_target_with_budget(node, code, ancestors, budget)", + "new": " NativeRules::::target(node, code, ancestors, budget)", + "expect": [ + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "const-declaration-needs-no-slot", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " \"lexical_declaration\"\n | \"variable_declaration\"", + "new": " \"variable_declaration\"", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "namespace-statement-needs-no-slot", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " | \"expression_statement\"\n | \"required_parameter\"", + "new": " | \"required_parameter\"", + "expect": [ + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "ambient-wrapper-does-not-skip-the-declare-token", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "|| matches!(node.kind(), \"then\" | \"ambient_declaration\"))", + "new": "|| node.kind() == \"then\")", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "ambient-wrapper-skips-comments", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " && !record.evidence.node().is_named()\n {", + "new": " && (!record.evidence.node().is_named() || record.evidence.node().is_extra())\n {", + "expect": [ + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "decorator-not-skipped", + "file": "big-code-analysis-ast/src/checker/js_doc_binding.rs", + "old": "skips: |node, _| node.kind_id() == $lang::Decorator,", + "new": "skips: |node, _| node.kind_id() == $lang::Decorator && node.is_extra(),", + "expect": [ + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member" + ] + }, + { + "name": "nearest-block-is-the-first-block", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " for (at, n) in before.iter().enumerate().rev() {\n budget.step()?;\n if !hidden(n, code) {", + "new": " for (at, n) in before.iter().enumerate() {\n budget.step()?;\n if !hidden(n, code) {", + "expect": [ + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document" + ] + }, + { + "name": "superseded-block-is-unattached", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " && !self.kept.is_empty()", + "new": " && self.kept.is_empty()", + "expect": [ + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected" + ] + }, + { + "name": "plain-comment-not-read-past-typescript", + "file": "big-code-analysis-ast/src/checker/typescript.rs", + "old": " |node, code| Self::is_comment(node) && !Self::is_doc_comment(node, code),", + "new": " |_, _| false,", + "expect": [ + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected" + ] + }, + { + "name": "plain-comment-not-read-past-tsx", + "file": "big-code-analysis-ast/src/checker/tsx.rs", + "old": " |node, code| Self::is_comment(node) && !Self::is_doc_comment(node, code),", + "new": " |_, _| false,", + "expect": [ + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected" + ] + }, + { + "name": "module-tag-binds-forward", + "file": "big-code-analysis-ast/src/documentation/recognition.rs", + "old": " crate::LANG::Typescript | crate::LANG::Tsx => Ok(Some(\n !crate::lang_helpers::doc_text::tsdoc_module_with_budget(bytes, budget)?,\n )),", + "new": " crate::LANG::Typescript | crate::LANG::Tsx => Ok(Some(true)),", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document" + ] + }, + { + "name": "module-block-is-not-the-file-document", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " if file {\n draft.target = Some(NodeId(0));", + "new": " if !file {\n draft.target = Some(NodeId(0));", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document" + ] + }, + { + "name": "packagedocumentation-tag-not-recognized", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " && (title == b\"module\" || title == b\"packageDocumentation\")", + "new": " && title == b\"module\"", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document" + ] + }, + { + "name": "module-tag-not-recognized", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " && (title == b\"module\" || title == b\"packageDocumentation\")", + "new": " && title == b\"packageDocumentation\"", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document" + ] + }, + { + "name": "block-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start = star + 1;", + "new": " line.content.start = star;", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source" + ] + }, + { + "name": "star-strips-every-following-space", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.content.start < line.content.end && bytes[line.content.start] == b' ' {", + "new": " while line.content.start < line.content.end && bytes[line.content.start] == b' ' {", + "expect": [ + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source" + ] + }, + { + "name": "empty-first-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while first < end && block.lines[first].content.is_empty() {", + "new": " while first > end && block.lines[first].content.is_empty() {", + "expect": [ + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source" + ] + }, + { + "name": "crlf-not-decoded", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.ending.len() == 2 {", + "new": " if line.ending.len() == 3 {", + "expect": [ + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "last-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " last.content.end -= 1;", + "new": " last.content.end -= 0;", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "block-opener-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let prefix = if profile == Profile::GoDoc { 2 } else { 3 };", + "new": " let prefix = if profile == Profile::GoDoc { 2 } else { 2 };", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "block-marker-not-recognized", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " matches!(s, [b'/', b'*', b'*', b, ..] if *b != b'/')", + "new": " matches!(s, [b'/', b'*', b'*', b, ..] if *b == b'/')", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "forward-block-has-no-target", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " target,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "new": " target: None,\n scope,\n binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "target-node-is-not-an-owner", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence));", + "new": " self.index.canonical.nodes[id.0].projection = Projection::Pending;", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "binding-wrapper-dropped", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " binding: run.target,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "new": " binding: None,\n role: DocumentRole::Primary,\n unresolved: run.target_uncertainty,", + "expect": [ + "documentation::collector::ts_tests::typescript_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::tsx_leading_block_documents_the_declaration_after_it", + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::tsx_block_before_export_or_declare_documents_the_wrapped_declaration", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::typescript_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::tsx_nearest_block_before_the_declaration_is_selected", + "documentation::collector::ts_tests::typescript_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::tsx_module_tag_makes_the_block_a_file_document", + "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source", + "documentation::collector::ts_tests::tsx_function_with_a_jsx_element_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_forms_without_an_owner_keep_their_document_and_no_association", + "documentation::collector::ts_tests::tsx_forms_without_an_owner_keep_their_document_and_no_association" + ] + }, + { + "name": "lexical-scope-is-the-root", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " let scope = self.evidence_id(run.containing)?.unwrap_or(NodeId(0));\n let code_before = self.evidence_id(run.code_before)?;", + "new": " let scope = NodeId(0);\n let code_before = self.evidence_id(run.code_before)?;", + "expect": [ + "documentation::collector::ts_tests::typescript_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_class_or_interface_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::tsx_enum_member_owns_its_leading_block", + "documentation::collector::ts_tests::typescript_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::tsx_each_overload_signature_and_the_implementation_own_their_block", + "documentation::collector::ts_tests::typescript_block_before_a_decorator_documents_the_decorated_class_or_member", + "documentation::collector::ts_tests::tsx_block_before_a_decorator_documents_the_decorated_class_or_member" + ] + } + ] +} From 60d1c3eb10bb6e1bf92ea1255faa390b48cfbc3d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:27:40 -0800 Subject: [PATCH 095/221] test(loc): guard TypeScript and TSX documentation rows before wrapper and binding work --- src/metrics/loc/documentation_tests.rs | 329 ++++++++++++++++++ ...documentation-ts-unit1-legacy-perturb.json | 42 +++ 2 files changed, 371 insertions(+) create mode 100644 utils/documentation-ts-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index ae9cfacb0..1ef9627e1 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1378,3 +1378,332 @@ fn documentation_php_source_and_legacy_views_are_independent() { assert_ne!(rendered_total, 0); assert_ne!(built_total, 0); } + +#[cfg(feature = "typescript")] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_typescript_and_tsx_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + struct Row<'a> { + language: LANG, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + documents: usize, + } + let ts = documentation::source("primary.ts"); + let tsx = documentation::source("primary.tsx"); + let rows = [ + Row { + language: LANG::Typescript, + source: b"/** above */\ndeclare /** inside */ function f(): void;\n", + loc: [2, 1, 0, 2, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** above */\ndeclare /** inside */ function f(): void;\n", + loc: [2, 1, 0, 2, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/**audit*/\nexport default function() {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/**audit*/\nexport default function() {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/**audit*/\nexport default class {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/**audit*/\nexport default class {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** d */\nnamespace N {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** d */\nnamespace N {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** d */\nexport namespace N {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** d */\nexport namespace N {}\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** d */\ndeclare namespace N {}\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** d */\ndeclare namespace N {}\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/**audit*/\nconst x = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/**audit*/\nconst x = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** @packageDocumentation */\nexport const x = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** @packageDocumentation */\nexport const x = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** d */\ndeclare const x: number;\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** d */\ndeclare const x: number;\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"function f(/**audit*/ x: number) {}\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"function f(/**audit*/ x: number) {}\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/**one*/\nfunction f(x: string): string;\n/**two*/\n\ +function f(x: number): number;\n", + loc: [4, 2, 0, 2, 0, 2], + dloc_rows: &[0, 2], + documents: 2, + }, + Row { + language: LANG::Tsx, + source: b"/**one*/\nfunction f(x: string): string;\n/**two*/\n\ +function f(x: number): number;\n", + loc: [4, 2, 0, 2, 0, 2], + dloc_rows: &[0, 2], + documents: 2, + }, + Row { + language: LANG::Typescript, + source: b"/**audit*/\nexport const {x} = value;\n", + loc: [2, 1, 1, 1, 0, 0], + dloc_rows: &[], + documents: 0, + }, + Row { + language: LANG::Tsx, + source: b"/**audit*/\nexport const {x} = value;\n", + loc: [2, 1, 1, 1, 0, 0], + dloc_rows: &[], + documents: 0, + }, + Row { + language: LANG::Typescript, + source: b"class C {\n/**a*/\n@dec\n/**b*/\nm() {}\n}\n", + loc: [6, 4, 0, 2, 0, 1], + dloc_rows: &[1], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"class C {\n/**a*/\n@dec\n/**b*/\nm() {}\n}\n", + loc: [6, 4, 0, 2, 0, 1], + dloc_rows: &[1], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** above */\nexport /** inside */ function f(): void {}\n", + loc: [2, 1, 1, 2, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** above */\nexport /** inside */ function f(): void {}\n", + loc: [2, 1, 1, 2, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** @packageDocumentation */\n/** d */\nfunction f(): void {}\n", + loc: [3, 1, 0, 2, 0, 2], + dloc_rows: &[0, 1], + documents: 2, + }, + Row { + language: LANG::Tsx, + source: b"/** @packageDocumentation */\n/** d */\nfunction f(): void {}\n", + loc: [3, 1, 0, 2, 0, 2], + dloc_rows: &[0, 1], + documents: 2, + }, + Row { + language: LANG::Tsx, + source: b"/**audit*/\nfunction f() { return
; }\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: &ts, + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: &tsx, + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Typescript, + source: b"/** d */\nexport const x = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + Row { + language: LANG::Tsx, + source: b"/** d */\nexport const x = 1;\n", + loc: [2, 1, 1, 1, 0, 1], + dloc_rows: &[0], + documents: 1, + }, + ]; + for row in rows { + let name = row.source.escape_ascii(); + let parser = + crate::langs::AnyParser::parse(row.language, row.source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error(), "{name}"); + let idle = observations(); + let unbuilt = evidence_built::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let collected = observations(); + let built = evidence_built::observed(); + // expected: the collector enters each named or unnamed parse-tree node once. + assert_eq!( + collected.visits - idle.visits, + parser.root_node().preorder().count(), + "{name}" + ); + // expected: one completed render per published document. + assert_eq!( + collected.renders - idle.renders, + index.documents().len(), + "{name}" + ); + assert_eq!(index.documents().len(), row.documents, "{name}"); + // expected: one marker member per selected block, none for unselected candidates. + assert_eq!(built - unbuilt, row.documents, "{name}"); + let space = analyze( + Source::new(row.language, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = observations(); + // expected: legacy LOC does not collect documentation a second time. + assert_eq!(analyzed.visits - collected.visits, 0, "{name}"); + assert_eq!(analyzed.renders - collected.renders, 0, "{name}"); + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc(), + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + } +} diff --git a/utils/documentation-ts-unit1-legacy-perturb.json b/utils/documentation-ts-unit1-legacy-perturb.json new file mode 100644 index 000000000..d3fd77e71 --- /dev/null +++ b/utils/documentation-ts-unit1-legacy-perturb.json @@ -0,0 +1,42 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis", + "--all-features", + "--lib", + "documentation_typescript_and_tsx_source_and_legacy_views_are_independent" + ], + "cases": [ + { + "name": "decorator-not-skipped", + "file": "big-code-analysis-ast/src/checker/js_doc_binding.rs", + "old": "skips: |node, _| node.kind_id() == $lang::Decorator,", + "new": "skips: |node, _| node.kind_id() == $lang::Decorator && node.is_extra(),", + "expect": [ + "metrics::loc::documentation_tests::documentation_typescript_and_tsx_source_and_legacy_views_are_independent" + ] + }, + { + "name": "function-signature-not-a-target", + "file": "big-code-analysis-ast/src/roles/js_family.rs", + "old": " FunctionSignature,\n MethodSignature,", + "new": " MethodSignature,", + "expect": [ + "metrics::loc::documentation_tests::documentation_typescript_and_tsx_source_and_legacy_views_are_independent" + ] + }, + { + "name": "packagedocumentation-tag-not-recognized", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " && (title == b\"module\" || title == b\"packageDocumentation\")", + "new": " && title == b\"module\"", + "expect": [ + "metrics::loc::documentation_tests::documentation_typescript_and_tsx_source_and_legacy_views_are_independent" + ] + } + ] +} From bd14ac4fe35a6f37ae0742e42edd63d10de659b5 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:53:59 -0800 Subject: [PATCH 096/221] test(documentation): pin Kotlin KDoc owners, pending forms and text in the source view --- .../src/documentation/collector.rs | 2 + .../documentation/collector/kotlin_tests.rs | 1476 +++++++++++++++++ utils/documentation-kotlin-unit1-perturb.json | 469 ++++++ 3 files changed, 1947 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs create mode 100644 utils/documentation-kotlin-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 2f1bad07c..8cbdaf355 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1014,6 +1014,8 @@ mod form_tests; #[cfg(test)] mod go_tests; #[cfg(test)] +mod kotlin_tests; +#[cfg(test)] mod lua_tests; #[cfg(test)] mod named_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs b/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs new file mode 100644 index 000000000..423c312c8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs @@ -0,0 +1,1476 @@ +//! Kotlin KDoc source-view tests compare documents, associations, retained candidates and +//! pending assessments through both entry points. The grammar test collects nothing and +//! pins the tree shapes used by those tests. Node queries are checked beside the view. + +#[cfg(feature = "kotlin")] +use crate::documentation::*; +#[cfg(feature = "kotlin")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "kotlin")] +use std::ops::Range; + +#[cfg(feature = "kotlin")] +use Run::{Copied, Decoded}; + +#[cfg(feature = "kotlin")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "kotlin")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(feature = "kotlin")] +#[derive(Debug, PartialEq, Eq)] +struct Link { + document: usize, + resolution: Resolution, + owner: (&'static str, Range), +} + +#[cfg(feature = "kotlin")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +} + +/// Documents, associations, retained candidates and order-independent pending assessments. +/// Shared values are asserted by `published`; node queries are checked separately. +#[cfg(feature = "kotlin")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + associations: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(feature = "kotlin")] +const AWAITS_OWNER: &str = "Selected local or wrapper form awaits owner projection"; +#[cfg(feature = "kotlin")] +const NEEDS_PROJECTION: &str = "Recognized declaration requires a semantic projection"; +#[cfg(feature = "kotlin")] +const SIGNATURE: &str = "KDoc signature or parameter form awaits owner projection"; + +#[cfg(feature = "kotlin")] +type RetainedPair<'a> = ( + &'a [u8], + Doc, + &'static str, + Range, + &'a [Range], +); + +#[cfg(feature = "kotlin")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "kotlin")] +fn owned(document: Doc, kind: &'static str, range: Range) -> View { + View { + documents: vec![document], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owner: (kind, range), + }], + ..View::default() + } +} + +#[cfg(feature = "kotlin")] +fn pending( + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +) -> Pending { + Pending { + axis, + reason, + node, + document, + } +} + +#[cfg(feature = "kotlin")] +fn unordered(entries: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = entries.into_iter().collect(); + // Assessment order is unspecified; both the observed and expected lists use this key. + sorted.sort_by_cached_key(|entry| { + ( + entry.reason, + entry.node.as_ref().map(|(_, range)| range.start), + entry.node.as_ref().map(|(_, range)| range.end), + entry.document, + ) + }); + sorted +} + +#[cfg(feature = "kotlin")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "kotlin")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "kotlin")] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("block_comment", range.clone())) + ); + range +} + +#[cfg(feature = "kotlin")] +fn origin_run(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "kotlin")] +fn published(index: &DocumentationIndex<'_>) -> View { + // bca: suppress(halstead) -- one reading of the four lists and their shared invariants. + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let position = |document| ordered.iter().position(|known| *known == document).unwrap(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|entry| (entry.output.range(), origin_run(&entry.origin))) + .collect(), + } + }) + .collect(); + let associations = index + .associations() + .map(|association| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "KDoc"); + assert_eq!(attachment.publication, Publication::Unknown); + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let comment = first.get().node().unwrap().node(); + assert_eq!(Some(attachment.lexical_scope.node()), comment.parent()); + let owner = facts.associated_owner(association, 0).unwrap(); + let Owner::Node(declared) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declared.node()) + ); + Link { + document: position(document), + resolution: attachment.resolution, + owner: site(declared.node()), + } + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect(); + let assessments = unordered(index.assessments().map(|assessment| Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| site(node.node())), + document: index.assessed_document(assessment).unwrap().map(position), + })); + assert_eq!(index.capability(), Capability::Partial); + // Qualifications belong to named-reference commands, absent from all these KDoc sources. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + associations, + evidence, + assessments, + } +} + +#[cfg(feature = "kotlin")] +fn clean(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Kotlin, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{}", + source.escape_ascii() + ); + parser +} + +#[cfg(feature = "kotlin")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Kotlin, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(feature = "kotlin")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2]) -> View { + let [typed, raw] = indexes.each_ref().map(published); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "kotlin")] +fn view(source: &[u8]) -> View { + let parser = clean(source); + agreed(&indexes(&parser, DocumentationOptions::default())) +} + +#[cfg(feature = "kotlin")] +fn retained(source: &[u8]) -> View { + let parser = clean(source); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + agreed(&indexes(&parser, options)) +} + +#[cfg(feature = "kotlin")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|node| node.as_tree_sitter()) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "kotlin")] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static str, Range)> { + let mut cursor = parent.walk(); + let mut result = Vec::new(); + if cursor.goto_first_child() { + loop { + let child = cursor.node(); + result.push((cursor.field_name(), child.kind(), child.byte_range())); + if !cursor.goto_next_sibling() { + break; + } + } + } + result +} + +#[cfg(feature = "kotlin")] +fn grammar_parse(source: &[u8], has_error: bool) -> AnyParser { + // bca: suppress(halstead) -- comparing typed and raw grammar trees is one cohesive check. + let parser = AnyParser::parse(LANG::Kotlin, source.to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + assert_eq!(root.has_error(), has_error, "{}", source.escape_ascii()); + assert_eq!(root.end_byte(), source.len()); + let mut raw = tree_sitter::Parser::new(); + raw.set_language(&LANG::Kotlin.tree_sitter_language().unwrap()) + .unwrap(); + let raw_tree = raw.parse(source, None).unwrap(); + let typed_nodes: Vec<_> = parser + .root_node() + .preorder() + .map(|node| { + let node = node.as_tree_sitter(); + ( + site(node), + node.has_error(), + node.is_error(), + node.is_missing(), + node.is_extra(), + node.is_named(), + ) + }) + .collect(); + let mut raw_nodes = vec![raw_tree.root_node()]; + let mut raw_facts = Vec::new(); + while let Some(node) = raw_nodes.pop() { + raw_facts.push(( + site(node), + node.has_error(), + node.is_error(), + node.is_missing(), + node.is_extra(), + node.is_named(), + )); + let children: Vec<_> = node.children(&mut node.walk()).collect(); + raw_nodes.extend(children.into_iter().rev()); + } + assert_eq!(typed_nodes, raw_facts); + if !has_error { + assert!( + typed_nodes + .iter() + .all(|(_, error, is_error, missing, _, _)| { !error && !is_error && !missing }) + ); + } + parser +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_kdoc_before_a_top_level_declaration_documents_it() { + let declarations: [(&[u8], Doc, &str, Range); 4] = [ + ( + b"/**audit*/\nfun f() {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + "function_declaration", + 11..21, + ), + ( + b"/** d */\nclass C {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 9..19, + ), + ( + b"/** d */\nobject O {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "object_declaration", + 9..20, + ), + ( + b"/** d */\ntypealias T = Int\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "type_alias", + 9..26, + ), + ]; + for (source, document, kind, range) in declarations { + assert_eq!( + view(source), + owned(document, kind, range), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_kdoc_before_a_member_documents_the_member_not_the_class() { + let members: [(&[u8], Doc, &str, Range); 5] = [ + ( + b"class C {\n /** d */\n companion object {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "companion_object", + 27..46, + ), + ( + b"class C {\n /** d */\n constructor() {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "secondary_constructor", + 27..43, + ), + ( + b"class C {\n /** d */\n fun m() {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "function_declaration", + 27..37, + ), + ( + b"class C {\n /** d */\n class N {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "class_declaration", + 27..37, + ), + ( + b"class C {\n /**audit*/\n constructor(x: Int) {}\n}\n", + comment(14..24, "audit", [(0..5, Copied(17..22))]), + "secondary_constructor", + 29..51, + ), + ]; + for (source, document, kind, range) in members { + let mut expected = owned(document, kind, range); + if source == b"class C {\n /**audit*/\n constructor(x: Int) {}\n}\n" { + // The undocumented parameter pins today's pending projection, not its later design. + expected.assessments = unordered([pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("parameter", 41..47)), + None, + )]); + } + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + } + assert_eq!( + view(b"enum class E {\n /** a */\n A,\n /** b */\n B\n}\n"), + View { + documents: vec![ + comment(19..27, "a", [(0..1, Copied(23..24))]), + comment(39..47, "b", [(0..1, Copied(43..44))]), + ], + associations: vec![ + Link { + document: 0, + resolution: Resolution::Resolved, + owner: ("enum_entry", 32..33), + }, + Link { + document: 1, + resolution: Resolution::Resolved, + owner: ("enum_entry", 52..53), + }, + ], + ..View::default() + } + ); +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc() { + let declarations: [(&[u8], Doc, &str, Range); 3] = [ + ( + b"/**audit*/\n@Deprecated(\"x\") fun f() {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + "function_declaration", + 11..38, + ), + ( + b"/** d */\n@Deprecated(\"x\") class C {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 9..36, + ), + ( + b"class C {\n /** d */\n @JvmStatic fun m() {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "function_declaration", + 27..48, + ), + ]; + for (source, document, kind, range) in declarations { + assert_eq!( + view(source), + owned(document, kind, range), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded() { + #[allow(clippy::single_range_in_vec_init)] + let pairs: [RetainedPair<'_>; 4] = [ + ( + b"/**old*/\n/**new*/\nfun f() {}\n", + comment(9..17, "new", [(0..3, Copied(12..15))]), + "function_declaration", + 18..28, + &[0..8], + ), + ( + b"/**old*/\n// plain\n/**new*/\nfun f() {}\n", + comment(18..26, "new", [(0..3, Copied(21..24))]), + "function_declaration", + 27..37, + &[0..8], + ), + ( + b"/**old*/\n\n/**new*/\n\nfun f() {}\n", + comment(10..18, "new", [(0..3, Copied(13..16))]), + "function_declaration", + 20..30, + &[0..8], + ), + ( + b"/**a*/\n/**b*/\n/**c*/\nclass C {}\n", + comment(14..20, "c", [(0..1, Copied(17..18))]), + "class_declaration", + 21..31, + &[0..6, 7..13], + ), + ]; + for (source, document, kind, range, candidates) in pairs { + let mut expected = owned(document, kind, range); + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + expected.evidence.extend( + candidates + .iter() + .cloned() + .map(|range| (CandidateDisposition::Superseded, range)), + ); + assert_eq!(retained(source), expected, "{}", source.escape_ascii()); + } + for (source, range) in [ + (b"/** d */\n// plain\nfun f() {}\n".as_slice(), 18..28), + (b"/** d */\n\nfun f() {}\n".as_slice(), 10..20), + ] { + assert_eq!( + view(source), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "function_declaration", + range, + ), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_plain_comments_are_no_documentation() { + for source in [b"/* d */\nfun f() {}\n".as_slice(), b"// d\nfun f() {}\n"] { + assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); + assert_eq!( + retained(source), + View::default(), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_kdoc_text_over_several_lines() { + let rows: [(&[u8], Doc, Range); 5] = [ + ( + b"/**\n * a\n * b\n */\nfun f() {}\n", + comment( + 0..17, + "a\nb", + [ + (0..1, Copied(7..8)), + (1..2, Copied(8..9)), + (2..3, Copied(12..13)), + ], + ), + 18..28, + ), + ( + b"/**\n * a \n * b\n */\nfun f() {}\n", + comment( + 0..21, + "a \n b", + [ + (0..3, Copied(7..10)), + (3..4, Copied(10..11)), + (4..7, Copied(14..17)), + ], + ), + 22..32, + ), + ( + b"/**\n * Sum.\n *\n * @return x\n */\nfun f() {}\n", + comment( + 0..31, + "Sum.\n\n@return x", + [ + (0..4, Copied(7..11)), + (4..5, Copied(11..12)), + (5..6, Copied(14..15)), + (6..15, Copied(18..27)), + ], + ), + 32..42, + ), + ( + b"/** a\n * b */\nfun f() {}\n", + comment( + 0..13, + "a\nb", + [ + (0..1, Copied(4..5)), + (1..2, Copied(5..6)), + (2..3, Copied(9..10)), + ], + ), + 14..24, + ), + ( + b"class C {\n /**\n * a\n * b\n */\n fun m() {}\n}\n", + comment( + 14..43, + "a\nb", + [ + (0..1, Copied(25..26)), + (1..2, Copied(26..27)), + (2..3, Copied(34..35)), + ], + ), + 48..58, + ), + ]; + for (source, document, range) in rows { + assert_eq!( + view(source), + owned(document, "function_declaration", range), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "kotlin")] +#[test] +fn kotlin_kdoc_with_crlf_line_endings() { + assert_eq!( + view(b"/** d */\r\nfun f() {}\r\n"), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "function_declaration", + 10..20, + ) + ); + assert_eq!( + view(b"/**\r\n * a\r\n * b\r\n */\r\nfun f() {}\r\n"), + owned( + comment( + 0..20, + "a\nb", + [ + (0..1, Copied(8..9)), + (1..2, Decoded(9..11)), + (2..3, Copied(14..15)), + ], + ), + "function_declaration", + 22..32, + ) + ); +} + +#[cfg(feature = "kotlin")] +fn check_query( + parser: &AnyParser, + indexes: &[DocumentationIndex<'_>; 2], + kind: &str, + range: Range, + pending_owner: bool, + expected: &[(AssessmentAxis, &str)], +) { + // bca: suppress(nargs) -- a query needs its parse, indexes, node, status and assessments. + let node = node_at(parser, kind, range); + for index in indexes { + let projection = index.node_projection(node).unwrap(); + assert_eq!(projection.pending(), pending_owner); + if pending_owner { + assert_eq!(projection.owners().count(), 0); + } else { + let owners: Vec<_> = projection.owners().collect(); + let [owner] = owners[..] else { + panic!("one owner, found {owners:?}") + }; + let Owner::Node(declared) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + assert_eq!(declared.node(), node); + } + let query = index.node_associations(node).unwrap(); + assert_eq!(query.associations().count(), 0); + assert_eq!(query.projection_pending(), pending_owner); + let mut actual: Vec<_> = query + .assessments() + .map(|assessment| (assessment.get().axis, assessment.get().reason)) + .collect(); + actual.sort_by_key(|(_, reason)| *reason); + let mut expected = expected.to_vec(); + expected.sort_by_key(|(_, reason)| *reason); + assert_eq!(actual, expected); + } +} + +/// These documents and assessments pin today's pending forms, not their later owner projection. +#[cfg(feature = "kotlin")] +#[test] +#[allow(clippy::too_many_lines)] +fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { + for (source, fragment, text, node) in [ + (b"/** d */\nval x = 1\n".as_slice(), 0..8, 4..5, 9..18), + ( + b"class C {\n /** d */\n val p = 1\n}\n".as_slice(), + 14..22, + 18..19, + 27..36, + ), + ] { + assert_eq!( + view(source), + View { + documents: vec![comment(fragment, "d", [(0..1, Copied(text))])], + assessments: unordered([ + pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + Some(("property_declaration", node.clone())), + Some(0), + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("property_declaration", node)), + None, + ), + ]), + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } + let class_parameter = b"class C(/**audit*/ val x: Int)\n"; + let class_expected = View { + documents: vec![comment(8..18, "audit", [(0..5, Copied(11..16))])], + assessments: unordered([ + pending( + AssessmentAxis::Selection, + SIGNATURE, + Some(("block_comment", 8..18)), + None, + ), + pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + Some(("class_parameter", 19..29)), + Some(0), + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("primary_constructor", 7..30)), + None, + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("class_parameter", 19..29)), + None, + ), + ]), + ..View::default() + }; + assert_eq!(view(class_parameter), class_expected); + let function_parameter = b"fun f(/**p*/ x: Int) {}\n"; + let function_expected = View { + documents: vec![comment(6..12, "p", [(0..1, Copied(9..10))])], + assessments: unordered([ + pending( + AssessmentAxis::Selection, + SIGNATURE, + Some(("block_comment", 6..12)), + None, + ), + pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + Some(("parameter", 13..19)), + Some(0), + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("parameter", 13..19)), + None, + ), + ]), + ..View::default() + }; + assert_eq!(view(function_parameter), function_expected); + + let parser = clean(b"/** d */\nval x = 1\n"); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both), + View { + documents: vec![comment(0..8, "d", [(0..1, Copied(4..5))])], + assessments: unordered([ + pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + Some(("property_declaration", 9..18)), + Some(0) + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("property_declaration", 9..18)), + None + ), + ]), + ..View::default() + } + ); + check_query( + &parser, + &both, + "property_declaration", + 9..18, + true, + &[ + (AssessmentAxis::Owner, AWAITS_OWNER), + (AssessmentAxis::Owner, NEEDS_PROJECTION), + ], + ); + + let parser = clean(class_parameter); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!(agreed(&both), class_expected); + check_query( + &parser, + &both, + "class_declaration", + 0..30, + false, + &[(AssessmentAxis::Selection, SIGNATURE)], + ); + check_query( + &parser, + &both, + "primary_constructor", + 7..30, + true, + &[ + (AssessmentAxis::Owner, NEEDS_PROJECTION), + (AssessmentAxis::Selection, SIGNATURE), + ], + ); + check_query( + &parser, + &both, + "class_parameter", + 19..29, + true, + &[ + (AssessmentAxis::Owner, AWAITS_OWNER), + (AssessmentAxis::Owner, NEEDS_PROJECTION), + (AssessmentAxis::Owner, NEEDS_PROJECTION), + (AssessmentAxis::Selection, SIGNATURE), + ], + ); + + let parser = clean(function_parameter); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!(agreed(&both), function_expected); + check_query( + &parser, + &both, + "function_declaration", + 0..23, + false, + &[(AssessmentAxis::Selection, SIGNATURE)], + ); + check_query( + &parser, + &both, + "parameter", + 13..19, + true, + &[ + (AssessmentAxis::Owner, AWAITS_OWNER), + (AssessmentAxis::Owner, NEEDS_PROJECTION), + (AssessmentAxis::Selection, SIGNATURE), + ], + ); +} + +/// These documents and assessments pin today's pending forms, not their later owner projection. +#[cfg(feature = "kotlin")] +#[test] +#[allow(clippy::too_many_lines)] +fn kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments() { + let rows: [(&[u8], Doc, Vec); 6] = [ + ( + b"public /**audit*/ inline fun f() {}\n", + comment(7..17, "audit", [(0..5, Copied(10..15))]), + unordered([ + pending( + AssessmentAxis::Selection, + SIGNATURE, + Some(("block_comment", 7..17)), + None, + ), + pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), + ]), + ), + ( + b"public /**audit*/ fun f() {}\n", + comment(7..17, "audit", [(0..5, Copied(10..15))]), + unordered([pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0))]), + ), + ( + b"class C private /**audit*/ constructor()\n", + comment(16..26, "audit", [(0..5, Copied(19..24))]), + unordered([ + pending( + AssessmentAxis::Selection, + SIGNATURE, + Some(("block_comment", 16..26)), + None, + ), + pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("primary_constructor", 8..40)), + None, + ), + ]), + ), + ( + b"class C /**audit*/ constructor()\n", + comment(8..18, "audit", [(0..5, Copied(11..16))]), + unordered([ + pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("primary_constructor", 19..32)), + None, + ), + ]), + ), + ( + b"fun f() /**audit*/ {}\n", + comment(8..18, "audit", [(0..5, Copied(11..16))]), + unordered([pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0))]), + ), + ( + b"class C {\n fun f() /**audit*/ {}\n}\n", + comment(22..32, "audit", [(0..5, Copied(25..30))]), + unordered([pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0))]), + ), + ]; + for (source, document, assessments) in rows { + assert_eq!( + view(source), + View { + documents: vec![document], + assessments, + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } + let leading = b"/**first*/\nfun f() /**audit*/ {}\n"; + assert_eq!( + view(leading), + View { + documents: vec![ + comment(0..10, "first", [(0..5, Copied(3..8))]), + comment(19..29, "audit", [(0..5, Copied(22..27))]), + ], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owner: ("function_declaration", 11..32), + }], + assessments: unordered([pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(1))]), + ..View::default() + } + ); + for (source, expected, queries) in [ + ( + b"public /**audit*/ inline fun f() {}\n".as_slice(), + View { + documents: vec![comment(7..17, "audit", [(0..5, Copied(10..15))])], + assessments: unordered([ + pending( + AssessmentAxis::Selection, + SIGNATURE, + Some(("block_comment", 7..17)), + None, + ), + pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), + ]), + ..View::default() + }, + vec![( + "function_declaration", + 0..35, + false, + vec![ + (AssessmentAxis::Selection, SIGNATURE), + (AssessmentAxis::Owner, AWAITS_OWNER), + ], + )], + ), + ( + b"class C private /**audit*/ constructor()\n".as_slice(), + View { + documents: vec![comment(16..26, "audit", [(0..5, Copied(19..24))])], + assessments: unordered([ + pending( + AssessmentAxis::Selection, + SIGNATURE, + Some(("block_comment", 16..26)), + None, + ), + pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("primary_constructor", 8..40)), + None, + ), + ]), + ..View::default() + }, + vec![ + ( + "class_declaration", + 0..40, + false, + vec![ + (AssessmentAxis::Selection, SIGNATURE), + (AssessmentAxis::Owner, AWAITS_OWNER), + ], + ), + ( + "primary_constructor", + 8..40, + true, + vec![ + (AssessmentAxis::Owner, NEEDS_PROJECTION), + (AssessmentAxis::Selection, SIGNATURE), + (AssessmentAxis::Owner, AWAITS_OWNER), + ], + ), + ], + ), + ( + b"fun f() /**audit*/ {}\n".as_slice(), + View { + documents: vec![comment(8..18, "audit", [(0..5, Copied(11..16))])], + assessments: unordered([pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + None, + Some(0), + )]), + ..View::default() + }, + vec![( + "function_declaration", + 0..21, + false, + vec![(AssessmentAxis::Owner, AWAITS_OWNER)], + )], + ), + ] { + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!(agreed(&both), expected); + for (kind, range, pending, assessments) in queries { + check_query(&parser, &both, kind, range, pending, &assessments); + } + } +} + +#[cfg(feature = "kotlin")] +#[test] +#[allow(clippy::too_many_lines)] +fn kotlin_grammar_shapes_the_unit_relies_on() { + let source = b"/**audit*/\nfun f() {}\n"; + let parser = grammar_parse(source, false); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("source_file", 0..22)); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, "block_comment", 0..10), + (None, "function_declaration", 11..21) + ] + ); + assert!(node_at(&parser, "block_comment", 0..10).is_extra()); + + let parser = grammar_parse( + b"class C {}\nobject O {}\ntypealias T = Int\nfun f() {}\nval x = 1\n", + false, + ); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "class_declaration", 0..10), + (None, "object_declaration", 11..22), + (None, "type_alias", 23..40), + (None, "function_declaration", 41..51), + (None, "property_declaration", 52..61), + ] + ); + + let parser = grammar_parse( + b"class C {\n companion object {}\n constructor() {}\n fun m() {}\n \ + class N {}\n val p = 1\n}\n", + false, + ); + assert_eq!( + parts(node_at(&parser, "class_body", 8..100)), + [ + (None, "{", 8..9), + (None, "companion_object", 14..33), + (None, "secondary_constructor", 38..54), + (None, "function_declaration", 59..69), + (None, "class_declaration", 74..84), + (None, "property_declaration", 89..98), + (None, "}", 99..100), + ] + ); + + let parser = grammar_parse( + b"enum class E {\n /** a */\n A,\n /** b */\n B\n}\n", + false, + ); + let body = node_at(&parser, "enum_class_body", 13..55); + assert_eq!( + parts(body), + [ + (None, "{", 13..14), + (None, "block_comment", 19..27), + (None, "enum_entry", 32..33), + (None, ",", 33..34), + (None, "block_comment", 39..47), + (None, "enum_entry", 52..53), + (None, "}", 54..55), + ] + ); + assert!(!body.child(3).unwrap().is_named()); + + let parser = grammar_parse(b"/**audit*/\n@Deprecated(\"x\") fun f() {}\n", false); + let root = parser.ts_tree().root_node(); + let comment = node_at(&parser, "block_comment", 0..10); + let function = comment.next_sibling().unwrap(); + assert_eq!(comment.parent(), Some(root)); + assert_eq!(site(function), ("function_declaration", 11..38)); + let modifiers = function.child(0).unwrap(); + assert_eq!(site(modifiers), ("modifiers", 11..27)); + assert_eq!(parts(modifiers), [(None, "annotation", 11..27)]); + + let parser = grammar_parse(b"class C(/**audit*/ val x: Int)\n", false); + let class = node_at(&parser, "class_declaration", 0..30); + let constructor = node_at(&parser, "primary_constructor", 7..30); + let parameters = node_at(&parser, "class_parameters", 7..30); + assert_eq!(constructor.parent(), Some(class)); + assert_eq!(parameters.parent(), Some(constructor)); + assert_eq!( + parts(parameters), + [ + (None, "(", 7..8), + (None, "block_comment", 8..18), + (None, "class_parameter", 19..29), + (None, ")", 29..30), + ] + ); + assert!( + parts(node_at(&parser, "class_parameter", 19..29)) + .iter() + .all(|(_, kind, _)| *kind != "block_comment") + ); + + let parser = grammar_parse(b"fun f(/**p*/ x: Int) {}\n", false); + let parameters = node_at(&parser, "function_value_parameters", 5..20); + assert_eq!( + parts(parameters), + [ + (None, "(", 5..6), + (None, "block_comment", 6..12), + (None, "parameter", 13..19), + (None, ")", 19..20), + ] + ); + assert!( + parts(node_at(&parser, "parameter", 13..19)) + .iter() + .all(|(_, kind, _)| *kind != "block_comment") + ); + + let parser = grammar_parse(b"public /**audit*/ inline fun f() {}\n", false); + let function = node_at(&parser, "function_declaration", 0..35); + let modifiers = function.child(0).unwrap(); + assert_eq!(site(modifiers), ("modifiers", 0..24)); + assert_eq!( + parts(modifiers), + [ + (None, "visibility_modifier", 0..6), + (None, "block_comment", 7..17), + (None, "function_modifier", 18..24), + ] + ); + + let parser = grammar_parse(b"public /**audit*/ fun f() {}\n", false); + let function = node_at(&parser, "function_declaration", 0..28); + assert_eq!( + parts(function)[..3], + [ + (None, "modifiers", 0..6), + (None, "block_comment", 7..17), + (None, "fun", 18..21), + ] + ); + assert!(!function.child(2).unwrap().is_named()); + assert!( + parts(function.child(0).unwrap()) + .iter() + .all(|(_, kind, _)| *kind != "block_comment") + ); + + let parser = grammar_parse(b"class C private /**audit*/ constructor()\n", false); + let constructor = node_at(&parser, "primary_constructor", 8..40); + assert_eq!( + parts(constructor), + [ + (None, "modifiers", 8..15), + (None, "block_comment", 16..26), + (None, "constructor", 27..38), + (None, "class_parameters", 38..40), + ] + ); + assert!(!constructor.child(2).unwrap().is_named()); + + let parser = grammar_parse(b"class C /**audit*/ constructor()\n", false); + let class = node_at(&parser, "class_declaration", 0..32); + assert_eq!( + parts(class)[2..4], + [ + (None, "block_comment", 8..18), + (None, "primary_constructor", 19..32), + ] + ); + assert!( + parts(node_at(&parser, "primary_constructor", 19..32)) + .iter() + .all(|(_, kind, _)| *kind != "block_comment") + ); + + let parser = grammar_parse(b"fun f() /**audit*/ {}\n", false); + assert_eq!( + parts(node_at(&parser, "function_declaration", 0..21))[2..5], + [ + (None, "function_value_parameters", 5..7), + (None, "block_comment", 8..18), + (None, "function_body", 19..21), + ] + ); + + let parser = grammar_parse(b"/* a */\n// b\n/** c */\nfun f() {}\n", false); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "block_comment", 0..7), + (None, "line_comment", 8..12), + (None, "block_comment", 13..21), + (None, "function_declaration", 22..32), + ] + ); + let source = b"/**\r\n * a\r\n * b\r\n */\r\nfun f() {}\r\n"; + let parser = grammar_parse(source, false); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("source_file", 0..34)); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + parts(root), + [ + (None, "block_comment", 0..20), + (None, "function_declaration", 22..32), + ] + ); + let comment = node_at(&parser, "block_comment", 0..20); + assert_eq!(comment.end_position().row - comment.start_position().row, 3); + assert_eq!( + source[comment.byte_range()] + .windows(2) + .filter(|pair| *pair == b"\r\n") + .count(), + 3 + ); + let function = node_at(&parser, "function_declaration", 22..32); + assert_eq!(&source[comment.end_byte()..function.start_byte()], b"\r\n"); + + let parser = grammar_parse( + b"fun g() {}\n/** d */\n@Suppress(\"x\")\nfun f() {}\n", + false, + ); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "function_declaration", 0..10), + (None, "block_comment", 11..19), + (None, "annotated_expression", 20..34), + (None, "function_declaration", 35..45), + ] + ); + let parser = grammar_parse(b"/** d */\ncontext(Foo)\nfun f() {}\n", false); + assert_eq!( + parts(parser.ts_tree().root_node()), + [ + (None, "block_comment", 0..8), + (None, "call_expression", 9..21), + (None, "function_declaration", 22..32), + ] + ); + let parser = grammar_parse( + b"class C {\n val q: Int\n /** g */\n get() = 1\n}\n", + false, + ); + let property = node_at(&parser, "property_declaration", 14..59); + assert_eq!( + parts(property), + [ + (None, "val", 14..17), + (None, "variable_declaration", 18..24), + (None, "block_comment", 33..41), + (None, "getter", 50..59), + ] + ); + assert!( + parts(node_at(&parser, "getter", 50..59)) + .iter() + .all(|(_, kind, _)| *kind != "block_comment") + ); + let parser = grammar_parse(b"@Deprecated(\"x\")\n/** d */\nfun f() {}\n", false); + let function = node_at(&parser, "function_declaration", 0..36); + assert_eq!( + parts(function)[..3], + [ + (None, "modifiers", 0..16), + (None, "block_comment", 17..25), + (None, "fun", 26..29), + ] + ); + assert!(!function.child(2).unwrap().is_named()); + assert!( + parts(function.child(0).unwrap()) + .iter() + .all(|(_, kind, _)| *kind != "block_comment") + ); + + for (source, error) in [ + ( + b"class C { /**audit*/ constructor(x: Int) {} }\n".as_slice(), + true, + ), + ( + b"class C { /**audit*/ constructor(x: Int) {}\n}\n".as_slice(), + false, + ), + ] { + let parser = grammar_parse(source, error); + let root = parser.ts_tree().root_node(); + assert_eq!(root.has_error(), error); + let class = node_at(&parser, "class_declaration", 0..45); + let body = node_at(&parser, "class_body", 8..45); + assert_eq!(class.has_error(), error); + assert_eq!(body.has_error(), error); + assert_eq!( + parts(body), + [ + (None, "{", 8..9), + (None, "block_comment", 10..20), + (None, "secondary_constructor", 21..43), + (None, "}", 44..45), + ] + ); + assert!(parser.root_node().preorder().all(|node| { + let node = node.as_tree_sitter(); + !node.is_error() && !node.is_missing() && (error || !node.has_error()) + })); + assert!( + body.children(&mut body.walk()) + .all(|child| !child.has_error()) + ); + } + let source = b"class C { fun m() {} }\n"; + let parser = grammar_parse(source, true); + let root = parser.ts_tree().root_node(); + assert!(root.has_error()); + let body = node_at(&parser, "enum_class_body", 8..22); + assert_eq!( + parts(body), + [ + (None, "{", 8..9), + (None, "ERROR", 10..20), + (None, "}", 21..22), + ] + ); + let error = node_at(&parser, "ERROR", 10..20); + assert!(error.is_error()); + assert_eq!(parts(error), [(None, "function_declaration", 10..20)]); + assert_eq!( + parser + .root_node() + .preorder() + .filter(|node| node.as_tree_sitter().is_error()) + .count(), + 1 + ); + assert!( + parser + .root_node() + .preorder() + .all(|node| !node.as_tree_sitter().is_missing()) + ); +} diff --git a/utils/documentation-kotlin-unit1-perturb.json b/utils/documentation-kotlin-unit1-perturb.json new file mode 100644 index 000000000..e6f4df746 --- /dev/null +++ b/utils/documentation-kotlin-unit1-perturb.json @@ -0,0 +1,469 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis-ast", + "--all-features", + "--lib", + "documentation::" + ], + "cases": [ + { + "name": "kotlin-class-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " ClassDeclaration,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it", + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc", + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-object-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " ObjectDeclaration,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it" + ] + }, + { + "name": "kotlin-companion-object-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " CompanionObject,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class" + ] + }, + { + "name": "kotlin-function-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " FunctionDeclaration,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it", + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc", + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-type-alias-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " TypeAlias,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it" + ] + }, + { + "name": "kotlin-secondary-constructor-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " SecondaryConstructor,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class" + ] + }, + { + "name": "kotlin-enum-entry-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " EnumEntry,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class" + ] + }, + { + "name": "kotlin-property-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " PropertyDeclaration,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-parameter-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " Parameter,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-class-parameter-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " ClassParameter,\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-property-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"class_parameter\" | \"parameter\" | \"primary_constructor\" | \"property_declaration\"\n", + "new": " \"class_parameter\" | \"parameter\" | \"primary_constructor\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-class-parameter-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"class_parameter\" | \"parameter\" | \"primary_constructor\" | \"property_declaration\"\n", + "new": " \"parameter\" | \"primary_constructor\" | \"property_declaration\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-parameter-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"class_parameter\" | \"parameter\" | \"primary_constructor\" | \"property_declaration\"\n", + "new": " \"class_parameter\" | \"primary_constructor\" | \"property_declaration\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-primary-constructor-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"class_parameter\" | \"parameter\" | \"primary_constructor\" | \"property_declaration\"\n", + "new": " \"class_parameter\" | \"parameter\" | \"property_declaration\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-primary-constructor-is-no-slot-candidate", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"class_parameter\" | \"parameter\" | \"primary_constructor\"\n", + "new": " \"class_parameter\" | \"parameter\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-class-parameter-list-block-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " \"class_parameters\"\n | \"class_parameter\"\n", + "new": " \"class_parameter\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-function-parameter-list-block-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " | \"function_value_parameters\"\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-primary-constructor-block-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " | \"primary_constructor\"\n | \"modifiers\"\n", + "new": " | \"modifiers\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-modifier-list-block-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " | \"primary_constructor\"\n | \"modifiers\"\n", + "new": " | \"primary_constructor\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-local-docs-off", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " const SOURCE_LOCAL_DOCS: bool = true;", + "new": " const SOURCE_LOCAL_DOCS: bool = false;", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-modifier-list-block-binds-forward", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " | Kotlin::Setter\n | Kotlin::Modifiers\n", + "new": " | Kotlin::Setter\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-primary-constructor-block-binds-forward", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " Kotlin::PrimaryConstructor\n | Kotlin::Getter\n", + "new": " Kotlin::Getter\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-declaration-child-block-binds-forward", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " crate::roles::kotlin::doc_target::lists_kind(kind)\n", + "new": " false\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-forward-direction-inverted", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " !ancestors.parent(comment).is_some_and(|parent| {", + "new": " ancestors.parent(comment).is_some_and(|parent| {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it", + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc", + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-adjacent-blocks-join", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " ..DocBinding::new(KeptDocs::Last { joins: never_joins })", + "new": " ..DocBinding::new(KeptDocs::Last { joins: |a, b, c| !never_joins(a, b, c) })", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded" + ] + }, + { + "name": "first-block-before-the-declaration-wins", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " for (at, node) in before.iter().enumerate().rev() {", + "new": " for (at, node) in before.iter().enumerate() {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded" + ] + }, + { + "name": "superseded-block-is-unattached", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " MarkerSelection::Superseded\n } else {", + "new": " MarkerSelection::Unattached\n } else {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded" + ] + }, + { + "name": "unbound-candidates-are-retained-without-the-option", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " if selection != MarkerSelection::Selected && !request.retain_unbound {", + "new": " if selection != MarkerSelection::Selected && request.retain_unbound {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded" + ] + }, + { + "name": "kotlin-every-block-comment-is-kdoc", + "file": "big-code-analysis-ast/src/lang_helpers/doc_text.rs", + "old": " s.starts_with(b\"/**\") && s != b\"/**/\"", + "new": " s.starts_with(b\"/*\") && s != b\"/**/\"", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_plain_comments_are_no_documentation" + ] + }, + { + "name": "kotlin-line-comment-is-kdoc", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " DocComment { owns [BlockComment(text_gated_by opens_with_kdoc_marker no_chain)] }", + "new": " DocComment { owns [LineComment, BlockComment(text_gated_by opens_with_kdoc_marker no_chain)] }", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_plain_comments_are_no_documentation" + ] + }, + { + "name": "local-block-without-a-target-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " _ => draft.pending = true,", + "new": " _ => {}", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "pending-target-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " Projection::Pending | Projection::Unsupported => pending = true,", + "new": " Projection::Pending | Projection::Unsupported => {}", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "pending-node-is-not-assessed", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " Projection::Pending\n ) {\n let assessment = self.index.assessments.len();", + "new": " Projection::Pending\n ) && id == usize::MAX {\n let assessment = self.index.assessments.len();", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "kotlin-primary-constructor-keeps-its-owner-context", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": "matches!(kind, \"primary_constructor\" | \"getter\" | \"setter\")", + "new": "matches!(kind, \"getter\" | \"setter\")", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "modifier-list-keeps-its-owner-context", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " | \"property_promotion_parameter\"\n | \"modifiers\"\n", + "new": " | \"property_promotion_parameter\"\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + }, + { + "name": "function-parameter-list-keeps-its-owner-context", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " | \"function_value_parameters\"\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "class-parameter-list-keeps-its-owner-context", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " | \"class_parameters\"\n", + "new": "", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "block-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start = star + 1;", + "new": " line.content.start = star;", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings" + ] + }, + { + "name": "space-after-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "bytes[line.content.start] == b' ' {\n line.content.start += 1;", + "new": "bytes[line.content.start] == b' ' {\n line.content.start += 0;", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings" + ] + }, + { + "name": "empty-first-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while first < end && block.lines[first].content.is_empty() {", + "new": " while first > end && block.lines[first].content.is_empty() {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings" + ] + }, + { + "name": "empty-last-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while end > first && block.lines[end - 1].content.is_empty() {", + "new": " while end < first && block.lines[end - 1].content.is_empty() {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings" + ] + }, + { + "name": "crlf-inside-block-is-copied", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.ending.len() == 2 {", + "new": " if line.ending.len() == 3 {", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings" + ] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it", + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc", + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "last-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " last.content.end -= 1;\n", + "new": " last.content.end -= 0;\n", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it", + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc", + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments" + ] + }, + { + "name": "block-opener-two-bytes", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let prefix = if profile == Profile::GoDoc { 2 } else { 3 };", + "new": " let prefix = if profile == Profile::GoDoc { 2 } else { 2 };", + "expect": [ + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_top_level_declaration_documents_it", + "documentation::collector::kotlin_tests::kotlin_kdoc_before_a_member_documents_the_member_not_the_class", + "documentation::collector::kotlin_tests::kotlin_annotation_in_the_modifier_list_does_not_detach_the_kdoc", + "documentation::collector::kotlin_tests::kotlin_last_kdoc_before_a_declaration_wins_and_older_blocks_are_superseded", + "documentation::collector::kotlin_tests::kotlin_kdoc_text_over_several_lines", + "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings", + "documentation::collector::kotlin_tests::kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments", + "documentation::collector::kotlin_tests::kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments" + ] + } + ] +} From 235cf418df6ec03d1805719c84f7f4c38bcda28b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:54:16 -0800 Subject: [PATCH 097/221] test(loc): guard Kotlin documentation rows before owner and selection work --- src/metrics/loc/documentation_tests.rs | 163 ++++++++++++++++++ ...mentation-kotlin-unit1-legacy-perturb.json | 28 +++ 2 files changed, 191 insertions(+) create mode 100644 utils/documentation-kotlin-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index abba1b07c..8dd392645 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1594,3 +1594,166 @@ fn documentation_ruby_source_and_legacy_views_are_independent() { assert_ne!(renders_total, 0); assert_ne!(evidence_total, 0); } + +#[cfg(feature = "kotlin")] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_kotlin_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + struct Row<'a> { + name: &'static str, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + } + let fixture = documentation::source("primary.kt"); + let rows = [ + Row { + name: "l01_property", + source: b"class C {\n /** d */\n val p = 1\n}\n", + loc: [4, 3, 1, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l02_class_parameter", + source: b"class C(/**audit*/ val x: Int)\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l03_function_parameter", + source: b"fun f(/**p*/ x: Int) {}\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l04_modifier_list", + source: b"public /**audit*/ inline fun f() {}\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l05_before_constructor", + source: b"class C private /**audit*/ constructor()\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l06_before_body", + source: b"fun f() /**audit*/ {}\n", + loc: [1, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l07_split_annotation", + source: b"fun g() {}\n/** d */\n@Suppress(\"x\")\nfun f() {}\n", + loc: [4, 3, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l08_context_top_level", + source: b"/** d */\ncontext(Foo)\nfun f() {}\n", + loc: [3, 2, 1, 1, 0, 0], + dloc_rows: &[], + }, + Row { + name: "l09_older_and_newer", + source: b"/**old*/\n// plain\n/**new*/\nfun f() {}\n", + loc: [4, 1, 0, 3, 0, 1], + dloc_rows: &[2], + }, + Row { + name: "l10_before_accessor", + source: b"class C {\n val q: Int\n /** g */\n get() = 1\n}\n", + loc: [5, 4, 1, 1, 0, 1], + dloc_rows: &[2], + }, + Row { + name: "l11_after_annotation", + source: b"@Deprecated(\"x\")\n/** d */\nfun f() {}\n", + loc: [3, 2, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l12_fixture_primary_kt", + source: &fixture, + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + ]; + let (mut renders_total, mut evidence_total) = (0, 0); + for row in rows { + let name = row.name; + let parser = + crate::langs::AnyParser::parse(LANG::Kotlin, row.source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error(), "{name}"); + let idle = observations(); + let unbuilt = evidence_built::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let collected = observations(); + let built = evidence_built::observed(); + // expected: the collector enters every tree node once, named or not, root included. + assert_eq!( + collected.visits - idle.visits, + parser.root_node().preorder().count(), + "{name}" + ); + // expected: the collection renders each of its own published documents once. + let renders = collected.renders - idle.renders; + assert_eq!(renders, index.documents().len(), "{name}"); + // expected: default options build one member per selected document fragment. + let members = built - unbuilt; + assert_eq!( + members, + index + .documents() + .map(|document| document.get().fragment_count()) + .sum::(), + "{name}" + ); + renders_total += renders; + evidence_total += members; + + let space = analyze( + Source::new(LANG::Kotlin, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc(), + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + let analyzed = observations(); + // expected: analyze uses legacy LOC rows and builds no documentation index or evidence. + assert_eq!(analyzed.visits - collected.visits, 0, "{name}"); + assert_eq!(analyzed.renders - collected.renders, 0, "{name}"); + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + } + // The context row need not publish a document; the others control both positive deltas. + assert_ne!(renders_total, 0); + assert_ne!(evidence_total, 0); +} diff --git a/utils/documentation-kotlin-unit1-legacy-perturb.json b/utils/documentation-kotlin-unit1-legacy-perturb.json new file mode 100644 index 000000000..c4b215746 --- /dev/null +++ b/utils/documentation-kotlin-unit1-legacy-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_kotlin_source_and_legacy_views_are_independent"], + "cases": [ + { + "name": "kotlin-forward-direction-inverted", + "file": "big-code-analysis-ast/src/checker/kotlin.rs", + "old": " !ancestors.parent(comment).is_some_and(|parent| {", + "new": " ancestors.parent(comment).is_some_and(|parent| {", + "expect": ["metrics::loc::documentation_tests::documentation_kotlin_source_and_legacy_views_are_independent"] + }, + { + "name": "kotlin-function-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " FunctionDeclaration,\n", + "new": "", + "expect": ["metrics::loc::documentation_tests::documentation_kotlin_source_and_legacy_views_are_independent"] + }, + { + "name": "kotlin-property-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/kotlin.rs", + "old": " PropertyDeclaration,\n", + "new": "", + "expect": ["metrics::loc::documentation_tests::documentation_kotlin_source_and_legacy_views_are_independent"] + } + ] +} From 926397c387b88d83829e5ec8e58648a5840a4d9b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:07:29 -0800 Subject: [PATCH 098/221] test(documentation): pin Groovydoc owners, detachment and text in the source view --- .../src/documentation/collector.rs | 2 + .../documentation/collector/groovy_tests.rs | 812 ++++++++++++++++++ utils/documentation-groovy-unit1-perturb.json | 210 +++++ 3 files changed, 1024 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/groovy_tests.rs create mode 100644 utils/documentation-groovy-unit1-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 2f1bad07c..72d6e46d9 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1014,6 +1014,8 @@ mod form_tests; #[cfg(test)] mod go_tests; #[cfg(test)] +mod groovy_tests; +#[cfg(test)] mod lua_tests; #[cfg(test)] mod named_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs b/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs new file mode 100644 index 000000000..a0e346123 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs @@ -0,0 +1,812 @@ +//! Groovydoc source-view tests compare documents, associations, retained candidates and +//! pending assessments through both entry points. The grammar test collects nothing and +//! pins the tree shapes the source-view tests rely on. Node queries are not in the view. + +#[cfg(feature = "groovy")] +use crate::documentation::*; +#[cfg(feature = "groovy")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "groovy")] +use std::ops::Range; + +#[cfg(feature = "groovy")] +use Run::{Copied, Decoded}; + +#[cfg(feature = "groovy")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "groovy")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: String, + map: Vec<(Range, Run)>, +} + +#[cfg(feature = "groovy")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: (&'static str, Range), + document: Option, +} + +/// Documents, associations (with document positions and node owners), retained candidates +/// and order-independent pending assessments. Shared values are asserted by `published`; +/// node queries are not included. An empty view has nothing published or pending. +#[cfg(feature = "groovy")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + owners: Vec<(usize, Resolution, &'static str, Range)>, + evidence: Vec<(CandidateDisposition, Range)>, + pending: Vec, +} + +#[cfg(feature = "groovy")] +fn comment( + fragment: Range, + text: &str, + map: [(Range, Run); N], +) -> Doc { + Doc { + role: DocumentRole::Primary, + composition: Composition::Single, + fragments: vec![fragment], + text: text.to_owned(), + map: map.into(), + } +} + +#[cfg(feature = "groovy")] +fn owned(document: Doc, kind: &'static str, range: Range) -> View { + View { + documents: vec![document], + owners: vec![(0, Resolution::Resolved, kind, range)], + ..View::default() + } +} + +#[cfg(feature = "groovy")] +fn unordered(entries: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = entries.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +#[cfg(feature = "groovy")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "groovy")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "groovy")] +fn fragment_span(fragment: &Fragment<'_>) -> Range { + let range = span(fragment.source()); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + fragment.node().map(|node| site(node.node())), + Some(("groovydoc_comment", range.clone())) + ); + range +} + +#[cfg(feature = "groovy")] +fn run_of(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "groovy")] +fn published(index: &DocumentationIndex<'_>) -> View { + // bca: suppress(halstead) -- one reading of the four published lists and their shared rules. + let facts = index.facts(); + let ordered: Vec<_> = index.documents().collect(); + let position = |document| ordered.iter().position(|known| *known == document).unwrap(); + let documents = ordered + .iter() + .map(|&document| { + let complete = index.complete_text(document).unwrap().unwrap(); + Doc { + role: document.get().role(), + composition: document.get().composition(), + fragments: (0..document.get().fragment_count()) + .map(|at| fragment_span(facts.document_fragment(document, at).unwrap().get())) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|run| (run.output.range(), run_of(&run.origin))) + .collect(), + } + }) + .collect(); + let owners = index + .associations() + .map(|association| { + let attachment = association.get(); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(attachment.convention.name(), "Groovydoc"); + assert_eq!(attachment.publication, Publication::Unknown); + let document = facts.associated_document(association).unwrap(); + let first = facts.document_fragment(document, 0).unwrap(); + let comment = first.get().node().unwrap().node(); + assert_eq!(Some(attachment.lexical_scope.node()), comment.parent()); + let owner = facts.associated_owner(association, 0).unwrap(); + let Owner::Node(declared) = owner.get() else { + panic!("one node owner, found {:?}", owner.get()) + }; + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declared.node()) + ); + let (kind, range) = site(declared.node()); + (position(document), attachment.resolution, kind, range) + }) + .collect(); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect(); + let pending = unordered(index.assessments().map(|assessment| Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: site(assessment.get().node.unwrap().node()), + document: index.assessed_document(assessment).unwrap().map(position), + })); + assert_eq!(index.capability(), Capability::Partial); + // Qualifications belong to named-reference commands, which none of these cases has. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + owners, + evidence, + pending, + } +} + +#[cfg(feature = "groovy")] +fn clean(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Groovy, source.to_vec(), None, None).unwrap(); + assert!( + !parser.ts_tree().root_node().has_error(), + "{}", + source.escape_ascii() + ); + parser +} + +#[cfg(feature = "groovy")] +fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Groovy, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(feature = "groovy")] +fn agreed(indexes: &[DocumentationIndex<'_>; 2]) -> View { + let [typed, raw] = indexes.each_ref().map(published); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "groovy")] +fn view(source: &[u8]) -> View { + agreed(&indexes(&clean(source), DocumentationOptions::default())) +} + +#[cfg(feature = "groovy")] +fn retained(source: &[u8]) -> View { + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + agreed(&indexes(&clean(source), options)) +} + +#[cfg(feature = "groovy")] +fn node_at<'a>(parser: &'a AnyParser, kind: &str, range: Range) -> tree_sitter::Node<'a> { + let found: Vec<_> = parser + .root_node() + .preorder() + .map(|candidate| candidate.as_tree_sitter()) + .filter(|candidate| candidate.kind() == kind && candidate.byte_range() == range) + .collect(); + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +#[cfg(feature = "groovy")] +fn named_children(parent: tree_sitter::Node<'_>) -> Vec> { + parent.named_children(&mut parent.walk()).collect() +} + +#[cfg(feature = "groovy")] +fn shapes(nodes: &[tree_sitter::Node<'_>]) -> Vec<(&'static str, Range)> { + nodes.iter().map(|node| site(*node)).collect() +} + +#[cfg(feature = "groovy")] +fn parts(parent: tree_sitter::Node<'_>) -> Vec<(&'static str, Range)> { + parent.children(&mut parent.walk()).map(site).collect() +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_type_declarations_own_the_block_above_them() { + let types: [(&[u8], Doc, &str, Range); 7] = [ + ( + b"/** d */\nclass C {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 9..19, + ), + ( + b"/**audit*/\nclass C {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + "class_declaration", + 11..21, + ), + ( + b"/** d */\ntrait T {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "trait_declaration", + 9..19, + ), + ( + b"/** d */\ninterface I {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "interface_declaration", + 9..23, + ), + ( + b"/** d */\nenum E { A }\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "enum_declaration", + 9..21, + ), + ( + b"/** d */\nrecord R(int x) {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "record_declaration", + 9..27, + ), + ( + b"/** d */\n@interface A {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "annotation_type_declaration", + 9..24, + ), + ]; + for (source, document, kind, owner) in types { + assert_eq!( + view(source), + owned(document, kind, owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_method_constructor_and_enum_constant_own_the_block_above_them() { + let members: [(&[u8], Doc, &str, Range); 3] = [ + ( + b"class C {\n /** d */\n void m() {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "method_declaration", + 27..38, + ), + ( + b"class C {\n /** d */\n C() {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "constructor_declaration", + 27..33, + ), + ( + b"enum E {\n /** d */\n A\n}\n", + comment(13..21, "d", [(0..1, Copied(17..18))]), + "enum_constant", + 26..27, + ), + ]; + for (source, document, kind, owner) in members { + assert_eq!( + view(source), + owned(document, kind, owner), + "{}", + source.escape_ascii() + ); + } + assert_eq!( + view(b"enum E {\n /** a */\n A,\n /** b */\n B\n}\n"), + View { + documents: vec![ + comment(13..21, "a", [(0..1, Copied(17..18))]), + comment(33..41, "b", [(0..1, Copied(37..38))]), + ], + owners: vec![ + (0, Resolution::Resolved, "enum_constant", 26..27), + (1, Resolution::Resolved, "enum_constant", 46..47), + ], + ..View::default() + } + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_annotation_between_block_and_declaration_does_not_detach() { + let rows: [(&[u8], Doc, &str, Range); 3] = [ + ( + b"/**audit*/\n@Deprecated class C {}\n", + comment(0..10, "audit", [(0..5, Copied(3..8))]), + "class_declaration", + 11..33, + ), + ( + b"/** d */\n@Deprecated\nclass C {}\n", + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 9..31, + ), + ( + b"class C {\n /** d */\n @Deprecated\n void m() {}\n}\n", + comment(14..22, "d", [(0..1, Copied(18..19))]), + "method_declaration", + 27..54, + ), + ]; + for (source, document, kind, owner) in rows { + assert_eq!( + view(source), + owned(document, kind, owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_blank_row_between_block_and_declaration_does_not_detach() { + assert_eq!( + view(b"/** d */\n\nclass C {}\n"), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 10..20 + ) + ); + assert_eq!( + view(b"class C {\n /** d */\n\n void m() {}\n}\n"), + owned( + comment(14..22, "d", [(0..1, Copied(18..19))]), + "method_declaration", + 28..39 + ) + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_plain_comment_between_block_and_declaration_detaches() { + for source in [ + b"/** d */\n// plain\nclass C {}\n".as_slice(), + b"/** d */\n/* plain */\nclass C {}\n", + ] { + let mut expected = View::default(); + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + expected + .evidence + .push((CandidateDisposition::Unattached, 0..8)); + assert_eq!(retained(source), expected, "{}", source.escape_ascii()); + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_block_above_package_documents_the_first_declaration() { + assert_eq!( + view(b"/** d */\npackage p\nclass C {}\n"), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 19..29 + ) + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_script_level_method_owns_the_block_above_it() { + assert_eq!( + view(b"/** d */\ndef f() {}\n"), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "method_declaration", + 9..19 + ) + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_plain_comments_are_no_documentation() { + for source in [b"/* d */\nclass C {}\n".as_slice(), b"// d\nclass C {}\n"] { + assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); + assert_eq!( + retained(source), + View::default(), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_block_text_over_several_lines() { + let rows: [(&[u8], Doc, &str, Range); 5] = [ + ( + b"/**\n * a\n * b\n */\nclass C {}\n", + comment( + 0..17, + "a\nb", + [ + (0..1, Copied(7..8)), + (1..2, Copied(8..9)), + (2..3, Copied(12..13)), + ], + ), + "class_declaration", + 18..28, + ), + ( + b"/**\n * a \n * b\n */\nclass C {}\n", + comment( + 0..21, + "a \n b", + [ + (0..3, Copied(7..10)), + (3..4, Copied(10..11)), + (4..7, Copied(14..17)), + ], + ), + "class_declaration", + 22..32, + ), + ( + b"/**\n * Sum.\n *\n * @since 1\n */\nclass C {}\n", + comment( + 0..30, + "Sum.\n\n@since 1", + [ + (0..4, Copied(7..11)), + (4..5, Copied(11..12)), + (5..6, Copied(14..15)), + (6..14, Copied(18..26)), + ], + ), + "class_declaration", + 31..41, + ), + ( + b"/** a\n * b */\nclass C {}\n", + comment( + 0..13, + "a\nb", + [ + (0..1, Copied(4..5)), + (1..2, Copied(5..6)), + (2..3, Copied(9..10)), + ], + ), + "class_declaration", + 14..24, + ), + ( + b"class C {\n /**\n * a\n */\n void m() {}\n}\n", + comment(14..34, "a", [(0..1, Copied(25..26))]), + "method_declaration", + 39..50, + ), + ]; + for (source, document, kind, owner) in rows { + assert_eq!( + view(source), + owned(document, kind, owner), + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_block_with_crlf_line_endings() { + assert_eq!( + view(b"/** d */\r\nclass C {}\r\n"), + owned( + comment(0..8, "d", [(0..1, Copied(4..5))]), + "class_declaration", + 10..20 + ) + ); + assert_eq!( + view(b"/**\r\n * a\r\n * b\r\n */\r\nclass C {}\r\n"), + owned( + comment( + 0..20, + "a\nb", + [ + (0..1, Copied(8..9)), + (1..2, Decoded(9..11)), + (2..3, Copied(14..15)), + ], + ), + "class_declaration", + 22..32 + ) + ); +} + +/// Pins today's pending field form; this test is expected to move when fields gain owners. +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_keeps_a_document_without_an_owner() { + assert_eq!( + view(b"class C {\n/**audit*/\nint x\n}\n"), + View { + documents: vec![comment(10..20, "audit", [(0..5, Copied(13..18))])], + pending: unordered([ + Pending { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: ("field_declaration", 21..26), + document: Some(0), + }, + Pending { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: ("field_declaration", 21..26), + document: None, + }, + ]), + ..View::default() + } + ); +} + +#[cfg(feature = "groovy")] +#[test] +#[allow(clippy::too_many_lines)] +fn groovy_grammar_shapes_the_unit_relies_on() { + let source = b"class C {}\ntrait T {}\ninterface I {}\nenum E { A }\n\ + record R(int x) {}\n@interface A {}\n"; + let parser = clean(source); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("source_file", 0..85)); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + shapes(&named_children(root)), + [ + ("class_declaration", 0..10), + ("trait_declaration", 11..21), + ("interface_declaration", 22..36), + ("enum_declaration", 37..49), + ("record_declaration", 50..68), + ("annotation_type_declaration", 69..84), + ] + ); + let annotation = node_at(&parser, "annotation_type_declaration", 69..84); + let at = annotation.child(0).unwrap(); + assert_eq!(site(at), ("@", 69..70)); + assert!(!at.is_named()); + let body = node_at(&parser, "enum_declaration", 37..49) + .child_by_field_name("body") + .unwrap(); + assert_eq!(site(body), ("enum_body", 44..49)); + assert_eq!( + node_at(&parser, "enum_constant", 46..47).parent(), + Some(body) + ); + + let parser = + clean(b"class C {\n C() {}\n void m() {}\n int x\n def y\n int a, b\n}\n"); + let body = node_at(&parser, "class_declaration", 0..71) + .child_by_field_name("body") + .unwrap(); + assert_eq!(site(body), ("class_body", 8..71)); + assert_eq!( + shapes(&named_children(body)), + [ + ("constructor_declaration", 14..20), + ("method_declaration", 25..36), + ("field_declaration", 41..46), + ("field_declaration", 51..56), + ("field_declaration", 61..69), + ] + ); + let fields = [ + (41..46, 45..46, None), + (51..56, 55..56, None), + (61..69, 65..66, Some(68..69)), + ]; + for (field, first, second) in fields { + let declaration = node_at(&parser, "field_declaration", field); + let actual: Vec<_> = named_children(declaration) + .into_iter() + .filter(|node| node.kind() == "variable_declarator") + .map(|node| node.byte_range()) + .collect(); + assert_eq!( + actual, + std::iter::once(first).chain(second).collect::>() + ); + } + + let parser = clean(b"enum E {\n /** a */\n A,\n /** b */\n B\n}\n"); + let body = node_at(&parser, "enum_declaration", 0..49) + .child_by_field_name("body") + .unwrap(); + assert_eq!(site(body), ("enum_body", 7..49)); + assert_eq!( + parts(body), + [ + ("{", 7..8), + ("groovydoc_comment", 13..21), + ("enum_constant", 26..27), + (",", 27..28), + ("groovydoc_comment", 33..41), + ("enum_constant", 46..47), + ("}", 48..49), + ] + ); + let comma = node_at(&parser, "enum_constant", 26..27) + .next_sibling() + .unwrap(); + assert_eq!(site(comma), (",", 27..28)); + assert!(!comma.is_named()); + + let parser = clean( + b"/** d */\n@Deprecated\nclass C {\n /** e */\n @Deprecated\n void m() {}\n}\n", + ); + let comment = node_at(&parser, "groovydoc_comment", 0..8); + let class = comment.next_sibling().unwrap(); + assert_eq!(comment.parent(), Some(parser.ts_tree().root_node())); + assert_eq!(site(class), ("class_declaration", 9..77)); + assert_eq!(class.child(0).map(site), Some(("annotation", 9..20))); + let body = class.child_by_field_name("body").unwrap(); + assert_eq!(site(body), ("class_body", 29..77)); + let comment = node_at(&parser, "groovydoc_comment", 35..43); + let method = comment.next_sibling().unwrap(); + assert_eq!(comment.parent(), Some(body)); + assert_eq!(site(method), ("method_declaration", 48..75)); + assert_eq!(method.child(0).map(site), Some(("annotation", 48..59))); + + let parser = clean(b"/** d */\npackage p\nclass C {}\n"); + assert_eq!( + shapes(&named_children(parser.ts_tree().root_node())), + [ + ("groovydoc_comment", 0..8), + ("package_declaration", 9..18), + ("class_declaration", 19..29), + ] + ); + + let parser = clean(b"/** d */\n/* b */\n// l\nclass C {}\n"); + let children = named_children(parser.ts_tree().root_node()); + assert_eq!( + shapes(&children), + [ + ("groovydoc_comment", 0..8), + ("block_comment", 9..16), + ("line_comment", 17..21), + ("class_declaration", 22..32), + ] + ); + assert!(children[..3].iter().all(tree_sitter::Node::is_extra)); + let source = parser.code(); + assert_eq!(source[children[2].end_byte()], b'\n'); + + let parser = clean(b"/**a*/ class C { /**b*/ C() {} }\n"); + let comment = node_at(&parser, "groovydoc_comment", 0..6); + let class = comment.next_sibling().unwrap(); + assert_eq!(site(class), ("class_declaration", 7..32)); + assert_eq!(comment.end_position().row, class.start_position().row); + let body = class.child_by_field_name("body").unwrap(); + assert_eq!(site(body), ("class_body", 15..32)); + let comment = node_at(&parser, "groovydoc_comment", 17..23); + let ctor = comment.next_sibling().unwrap(); + assert_eq!(comment.parent(), Some(body)); + assert_eq!(site(ctor), ("constructor_declaration", 24..30)); + assert_eq!(comment.end_position().row, ctor.start_position().row); + + let parser = clean(b"/** d */\ndef f() {}\ndef x = 1\n"); + assert_eq!( + shapes(&named_children(parser.ts_tree().root_node())), + [ + ("groovydoc_comment", 0..8), + ("method_declaration", 9..19), + ("local_variable_declaration", 20..29), + ] + ); + + let parser = clean(b"/** d */\n\nclass C {}\n"); + let comment = node_at(&parser, "groovydoc_comment", 0..8); + assert_eq!( + comment.next_sibling().map(site), + Some(("class_declaration", 10..20)) + ); + + let parser = clean(b"/** a */\n// plain\nclass C {}\n/** b */\n/* plain */\nclass D {}\n"); + assert_eq!( + shapes(&named_children(parser.ts_tree().root_node())), + [ + ("groovydoc_comment", 0..8), + ("line_comment", 9..17), + ("class_declaration", 18..28), + ("groovydoc_comment", 29..37), + ("block_comment", 38..49), + ("class_declaration", 50..60), + ] + ); + + let source = b"/**\r\n * a\r\n * b\r\n */\r\nclass C {}\r\n"; + let parser = clean(source); + let root = parser.ts_tree().root_node(); + assert_eq!(site(root), ("source_file", 0..34)); + assert_eq!(root.end_byte(), source.len()); + assert_eq!( + shapes(&named_children(root)), + [("groovydoc_comment", 0..20), ("class_declaration", 22..32)] + ); + let comment = node_at(&parser, "groovydoc_comment", 0..20); + let class = comment.next_sibling().unwrap(); + assert_eq!(&source[comment.end_byte()..class.start_byte()], b"\r\n"); + assert_eq!(comment.end_position().row - comment.start_position().row, 3); + assert_eq!( + source[comment.byte_range()] + .windows(2) + .filter(|pair| *pair == b"\r\n") + .count(), + 3 + ); +} diff --git a/utils/documentation-groovy-unit1-perturb.json b/utils/documentation-groovy-unit1-perturb.json new file mode 100644 index 000000000..d3abefcff --- /dev/null +++ b/utils/documentation-groovy-unit1-perturb.json @@ -0,0 +1,210 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "groovy-class-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " ClassDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "groovy-trait-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " TraitDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them"] + }, + { + "name": "groovy-interface-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " InterfaceDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them"] + }, + { + "name": "groovy-enum-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " EnumDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them"] + }, + { + "name": "groovy-record-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " RecordDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them"] + }, + { + "name": "groovy-annotation-type-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " AnnotationTypeDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them"] + }, + { + "name": "groovy-method-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " MethodDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_script_level_method_owns_the_block_above_it", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines"] + }, + { + "name": "groovy-constructor-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " ConstructorDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them"] + }, + { + "name": "groovy-enum-constant-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " EnumConstant,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them"] + }, + { + "name": "groovy-field-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " FieldDeclaration,\n", + "new": "", + "expect": ["documentation::collector::groovy_tests::groovy_field_keeps_a_document_without_an_owner"] + }, + { + "name": "groovy-every-comment-is-groovydoc", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": "DocComment { owns [GroovydocComment(text_gated_by opens_with_groovydoc_marker no_chain)] }", + "new": "DocComment { owns [GroovydocComment(text_gated_by opens_with_groovydoc_marker no_chain), BlockComment, LineComment] }", + "expect": ["documentation::collector::groovy_tests::groovy_plain_comment_between_block_and_declaration_detaches", "documentation::collector::groovy_tests::groovy_plain_comments_are_no_documentation"] + }, + { + "name": "groovydoc-marker-needs-white-space", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": "crate::roles::byte_gate!(opens_with_groovydoc_marker, java_doc);", + "new": "fn opens_with_groovydoc_marker(node: &crate::Node<'_>, code: &[u8]) -> bool {\n let bytes = node_bytes(node, code);\n java_doc(bytes) && bytes.get(3).is_some_and(u8::is_ascii_whitespace)\n}", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_field_keeps_a_document_without_an_owner"] + }, + { + "name": "groovy-package-is-not-skipped", + "file": "big-code-analysis-ast/src/checker/groovy.rs", + "old": "skips: |node, _| node.kind_id() == Groovy::PackageDeclaration,", + "new": "skips: |node, _| node.kind_id() == Groovy::ImportDeclaration,", + "expect": ["documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration"] + }, + { + "name": "groovy-own-row-block-is-hidden", + "file": "big-code-analysis-ast/src/checker/groovy.rs", + "old": "next.start_row() == comment.end_row()", + "new": "next.start_row() != comment.end_row()", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration", "documentation::collector::groovy_tests::groovy_script_level_method_owns_the_block_above_it", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings", "documentation::collector::groovy_tests::groovy_field_keeps_a_document_without_an_owner"] + }, + { + "name": "groovy-blank-row-hides-the-block", + "file": "big-code-analysis-ast/src/checker/groovy.rs", + "old": "next.start_row() == comment.end_row()", + "new": "next.start_row() != comment.end_row() + 1", + "expect": ["documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach"] + }, + { + "name": "groovy-nearest-reads-past-a-plain-comment", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " return Ok(forward(member)?.then_some(*member));", + "new": " if forward(member)? {\n return Ok(Some(*member));\n }", + "expect": ["documentation::collector::groovy_tests::groovy_plain_comment_between_block_and_declaration_detaches"] + }, + { + "name": "groovy-field-is-not-pending", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": "Profile::Groovydoc => matches!(node.kind(), \"field_declaration\"),", + "new": "Profile::Groovydoc => matches!(node.kind(), \"constant_declaration\"),", + "expect": ["documentation::collector::groovy_tests::groovy_field_keeps_a_document_without_an_owner"] + }, + { + "name": "groovy-same-row-assessment-on-other-rows", + "file": "big-code-analysis-ast/src/documentation/forms.rs", + "old": " && next.start_row() == node.end_row()\n", + "new": " && next.start_row() != node.end_row()\n", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_plain_comment_between_block_and_declaration_detaches", "documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration", "documentation::collector::groovy_tests::groovy_script_level_method_owns_the_block_above_it", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings", "documentation::collector::groovy_tests::groovy_field_keeps_a_document_without_an_owner"] + }, + { + "name": "target-less-block-is-selected", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " MarkerSelection::Unattached\n };\n", + "new": " MarkerSelection::Selected\n };\n", + "expect": ["documentation::collector::groovy_tests::groovy_plain_comment_between_block_and_declaration_detaches"] + }, + { + "name": "detached-block-is-superseded", + "file": "big-code-analysis-ast/src/documentation/streaming/markers.rs", + "old": " && !self.kept.is_empty()\n", + "new": " && self.kept.is_empty()\n", + "expect": ["documentation::collector::groovy_tests::groovy_plain_comment_between_block_and_declaration_detaches"] + }, + { + "name": "block-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " line.content.start = star + 1;", + "new": " line.content.start = star;", + "expect": ["documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "space-after-star-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": "bytes[line.content.start] == b' ' {\n line.content.start += 1;", + "new": "bytes[line.content.start] == b' ' {\n line.content.start += 0;", + "expect": ["documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "block-indentation-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let star = line.content.start + indent;\n", + "new": " let star = line.content.start + indent.min(0);\n", + "expect": ["documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "empty-first-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while first < end && block.lines[first].content.is_empty() {", + "new": " while first > end && block.lines[first].content.is_empty() {", + "expect": ["documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "empty-last-line-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " while end > first && block.lines[end - 1].content.is_empty() {", + "new": " while end < first && block.lines[end - 1].content.is_empty() {", + "expect": ["documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "crlf-inside-block-is-copied", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " if line.ending.len() == 2 {", + "new": " if line.ending.len() == 3 {", + "expect": ["documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "first-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " lines[0].content.start += 1;\n", + "new": " lines[0].content.start += 0;\n", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration", "documentation::collector::groovy_tests::groovy_script_level_method_owns_the_block_above_it", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "last-line-space-kept", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " last.content.end -= 1;\n", + "new": " last.content.end -= 0;\n", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration", "documentation::collector::groovy_tests::groovy_script_level_method_owns_the_block_above_it", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] + }, + { + "name": "block-opener-is-two-bytes-wide", + "file": "big-code-analysis-ast/src/documentation/text/comments.rs", + "old": " let prefix = if profile == Profile::GoDoc { 2 } else { 3 };", + "new": " let prefix = if profile == Profile::GoDoc { 2 } else { 2 };", + "expect": ["documentation::collector::groovy_tests::groovy_type_declarations_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_method_constructor_and_enum_constant_own_the_block_above_them", "documentation::collector::groovy_tests::groovy_annotation_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_blank_row_between_block_and_declaration_does_not_detach", "documentation::collector::groovy_tests::groovy_block_above_package_documents_the_first_declaration", "documentation::collector::groovy_tests::groovy_script_level_method_owns_the_block_above_it", "documentation::collector::groovy_tests::groovy_block_text_over_several_lines", "documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings", "documentation::collector::groovy_tests::groovy_field_keeps_a_document_without_an_owner"] + } + ] +} From b51e5c638dda730330f536a730a7e21ef5faf650 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:07:38 -0800 Subject: [PATCH 099/221] test(loc): guard Groovy documentation rows before field and same-row work --- src/metrics/loc/documentation_tests.rs | 174 ++++++++++++++++++ ...mentation-groovy-unit1-legacy-perturb.json | 28 +++ 2 files changed, 202 insertions(+) create mode 100644 utils/documentation-groovy-unit1-legacy-perturb.json diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index abba1b07c..b22599261 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1594,3 +1594,177 @@ fn documentation_ruby_source_and_legacy_views_are_independent() { assert_ne!(renders_total, 0); assert_ne!(evidence_total, 0); } + +#[cfg(feature = "groovy")] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_groovy_source_and_legacy_views_are_independent() { + use big_code_analysis_ast::documentation::streaming::markers::evidence_built; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, observations, + }; + struct Row<'a> { + name: &'static str, + source: &'a [u8], + loc: [u64; 6], + dloc_rows: &'a [usize], + } + let primary = documentation::source("primary.groovy"); + let spaces = documentation::source("groovy-spaces.groovy"); + let rows = [ + Row { + name: "l01_field_own_row", + source: b"class C {\n /** d */\n int x\n}\n", + loc: [4, 3, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l02_field_two_declarators", + source: b"class C {\n /** d */\n int a, b\n}\n", + loc: [4, 3, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l03_property", + source: b"class C {\n /** d */\n def x\n}\n", + loc: [4, 3, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l04_same_row_class", + source: b"/**audit*/ class C {}\n", + loc: [1, 1, 0, 1, 0, 0], + dloc_rows: &[], + }, + Row { + name: "l05_same_row_method", + source: b"class C { /**audit*/ void f() {} }\n", + loc: [1, 1, 0, 1, 0, 0], + dloc_rows: &[], + }, + Row { + name: "l06_same_row_constructor", + source: b"class C { /**audit*/ C() {} }\n", + loc: [1, 1, 0, 1, 0, 0], + dloc_rows: &[], + }, + Row { + name: "l07_same_row_field", + source: b"class C { /**audit*/ int x }\n", + loc: [1, 1, 0, 1, 0, 0], + dloc_rows: &[], + }, + Row { + name: "l08_block_above_package", + source: b"/** d */\npackage p\nclass C {}\n", + loc: [3, 2, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l09_constructor_own_row", + source: b"class C {\n /** d */\n C() {}\n}\n", + loc: [4, 3, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l10_enum_constant", + source: b"enum E {\n /** d */\n A\n}\n", + loc: [4, 3, 0, 1, 0, 1], + dloc_rows: &[1], + }, + Row { + name: "l11_script_level_def", + source: b"/** d */\ndef f() {}\n", + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l12_fixture_primary", + source: &primary, + loc: [2, 1, 0, 1, 0, 1], + dloc_rows: &[0], + }, + Row { + name: "l13_fixture_groovy_spaces", + source: &spaces, + loc: [11, 6, 1, 5, 0, 5], + dloc_rows: &[0, 2, 4, 6, 8], + }, + ]; + let mut renders_total = 0; + for row in rows { + let name = row.name; + let parser = + crate::langs::AnyParser::parse(LANG::Groovy, row.source.to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + assert!(!root.has_error(), "{name}"); + let nodes = parser.root_node().preorder().count(); + let idle = observations(); + let unbuilt = evidence_built::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ) + .unwrap(); + let collected = observations(); + let built = evidence_built::observed(); + let visits = collected.visits - idle.visits; + // expected: the collector's walk enters each node exactly once, named or unnamed. + assert_eq!(visits, nodes, "{name}"); + assert_ne!(visits, 0, "{name}"); + let renders = collected.renders - idle.renders; + // expected: the collector renders text once for each published document. + assert_eq!(renders, index.documents().len(), "{name}"); + renders_total += renders; + let members = built - unbuilt; + // expected: the marker stream builds one member per document fragment and one for + // each retained candidate, which also moves the counter on same-row sources. + assert_eq!( + members, + index + .documents() + .map(|doc| doc.get().fragment_count()) + .sum::() + + index.evidence().len(), + "{name}" + ); + assert_ne!(members, 0, "{name}"); + + let space = analyze( + Source::new(LANG::Groovy, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = observations(); + // expected: legacy LOC does not build or render a source documentation index. + assert_eq!(evidence_built::observed() - built, 0, "{name}"); + assert_eq!(analyzed.renders - collected.renders, 0, "{name}"); + assert_eq!(analyzed.visits - collected.visits, 0, "{name}"); + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + } + // The other nine rows control the zero render delta of the four same-row forms. + assert_ne!(renders_total, 0); +} diff --git a/utils/documentation-groovy-unit1-legacy-perturb.json b/utils/documentation-groovy-unit1-legacy-perturb.json new file mode 100644 index 000000000..e7c77d1db --- /dev/null +++ b/utils/documentation-groovy-unit1-legacy-perturb.json @@ -0,0 +1,28 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_groovy_source_and_legacy_views_are_independent"], + "cases": [ + { + "name": "groovy-own-row-block-is-hidden", + "file": "big-code-analysis-ast/src/checker/groovy.rs", + "old": "next.start_row() == comment.end_row()", + "new": "next.start_row() != comment.end_row()", + "expect": ["metrics::loc::documentation_tests::documentation_groovy_source_and_legacy_views_are_independent"] + }, + { + "name": "groovy-package-is-not-skipped", + "file": "big-code-analysis-ast/src/checker/groovy.rs", + "old": "skips: |node, _| node.kind_id() == Groovy::PackageDeclaration,", + "new": "skips: |node, _| node.kind_id() == Groovy::ImportDeclaration,", + "expect": ["metrics::loc::documentation_tests::documentation_groovy_source_and_legacy_views_are_independent"] + }, + { + "name": "groovy-field-is-not-a-target", + "file": "big-code-analysis-ast/src/roles/groovy.rs", + "old": " FieldDeclaration,\n", + "new": "", + "expect": ["metrics::loc::documentation_tests::documentation_groovy_source_and_legacy_views_are_independent"] + } + ] +} From 7c956774ac0b7a22cb9d3e814cf21a35dd165025 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:35 -0800 Subject: [PATCH 100/221] test(documentation): pass the variant to both entry points and pin candidate order Pass the named variant to collection, make expected documents literal, and guard retained candidate ordering and render activity. No production code changed. --- .../src/documentation/collector/js_tests.rs | 190 ++++++++---------- src/metrics/loc/documentation_tests.rs | 4 + 2 files changed, 83 insertions(+), 111 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/js_tests.rs b/big-code-analysis-ast/src/documentation/collector/js_tests.rs index 6adb5cf41..a206285fd 100644 --- a/big-code-analysis-ast/src/documentation/collector/js_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/js_tests.rs @@ -261,12 +261,16 @@ fn clean(language: LANG, source: &[u8]) -> AnyParser { } #[cfg(any(feature = "javascript", feature = "mozjs"))] -fn indexes(parser: &AnyParser, options: DocumentationOptions) -> [DocumentationIndex<'_>; 2] { +fn indexes( + language: LANG, + parser: &AnyParser, + options: DocumentationOptions, +) -> [DocumentationIndex<'_>; 2] { let context = DocumentationContext::default(); [ parser.documentation(&context, &options).unwrap(), collect( - parser.language(), + language, parser.ts_tree(), parser.code(), &context, @@ -287,7 +291,7 @@ fn agreed(indexes: &[DocumentationIndex<'_>; 2], root: tree_sitter::Node<'_>) -> fn view(language: LANG, source: &[u8]) -> View { let parser = clean(language, source); agreed( - &indexes(&parser, DocumentationOptions::default()), + &indexes(language, &parser, DocumentationOptions::default()), parser.ts_tree().root_node(), ) } @@ -299,7 +303,10 @@ fn retained(language: LANG, source: &[u8]) -> View { retain_unbound: true, ..DocumentationOptions::default() }; - agreed(&indexes(&parser, options), parser.ts_tree().root_node()) + agreed( + &indexes(language, &parser, options), + parser.ts_tree().root_node(), + ) } #[cfg(any(feature = "javascript", feature = "mozjs"))] @@ -404,54 +411,43 @@ fn mozjs_leading_block_documents_the_declaration_after_it() { } #[cfg(any(feature = "javascript", feature = "mozjs"))] -#[allow(clippy::type_complexity)] fn class_and_object_members_own_their_leading_block(language: LANG) { - let rows: [(&[u8], Range, &str, Range, &str); 5] = [ + let rows: [(&[u8], Doc, &str, Range); 5] = [ ( b"class C {\n /** m */\n m() {}\n}\n", - 12..20, + comment(12..20, "m", [(0..1, Copied(16..17))]), "method_definition", 23..29, - "m", ), ( b"class C {\n /** x */\n x = 1;\n}\n", - 12..20, + comment(12..20, "x", [(0..1, Copied(16..17))]), "field_definition", 23..28, - "x", ), ( b"use({\n /** p */\n p: 1,\n});\n", - 8..16, + comment(8..16, "p", [(0..1, Copied(12..13))]), "pair", 19..23, - "p", ), ( b"use({\n /** q */\n q,\n});\n", - 8..16, + comment(8..16, "q", [(0..1, Copied(12..13))]), "shorthand_property_identifier", 19..20, - "q", ), ( b"use({\n /** m */\n m() {},\n});\n", - 8..16, + comment(8..16, "m", [(0..1, Copied(12..13))]), "method_definition", 19..25, - "m", ), ]; - for (source, fragment, kind, owner, text) in rows { - let offset = fragment.start + 4; + for (source, document, kind, range) in rows { assert_eq!( view(language, source), - node_owner( - comment(fragment, text, [(0..1, Copied(offset..offset + 1))]), - kind, - owner - ), + node_owner(document, kind, range), "{}", source.escape_ascii() ); @@ -470,99 +466,71 @@ fn mozjs_class_and_object_members_own_their_leading_block() { } #[cfg(any(feature = "javascript", feature = "mozjs"))] -#[allow(clippy::type_complexity)] fn exported_declaration_owns_the_block_and_the_export_is_the_binding(language: LANG) { - let rows: [( - &[u8], - Range, - Range, - Range, - &str, - Range, - &str, - ); 5] = [ + let exported = [ ( - b"/**audit*/\nexport function f() {}\n", - 0..10, - 3..8, + &b"/**audit*/\nexport function f() {}\n"[..], + comment(0..10, "audit", [(0..5, Copied(3..8))]), 11..33, "function_declaration", 18..33, - "audit", ), ( - b"/** d */\nexport function* g() {}\n", - 0..8, - 4..5, + &b"/** d */\nexport function* g() {}\n"[..], + comment(0..8, "d", [(0..1, Copied(4..5))]), 9..32, "generator_function_declaration", 16..32, - "d", ), ( - b"/** d */\nexport class C {}\n", - 0..8, - 4..5, + &b"/** d */\nexport class C {}\n"[..], + comment(0..8, "d", [(0..1, Copied(4..5))]), 9..26, "class_declaration", 16..26, - "d", ), ( - b"/** d */\nexport default function f() {}\n", - 0..8, - 4..5, + &b"/** d */\nexport default function f() {}\n"[..], + comment(0..8, "d", [(0..1, Copied(4..5))]), 9..39, "function_declaration", 24..39, - "d", - ), - ( - b"export class C {\n /** m */\n m() {}\n}\n", - 19..27, - 23..24, - 0..38, - "method_definition", - 30..36, - "m", ), ]; - for (source, fragment, copied, export, kind, owner, text) in rows { + for (source, document, export, kind, owner) in exported { let parser = clean(language, source); - let both = indexes(&parser, DocumentationOptions::default()); + let both = indexes(language, &parser, DocumentationOptions::default()); assert_eq!( agreed(&both, parser.ts_tree().root_node()), - node_owner( - comment( - fragment.clone(), - text, - [(0..copied.len(), Copied(copied.clone()))] - ), - kind, - owner.clone() - ), + node_owner(document, kind, owner.clone()), "{}", source.escape_ascii() ); - if fragment.start == 0 { - let wrapper = node_at(&parser, "export_statement", export); - for index in &both { - let projection = index.node_projection(wrapper).unwrap(); - assert!(!projection.pending()); - let owners: Vec<_> = projection.owners().collect(); - let [found] = owners[..] else { - panic!("one projected owner, found {owners:?}") - }; - let Owner::Node(declared) = found.get() else { - panic!("node owner: {found:?}") - }; - assert_eq!(site(declared.node()), (kind, owner.clone())); - let query = index.node_associations(wrapper).unwrap(); - assert_eq!(query.associations().len(), 1); - assert!(!query.projection_pending()); - } + let wrapper = node_at(&parser, "export_statement", export); + for index in &both { + let projection = index.node_projection(wrapper).unwrap(); + assert!(!projection.pending()); + let owners: Vec<_> = projection.owners().collect(); + let [found] = owners[..] else { + panic!("one projected owner, found {owners:?}") + }; + let Owner::Node(declared) = found.get() else { + panic!("node owner: {found:?}") + }; + assert_eq!(site(declared.node()), (kind, owner.clone())); + let query = index.node_associations(wrapper).unwrap(); + assert_eq!(query.associations().len(), 1); + assert!(!query.projection_pending()); } } + assert_eq!( + view(language, b"export class C {\n /** m */\n m() {}\n}\n"), + node_owner( + comment(19..27, "m", [(0..1, Copied(23..24))]), + "method_definition", + 30..36 + ) + ); } #[cfg(feature = "javascript")] @@ -597,6 +565,18 @@ fn nearest_block_comment_before_a_declaration_decides(language: LANG) { .evidence .push((CandidateDisposition::Superseded, 16..24)); assert_eq!(retained(language, superseded), expected); + let three = b"function z() {}\n/**a*/\n/**b*/\n/**c*/\nfunction f() {}\n"; + let mut expected = node_owner( + comment(30..36, "c", [(0..1, Copied(33..34))]), + "function_declaration", + 37..52, + ); + assert_eq!(view(language, three), expected); + expected.evidence.extend([ + (CandidateDisposition::Superseded, 16..22), + (CandidateDisposition::Superseded, 23..29), + ]); + assert_eq!(retained(language, three), expected); let detached = b"function z() {}\n/** d */\n/* plain */\nfunction f() {}\n"; let mut expected = View::default(); assert_eq!(view(language, detached), expected); @@ -618,52 +598,38 @@ fn mozjs_nearest_block_comment_before_a_declaration_decides() { } #[cfg(any(feature = "javascript", feature = "mozjs"))] -#[allow(clippy::type_complexity)] fn file_tag_documents_the_file(language: LANG) { - let rows: [(&[u8], Range, &str, Range, Range); 5] = [ + let rows: [(&[u8], Doc, Range); 5] = [ ( b"/**@file audit*/\nfunction f() {}\n", - 0..16, - "@file audit", - 3..14, + comment(0..16, "@file audit", [(0..11, Copied(3..14))]), 0..33, ), ( b"/** @fileoverview audit */\nfunction f() {}\n", - 0..26, - "@fileoverview audit", - 4..23, + comment(0..26, "@fileoverview audit", [(0..19, Copied(4..23))]), 0..43, ), ( b"/** @overview audit */\nfunction f() {}\n", - 0..22, - "@overview audit", - 4..19, + comment(0..22, "@overview audit", [(0..15, Copied(4..19))]), 0..39, ), ( b"/** @module m */\nfunction f() {}\n", - 0..16, - "@module m", - 4..13, + comment(0..16, "@module m", [(0..9, Copied(4..13))]), 0..33, ), ( b"/** @file audit */\n\"use strict\";\n", - 0..18, - "@file audit", - 4..15, + comment(0..18, "@file audit", [(0..11, Copied(4..15))]), 0..33, ), ]; - for (source, fragment, text, copied, root) in rows { + for (source, document, root) in rows { assert_eq!( view(language, source), - owned( - file(comment(fragment, text, [(0..text.len(), Copied(copied))])), - Holder::File(root) - ), + owned(file(document), Holder::File(root)), "{}", source.escape_ascii() ); @@ -904,6 +870,7 @@ fn mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf() { // The ownerless documents and pending assessments are today's outcome, not the later design. #[cfg(any(feature = "javascript", feature = "mozjs"))] fn declarations_awaiting_an_owner_keep_their_pending_outcome(language: LANG) { + // bca: suppress(halstead) -- the body of one test, run for both variants. let ordinary: [(&[u8], &str, Range); 4] = [ ( b"/**audit*/\nconst f = () => 1;\n", @@ -924,7 +891,7 @@ fn declarations_awaiting_an_owner_keep_their_pending_outcome(language: LANG) { ]; for (source, kind, range) in ordinary { let parser = clean(language, source); - let both = indexes(&parser, DocumentationOptions::default()); + let both = indexes(language, &parser, DocumentationOptions::default()); assert_eq!( agreed(&both, parser.ts_tree().root_node()), View { @@ -942,7 +909,7 @@ fn declarations_awaiting_an_owner_keep_their_pending_outcome(language: LANG) { } let source = b"/**audit*/\nexport const e = 3;\n"; let parser = clean(language, source); - let both = indexes(&parser, DocumentationOptions::default()); + let both = indexes(language, &parser, DocumentationOptions::default()); assert_eq!( agreed(&both, parser.ts_tree().root_node()), View { @@ -967,7 +934,7 @@ fn declarations_awaiting_an_owner_keep_their_pending_outcome(language: LANG) { ]; for (source, range) in anonymous { let parser = clean(language, source); - let both = indexes(&parser, DocumentationOptions::default()); + let both = indexes(language, &parser, DocumentationOptions::default()); assert_eq!( agreed(&both, parser.ts_tree().root_node()), View { @@ -1006,6 +973,7 @@ fn mozjs_declarations_awaiting_an_owner_keep_their_pending_outcome() { #[cfg(any(feature = "javascript", feature = "mozjs"))] #[allow(clippy::too_many_lines)] fn grammar_shapes_the_unit_relies_on(language: LANG) { + // bca: suppress(abc, halstead) -- the body of the grammar test, run for both variants. let source = b"function f() {}\nfunction* g() {}\nclass C {}\n"; let parser = clean(language, source); let root = parser.ts_tree().root_node(); diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index aa2e57df1..7adc2c5ee 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1489,6 +1489,7 @@ fn documentation_js_source_and_legacy_views_are_independent() { }, ]; let mut ran = 0; + let mut rendered = 0; for row in rows { for &lang in row.variants { if !lang.is_enabled() { @@ -1532,6 +1533,7 @@ fn documentation_js_source_and_legacy_views_are_independent() { ); assert_ne!(visits, 0, "{name}"); assert_ne!(members, 0, "{name}"); + rendered += renders; let space = analyze( Source::new(lang, row.source), MetricsOptions::default().with_only(&[Metric::Loc]), @@ -1565,4 +1567,6 @@ fn documentation_js_source_and_legacy_views_are_independent() { } } assert!(ran > 0); + // A row without a document renders nothing, so the control for `renders` is the total. + assert_ne!(rendered, 0); } From ee18916929e3e555165056890fab087ea37ed716 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:25:48 -0800 Subject: [PATCH 101/221] test(documentation): close gaps in the Java field-owner tests Pin collection-budget charges in the declarator scan and bound the slot-loop checkpoint count. Assert additional field and constant query, recovery, and documentation outcomes. Check that collection counters move while legacy LOC rows remain unchanged, with perturbations for both AST and root-crate behavior. No production code changed. --- .../src/documentation/collector/java_tests.rs | 73 ++++++++++++++++++- src/metrics/loc/documentation_tests.rs | 53 +++++++++++++- ...cumentation-java-unit1-legacy-perturb.json | 35 +++++++++ utils/documentation-java-unit1-perturb.json | 35 +++++++++ 4 files changed, 193 insertions(+), 3 deletions(-) create mode 100644 utils/documentation-java-unit1-legacy-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector/java_tests.rs b/big-code-analysis-ast/src/documentation/collector/java_tests.rs index e0db79e03..cae17f6db 100644 --- a/big-code-analysis-ast/src/documentation/collector/java_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/java_tests.rs @@ -39,6 +39,14 @@ fn owner_text<'s>(index: &DocumentationIndex<'s>, owner: FactRef<'_, Owner<'s>>) .map(|piece| format!("{}..{}", piece.range().start, piece.range().end)) .collect(); assert!(!slot.source.has_excluded_gap()); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .qualifications() + .len(), + 0 + ); format!( "Slot({:?} #{} {} in {})", slot.role, @@ -59,6 +67,7 @@ fn documents(index: &DocumentationIndex<'_>) -> Vec { index .documents() .map(|document| { + assert_eq!(document.get().composition(), Composition::Single); let fragments = (0..document.get().fragment_count()) .map(|position| { let fragment = index.facts().document_fragment(document, position).unwrap(); @@ -185,6 +194,8 @@ fn both( ) .unwrap(), ] { + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); check(parser.ts_tree().root_node(), &index); } } @@ -673,13 +684,22 @@ fn java_field_queries_answer_per_slot_and_per_declaration() { let declaration = index.owner_associations(enclosing).unwrap(); assert_eq!(declaration.associations().len(), 0); assert_eq!(declaration.assessments().count(), 0); - for (kind, range) in [("variable_declarator", 25..26), ("identifier", 25..26)] { + for (kind, range) in [ + ("integral_type", 21..24), + ("variable_declarator", 25..26), + ("identifier", 25..26), + (";", 26..27), + ] { assert!(matches!( index.node_associations(node(root, kind, range.clone())), Err(OwnerError::UnsupportedOwner) )); assert!(matches!( - index.node_projection(node(root, kind, range)), + index.node_projection(node(root, kind, range.clone())), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_owners(node(root, kind, range)), Err(OwnerError::UnsupportedOwner) )); } @@ -1051,6 +1071,18 @@ fn java_field_with_a_syntax_error_stays_pending() { // expected: the file only. assert_eq!(index.facts().owners().len(), 1); }); + // The same guard keeps a constant pending: `=` without a value is an `ERROR` child. + let source = "interface I { /**audit*/ int K = ; }"; + both(source, DocumentationOptions::default(), |root, index| { + let constant = node(root, "constant_declaration", 25..34); + assert!(constant.has_error()); + assert_eq!(node(root, "ERROR", 31..32).parent().unwrap(), constant); + assert_eq!(documents(index), [(vec![14..24], Some("audit".to_owned()))]); + assert_eq!(associations(index), []); + assert!(index.node_projection(constant).unwrap().pending()); + // expected: the file only; the interface holds the error too. + assert_eq!(index.facts().owners().len(), 1); + }); } #[cfg(feature = "java")] @@ -1409,54 +1441,63 @@ fn java_declarator_scan_charges_one_step_per_child() { ( "class C { /**audit*/ int x; }", "field_declaration", + // expected: type, declarator, `;`. 3, Some(vec![25..26]), ), ( "class C { /**audit*/ int a, b; }", "field_declaration", + // expected: type, declarator, `,`, declarator, `;`. 5, Some(vec![25..26, 28..29]), ), ( "class C { /**audit*/ int a = 1, b[] = {2}, c; }", "field_declaration", + // expected: type, three declarators with two `,`, `;`. 7, Some(vec![25..26, 32..33, 43..44]), ), ( "class C {\n /** a */\n int x,\n /** b */\n y;\n}\n", "field_declaration", + // expected: type, declarator, `,`, comment, declarator, `;`. 6, Some(vec![27..28, 43..44]), ), ( "class C { /**audit*/ @Deprecated int x; }", "field_declaration", + // expected: modifiers, type, declarator, `;`. 4, Some(vec![37..38]), ), ( "interface I { /**audit*/ int K = 1; }", "constant_declaration", + // expected: type, declarator, `;`. 3, Some(vec![29..30]), ), ( "class C { /**audit*/ int a, _; }", "field_declaration", + // expected: type, declarator, `,`, and the unnamed declarator that ends the scan. 4, None, ), ( "class C { /**audit*/ int _, a; }", "field_declaration", + // expected: type and the unnamed declarator that ends the scan. 2, None, ), ( wide_source.as_str(), "field_declaration", + // expected: type, 300 declarators, 299 `,`, `;`. 601, None::>>, ), @@ -1533,21 +1574,34 @@ fn java_field_width_costs_linear_work() { let before = observations(); let index = parser.documentation(&context, &options).unwrap(); let after = observations(); + // expected: 12 nodes beside the declarators (`program`, `class_declaration`, + // `class`, `identifier`, `class_body`, `{`, `block_comment`, `field_declaration`, + // `integral_type`, `int`, `;`, `}`), a declarator and its name per field, and + // one comma less than fields. assert_eq!(parser.root_node().preorder().count(), 3 * width + 11); + // expected: one visit and one child batch per node. assert_eq!(after.visits - before.visits, 3 * width + 11); assert_eq!(after.child_batches - before.child_batches, 3 * width + 11); + // expected: every node but the root, which returns first. assert_eq!( after.target_classifications - before.target_classifications, 3 * width + 10 ); + // expected: the file, the class and the declaration; a slot is pushed without + // an owner projection. assert_eq!(after.owner_projections - before.owner_projections, 3); + // expected: one search for the comment fragment and one per slot; each is one + // comparison with one included range. assert_eq!( after.intersection_searches - before.intersection_searches, width + 1 ); + // expected: the profile requests no field name, and nothing looks one up. assert_eq!(after.field_requests - before.field_requests, 0); assert_eq!(after.field_lookups - before.field_lookups, 0); + // expected: one document. assert_eq!(after.renders - before.renders, 1); + // expected: file, class, declaration and one slot per field. assert_eq!(index.facts().owners().len(), width + 3); assert_eq!(index.documents().len(), 1); assert_eq!(index.associations().len(), 1); @@ -1581,6 +1635,7 @@ fn java_field_width_collection_observes_cancellation_in_the_slot_loop() { parser.documentation(&context, &options).unwrap(); let polls = observations().polls - before.polls; let mut inside = 0; + let mut scanning = 0; for checkpoint in 1..=polls { let before = observations(); let result = crate::documentation::budget::cancel_after(checkpoint, || { @@ -1596,10 +1651,24 @@ fn java_field_width_collection_observes_cancellation_in_the_slot_loop() { if owners == 3 && searches < width + 1 { inside += 1; } + // Every node but the closing brace of the class body is entered and the + // declaration has no owner yet: the walk is between the declaration's last + // child and its slots, where only the declarator scan is long. + if owners == 2 && after.visits - before.visits == 3 * width + 10 { + scanning += 1; + } } // expected: 6 checkpoints fall in the 6144 step charges of the slot loop // (3 per slot, one checkpoint per 1024); the last may follow the last search. assert!(inside >= 5, "{inside}"); + // expected: no more than those 6; a loop that charges more steps for a later + // slot holds more. + assert!(inside <= 6, "{inside}"); + // expected: the scan charges one step for each of the 4097 children of the + // declaration (the type, 2048 declarators, 2047 commas and `;`), which hold 4 + // checkpoints, or 5 with the few steps before it. Without those charges fewer + // than 1024 steps lie there, which hold at most one. + assert!((4..=5).contains(&scanning), "{scanning}"); let index = crate::documentation::budget::cancel_after(polls + 1, || { parser.documentation(&context, &options) }) diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index abf1dfc1c..724002628 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1207,54 +1207,79 @@ fn documentation_lua_source_and_legacy_views_are_independent() { #[cfg(feature = "java")] #[test] +#[allow(clippy::too_many_lines)] fn documentation_java_field_owners_leave_legacy_rows_unchanged() { use big_code_analysis_ast::documentation::streaming::markers::evidence_built; use big_code_analysis_ast::{AnyParser, documentation::*}; - for (source, documents, owners, loc) in [ + for (source, documents, owners, projections, loc, rows) in [ ( "class C { /**audit*/ int x; }\n", 1, vec![1], + // expected: file, class, field declaration. + 3, [1, 1, 0, 1, 0, 1], + vec![0], ), ( "class C { /**audit*/ int a, b; }\n", 1, vec![2], + // expected: file, class, field declaration. + 3, [1, 1, 0, 1, 0, 1], + vec![0], ), ( "interface I { /**audit*/ int K = 1; }\n", 1, vec![1], + // expected: file, interface, constant declaration. + 3, [1, 1, 0, 1, 0, 1], + vec![0], ), ( "enum E { /**a*/ A, /**b*/ B; /**f*/ int x; }\n", 3, vec![1, 1, 1], + // expected: file, enum, two constants, field declaration. + 5, [1, 1, 0, 1, 0, 1], + vec![0], ), ( "class C {\n /** a */\n int x,\n /** b */\n y;\n}\n", 1, vec![2], + // expected: file, class, field declaration. + 3, [6, 4, 0, 2, 0, 1], + vec![1], ), ( "class C {\n/** d */\nint x\n/** e */\nint y;\n}\n", 1, vec![], + // expected: file and the second field declaration; the class and the first + // field hold the syntax error and stay pending. + 2, [6, 5, 0, 2, 0, 1], + vec![1], ), ( "class C {\n int x;\n /**d*/\n ;\n void f() {}\n}\n", 0, vec![], + // expected: file, class, field declaration, method. + 4, [6, 5, 0, 1, 0, 0], + vec![], ), ] { let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let idle = observations(); + let unbuilt = evidence_built::observed(); let index = parser .documentation( &DocumentationContext::default(), @@ -1272,6 +1297,25 @@ fn documentation_java_field_owners_leave_legacy_rows_unchanged() { ); let before = observations(); let built = evidence_built::observed(); + // The collection moves each counter on this thread, so a zero across `analyze` + // is a reading. The last row has no document; the other six move the render + // and evidence counters. + // expected: the walk enters every node once. + assert_eq!( + before.visits - idle.visits, + parser.root_node().preorder().count(), + "{source}" + ); + // expected: one render and one built member per document; each has one fragment. + assert_eq!(before.renders - idle.renders, documents, "{source}"); + assert_eq!(built - unbuilt, documents, "{source}"); + assert_eq!( + before.owner_projections - idle.owner_projections, + projections, + "{source}" + ); + // The checkpoint total has no closed form. + assert_ne!(before.polls - idle.polls, 0, "{source}"); let space = analyze( Source::new(LANG::Java, source.as_bytes()), MetricsOptions::default().with_only(&[Metric::Loc]), @@ -1290,6 +1334,13 @@ fn documentation_java_field_owners_leave_legacy_rows_unchanged() { loc, "{source}" ); + assert_eq!( + (0..source.len()) + .filter(|row| stats.dloc.lines.contains(*row)) + .collect::>(), + rows, + "{source}" + ); let after = observations(); assert_eq!(evidence_built::observed() - built, 0, "{source}"); assert_eq!(after.renders - before.renders, 0, "{source}"); diff --git a/utils/documentation-java-unit1-legacy-perturb.json b/utils/documentation-java-unit1-legacy-perturb.json new file mode 100644 index 000000000..7f3542a88 --- /dev/null +++ b/utils/documentation-java-unit1-legacy-perturb.json @@ -0,0 +1,35 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_java_field_owners_leave_legacy_rows_unchanged"], + "cases": [ + { + "name": "java-field-projection-disabled", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "new": " if false\n && self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "expect": ["metrics::loc::documentation_tests::documentation_java_field_owners_leave_legacy_rows_unchanged"] + }, + { + "name": "bound-comment-bills-no-documentation-row", + "file": "src/metrics/loc/shared.rs", + "old": " LegacyEvent::BoundComment(member) => {\n stats\n .dloc\n .lines\n .insert_range(member.start_row(), member.end_row());\n }", + "new": " LegacyEvent::BoundComment(member) => {\n let _ = member;\n }", + "expect": ["metrics::loc::documentation_tests::documentation_java_field_owners_leave_legacy_rows_unchanged"] + }, + { + "name": "bound-documentation-row-moves-to-the-next-comment", + "file": "src/metrics/loc/shared.rs", + "old": " LegacyEvent::BoundComment(member) => {\n stats\n .dloc\n .lines\n .insert_range(member.start_row(), member.end_row());\n }", + "new": " LegacyEvent::BoundComment(member) => {\n let shift = if member.start_row() == 1 { 2 } else { 0 };\n stats\n .dloc\n .lines\n .insert_range(member.start_row() + shift, member.end_row() + shift);\n }", + "expect": ["metrics::loc::documentation_tests::documentation_java_field_owners_leave_legacy_rows_unchanged"] + }, + { + "name": "observation-counters-do-not-count", + "file": "big-code-analysis-ast/src/observation.rs", + "old": " COUNT.with(|count| count.set(count.get() + 1));", + "new": " COUNT.with(|count| count.set(count.get()));", + "expect": ["metrics::loc::documentation_tests::documentation_java_field_owners_leave_legacy_rows_unchanged"] + } + ] +} diff --git a/utils/documentation-java-unit1-perturb.json b/utils/documentation-java-unit1-perturb.json index 026d2c3f6..02d2ddbb2 100644 --- a/utils/documentation-java-unit1-perturb.json +++ b/utils/documentation-java-unit1-perturb.json @@ -156,6 +156,41 @@ "old": " if prelex {\n draft.unresolved = Some(UnresolvedReason::GrammarBoundary);\n }", "new": " if prelex {\n draft.unresolved = None;\n }", "expect": ["documentation::collector::java_tests::java_field_comment_with_a_raw_unicode_escape_lists_its_slot_unresolved", "documentation::collector::java_tests::java_pending_field_comment_with_a_raw_unicode_escape_keeps_an_ownerless_association"] + }, + { + "name": "java-declarator-scan-ignores-the-collection-budget", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let Some(names) = java_declarator_names(&self.index.canonical, id, budget)? else {", + "new": " let Some(names) = crate::documentation::budget::infallible(java_declarator_names(\n &self.index.canonical,\n id,\n &crate::documentation::budget::NoBudget,\n )) else {", + "expect": ["documentation::collector::java_tests::java_field_width_collection_observes_cancellation_in_the_slot_loop"] + }, + { + "name": "java-enum-body-fields-are-not-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "new": " if self.index.profile == Profile::Javadoc\n && node\n .parent()\n .is_none_or(|parent| parent.kind() != \"enum_body_declarations\")\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "expect": ["documentation::collector::java_tests::java_enum_constants_and_enum_field_have_their_own_owners"] + }, + { + "name": "java-anonymous-class-fields-are-not-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::Javadoc\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "new": " if self.index.profile == Profile::Javadoc\n && node\n .parent()\n .and_then(|body| body.parent())\n .is_none_or(|outer| outer.kind() != \"object_creation_expression\")\n && matches!(node.kind(), \"field_declaration\" | \"constant_declaration\")", + "expect": ["documentation::collector::java_tests::java_fields_of_records_anonymous_and_local_classes_own_field_slots"] + }, + { + "name": "java-comment-child-keeps-the-declaration-pending", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if declarator.evidence.node().kind() != \"variable_declarator\" {\n continue;\n }", + "new": " if declarator.evidence.node().kind() == \"block_comment\" {\n return Ok(None);\n }\n if declarator.evidence.node().kind() != \"variable_declarator\" {\n continue;\n }", + "expect": ["documentation::collector::java_tests::java_second_comment_inside_a_field_declaration_is_not_documentation", "documentation::collector::java_tests::java_comment_inside_a_field_declaration_does_not_document_it", "documentation::collector::java_tests::java_declarator_scan_charges_one_step_per_child"] + }, + { + "name": "java-constant-with-an-error-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if node.has_error()\n || node.is_missing()\n || !self", + "new": " if (node.has_error() && node.kind() != \"constant_declaration\")\n || node.is_missing()\n || !self", + "expect": ["documentation::collector::java_tests::java_field_with_a_syntax_error_stays_pending"] } ] } From bf10a95a2562f1fd5e9e7291f861ebbfc4e99a2c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:32:10 -0800 Subject: [PATCH 102/221] test(documentation): tighten the TypeScript grammar checks and pin candidate order Check the complete export child list, derive the CRLF slice from the tree, and pin the order of two retained candidates. Borrow expected views, identify the variant on failure, and annotate cohesive test helpers; no production code changed. --- .../src/documentation/collector/ts_tests.rs | 86 ++++++++++++------- src/metrics/loc/documentation_tests.rs | 2 +- 2 files changed, 54 insertions(+), 34 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/ts_tests.rs b/big-code-analysis-ast/src/documentation/collector/ts_tests.rs index 5908b825b..1bb7d5868 100644 --- a/big-code-analysis-ast/src/documentation/collector/ts_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/ts_tests.rs @@ -205,6 +205,7 @@ fn run_of(origin: &Origin<'_>) -> Run { #[cfg(feature = "typescript")] fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + // bca: suppress(halstead) -- one reading of the four published lists and the rules they share. let facts = index.facts(); let ordered: Vec<_> = index.documents().collect(); let position = |document| ordered.iter().position(|known| *known == document).unwrap(); @@ -333,10 +334,9 @@ fn view(language: LANG, source: &[u8], retain_unbound: bool) -> View { } #[cfg(feature = "typescript")] -#[allow(clippy::needless_pass_by_value)] -fn check(language: LANG, source: &[u8], expected: View) { +fn check(language: LANG, source: &[u8], expected: &View) { assert_eq!( - view(language, source, false), + &view(language, source, false), expected, "{language:?}: {}", source.escape_ascii() @@ -351,12 +351,7 @@ fn check_retained( disposition: CandidateDisposition, range: Range, ) { - assert_eq!( - view(language, source, false), - expected, - "{language:?}: {}", - source.escape_ascii() - ); + check(language, source, &expected); expected.evidence.push((disposition, range)); assert_eq!( view(language, source, true), @@ -392,7 +387,7 @@ fn leading_block_documents_the_declaration_after_it(language: LANG) { check( language, source, - owned(comment(0..8, "d", [(0..1, Copied(4..5))]), owner), + &owned(comment(0..8, "d", [(0..1, Copied(4..5))]), owner), ); } } @@ -452,7 +447,7 @@ fn class_or_interface_member_owns_its_leading_block(language: LANG) { check( language, source, - owned(comment(fragment, "d", [(0..1, Copied(text))]), owner), + &owned(comment(fragment, "d", [(0..1, Copied(text))]), owner), ); } } @@ -473,7 +468,7 @@ fn enum_member_owns_its_leading_block(language: LANG) { check( language, b"enum E {\n /** a */\n A,\n /** b */\n B = 1,\n}\n", - View { + &View { documents: vec![ comment(11..19, "a", [(0..1, Copied(15..16))]), comment(27..35, "b", [(0..1, Copied(31..32))]), @@ -492,7 +487,7 @@ fn enum_member_owns_its_leading_block(language: LANG) { check( language, b"enum E {\n /** s */\n \"s\",\n}\n", - owned( + &owned( comment(11..19, "s", [(0..1, Copied(15..16))]), ("string", 22..25), ), @@ -515,7 +510,7 @@ fn each_overload_signature_and_the_implementation_own_their_block(language: LANG check( language, b"/**one*/\nfunction f(x: string): string;\n/**two*/\nfunction f(x: number): number;\n", - View { + &View { documents: vec![ comment(0..8, "one", [(0..3, Copied(3..6))]), comment(40..48, "two", [(0..3, Copied(43..46))]), @@ -544,7 +539,7 @@ fn each_overload_signature_and_the_implementation_own_their_block(language: LANG language, b"/** sig */\nfunction f(x: string): string;\nfunction f(x: number): number;\n\ /** impl */\nfunction f(x: any): any { return x; }\n", - View { + &View { documents: vec![ comment(0..10, "sig", [(0..3, Copied(4..7))]), comment(73..84, "impl", [(0..4, Copied(77..81))]), @@ -573,7 +568,7 @@ fn each_overload_signature_and_the_implementation_own_their_block(language: LANG language, b"class C {\n /** one */\n m(x: string): void;\n /** two */\n m(x: number): void;\n \ /** impl */\n m(x: any): void {}\n}\n", - View { + &View { documents: vec![ comment(12..22, "one", [(0..3, Copied(16..19))]), comment(47..57, "two", [(0..3, Copied(51..54))]), @@ -655,13 +650,13 @@ fn block_before_export_or_declare_documents_the_wrapped_declaration(language: LA check( language, source, - wrapped(comment(0..8, "d", [(0..1, Copied(4..5))]), owner, binding), + &wrapped(comment(0..8, "d", [(0..1, Copied(4..5))]), owner, binding), ); } check( language, b"/**audit*/\ndeclare function f(): void;\n", - wrapped( + &wrapped( comment(0..10, "audit", [(0..5, Copied(3..8))]), ("function_signature", 19..38), ("ambient_declaration", 11..38), @@ -730,13 +725,13 @@ fn block_before_a_decorator_documents_the_decorated_class_or_member(language: LA check( language, source, - owned(comment(fragment, "d", [(0..1, Copied(text))]), owner), + &owned(comment(fragment, "d", [(0..1, Copied(text))]), owner), ); } check( language, b"/** d */\n@dec\nexport class C {}\n", - wrapped( + &wrapped( comment(0..8, "d", [(0..1, Copied(4..5))]), ("class_declaration", 21..31), ("export_statement", 9..31), @@ -779,6 +774,22 @@ fn nearest_block_before_the_declaration_is_selected(language: LANG) { CandidateDisposition::Superseded, 0..10, ); + let source = b"/** a */\n/** b */\n/** c */\nfunction f(): void {}\n"; + let mut expected = owned( + comment(18..26, "c", [(0..1, Copied(22..23))]), + ("function_declaration", 27..48), + ); + check(language, source, &expected); + expected.evidence.extend([ + (CandidateDisposition::Superseded, 0..8), + (CandidateDisposition::Superseded, 9..17), + ]); + assert_eq!( + view(language, source, true), + expected, + "{language:?}: {}", + source.escape_ascii() + ); // The plain `//` comment is not a candidate, even with retention enabled. let source = b"/** d */\n// plain\nfunction f(): void {}\n"; let expected = owned( @@ -814,22 +825,22 @@ fn module_tag_makes_the_block_a_file_document(language: LANG) { check( language, b"/** @packageDocumentation */\nexport const x = 1;\n", - with_const, + &with_const, ); check( language, b"/** @module */\nfunction f(): void {}\n", - file_owned(comment(0..14, "@module", [(0..7, Copied(4..11))]), 0..37), + &file_owned(comment(0..14, "@module", [(0..7, Copied(4..11))]), 0..37), ); check( language, b"/**\n * @module m\n */\nfunction f(): void {}\n", - file_owned(comment(0..20, "@module m", [(0..9, Copied(7..16))]), 0..43), + &file_owned(comment(0..20, "@module m", [(0..9, Copied(7..16))]), 0..43), ); check( language, b"/** @packageDocumentation */\n/** d */\nfunction f(): void {}\n", - View { + &View { documents: vec![ file(comment( 0..28, @@ -871,7 +882,7 @@ fn block_text_is_cleaned_and_mapped_to_its_source(language: LANG) { check( language, b"/**audit*/\nfunction f(): void {}\n", - owned( + &owned( comment(0..10, "audit", [(0..5, Copied(3..8))]), ("function_declaration", 11..32), ), @@ -879,7 +890,7 @@ fn block_text_is_cleaned_and_mapped_to_its_source(language: LANG) { check( language, b"/**\n * a \n * b\n */\nfunction f(): void {}\n", - owned( + &owned( comment( 0..21, "a \n b", @@ -895,7 +906,7 @@ fn block_text_is_cleaned_and_mapped_to_its_source(language: LANG) { check( language, b"/**\r\n * a\r\n * b\r\n */\r\nfunction f(): void {}\r\n", - owned( + &owned( comment( 0..20, "a\nb", @@ -927,7 +938,7 @@ fn tsx_function_with_a_jsx_element_owns_its_leading_block() { check( LANG::Tsx, b"/**audit*/\nfunction f() { return
; }\n", - owned( + &owned( comment(0..10, "audit", [(0..5, Copied(3..8))]), ("function_declaration", 11..42), ), @@ -935,7 +946,7 @@ fn tsx_function_with_a_jsx_element_owns_its_leading_block() { check( LANG::Tsx, b"/** d */\nexport default function App() { return
; }\n", - wrapped( + &wrapped( comment(0..8, "d", [(0..1, Copied(4..5))]), ("function_declaration", 24..57), ("export_statement", 9..57), @@ -947,6 +958,7 @@ fn tsx_function_with_a_jsx_element_owns_its_leading_block() { // const bindings and the child of a declare wrapper gain owner projections. #[cfg(feature = "typescript")] fn forms_without_an_owner_keep_their_document_and_no_association(language: LANG) { + // bca: suppress(halstead) -- one table of the ten cases of the group and their views. let source = b"/** above */\ndeclare /** inside */ function f(): void;\n"; check_retained( language, @@ -1013,7 +1025,7 @@ fn forms_without_an_owner_keep_their_document_and_no_association(language: LANG) ), ]; for (source, document, bound, extra) in rows { - check(language, source, unowned(document, bound, extra)); + check(language, source, &unowned(document, bound, extra)); } } @@ -1070,6 +1082,7 @@ fn unnamed(parser: &AnyParser, kind: &str, range: Range) { #[cfg(feature = "typescript")] #[allow(clippy::too_many_lines)] fn grammar_shapes_the_unit_relies_on(language: LANG) { + // bca: suppress(abc, halstead) -- sixteen independent shapes, each a parse and its assertions. let parser = clean( language, b"export function f(): void {}\nexport default function g(): void {}\n", @@ -1115,8 +1128,14 @@ fn grammar_shapes_the_unit_relies_on(language: LANG) { let parser = clean(language, b"export default function() {}\n"); let export = node_at(&parser, "export_statement", 0..28); - field(export, "value", ("function_expression", 15..28)); - assert!(export.child_by_field_name("declaration").is_none()); + assert_eq!( + parts(export), + [ + (None, ("export", 0..6)), + (None, ("default", 7..14)), + (Some("value"), ("function_expression", 15..28)), + ] + ); let parser = clean(language, b"export default class {}\n"); field( node_at(&parser, "export_statement", 0..23), @@ -1371,8 +1390,9 @@ fn grammar_shapes_the_unit_relies_on(language: LANG) { ] ); let comment = node_at(&parser, "comment", 0..14); + let function = node_at(&parser, "function_declaration", 16..37); assert_eq!(comment.end_position().row - comment.start_position().row, 2); - assert_eq!(&source[comment.end_byte()..16], b"\r\n"); + assert_eq!(&source[comment.end_byte()..function.start_byte()], b"\r\n"); } #[cfg(feature = "typescript")] diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 1ef9627e1..a9206f3a9 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -1646,7 +1646,7 @@ function f(x: number): number;\n", }, ]; for row in rows { - let name = row.source.escape_ascii(); + let name = format!("{:?}: {}", row.language, row.source.escape_ascii()); let parser = crate::langs::AnyParser::parse(row.language, row.source.to_vec(), None, None).unwrap(); assert!(!parser.ts_tree().root_node().has_error(), "{name}"); From 22caf681145909ddd881b354294b315ae127b7d2 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:05:49 -0800 Subject: [PATCH 103/221] test(documentation): pin Groovydoc candidate order and the plain-comment control Pin two retained candidates in source order and assert the plain-comment and same-row grammar controls. No production code changed. --- .../documentation/collector/groovy_tests.rs | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs b/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs index a0e346123..5a37e2f57 100644 --- a/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs @@ -321,6 +321,19 @@ fn groovy_type_declarations_own_the_block_above_them() { source.escape_ascii() ); } + // Only the nearest block documents the class; the two before it are retained on request. + let source = b"/** a */\n/** b */\n/** c */\nclass C {}\n"; + let mut expected = owned( + comment(18..26, "c", [(0..1, Copied(22..23))]), + "class_declaration", + 27..37, + ); + assert_eq!(view(source), expected); + expected.evidence.extend([ + (CandidateDisposition::Superseded, 0..8), + (CandidateDisposition::Superseded, 9..17), + ]); + assert_eq!(retained(source), expected); } #[cfg(feature = "groovy")] @@ -469,7 +482,14 @@ fn groovy_script_level_method_owns_the_block_above_it() { #[cfg(feature = "groovy")] #[test] fn groovy_plain_comments_are_no_documentation() { - for source in [b"/* d */\nclass C {}\n".as_slice(), b"// d\nclass C {}\n"] { + let plain: [(&[u8], &str, Range); 2] = [ + (b"/* d */\nclass C {}\n", "block_comment", 0..7), + (b"// d\nclass C {}\n", "line_comment", 0..4), + ]; + for (source, kind, range) in plain { + let parser = clean(source); + // The tree holds the plain comment, so each empty view is the collector's answer to it. + assert_eq!(parts(parser.ts_tree().root_node())[0], (kind, range)); assert_eq!(view(source), View::default(), "{}", source.escape_ascii()); assert_eq!( retained(source), @@ -749,6 +769,7 @@ fn groovy_grammar_shapes_the_unit_relies_on() { let parser = clean(b"/**a*/ class C { /**b*/ C() {} }\n"); let comment = node_at(&parser, "groovydoc_comment", 0..6); let class = comment.next_sibling().unwrap(); + assert_eq!(comment.parent(), Some(parser.ts_tree().root_node())); assert_eq!(site(class), ("class_declaration", 7..32)); assert_eq!(comment.end_position().row, class.start_position().row); let body = class.child_by_field_name("body").unwrap(); From d32dc0c4719734fdf1430933ffd57ef0b1cd5f0f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:10:37 -0800 Subject: [PATCH 104/221] test(documentation): give the Kotlin node queries a control and assert each view once Add a two-association control for owner queries and remove redundant view and grammar assertions. This changes test code only; no production code changed. --- .../documentation/collector/kotlin_tests.rs | 273 +++++++----------- 1 file changed, 109 insertions(+), 164 deletions(-) diff --git a/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs b/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs index 423c312c8..87f29f94d 100644 --- a/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs @@ -1,6 +1,6 @@ //! Kotlin KDoc source-view tests compare documents, associations, retained candidates and //! pending assessments through both entry points. The grammar test collects nothing and -//! pins the tree shapes used by those tests. Node queries are checked beside the view. +//! pins the tree shapes the unit relies on. Node queries are checked beside the view. #[cfg(feature = "kotlin")] use crate::documentation::*; @@ -323,51 +323,43 @@ fn parts(parent: tree_sitter::Node<'_>) -> Vec<(Option<&'static str>, &'static s } #[cfg(feature = "kotlin")] -fn grammar_parse(source: &[u8], has_error: bool) -> AnyParser { - // bca: suppress(halstead) -- comparing typed and raw grammar trees is one cohesive check. - let parser = AnyParser::parse(LANG::Kotlin, source.to_vec(), None, None).unwrap(); - let root = parser.ts_tree().root_node(); - assert_eq!(root.has_error(), has_error, "{}", source.escape_ascii()); - assert_eq!(root.end_byte(), source.len()); - let mut raw = tree_sitter::Parser::new(); - raw.set_language(&LANG::Kotlin.tree_sitter_language().unwrap()) - .unwrap(); - let raw_tree = raw.parse(source, None).unwrap(); - let typed_nodes: Vec<_> = parser - .root_node() - .preorder() - .map(|node| { - let node = node.as_tree_sitter(); - ( - site(node), +fn flagged(root: tree_sitter::Node<'_>) -> Vec<(&'static str, Range, [bool; 5])> { + let mut unvisited = vec![root]; + let mut nodes = Vec::new(); + while let Some(node) = unvisited.pop() { + nodes.push(( + node.kind(), + node.byte_range(), + [ node.has_error(), node.is_error(), node.is_missing(), node.is_extra(), node.is_named(), - ) - }) - .collect(); - let mut raw_nodes = vec![raw_tree.root_node()]; - let mut raw_facts = Vec::new(); - while let Some(node) = raw_nodes.pop() { - raw_facts.push(( - site(node), - node.has_error(), - node.is_error(), - node.is_missing(), - node.is_extra(), - node.is_named(), + ], )); let children: Vec<_> = node.children(&mut node.walk()).collect(); - raw_nodes.extend(children.into_iter().rev()); + unvisited.extend(children.into_iter().rev()); } - assert_eq!(typed_nodes, raw_facts); + nodes +} + +#[cfg(feature = "kotlin")] +fn grammar_parse(source: &[u8], has_error: bool) -> AnyParser { + let parser = AnyParser::parse(LANG::Kotlin, source.to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + assert_eq!(root.has_error(), has_error, "{}", source.escape_ascii()); + assert_eq!(root.end_byte(), source.len()); + let mut raw = tree_sitter::Parser::new(); + raw.set_language(&LANG::Kotlin.tree_sitter_language().unwrap()) + .unwrap(); + let typed = flagged(root); + assert_eq!(typed, flagged(raw.parse(source, None).unwrap().root_node())); if !has_error { assert!( - typed_nodes + typed .iter() - .all(|(_, error, is_error, missing, _, _)| { !error && !is_error && !missing }) + .all(|(_, _, [error, is_error, missing, ..])| !error && !is_error && !missing) ); } parser @@ -415,7 +407,7 @@ fn kotlin_kdoc_before_a_top_level_declaration_documents_it() { #[cfg(feature = "kotlin")] #[test] fn kotlin_kdoc_before_a_member_documents_the_member_not_the_class() { - let members: [(&[u8], Doc, &str, Range); 5] = [ + let members: [(&[u8], Doc, &str, Range); 4] = [ ( b"class C {\n /** d */\n companion object {}\n}\n", comment(14..22, "d", [(0..1, Copied(18..19))]), @@ -440,28 +432,35 @@ fn kotlin_kdoc_before_a_member_documents_the_member_not_the_class() { "class_declaration", 27..37, ), - ( - b"class C {\n /**audit*/\n constructor(x: Int) {}\n}\n", - comment(14..24, "audit", [(0..5, Copied(17..22))]), - "secondary_constructor", - 29..51, - ), ]; for (source, document, kind, range) in members { - let mut expected = owned(document, kind, range); - if source == b"class C {\n /**audit*/\n constructor(x: Int) {}\n}\n" { - // The undocumented parameter pins today's pending projection, not its later design. - expected.assessments = unordered([pending( - AssessmentAxis::Owner, - NEEDS_PROJECTION, - Some(("parameter", 41..47)), - None, - )]); - } - assert_eq!(view(source), expected, "{}", source.escape_ascii()); + assert_eq!( + view(source), + owned(document, kind, range), + "{}", + source.escape_ascii() + ); } + let mut expected = owned( + comment(14..24, "audit", [(0..5, Copied(17..22))]), + "secondary_constructor", + 29..51, + ); + // The undocumented parameter pins today's pending projection, not its later design. + expected.assessments = unordered([pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("parameter", 41..47)), + None, + )]); + assert_eq!( + view(b"class C {\n /**audit*/\n constructor(x: Int) {}\n}\n"), + expected + ); + let parser = clean(b"enum class E {\n /** a */\n A,\n /** b */\n B\n}\n"); + let both = indexes(&parser, DocumentationOptions::default()); assert_eq!( - view(b"enum class E {\n /** a */\n A,\n /** b */\n B\n}\n"), + agreed(&both), View { documents: vec![ comment(19..27, "a", [(0..1, Copied(23..24))]), @@ -482,6 +481,22 @@ fn kotlin_kdoc_before_a_member_documents_the_member_not_the_class() { ..View::default() } ); + // The control for `check_query`, where no query holds an association: the query of an + // entry holds the association of its own document and not that of the other entry. + for index in &both { + for (at, range) in [32..33, 52..53].into_iter().enumerate() { + let query = index + .node_associations(node_at(&parser, "enum_entry", range)) + .unwrap(); + let documents: Vec<_> = query + .associations() + .map(|association| index.facts().associated_document(association).unwrap()) + .collect(); + assert_eq!(documents, [index.documents().nth(at).unwrap()]); + assert!(!query.projection_pending()); + assert_eq!(query.assessments().count(), 0); + } + } } #[cfg(feature = "kotlin")] @@ -705,15 +720,13 @@ fn kotlin_kdoc_with_crlf_line_endings() { #[cfg(feature = "kotlin")] fn check_query( - parser: &AnyParser, indexes: &[DocumentationIndex<'_>; 2], - kind: &str, - range: Range, + node: tree_sitter::Node<'_>, pending_owner: bool, expected: &[(AssessmentAxis, &str)], ) { - // bca: suppress(nargs) -- a query needs its parse, indexes, node, status and assessments. - let node = node_at(parser, kind, range); + let mut expected = expected.to_vec(); + expected.sort_by_key(|(_, reason)| *reason); for index in indexes { let projection = index.node_projection(node).unwrap(); assert_eq!(projection.pending(), pending_owner); @@ -737,8 +750,6 @@ fn check_query( .map(|assessment| (assessment.get().axis, assessment.get().reason)) .collect(); actual.sort_by_key(|(_, reason)| *reason); - let mut expected = expected.to_vec(); - expected.sort_by_key(|(_, reason)| *reason); assert_eq!(actual, expected); } } @@ -748,39 +759,27 @@ fn check_query( #[test] #[allow(clippy::too_many_lines)] fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { - for (source, fragment, text, node) in [ - (b"/** d */\nval x = 1\n".as_slice(), 0..8, 4..5, 9..18), - ( - b"class C {\n /** d */\n val p = 1\n}\n".as_slice(), - 14..22, - 18..19, - 27..36, - ), - ] { - assert_eq!( - view(source), - View { - documents: vec![comment(fragment, "d", [(0..1, Copied(text))])], - assessments: unordered([ - pending( - AssessmentAxis::Owner, - AWAITS_OWNER, - Some(("property_declaration", node.clone())), - Some(0), - ), - pending( - AssessmentAxis::Owner, - NEEDS_PROJECTION, - Some(("property_declaration", node)), - None, - ), - ]), - ..View::default() - }, - "{}", - source.escape_ascii() - ); - } + assert_eq!( + view(b"class C {\n /** d */\n val p = 1\n}\n"), + View { + documents: vec![comment(14..22, "d", [(0..1, Copied(18..19))])], + assessments: unordered([ + pending( + AssessmentAxis::Owner, + AWAITS_OWNER, + Some(("property_declaration", 27..36)), + Some(0), + ), + pending( + AssessmentAxis::Owner, + NEEDS_PROJECTION, + Some(("property_declaration", 27..36)), + None, + ), + ]), + ..View::default() + } + ); let class_parameter = b"class C(/**audit*/ val x: Int)\n"; let class_expected = View { documents: vec![comment(8..18, "audit", [(0..5, Copied(11..16))])], @@ -812,7 +811,6 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { ]), ..View::default() }; - assert_eq!(view(class_parameter), class_expected); let function_parameter = b"fun f(/**p*/ x: Int) {}\n"; let function_expected = View { documents: vec![comment(6..12, "p", [(0..1, Copied(9..10))])], @@ -838,7 +836,6 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { ]), ..View::default() }; - assert_eq!(view(function_parameter), function_expected); let parser = clean(b"/** d */\nval x = 1\n"); let both = indexes(&parser, DocumentationOptions::default()); @@ -864,10 +861,8 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { } ); check_query( - &parser, &both, - "property_declaration", - 9..18, + node_at(&parser, "property_declaration", 9..18), true, &[ (AssessmentAxis::Owner, AWAITS_OWNER), @@ -879,18 +874,14 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { let both = indexes(&parser, DocumentationOptions::default()); assert_eq!(agreed(&both), class_expected); check_query( - &parser, &both, - "class_declaration", - 0..30, + node_at(&parser, "class_declaration", 0..30), false, &[(AssessmentAxis::Selection, SIGNATURE)], ); check_query( - &parser, &both, - "primary_constructor", - 7..30, + node_at(&parser, "primary_constructor", 7..30), true, &[ (AssessmentAxis::Owner, NEEDS_PROJECTION), @@ -898,10 +889,8 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { ], ); check_query( - &parser, &both, - "class_parameter", - 19..29, + node_at(&parser, "class_parameter", 19..29), true, &[ (AssessmentAxis::Owner, AWAITS_OWNER), @@ -915,18 +904,14 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { let both = indexes(&parser, DocumentationOptions::default()); assert_eq!(agreed(&both), function_expected); check_query( - &parser, &both, - "function_declaration", - 0..23, + node_at(&parser, "function_declaration", 0..23), false, &[(AssessmentAxis::Selection, SIGNATURE)], ); check_query( - &parser, &both, - "parameter", - 13..19, + node_at(&parser, "parameter", 13..19), true, &[ (AssessmentAxis::Owner, AWAITS_OWNER), @@ -941,44 +926,12 @@ fn kotlin_property_and_parameter_kdoc_is_a_document_with_pending_assessments() { #[test] #[allow(clippy::too_many_lines)] fn kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments() { - let rows: [(&[u8], Doc, Vec); 6] = [ - ( - b"public /**audit*/ inline fun f() {}\n", - comment(7..17, "audit", [(0..5, Copied(10..15))]), - unordered([ - pending( - AssessmentAxis::Selection, - SIGNATURE, - Some(("block_comment", 7..17)), - None, - ), - pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), - ]), - ), + let rows: [(&[u8], Doc, Vec); 3] = [ ( b"public /**audit*/ fun f() {}\n", comment(7..17, "audit", [(0..5, Copied(10..15))]), unordered([pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0))]), ), - ( - b"class C private /**audit*/ constructor()\n", - comment(16..26, "audit", [(0..5, Copied(19..24))]), - unordered([ - pending( - AssessmentAxis::Selection, - SIGNATURE, - Some(("block_comment", 16..26)), - None, - ), - pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0)), - pending( - AssessmentAxis::Owner, - NEEDS_PROJECTION, - Some(("primary_constructor", 8..40)), - None, - ), - ]), - ), ( b"class C /**audit*/ constructor()\n", comment(8..18, "audit", [(0..5, Copied(11..16))]), @@ -992,11 +945,6 @@ fn kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments() { ), ]), ), - ( - b"fun f() /**audit*/ {}\n", - comment(8..18, "audit", [(0..5, Copied(11..16))]), - unordered([pending(AssessmentAxis::Owner, AWAITS_OWNER, None, Some(0))]), - ), ( b"class C {\n fun f() /**audit*/ {}\n}\n", comment(22..32, "audit", [(0..5, Copied(25..30))]), @@ -1124,8 +1072,13 @@ fn kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments() { let parser = clean(source); let both = indexes(&parser, DocumentationOptions::default()); assert_eq!(agreed(&both), expected); - for (kind, range, pending, assessments) in queries { - check_query(&parser, &both, kind, range, pending, &assessments); + for (kind, range, pending_owner, assessments) in queries { + check_query( + &both, + node_at(&parser, kind, range), + pending_owner, + &assessments, + ); } } } @@ -1134,11 +1087,9 @@ fn kotlin_kdoc_inside_a_declaration_is_a_document_with_pending_assessments() { #[test] #[allow(clippy::too_many_lines)] fn kotlin_grammar_shapes_the_unit_relies_on() { - let source = b"/**audit*/\nfun f() {}\n"; - let parser = grammar_parse(source, false); + let parser = grammar_parse(b"/**audit*/\nfun f() {}\n", false); let root = parser.ts_tree().root_node(); assert_eq!(site(root), ("source_file", 0..22)); - assert_eq!(root.end_byte(), source.len()); assert_eq!( parts(root), [ @@ -1330,7 +1281,6 @@ fn kotlin_grammar_shapes_the_unit_relies_on() { let parser = grammar_parse(source, false); let root = parser.ts_tree().root_node(); assert_eq!(site(root), ("source_file", 0..34)); - assert_eq!(root.end_byte(), source.len()); assert_eq!( parts(root), [ @@ -1419,8 +1369,6 @@ fn kotlin_grammar_shapes_the_unit_relies_on() { ), ] { let parser = grammar_parse(source, error); - let root = parser.ts_tree().root_node(); - assert_eq!(root.has_error(), error); let class = node_at(&parser, "class_declaration", 0..45); let body = node_at(&parser, "class_body", 8..45); assert_eq!(class.has_error(), error); @@ -1443,10 +1391,7 @@ fn kotlin_grammar_shapes_the_unit_relies_on() { .all(|child| !child.has_error()) ); } - let source = b"class C { fun m() {} }\n"; - let parser = grammar_parse(source, true); - let root = parser.ts_tree().root_node(); - assert!(root.has_error()); + let parser = grammar_parse(b"class C { fun m() {} }\n", true); let body = node_at(&parser, "enum_class_body", 8..22); assert_eq!( parts(body), From bf99357f995d44e4b006245b6f647a1f6668a4cf Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:51:52 -0800 Subject: [PATCH 105/221] test(documentation): say why the Kotlin grammar test pins an error flag Two sources of the grammar test are one-row class bodies that parse with the error flag at the pinned grammar. The test asserts the flag on purpose, so that a grammar bump that removes it is noticed; no source-view test collects such a source. The test said nothing about that, and its name reads as if the unit relied on the flag. One comment above the two sources says so. No assertion, expected value or source changes. --- .../src/documentation/collector/kotlin_tests.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs b/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs index 87f29f94d..d6ca6145c 100644 --- a/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/kotlin_tests.rs @@ -1358,6 +1358,9 @@ fn kotlin_grammar_shapes_the_unit_relies_on() { .all(|(_, kind, _)| *kind != "block_comment") ); + // The pinned grammar flags an error for a class body whose member shares the row of the + // closing brace, here and in the source after this loop. No source-view test collects such + // a source; the flag is pinned so that a grammar bump that removes it fails this test. for (source, error) in [ ( b"class C { /**audit*/ constructor(x: Int) {} }\n".as_slice(), From 8a48438fe2587ed59e2cf3f8cdd0db9cdc0e2ff1 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:35:10 -0800 Subject: [PATCH 106/221] feat(documentation): add a hidden Ast::documentation with path provenance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Return the typed parser’s documentation index, borrowing the held Ast. Supply the final component of a from_path path only when the context names no logical filename; explicit names win and display labels are ignored. Keep the method hidden and outside the stability contract. Metric code and behavior are unchanged. --- CHANGELOG.md | 10 + docs/development/documentation_extraction.md | 6 +- src/spaces.rs | 7 + src/spaces/ast.rs | 64 +- tests/README.md | 2 +- tests/api/documentation_facade.rs | 978 ++++++++++++++++++ tests/api/main.rs | 4 + utils/documentation-facade-unit1-perturb.json | 196 ++++ 8 files changed, 1259 insertions(+), 8 deletions(-) create mode 100644 tests/api/documentation_facade.rs create mode 100644 utils/documentation-facade-unit1-perturb.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 79e40afe2..fe52b2766 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -67,6 +67,16 @@ for historical reference. on `Parser` and `AnyParser`. The root library's documentation facade follows separately; existing metric behavior is unchanged. (#1656) +- Added a hidden, unstable `Ast::documentation` to the root library. It hands + its context and options to the AST crate's typed documentation collector and + returns that collector's index, which borrows the `Ast`. An `Ast` read with + `Ast::from_path` supplies the final component of its path as the logical + filename when the context names none; a display name is never used for it. + The method is `#[doc(hidden)]` and outside the stability contract + (`STABILITY.md`): its signature names `big-code-analysis-ast` types that the + root library does not re-export, and it may change in any release. Existing + metric behavior is unchanged. (#1680) + ### Changed - **(breaking), deferred to the next major (3.0):** the MI of a space diff --git a/docs/development/documentation_extraction.md b/docs/development/documentation_extraction.md index e6e0b7673..44da478ef 100644 --- a/docs/development/documentation_extraction.md +++ b/docs/development/documentation_extraction.md @@ -467,8 +467,10 @@ Offsets refer to the actual parsed buffer, including file-loading normalization and C-family masking. `Ast::source()` is that buffer. Masking preserves comment bytes but does not justify recovering an original identifier from dollar runs. -Logical filename is explicit caller metadata. The facade issue adds a private -path-provenance field populated by `Ast::from_path`; today no such field exists. +Logical filename is explicit caller metadata. `Ast` holds a private +path-provenance field populated by `Ast::from_path`: the final component of the +path. The hidden `Ast::documentation` supplies it when the context names no +logical filename; an explicit one always wins. `Source::with_name` and adopted-tree display labels remain display labels. A logical filename is context for documentation rules, not a filesystem credential. diff --git a/src/spaces.rs b/src/spaces.rs index a39d64779..7175d8887 100644 --- a/src/spaces.rs +++ b/src/spaces.rs @@ -446,10 +446,17 @@ pub struct Source<'a> { pub struct Ast { inner: crate::langs::AnyParser, name: Option, + provenance: Option, } // `impl fmt::Debug for Ast` and `impl Ast` live in `spaces/ast.rs`. +/// The file an [`Ast`] was read from, as documentation rules may use it: the +/// final component of the path given to [`Ast::from_path`], held as the context +/// a collection receives when its caller names no file. A display name is a +/// label a caller can set to anything, so it is never read into this. +struct PathProvenance(big_code_analysis_ast::documentation::DocumentationContext); + /// Per-traversal options for [`analyze`] / [`Ast::metrics`]. /// /// Marked `#[non_exhaustive]` so future option fields can land diff --git a/src/spaces/ast.rs b/src/spaces/ast.rs index ca19d93ee..aaed388b2 100644 --- a/src/spaces/ast.rs +++ b/src/spaces/ast.rs @@ -7,6 +7,10 @@ use super::*; +use big_code_analysis_ast::documentation::{ + CollectionError, DocumentationContext, DocumentationIndex, DocumentationOptions, +}; + use crate::langs::AnyParser; use crate::macros::with_any_parser; use crate::ops::ops_inner; @@ -44,7 +48,11 @@ impl Ast { preproc, } = source; let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?; - Ok(Self { inner, name }) + Ok(Self { + inner, + name, + provenance: None, + }) } /// Adopt a caller-built [`tree_sitter::Tree`], reusing it instead of @@ -71,7 +79,11 @@ impl Ast { name: Option, ) -> Result { let inner = AnyParser::from_tree(lang, tree, code)?; - Ok(Self { inner, name }) + Ok(Self { + inner, + name, + provenance: None, + }) } /// Read `path`, detect its language, and parse it into a reusable @@ -109,15 +121,45 @@ impl Ast { // lossy conversion rather than corrupting it, matching `analyze`'s // strict default. let name = path.to_str().ok_or(FromPathError::NonUtf8Path)?.to_owned(); + let provenance = PathProvenance::of(&name); let code = crate::read_file_with_eol_classified(path) .map_err(FromPathError::Io)? .map_err(FromPathError::Skipped)?; let lang = crate::guess_language(&code, path) .0 .ok_or(FromPathError::UnknownLanguage)?; - Ok(Self::parse( - Source::from_bytes(lang, code).with_name(Some(name)), - )?) + let mut ast = Self::parse(Source::from_bytes(lang, code).with_name(Some(name)))?; + ast.provenance = provenance; + Ok(ast) + } + + /// Collect source documentation from the held parse. + /// + /// Hidden and unstable: the types it names belong to `big-code-analysis-ast` + /// and are not re-exported here. + /// + /// The index borrows this `Ast`, and its offsets refer to [`Ast::source`]. A + /// `context` that names a logical filename is passed on as it is. One that + /// names none receives the final component of the path [`Ast::from_path`] + /// read this `Ast` from. An `Ast` built any other way has no such path, and + /// its display name is never used in its place. + /// + /// # Errors + /// + /// The error of the typed parser's documentation method, unchanged: a + /// cancelled parse or collection, a profile that does not belong to the + /// language or has no adapter, and the detectable faults of an adopted tree. + #[doc(hidden)] + pub fn documentation( + &self, + context: &DocumentationContext, + options: &DocumentationOptions, + ) -> Result, CollectionError> { + let context = match &self.provenance { + Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from, + _ => context, + }; + self.inner.documentation(context, options) } /// Run the metric walker against the held parse. Safe to call @@ -405,3 +447,15 @@ impl Ast { self.inner.root_node() } } + +impl PathProvenance { + /// `None` where the path has no final component, as `..` and a root have + /// none. `utf8_path` is the string [`Ast::from_path`] has already converted + /// with an error, so its final component converts as well. + fn of(utf8_path: &str) -> Option { + let filename = Path::new(utf8_path).file_name()?.to_str()?; + Some(Self(DocumentationContext { + logical_filename: Some(filename.to_owned()), + })) + } +} diff --git a/tests/README.md b/tests/README.md index 89a122145..4152ca1be 100644 --- a/tests/README.md +++ b/tests/README.md @@ -34,7 +34,7 @@ tests/ │ ├── csharp/ hand-written synthetic .cs fixtures (C# corpus) │ ├── php/ hand-written synthetic .php fixtures (PHP corpus) │ └── snapshots/ accepted YAML snapshots for every corpus -├── api/ public API: AST seam, parser reuse, derives, book examples, suppression, self-scan generated-marker guard +├── api/ public API: AST seam, hidden documentation facade, parser reuse, derives, book examples, suppression, self-scan generated-marker guard ├── corpus/ corpus tests: serde, DeepSpeech, pdf.js, C#, PHP, iRules, orphan-snapshot guard ├── grammars/ grammar-specific: C, mozcpp, alterator string flattening ├── output_formats/ output-format tests: CSV, SARIF, Checkstyle diff --git a/tests/api/documentation_facade.rs b/tests/api/documentation_facade.rs new file mode 100644 index 000000000..f46d2c180 --- /dev/null +++ b/tests/api/documentation_facade.rs @@ -0,0 +1,978 @@ +//! The hidden `Ast::documentation`: the context and the options it hands to the +//! documentation collector of `big-code-analysis-ast`, the index and the errors it +//! returns, and the buffer and tree the index refers to. +//! +//! Values that the extraction contract (`docs/development/documentation_extraction.md`) +//! or the source bytes fix are written out. What a language unit may still change +//! (pending assessments, roles, publication) is compared with the collector called +//! directly on the same tree and bytes, never written out. + +#![allow(clippy::single_range_in_vec_init, clippy::naive_bytecount)] + +#[cfg(feature = "rust")] +use std::ops::Range; +#[cfg(feature = "rust")] +use std::path::Path; + +#[cfg(feature = "rust")] +use big_code_analysis::{ + Ast, AstCfg, FromPathError, LANG, Metric, MetricsOptions, ParseCancel, Source, tree_sitter, +}; +#[cfg(feature = "rust")] +use big_code_analysis_ast::documentation::{ + CandidateDisposition, CollectionError, CompleteText, DocumentationContext, DocumentationIndex, + DocumentationOptions, FactError, FactRef, Fragment, FragmentForm, NodeEvidence, Origin, + OriginView, Owner, OwnerError, Profile, Resolution, SourceError, SourcePiece, SourcePieces, + collect, observations, +}; + +/// The contract's primary row for Rust. +#[cfg(feature = "rust")] +const ROSTER: &[u8] = b"///audit\nfn f() {}"; + +/// Two dangling documentation comments: no item follows either. +#[cfg(feature = "rust")] +const DANGLING: &[u8] = b"fn f() {\n///a\n}\n///b\n"; + +/// The contract's source for the independence of documentation and metric pruning. +#[cfg(feature = "rust")] +const TESTS_AND_CODE: &[u8] = b"/// outer\n#[test]\nfn test_f() {}\n\n/// kept\nfn f() {}\n"; + +/// The contract's source for an excluded gap, then a plain function and a documented one. +#[cfg(feature = "rust")] +const GAP_THEN_DOCUMENTED: &[u8] = b"///x\n\nfn f() {}\nfn h() {}\n///y\nfn g() {}"; + +/// One run of a document's text: its output range, and the source range it copies or +/// `None` where the text is inserted. +#[cfg(feature = "rust")] +type Run = (Range, Option>); + +/// One document with the function that owns it: the fragments as source ranges, the +/// text, its runs, and the owner's range. +#[cfg(feature = "rust")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + fragments: Vec>, + text: String, + map: Vec, + owner: Range, +} + +#[cfg(feature = "rust")] +fn parsed(source: &[u8]) -> Ast { + let ast = Ast::parse(Source::new(LANG::Rust, source)).unwrap(); + assert!(!ast.as_tree_sitter().root_node().has_error()); + ast +} + +/// A tree parsed from the included ranges only, adopted with `label` as display name. +#[cfg(feature = "rust")] +fn adopted(source: &[u8], included: &[Range], label: Option<&str>) -> Ast { + let point = |offset: usize| { + let before = &source[..offset]; + let row = before.iter().filter(|byte| **byte == b'\n').count(); + let column = before + .iter() + .rev() + .take_while(|byte| **byte != b'\n') + .count(); + tree_sitter::Point::new(row, column) + }; + let ranges: Vec<_> = included + .iter() + .map(|range| tree_sitter::Range { + start_byte: range.start, + end_byte: range.end, + start_point: point(range.start), + end_point: point(range.end), + }) + .collect(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Rust.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + assert!(!tree.root_node().has_error()); + Ast::from_tree_sitter(LANG::Rust, tree, source.to_vec(), label.map(str::to_owned)).unwrap() +} + +#[cfg(feature = "rust")] +fn named(filename: &str) -> DocumentationContext { + DocumentationContext { + logical_filename: Some(filename.to_owned()), + } +} + +#[cfg(feature = "rust")] +fn unbound() -> DocumentationOptions { + DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + } +} + +/// The index under no context and default options. +#[cfg(feature = "rust")] +fn collected(ast: &Ast) -> DocumentationIndex<'_> { + ast.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap() +} + +#[cfg(feature = "rust")] +fn logical_filename<'i>(index: &'i DocumentationIndex<'_>) -> Option<&'i str> { + index.context().logical_filename.as_deref() +} + +/// The one node of this kind and byte range. +#[cfg(feature = "rust")] +fn node_at<'t>( + tree: &'t tree_sitter::Tree, + kind: &str, + range: Range, +) -> tree_sitter::Node<'t> { + let mut found = Vec::new(); + let mut stack = vec![tree.root_node()]; + while let Some(current) = stack.pop() { + if current.kind() == kind && current.byte_range() == range { + found.push(current); + } + let mut cursor = current.walk(); + stack.extend(current.children(&mut cursor)); + } + assert_eq!(found.len(), 1, "{kind} {range:?}"); + found[0] +} + +#[cfg(feature = "rust")] +fn spelled(node: tree_sitter::Node<'_>) -> String { + format!("{} {}..{}", node.kind(), node.start_byte(), node.end_byte()) +} + +#[cfg(feature = "rust")] +fn spans(pieces: &SourcePieces<'_>) -> Vec> { + pieces.pieces().iter().map(SourcePiece::range).collect() +} + +#[cfg(feature = "rust")] +fn owner_text<'s>(index: &DocumentationIndex<'s>, owner: FactRef<'_, Owner<'s>>) -> String { + match owner.get() { + Owner::Node(declared) => format!("Node({})", spelled(declared.node())), + Owner::File(root) => format!("File({})", spelled(root.node())), + Owner::Slot(slot) => format!( + "Slot({:?} #{} {:?} in {})", + slot.role, + slot.ordinal, + spans(&slot.source), + owner_text(index, index.facts().slot_enclosing(owner).unwrap()) + ), + other => format!("{other:?}"), + } +} + +/// What an index publishes, one line per record and in the index's own order: the +/// resolved profile, the capability, the options, the context and the number of +/// qualification records; every document with its fragments and its text and runs, or +/// its content state; every association; every pending assessment; every retained +/// candidate; every owner. Node queries are not part of it. +#[cfg(feature = "rust")] +fn published(index: &DocumentationIndex<'_>) -> Vec { + // bca: suppress(halstead) -- one flat reading of the index, record by record. + let facts = index.facts(); + let mut lines = vec![format!( + "{:?} {:?} {:?} {:?} qualifications {}", + index.profile(), + index.capability(), + index.options(), + index.context(), + index.qualifications().len() + )]; + let documents: Vec<_> = index.documents().collect(); + let position = |wanted| documents.iter().position(|known| *known == wanted); + for document in &documents { + let record = document.get(); + lines.push(format!( + "document {:?} {:?}", + record.role(), + record.composition() + )); + for at in 0..record.fragment_count() { + let fragment = facts.document_fragment(*document, at).unwrap(); + let fragment = fragment.get(); + lines.push(format!( + " fragment {:?} gap {} {:?} {:?}", + spans(fragment.source()), + fragment.source().has_excluded_gap(), + fragment.form(), + fragment.node().map(|carrier| spelled(carrier.node())) + )); + } + match index.complete_text(*document).unwrap() { + Some(complete) => { + lines.push(format!(" text {:?}", complete.text())); + for run in complete.mappings() { + lines.push(format!(" map {:?} {:?}", run.output.range(), run.origin)); + } + } + None => lines.push(format!(" content {:?}", record.content())), + } + } + for association in index.associations() { + let record = association.get(); + let owners: Vec<_> = (0..record.owner_count()) + .map(|at| owner_text(index, facts.associated_owner(association, at).unwrap())) + .collect(); + lines.push(format!( + "association {:?} {:?} {} {:?} binding {:?} scope {} owners {owners:?}", + position(facts.associated_document(association).unwrap()), + record.resolution, + record.convention.name(), + record.publication, + record.binding.map(|wrapper| spelled(wrapper.node())), + spelled(record.lexical_scope.node()) + )); + } + for assessment in index.assessments() { + let record = assessment.get(); + lines.push(format!( + "assessment {:?} {:?} {:?} {:?}", + record.axis, + record.reason, + record.node.map(|assessed| spelled(assessed.node())), + index + .assessed_document(assessment) + .unwrap() + .and_then(position) + )); + } + for candidate in index.evidence() { + let fragment = index.evidence_fragment(candidate).unwrap(); + lines.push(format!( + "evidence {:?} {:?} gap {}", + candidate.get().disposition, + spans(fragment.get().source()), + fragment.get().source().has_excluded_gap() + )); + } + for owner in facts.owners() { + lines.push(format!("owner {}", owner_text(index, owner))); + } + lines +} + +/// The range of a fragment and its comment node. A fragment here is one piece of +/// comment spelling, and its node is the `line_comment` that starts with it; the node +/// may end later, where it holds the line end. +#[cfg(feature = "rust")] +fn comment_span<'s>(fragment: &Fragment<'s>) -> (Range, tree_sitter::Node<'s>) { + let [piece] = fragment.source().pieces() else { + panic!("one piece, found {:?}", fragment.source().pieces()) + }; + let carrier = fragment.node().unwrap().node(); + assert_eq!(fragment.form(), FragmentForm::Comment); + assert_eq!( + (carrier.kind(), carrier.start_byte()), + ("line_comment", piece.range().start) + ); + (piece.range(), carrier) +} + +/// The runs of a complete text. A copied run here reads one piece, and a query for +/// the whole text returns the same runs. +#[cfg(feature = "rust")] +fn runs(complete: CompleteText<'_, '_>) -> Vec { + let map: Vec = complete + .mappings() + .iter() + .map(|run| match &run.origin { + Origin::Copied(pieces) => (run.output.range(), Some(spans(pieces)[0].clone())), + Origin::Synthetic => (run.output.range(), None), + other => panic!("a copied or an inserted run, found {other:?}"), + }) + .collect(); + let queried: Vec = complete + .origins(0..complete.text().len()) + .unwrap() + .map(|portion| match portion.origin { + OriginView::Copied(piece) => (portion.output, Some(piece.range())), + OriginView::Synthetic => (portion.output, None), + other => panic!("a copied or an inserted portion, found {other:?}"), + }) + .collect(); + assert_eq!(queried, map); + map +} + +/// The documents of an index in which every document is a run of `///` comments owned +/// by the function that follows it. What holds for every such document is asserted +/// here and is in no expected value: association `i` belongs to document `i` and is +/// resolved; its one owner is a `function_item` node, which is also its binding; and +/// its lexical scope is the parent of the document's first comment. +#[cfg(feature = "rust")] +fn documented_functions(index: &DocumentationIndex<'_>) -> Vec { + let facts = index.facts(); + assert_eq!(index.associations().len(), index.documents().len()); + let mut documents = Vec::new(); + for (document, association) in index.documents().zip(index.associations()) { + assert_eq!(facts.associated_document(association), Ok(document)); + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), 1); + let owner = facts.associated_owner(association, 0).unwrap(); + let Owner::Node(declared) = owner.get() else { + panic!("a node owner, found {:?}", owner.get()) + }; + let function = declared.node(); + assert_eq!(function.kind(), "function_item"); + assert_eq!( + association.get().binding.map(NodeEvidence::node), + Some(function) + ); + let fragments: Vec<_> = (0..document.get().fragment_count()) + .map(|at| comment_span(facts.document_fragment(document, at).unwrap().get())) + .collect(); + assert_eq!( + Some(association.get().lexical_scope.node()), + fragments[0].1.parent() + ); + let complete = index.complete_text(document).unwrap().unwrap(); + documents.push(Doc { + fragments: fragments.into_iter().map(|(range, _)| range).collect(), + text: complete.text().to_owned(), + map: runs(complete), + owner: function.byte_range(), + }); + } + documents +} + +#[cfg(feature = "rust")] +fn doc( + fragments: [Range; F], + text: &str, + map: [Run; R], + owner: Range, +) -> Doc { + Doc { + fragments: fragments.into(), + text: text.to_owned(), + map: map.into(), + owner, + } +} + +/// The retained candidates as disposition and included pieces, in the index's order. +#[cfg(feature = "rust")] +fn candidates(index: &DocumentationIndex<'_>) -> Vec<(CandidateDisposition, Vec>)> { + index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, spans(fragment.get().source())) + }) + .collect() +} + +/// A file under a new directory, as `/nested/`. +#[cfg(feature = "rust")] +fn written(directory: &Path, name: &str, bytes: &[u8]) -> std::path::PathBuf { + let nested = directory.join("nested"); + std::fs::create_dir_all(&nested).unwrap(); + let path = nested.join(name); + std::fs::write(&path, bytes).unwrap(); + path +} + +// `Ast` gained a field and the index is handed out by the root crate: both stay +// `Send + Sync`, as the contract asks of the index. +#[cfg(feature = "rust")] +const _: fn() = || { + fn assert_send_sync() {} + assert_send_sync::(); + assert_send_sync::>(); +}; + +#[cfg(feature = "rust")] +#[test] +fn contract_rows_reach_the_index_through_the_root_ast() { + type Row = (&'static [u8], Vec, &'static str); + let rows: [Row; 4] = [ + // The primary row: the fragment ends before the line end, and the text is + // the comment without its `///`. + ( + ROSTER, + vec![doc([0..8], "audit", [(0..5, Some(3..8))], 9..18)], + "source_file", + ), + // Two comments are one document; the line break between them is inserted. + ( + b"///a\n///b\nfn f() {}", + vec![doc( + [0..4, 5..9], + "a\nb", + [(0..1, Some(3..4)), (1..2, None), (2..3, Some(8..9))], + 10..19, + )], + "source_file", + ), + // A lexical scope that is not the root. + ( + b"mod m {\n///audit\nfn f() {}\n}", + vec![doc([8..16], "audit", [(0..5, Some(11..16))], 17..26)], + "declaration_list", + ), + // Two documents, in source order; an attribute stands between the first + // comment and its function. + ( + TESTS_AND_CODE, + vec![ + doc([0..9], "outer", [(0..5, Some(4..9))], 18..32), + doc([34..42], "kept", [(0..4, Some(38..42))], 43..52), + ], + "source_file", + ), + ]; + for (source, expected, scope) in rows { + let ast = parsed(source); + let index = collected(&ast); + let shown = String::from_utf8_lossy(source); + assert_eq!(documented_functions(&index), expected, "{shown}"); + let root = ast.as_tree_sitter().root_node(); + for association in index.associations() { + let lexical = association.get().lexical_scope.node(); + assert_eq!(lexical.kind(), scope, "{shown}"); + assert_eq!(lexical == root, scope == "source_file", "{shown}"); + } + // The index borrows the buffer the `Ast` holds, so its offsets are that + // buffer's. + assert!(std::ptr::eq(index.source(), ast.source()), "{shown}"); + assert_eq!(ast.source(), source, "{shown}"); + } +} + +#[cfg(feature = "rust")] +#[test] +fn an_undocumented_function_is_a_supported_owner_and_its_keyword_is_not() { + for (source, function, documents) in [(&b"fn f() {}"[..], 0..9, 0), (ROSTER, 9..18, 1)] { + let ast = parsed(source); + let index = collected(&ast); + // The root crate's own node wrapper reaches a query through its tree-sitter node. + let item = ast + .root_node() + .children() + .find(|child| child.kind() == "function_item") + .unwrap(); + assert_eq!(item.as_tree_sitter().byte_range(), function); + let query = index.node_associations(item.as_tree_sitter()).unwrap(); + assert!(!query.projection_pending()); + assert!( + !index + .node_projection(item.as_tree_sitter()) + .unwrap() + .pending() + ); + assert_eq!(query.associations().len(), documents); + assert_eq!(index.documents().len(), documents); + let keyword = item.children().next().unwrap(); + assert_eq!(keyword.kind(), "fn"); + assert_eq!( + index.node_associations(keyword.as_tree_sitter()).err(), + Some(OwnerError::UnsupportedOwner) + ); + } +} + +// test-lang-gates: hand-written(rust) — `from_path` picks the grammar from the +// `.rs` extension of each path, and nothing in the body names it +#[cfg(feature = "rust")] +#[test] +fn a_file_read_from_a_path_supplies_its_final_component() { + let directory = tempfile::tempdir().unwrap(); + let file = written(directory.path(), "lib.rs", b"///audit\nfn f() {}\n"); + let nested = file.parent().unwrap(); + let spellings = [ + file.clone(), + nested.join("..").join("nested").join("lib.rs"), + nested.join(".").join("lib.rs"), + ]; + for path in &spellings { + let ast = Ast::from_path(path).unwrap(); + // The display name is the whole path as given; only its final component is + // the logical filename. + assert_eq!(ast.name(), path.to_str()); + assert_eq!(logical_filename(&collected(&ast)), Some("lib.rs")); + } + assert_ne!(spellings[1].to_str(), spellings[0].to_str()); + // A relative path: cargo runs an integration test in the package root. + let relative = Ast::from_path(Path::new("src/lib.rs")).unwrap(); + assert_eq!(relative.name(), Some("src/lib.rs")); + assert_eq!(logical_filename(&collected(&relative)), Some("lib.rs")); + // A path without a final component names a directory, so there is no `Ast` to + // hold a provenance. + let above = nested.join(".."); + assert_eq!(above.file_name(), None); + assert!(matches!(Ast::from_path(&above), Err(FromPathError::Io(_)))); +} + +// test-lang-gates: hand-written(rust) — `from_path` picks the grammar from the +// `.rs` extension of the path, and nothing in the body names it +#[cfg(all(unix, feature = "rust"))] +#[test] +fn a_symbolic_link_supplies_its_own_name() { + let directory = tempfile::tempdir().unwrap(); + let file = written(directory.path(), "lib.rs", b"///audit\nfn f() {}\n"); + let link = file.with_file_name("link.rs"); + std::os::unix::fs::symlink(&file, &link).unwrap(); + let ast = Ast::from_path(&link).unwrap(); + // The link is followed for its bytes and never for its name: the path is not resolved. + assert_eq!(ast.name(), link.to_str()); + let index = collected(&ast); + assert_eq!(index.documents().len(), 1); + assert_eq!(logical_filename(&index), Some("link.rs")); +} + +#[cfg(feature = "rust")] +#[test] +fn a_display_label_never_becomes_a_logical_filename() { + let source = b"///audit\nfn f() {}\n"; + let labelled = + Ast::parse(Source::new(LANG::Rust, source).with_name(Some("lib.rs".to_owned()))).unwrap(); + assert_eq!(labelled.name(), Some("lib.rs")); + assert_eq!(logical_filename(&collected(&labelled)), None); + let taken = adopted(source, &[0..source.len()], Some("lib.rs")); + assert_eq!(taken.name(), Some("lib.rs")); + assert_eq!(logical_filename(&collected(&taken)), None); + // The same bytes under the same name, read from a path: the name is known. + let directory = tempfile::tempdir().unwrap(); + let read = Ast::from_path(&written(directory.path(), "lib.rs", source)).unwrap(); + assert_eq!(read.source(), source); + assert_eq!(logical_filename(&collected(&read)), Some("lib.rs")); +} + +#[cfg(feature = "rust")] +#[test] +fn an_explicit_logical_filename_always_wins() { + let source = b"///audit\nfn f() {}\n"; + let directory = tempfile::tempdir().unwrap(); + let read = Ast::from_path(&written(directory.path(), "lib.rs", source)).unwrap(); + let options = DocumentationOptions::default(); + // The provenance is there to be overridden. + assert_eq!(logical_filename(&collected(&read)), Some("lib.rs")); + for ast in [ + read, + parsed(source), + adopted(source, &[0..source.len()], Some("lib.rs")), + ] { + // An empty name is a name too. + for explicit in ["other.rs", ""] { + let index = ast.documentation(&named(explicit), &options).unwrap(); + assert_eq!(logical_filename(&index), Some(explicit)); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn offsets_of_a_file_refer_to_the_normalized_buffer() { + let bytes = b"///a\r\n///b\r\nfn f() {}\r\n"; + let directory = tempfile::tempdir().unwrap(); + let read = Ast::from_path(&written(directory.path(), "crlf.rs", bytes)).unwrap(); + // The reader turns each CRLF into LF before the parse. + assert_eq!(read.source(), b"///a\n///b\nfn f() {}\n"); + let index = collected(&read); + assert!(std::ptr::eq(index.source(), read.source())); + assert_eq!( + documented_functions(&index), + [doc( + [0..4, 5..9], + "a\nb", + [(0..1, Some(3..4)), (1..2, None), (2..3, Some(8..9))], + 10..19, + )] + ); + // The same bytes parsed as they are: every offset after the first line differs. + let verbatim = Ast::parse(Source::new(LANG::Rust, bytes)).unwrap(); + assert_eq!(verbatim.source(), bytes); + assert_eq!( + documented_functions(&collected(&verbatim)), + [doc( + [0..4, 6..10], + "a\nb", + [(0..1, Some(3..4)), (1..2, None), (2..3, Some(9..10))], + 12..21, + )] + ); +} + +#[cfg(feature = "rust")] +#[test] +fn a_cancelled_parse_is_reported_after_its_scope_and_the_next_parse_collects() { + let source = "/// doc\nfn f() {}\n".repeat(200); + let cancel = ParseCancel::new(); + cancel.cancel(); + let stopped = cancel.run(|| Ast::parse(Source::new(LANG::Rust, source.as_bytes())).unwrap()); + // The parse did stop: the tree is empty and the buffer is whole. + assert_eq!(stopped.as_tree_sitter().root_node().byte_range(), 0..0); + assert_eq!(stopped.source(), source.as_bytes()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + assert_eq!( + stopped.documentation(&context, &options).err(), + Some(CollectionError::Cancelled) + ); + // The next parse of the same bytes on this thread is complete. + let complete = parsed(source.as_bytes()); + let index = collected(&complete); + // expected: one comment before each of the 200 functions. + assert_eq!(index.documents().len(), 200); + assert_eq!(index.associations().len(), 200); +} + +#[cfg(feature = "rust")] +#[test] +fn an_empty_source_gives_an_empty_index() { + let cancel = ParseCancel::new(); + cancel.cancel(); + // An empty parse finishes before the parser first reads the flag, so a flag at + // parse time alone is no cancelled parse. + let under_flag = cancel.run(|| Ast::parse(Source::new(LANG::Rust, b"")).unwrap()); + for empty in [parsed(b""), under_flag] { + assert_eq!(empty.as_tree_sitter().root_node().byte_range(), 0..0); + let index = empty + .documentation(&DocumentationContext::default(), &unbound()) + .unwrap(); + assert_eq!(index.documents().len(), 0); + assert_eq!(index.associations().len(), 0); + assert_eq!(index.assessments().len(), 0); + assert_eq!(index.evidence().len(), 0); + } + // The same call on the primary row publishes its document. + assert_eq!(collected(&parsed(ROSTER)).documents().len(), 1); +} + +#[cfg(feature = "rust")] +#[test] +fn a_collection_under_a_cancelled_flag_is_cancelled_and_the_parse_stays_complete() { + let ast = parsed(ROSTER); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let documents = || { + ast.documentation(&context, &options) + .map(|index| index.documents().len()) + }; + let cancel = ParseCancel::new(); + // A flag that is installed and not cancelled stops nothing. + assert_eq!(cancel.run(documents), Ok(1)); + cancel.cancel(); + assert_eq!(cancel.run(documents), Err(CollectionError::Cancelled)); + // Outside the scope the same `Ast` collects again. + assert_eq!(documents(), Ok(1)); +} + +#[cfg(feature = "rust")] +#[test] +fn an_adopted_tree_is_collected_as_given() { + // One included range that ends after the first function. + let two = b"///x\nfn f() {}\n///y\nfn g() {}"; + let first = adopted(two, &[0..14], None); + assert_eq!( + documented_functions(&collected(&first)), + [doc([0..4], "x", [(0..1, Some(3..4))], 5..14)] + ); + // The whole source has two documents, so a parse of the buffer would too. + assert_eq!(collected(&parsed(two)).documents().len(), 2); + + // The contract's gap: the line end after the comment is excluded. The collector + // also keeps pending assessments for this comment. They are an unfinished state + // of the Rust adapter and are not written out, here or below. + let gap = b"///x\n\nfn f() {}"; + let split = adopted(gap, &[0..4, 6..15], None); + let context = DocumentationContext::default(); + let index = split.documentation(&context, &unbound()).unwrap(); + assert_eq!(index.documents().len(), 0); + assert_eq!(index.associations().len(), 0); + // The comment token runs to the end of the tree, because nothing included ends + // its line. It is kept as its two included pieces, never as one range over the gap. + let comment = node_at(split.as_tree_sitter(), "line_comment", 0..15); + assert_eq!(comment.parent(), Some(split.as_tree_sitter().root_node())); + assert_eq!( + candidates(&index), + [(CandidateDisposition::Unattached, vec![0..4, 6..15])] + ); + assert_eq!(collected(&split).evidence().len(), 0); + // Without the gap the comment documents the function. + assert_eq!( + documented_functions(&collected(&parsed(gap))), + [doc([0..4], "x", [(0..1, Some(3..4))], 6..15)] + ); + + // A document that lies wholly in the later range is published as usual. + let later = adopted(GAP_THEN_DOCUMENTED, &[0..4, 6..40], None); + assert_eq!( + documented_functions(&collected(&later)), + [doc([26..30], "y", [(0..1, Some(29..30))], 31..40)] + ); +} + +#[cfg(feature = "rust")] +#[test] +fn two_indexes_over_one_ast_are_independent() { + let ast = parsed(ROSTER); + let first = collected(&ast); + let second = collected(&ast); + assert_eq!(published(&first), published(&second)); + // A handle belongs to the index it came from. + let document = first.documents().next().unwrap(); + assert_eq!( + first.complete_text(document).unwrap().unwrap().text(), + "audit" + ); + assert_eq!( + second.complete_text(document).err(), + Some(FactError::ForeignIndex) + ); + // A node of the tree the `Ast` holds may be asked of both; the same node of + // another parse of the same bytes, or of a clone of the tree, of neither. + let function = node_at(ast.as_tree_sitter(), "function_item", 9..18); + let other = parsed(ROSTER); + let cloned = ast.as_tree_sitter().clone(); + for index in [&first, &second] { + let query = index.node_associations(function).unwrap(); + assert_eq!(query.associations().len(), 1); + for tree in [other.as_tree_sitter(), &cloned] { + assert_eq!( + index + .node_associations(node_at(tree, "function_item", 9..18)) + .err(), + Some(OwnerError::Source(SourceError::ForeignTree)) + ); + } + } +} + +#[cfg(feature = "rust")] +#[test] +fn the_other_ast_operations_neither_collect_nor_change_what_is_collected() { + let ast = parsed(TESTS_AND_CODE); + let idle = observations(); + let before = collected(&ast); + let collecting = observations(); + // The collection moves these counters on this thread, so a zero below is a reading. + // expected: the walk enters every node once. + assert_eq!( + collecting.visits - idle.visits, + ast.root_node().preorder().count() + ); + // expected: one render per document. + assert_eq!(collecting.renders - idle.renders, 2); + // expected: the file and the two functions. + assert_eq!(collecting.owner_projections - idle.owner_projections, 3); + // The checkpoint total has no closed form. + assert_ne!(collecting.polls - idle.polls, 0); + let view = published(&before); + + let metrics = |options: MetricsOptions| ast.metrics(options).unwrap().metrics.loc.dloc(); + // The metric options do take effect: the documentation rows of the test function + // are counted, or pruned with it. + assert_eq!(metrics(MetricsOptions::default()), 2); + assert_eq!( + metrics(MetricsOptions::default().with_exclude_tests(true)), + 1 + ); + assert_eq!( + metrics(MetricsOptions::default().with_mi_charges_docs(true)), + 2 + ); + assert_eq!( + metrics(MetricsOptions::default().with_only(&[Metric::Loc])), + 2 + ); + assert_eq!( + metrics(MetricsOptions::default().with_only(&[Metric::Cyclomatic])), + 0 + ); + assert_eq!(ast.ops().unwrap().spaces.len(), 2); + assert_eq!(ast.functions().len(), 2); + let functions = ["function_item".to_owned()]; + assert_eq!(ast.find(&functions).unwrap().len(), 2); + assert_eq!(ast.count(&functions).0, 2); + // A stripped copy is a buffer of its own. + assert_ne!(ast.strip_comments().as_deref(), Some(ast.source())); + assert_eq!(ast.suppressions().len(), 0); + for comment in [false, true] { + for span in [false, true] { + let configuration = || AstCfg { + id: String::new(), + language: String::new(), + comment, + span, + }; + assert!(ast.dump(configuration()).root.is_some()); + assert!(ast.dump_cursor(configuration()).root.is_some()); + assert!(ast.dump_indexed(configuration()).root.is_some()); + } + } + + let after = observations(); + assert_eq!(after.visits - collecting.visits, 0); + assert_eq!(after.renders - collecting.renders, 0); + assert_eq!(after.owner_projections - collecting.owner_projections, 0); + assert_eq!(after.polls - collecting.polls, 0); + // The buffer is the one that was parsed. The index taken before is still whole, + // and a new one says the same. + assert_eq!(ast.source(), TESTS_AND_CODE); + assert_eq!(published(&before), view); + assert_eq!(published(&collected(&ast)), view); +} + +#[cfg(feature = "rust")] +#[test] +fn the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes() { + let directory = tempfile::tempdir().unwrap(); + let read = Ast::from_path(&written(directory.path(), "lib.rs", TESTS_AND_CODE)).unwrap(); + let nothing = DocumentationContext::default(); + let defaults = DocumentationOptions::default(); + let both = DocumentationOptions { + retain_directives: true, + ..unbound() + }; + // Each row: the `Ast`, the caller's context, the context the collector must + // receive, the options, and how many documents and retained candidates there are. + let rows = [ + (parsed(ROSTER), ¬hing, nothing.clone(), defaults, 1, 0), + (parsed(DANGLING), ¬hing, nothing.clone(), unbound(), 0, 2), + ( + parsed(TESTS_AND_CODE), + &named("other.rs"), + named("other.rs"), + both, + 2, + 0, + ), + ( + adopted(GAP_THEN_DOCUMENTED, &[0..4, 6..40], Some("lib.rs")), + ¬hing, + nothing.clone(), + unbound(), + 1, + 1, + ), + // The provenance of a path is the same as its final component named outright. + (read, ¬hing, named("lib.rs"), defaults, 2, 0), + ]; + for (ast, context, received, options, documents, retained) in rows { + let index = ast.documentation(context, &options).unwrap(); + let direct = collect( + LANG::Rust, + ast.as_tree_sitter(), + ast.source(), + &received, + &options, + ) + .unwrap(); + let view = published(&index); + assert_eq!(view, published(&direct)); + assert_eq!( + (index.documents().len(), index.evidence().len()), + (documents, retained), + "{view:?}" + ); + } +} + +#[cfg(feature = "rust")] +#[test] +fn collection_options_reach_the_collector() { + let ast = parsed(DANGLING); + let context = DocumentationContext::default(); + let directives = DocumentationOptions { + retain_directives: true, + ..DocumentationOptions::default() + }; + // Neither comment has an item to document, and neither is a directive. + for options in [DocumentationOptions::default(), directives] { + let index = ast.documentation(&context, &options).unwrap(); + assert_eq!(index.documents().len(), 0); + assert_eq!(candidates(&index), []); + } + let index = ast.documentation(&context, &unbound()).unwrap(); + assert!(index.options().retain_unbound); + assert_eq!(index.documents().len(), 0); + // Both are kept on request, in source order. + assert_eq!( + candidates(&index), + [ + (CandidateDisposition::Unattached, vec![9..13]), + (CandidateDisposition::Unattached, vec![16..20]), + ] + ); +} + +#[cfg(feature = "rust")] +#[test] +fn collection_errors_come_back_unchanged() { + let directory = tempfile::tempdir().unwrap(); + let read = Ast::from_path(&written(directory.path(), "lib.rs", ROSTER)).unwrap(); + let context = DocumentationContext::default(); + let profiled = |profile| DocumentationOptions { + profile, + ..DocumentationOptions::default() + }; + for ast in [parsed(ROSTER), read] { + // A profile of another language. + assert_eq!( + ast.documentation(&context, &profiled(Profile::Javadoc)) + .err(), + Some(CollectionError::UnsupportedProfile { + language: LANG::Rust, + profile: Profile::Javadoc, + }) + ); + // The language's own profile, named or by default, resolves to itself. + for profile in [Profile::Rust, Profile::Default] { + let index = ast.documentation(&context, &profiled(profile)).unwrap(); + assert_eq!(index.profile(), Profile::Rust); + } + } + // A tree adopted with a buffer shorter than itself. + let tree = parsed(ROSTER).as_tree_sitter().clone(); + assert_eq!(tree.root_node().end_byte(), ROSTER.len()); + let short = Ast::from_tree_sitter(LANG::Rust, tree, ROSTER[..8].to_vec(), None).unwrap(); + assert_eq!( + short + .documentation(&context, &DocumentationOptions::default()) + .err(), + Some(CollectionError::SourceBounds) + ); +} + +#[cfg(feature = "rust")] +#[test] +fn a_long_logical_filename_is_charged_to_the_collection() { + let ast = parsed(b"fn f() {}"); + let checkpoints = |context: &DocumentationContext| { + let before = observations().polls; + let index = ast + .documentation(context, &DocumentationOptions::default()) + .unwrap(); + let after = observations().polls; + ( + after - before, + index.context().logical_filename.as_ref().map(String::len), + ) + }; + let (unnamed, absent) = checkpoints(&DocumentationContext::default()); + assert_eq!(absent, None); + // A collection has checkpoints of its own; their number has no closed form. + assert_ne!(unnamed, 0); + // 64 KiB of name, in one-byte and in two-byte characters. + for name in ["a".repeat(65_536), "é".repeat(32_768)] { + let (charged, length) = checkpoints(&named(&name)); + assert_eq!(length, Some(65_536)); + // expected: the copy of the name is charged by its bytes, and a checkpoint + // falls on every 16 KiB charged. + assert_eq!(charged - unnamed, 4); + } +} diff --git a/tests/api/main.rs b/tests/api/main.rs index 9fe42832e..57cb70629 100644 --- a/tests/api/main.rs +++ b/tests/api/main.rs @@ -33,6 +33,10 @@ mod book_ast_traversal_examples; #[cfg(feature = "rust")] mod book_library_examples; mod derive_eq_hash_ord; +// test-lang-gates: hand-written(rust) — a `mod` declaration has no body +// to read; the grammar is named inside the file it points at +#[cfg(feature = "rust")] +mod documentation_facade; // The feature gate moved here from the `mod parser_reuse` wrapper the // file used to carry: as a module it can be gated at the declaration, // and keeping the wrapper would have nested `parser_reuse` inside diff --git a/utils/documentation-facade-unit1-perturb.json b/utils/documentation-facade-unit1-perturb.json new file mode 100644 index 000000000..65779ff69 --- /dev/null +++ b/utils/documentation-facade-unit1-perturb.json @@ -0,0 +1,196 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--test", "api", "documentation_facade"], + "cases": [ + { + "name": "facade-provenance-not-stored", + "file": "src/spaces/ast.rs", + "old": " ast.provenance = provenance;\n", + "new": " let _ = provenance;\n", + "expect": ["documentation_facade::a_file_read_from_a_path_supplies_its_final_component", "documentation_facade::a_display_label_never_becomes_a_logical_filename", "documentation_facade::an_explicit_logical_filename_always_wins", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes"] + }, + { + "name": "facade-provenance-not-supplied", + "file": "src/spaces/ast.rs", + "old": " Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,", + "new": " Some(PathProvenance(read_from)) if false && context.logical_filename.is_none() => read_from,", + "expect": ["documentation_facade::a_file_read_from_a_path_supplies_its_final_component", "documentation_facade::a_display_label_never_becomes_a_logical_filename", "documentation_facade::an_explicit_logical_filename_always_wins", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes"] + }, + { + "name": "facade-display-label-read-as-logical-filename", + "file": "src/spaces/ast.rs", + "old": " let context = match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,\n _ => context,\n };\n", + "new": " let label = DocumentationContext {\n logical_filename: self.name.clone(),\n };\n let context = match &self.provenance {\n _ if context.logical_filename.is_none() => &label,\n _ => context,\n };\n", + "expect": ["documentation_facade::a_file_read_from_a_path_supplies_its_final_component", "documentation_facade::a_display_label_never_becomes_a_logical_filename", "documentation_facade::an_explicit_logical_filename_always_wins", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes"] + }, + { + "name": "facade-provenance-overrides-explicit-context", + "file": "src/spaces/ast.rs", + "old": " Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,", + "new": " Some(PathProvenance(read_from)) => read_from,", + "expect": ["documentation_facade::an_explicit_logical_filename_always_wins"] + }, + { + "name": "facade-provenance-is-the-whole-path", + "file": "src/spaces/ast.rs", + "old": " let filename = Path::new(utf8_path).file_name()?.to_str()?;", + "new": " let filename = utf8_path;", + "expect": ["documentation_facade::a_file_read_from_a_path_supplies_its_final_component", "documentation_facade::a_display_label_never_becomes_a_logical_filename", "documentation_facade::an_explicit_logical_filename_always_wins", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes"] + }, + { + "name": "facade-provenance-resolves-the-path", + "file": "src/spaces/ast.rs", + "old": " let filename = Path::new(utf8_path).file_name()?.to_str()?;", + "new": " let resolved = std::fs::canonicalize(utf8_path).ok()?;\n let filename = resolved.file_name()?.to_str()?;", + "expect": ["documentation_facade::a_symbolic_link_supplies_its_own_name"] + }, + { + "name": "facade-default-options-passed", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " self.inner.documentation(context, &DocumentationOptions::default())\n", + "expect": ["documentation_facade::an_adopted_tree_is_collected_as_given", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes", "documentation_facade::collection_options_reach_the_collector", "documentation_facade::collection_errors_come_back_unchanged"] + }, + { + "name": "facade-default-context-passed", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " self.inner.documentation(&DocumentationContext::default(), options)\n", + "expect": ["documentation_facade::a_file_read_from_a_path_supplies_its_final_component", "documentation_facade::a_display_label_never_becomes_a_logical_filename", "documentation_facade::an_explicit_logical_filename_always_wins", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes", "documentation_facade::a_long_logical_filename_is_charged_to_the_collection"] + }, + { + "name": "facade-collects-through-the-raw-seam", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " big_code_analysis_ast::documentation::collect(\n self.inner.language(),\n self.inner.ts_tree(),\n self.inner.code(),\n context,\n options,\n )\n", + "expect": ["documentation_facade::a_cancelled_parse_is_reported_after_its_scope_and_the_next_parse_collects"] + }, + { + "name": "facade-empty-root-reported-as-cancelled", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " if self.inner.ts_tree().root_node().end_byte() == 0 {\n return Err(CollectionError::Cancelled);\n }\n self.inner.documentation(context, options)\n", + "expect": ["documentation_facade::an_empty_source_gives_an_empty_index"] + }, + { + "name": "facade-shadows-the-installed-cancel-flag", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " crate::ParseCancel::new().run(|| self.inner.documentation(context, options))\n", + "expect": ["documentation_facade::a_collection_under_a_cancelled_flag_is_cancelled_and_the_parse_stays_complete"] + }, + { + "name": "facade-refuses-an-adopted-tree", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " if self.inner.parse_completion() == big_code_analysis_ast::parser::ParseCompletion::Adopted {\n return Err(CollectionError::Cancelled);\n }\n self.inner.documentation(context, options)\n", + "expect": ["documentation_facade::a_display_label_never_becomes_a_logical_filename", "documentation_facade::an_explicit_logical_filename_always_wins", "documentation_facade::an_adopted_tree_is_collected_as_given", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes", "documentation_facade::collection_errors_come_back_unchanged"] + }, + { + "name": "facade-flattens-errors-to-cancelled", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " self.inner\n .documentation(context, options)\n .map_err(|_| CollectionError::Cancelled)\n", + "expect": ["documentation_facade::collection_errors_come_back_unchanged"] + }, + { + "name": "adopted-tree-is-reparsed", + "file": "src/spaces/ast.rs", + "old": " let inner = AnyParser::from_tree(lang, tree, code)?;", + "new": " let _ = tree;\n let inner = AnyParser::parse(lang, code, None, None)?;", + "expect": ["documentation_facade::an_adopted_tree_is_collected_as_given", "documentation_facade::the_facade_publishes_what_the_collector_publishes_on_the_same_tree_and_bytes", "documentation_facade::collection_errors_come_back_unchanged"] + }, + { + "name": "metrics-run-the-collector", + "file": "src/spaces/ast.rs", + "old": " pub fn metrics(&self, options: MetricsOptions) -> Result {\n", + "new": " pub fn metrics(&self, options: MetricsOptions) -> Result {\n let _ = self.documentation(\n &DocumentationContext::default(),\n &DocumentationOptions::default(),\n );\n", + "expect": ["documentation_facade::the_other_ast_operations_neither_collect_nor_change_what_is_collected"] + }, + { + "name": "cancelled-parse-recorded-as-complete", + "file": "big-code-analysis-ast/src/node/parser_cache.rs", + "old": "(tree, ParseCompletion::Cancelled)", + "new": "(tree, ParseCompletion::Complete)", + "expect": ["documentation_facade::a_cancelled_parse_is_reported_after_its_scope_and_the_next_parse_collects"] + }, + { + "name": "logical-filename-copy-not-charged", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " budget.bytes(character.len_utf8())?;\n copied.push(character);", + "new": " copied.push(character);", + "expect": ["documentation_facade::a_long_logical_filename_is_charged_to_the_collection"] + }, + { + "name": "logical-filename-copy-charged-per-character", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " budget.bytes(character.len_utf8())?;", + "new": " budget.bytes(1)?;", + "expect": ["documentation_facade::a_long_logical_filename_is_charged_to_the_collection"] + }, + { + "name": "observation-counters-do-not-count", + "file": "big-code-analysis-ast/src/observation.rs", + "old": " COUNT.with(|count| count.set(count.get() + 1));", + "new": " COUNT.with(|count| count.set(count.get()));", + "expect": ["documentation_facade::the_other_ast_operations_neither_collect_nor_change_what_is_collected", "documentation_facade::a_long_logical_filename_is_charged_to_the_collection"] + }, + { + "name": "handles-of-another-index-accepted", + "file": "big-code-analysis-ast/src/documentation.rs", + "old": "if std::ptr::eq(&raw const self.scope, reference.scope) {", + "new": "if true || std::ptr::eq(&raw const self.scope, reference.scope) {", + "expect": ["documentation_facade::two_indexes_over_one_ast_are_independent"] + }, + { + "name": "nodes-of-another-tree-not-told-apart", + "file": "big-code-analysis-ast/src/documentation/canonical.rs", + "old": " if node.into_raw().tree != self.root.node().into_raw().tree {", + "new": " if false && node.into_raw().tree != self.root.node().into_raw().tree {", + "expect": ["documentation_facade::two_indexes_over_one_ast_are_independent"] + }, + { + "name": "file-reader-keeps-crlf", + "file": "big-code-analysis-ast/src/tools.rs", + "old": " data.extend_from_slice(start);\n\n file.read_to_end(&mut data)?;\n\n normalize_line_endings(&mut data);", + "new": " data.extend_from_slice(start);\n\n file.read_to_end(&mut data)?;", + "expect": ["documentation_facade::offsets_of_a_file_refer_to_the_normalized_buffer"] + }, + { + "name": "text-copied-twice", + "file": "big-code-analysis-ast/src/documentation/text.rs", + "old": " self.text.push_str(valid);", + "new": " self.text.push_str(valid);\n self.text.push_str(valid);", + "expect": ["documentation_facade::contract_rows_reach_the_index_through_the_root_ast", "documentation_facade::offsets_of_a_file_refer_to_the_normalized_buffer", "documentation_facade::an_adopted_tree_is_collected_as_given", "documentation_facade::two_indexes_over_one_ast_are_independent"] + }, + { + "name": "lexical-scope-is-always-the-root", + "file": "big-code-analysis-ast/src/documentation/collector/assembly.rs", + "old": " lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence,", + "new": " lexical_scope: self.index.canonical.nodes[0].evidence,", + "expect": ["documentation_facade::contract_rows_reach_the_index_through_the_root_ast"] + }, + { + "name": "documents-in-reverse-order", + "file": "big-code-analysis-ast/src/documentation/index.rs", + "old": " self.documents_ordered.iter().map(|&ordinal| FactRef {", + "new": " self.documents_ordered.iter().rev().map(|&ordinal| FactRef {", + "expect": ["documentation_facade::contract_rows_reach_the_index_through_the_root_ast"] + }, + { + "name": "retained-candidates-in-reverse-order", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " self.index.evidence.push(CandidateEvidence {\n fragment,\n disposition: if member.selection == markers::MarkerSelection::Superseded {", + "new": " self.index.evidence.insert(0, CandidateEvidence {\n fragment,\n disposition: if member.selection == markers::MarkerSelection::Superseded {", + "expect": ["documentation_facade::collection_options_reach_the_collector"] + }, + { + "name": "keyword-token-is-a-pending-owner", + "file": "big-code-analysis-ast/src/documentation/index.rs", + "old": " Projection::Unsupported => Err(OwnerError::UnsupportedOwner),", + "new": " Projection::Unsupported => Err(OwnerError::PendingOwner),", + "expect": ["documentation_facade::an_undocumented_function_is_a_supported_owner_and_its_keyword_is_not"] + } + ] +} From a7377f774dad7bede58820962139a2930cf3ae1c Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:59:20 -0800 Subject: [PATCH 107/221] test(documentation): close the gaps an audit found in the facade tests Cover display labels and logical filenames containing directories, uppercase text, and non-ASCII letters; pin the path-backed Ast Debug text. Verify constructor cost, repeated collections, and cancellation for a file read from a path. No production code changes. --- tests/api/documentation_facade.rs | 102 +++++++++++++++--- utils/documentation-facade-unit1-perturb.json | 77 +++++++++++++ 2 files changed, 166 insertions(+), 13 deletions(-) diff --git a/tests/api/documentation_facade.rs b/tests/api/documentation_facade.rs index f46d2c180..23f994ee6 100644 --- a/tests/api/documentation_facade.rs +++ b/tests/api/documentation_facade.rs @@ -505,6 +505,12 @@ fn a_file_read_from_a_path_supplies_its_final_component() { assert_eq!(logical_filename(&collected(&ast)), Some("lib.rs")); } assert_ne!(spellings[1].to_str(), spellings[0].to_str()); + // The name is supplied as it is written: upper case, a space, a hyphen, a second + // dot and a letter outside ASCII all stay. + let as_written = "Año Package-Info.v2.rs"; + let odd = written(directory.path(), as_written, b"///audit\nfn f() {}\n"); + let odd = Ast::from_path(&odd).unwrap(); + assert_eq!(logical_filename(&collected(&odd)), Some(as_written)); // A relative path: cargo runs an integration test in the package root. let relative = Ast::from_path(Path::new("src/lib.rs")).unwrap(); assert_eq!(relative.name(), Some("src/lib.rs")); @@ -533,20 +539,43 @@ fn a_symbolic_link_supplies_its_own_name() { assert_eq!(logical_filename(&index), Some("link.rs")); } +// test-lang-gates: hand-written(rust) — `from_path` picks the grammar from the +// `.rs` extension of the path, and nothing in the body names it +#[cfg(feature = "rust")] +#[test] +fn an_ast_read_from_a_path_prints_its_language_and_display_name_only() { + let directory = tempfile::tempdir().unwrap(); + let path = written(directory.path(), "lib.rs", b"///audit\nfn f() {}\n"); + let read = Ast::from_path(&path).unwrap(); + // This `Ast` holds a provenance. + assert_eq!(logical_filename(&collected(&read)), Some("lib.rs")); + // expected: the language and the display name, as before the field existed; `..` + // stands for every other field. + assert_eq!( + format!("{read:?}"), + format!("Ast {{ language: Rust, name: {:?}, .. }}", path.to_str()) + ); +} + #[cfg(feature = "rust")] #[test] fn a_display_label_never_becomes_a_logical_filename() { let source = b"///audit\nfn f() {}\n"; - let labelled = - Ast::parse(Source::new(LANG::Rust, source).with_name(Some("lib.rs".to_owned()))).unwrap(); - assert_eq!(labelled.name(), Some("lib.rs")); - assert_eq!(logical_filename(&collected(&labelled)), None); - let taken = adopted(source, &[0..source.len()], Some("lib.rs")); - assert_eq!(taken.name(), Some("lib.rs")); - assert_eq!(logical_filename(&collected(&taken)), None); - // The same bytes under the same name, read from a path: the name is known. let directory = tempfile::tempdir().unwrap(); - let read = Ast::from_path(&written(directory.path(), "lib.rs", source)).unwrap(); + let path = written(directory.path(), "lib.rs", source); + // A bare file name, and the whole path of the file read below: a caller may + // label a source with its path. + for label in ["lib.rs", path.to_str().unwrap()] { + let labelled = + Ast::parse(Source::new(LANG::Rust, source).with_name(Some(label.to_owned()))).unwrap(); + assert_eq!(labelled.name(), Some(label)); + assert_eq!(logical_filename(&collected(&labelled)), None); + let taken = adopted(source, &[0..source.len()], Some(label)); + assert_eq!(taken.name(), Some(label)); + assert_eq!(logical_filename(&collected(&taken)), None); + } + // The same bytes read from that path: the name is known. + let read = Ast::from_path(&path).unwrap(); assert_eq!(read.source(), source); assert_eq!(logical_filename(&collected(&read)), Some("lib.rs")); } @@ -565,8 +594,8 @@ fn an_explicit_logical_filename_always_wins() { parsed(source), adopted(source, &[0..source.len()], Some("lib.rs")), ] { - // An empty name is a name too. - for explicit in ["other.rs", ""] { + // A name with a directory is passed on whole, and an empty name is a name too. + for explicit in ["other.rs", "nested/other.rs", ""] { let index = ast.documentation(&named(explicit), &options).unwrap(); assert_eq!(logical_filename(&index), Some(explicit)); } @@ -671,6 +700,40 @@ fn a_collection_under_a_cancelled_flag_is_cancelled_and_the_parse_stays_complete assert_eq!(documents(), Ok(1)); } +// test-lang-gates: hand-written(rust) — `from_path` picks the grammar from the +// `.rs` extension of the path, and nothing in the body names it +#[cfg(feature = "rust")] +#[test] +fn a_file_read_from_a_path_is_cancelled_as_a_parsed_source_is() { + let source = "/// doc\nfn f() {}\n".repeat(200); + let directory = tempfile::tempdir().unwrap(); + let path = written(directory.path(), "lib.rs", source.as_bytes()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let read = Ast::from_path(&path).unwrap(); + // Every collection below is given the name the path supplies. + assert_eq!(logical_filename(&collected(&read)), Some("lib.rs")); + let documents = || { + read.documentation(&context, &options) + .map(|index| index.documents().len()) + }; + let cancel = ParseCancel::new(); + // expected: one comment before each of the 200 functions. + assert_eq!(cancel.run(documents), Ok(200)); + cancel.cancel(); + assert_eq!(cancel.run(documents), Err(CollectionError::Cancelled)); + assert_eq!(documents(), Ok(200)); + // The same file parsed under the cancelled flag: the parse did stop, and the + // collection reports it after the scope of the flag. + let stopped = cancel.run(|| Ast::from_path(&path).unwrap()); + assert_eq!(stopped.as_tree_sitter().root_node().byte_range(), 0..0); + assert_eq!(stopped.source(), source.as_bytes()); + assert_eq!( + stopped.documentation(&context, &options).err(), + Some(CollectionError::Cancelled) + ); +} + #[cfg(feature = "rust")] #[test] fn an_adopted_tree_is_collected_as_given() { @@ -755,7 +818,13 @@ fn two_indexes_over_one_ast_are_independent() { #[cfg(feature = "rust")] #[test] fn the_other_ast_operations_neither_collect_nor_change_what_is_collected() { - let ast = parsed(TESTS_AND_CODE); + let directory = tempfile::tempdir().unwrap(); + let path = written(directory.path(), "lib.rs", TESTS_AND_CODE); + let unbuilt = observations(); + // Read from a path, so that the view below holds a supplied logical filename. + // `from_path` builds through `Ast::parse`; the third constructor adopts a tree. + let ast = Ast::from_path(&path).unwrap(); + let whole = adopted(TESTS_AND_CODE, &[0..TESTS_AND_CODE.len()], None); let idle = observations(); let before = collected(&ast); let collecting = observations(); @@ -771,6 +840,13 @@ fn the_other_ast_operations_neither_collect_nor_change_what_is_collected() { assert_eq!(collecting.owner_projections - idle.owner_projections, 3); // The checkpoint total has no closed form. assert_ne!(collecting.polls - idle.polls, 0); + // Building an `Ast` collects nothing, whichever constructor builds it. + assert_eq!(whole.source(), ast.source()); + assert_eq!(idle.visits - unbuilt.visits, 0); + assert_eq!(idle.renders - unbuilt.renders, 0); + assert_eq!(idle.owner_projections - unbuilt.owner_projections, 0); + assert_eq!(idle.polls - unbuilt.polls, 0); + assert_eq!(logical_filename(&before), Some("lib.rs")); let view = published(&before); let metrics = |options: MetricsOptions| ast.metrics(options).unwrap().metrics.loc.dloc(); @@ -821,7 +897,7 @@ fn the_other_ast_operations_neither_collect_nor_change_what_is_collected() { assert_eq!(after.owner_projections - collecting.owner_projections, 0); assert_eq!(after.polls - collecting.polls, 0); // The buffer is the one that was parsed. The index taken before is still whole, - // and a new one says the same. + // and a new one says the same, the supplied name included. assert_eq!(ast.source(), TESTS_AND_CODE); assert_eq!(published(&before), view); assert_eq!(published(&collected(&ast)), view); diff --git a/utils/documentation-facade-unit1-perturb.json b/utils/documentation-facade-unit1-perturb.json index 65779ff69..eff16b087 100644 --- a/utils/documentation-facade-unit1-perturb.json +++ b/utils/documentation-facade-unit1-perturb.json @@ -191,6 +191,83 @@ "old": " Projection::Unsupported => Err(OwnerError::UnsupportedOwner),", "new": " Projection::Unsupported => Err(OwnerError::PendingOwner),", "expect": ["documentation_facade::an_undocumented_function_is_a_supported_owner_and_its_keyword_is_not"] + }, + { + "name": "facade-label-with-a-directory-stored-as-provenance", + "file": "src/spaces/ast.rs", + "old": " let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?;\n Ok(Self {\n inner,\n name,\n provenance: None,\n })", + "new": " let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?;\n Ok(Self {\n provenance: name\n .as_deref()\n .filter(|label| label.contains(std::path::MAIN_SEPARATOR))\n .and_then(PathProvenance::of),\n inner,\n name,\n })", + "expect": ["documentation_facade::a_display_label_never_becomes_a_logical_filename"] + }, + { + "name": "facade-adopted-label-with-a-directory-stored-as-provenance", + "file": "src/spaces/ast.rs", + "old": " let inner = AnyParser::from_tree(lang, tree, code)?;\n Ok(Self {\n inner,\n name,\n provenance: None,\n })", + "new": " let inner = AnyParser::from_tree(lang, tree, code)?;\n Ok(Self {\n provenance: name\n .as_deref()\n .filter(|label| label.contains(std::path::MAIN_SEPARATOR))\n .and_then(PathProvenance::of),\n inner,\n name,\n })", + "expect": ["documentation_facade::a_display_label_never_becomes_a_logical_filename"] + }, + { + "name": "facade-explicit-name-reduced-to-its-final-component", + "file": "src/spaces/ast.rs", + "old": " let context = match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,\n _ => context,\n };\n", + "new": " let reduced = context\n .logical_filename\n .as_deref()\n .and_then(|explicit| Path::new(explicit).file_name()?.to_str())\n .map(|component| DocumentationContext {\n logical_filename: Some(component.to_owned()),\n });\n let context = match (&self.provenance, &reduced) {\n (_, Some(component)) => component,\n (Some(PathProvenance(read_from)), None) if context.logical_filename.is_none() => {\n read_from\n }\n _ => context,\n };\n", + "expect": ["documentation_facade::an_explicit_logical_filename_always_wins"] + }, + { + "name": "facade-provenance-lowercased", + "file": "src/spaces/ast.rs", + "old": " logical_filename: Some(filename.to_owned()),", + "new": " logical_filename: Some(filename.to_lowercase()),", + "expect": ["documentation_facade::a_file_read_from_a_path_supplies_its_final_component"] + }, + { + "name": "ast-debug-names-the-provenance", + "file": "src/spaces/ast.rs", + "old": " .field(\"name\", &self.name)\n", + "new": " .field(\"name\", &self.name)\n .field(\"provenance\", &self.provenance.is_some())\n", + "expect": ["documentation_facade::an_ast_read_from_a_path_prints_its_language_and_display_name_only"] + }, + { + "name": "facade-provenance-supplied-once-per-display-name", + "file": "src/spaces/ast.rs", + "old": " let context = match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,\n _ => context,\n };\n", + "new": " static SUPPLIED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new());\n let repeated = self.name.as_ref().is_some_and(|name| {\n SUPPLIED.lock().is_ok_and(|mut supplied| {\n let known = supplied.contains(name);\n if !known {\n supplied.push(name.clone());\n }\n known\n })\n });\n let context = match &self.provenance {\n Some(PathProvenance(read_from)) if !repeated && context.logical_filename.is_none() => {\n read_from\n }\n _ => context,\n };\n", + "expect": ["documentation_facade::the_other_ast_operations_neither_collect_nor_change_what_is_collected"] + }, + { + "name": "parse-runs-the-collector", + "file": "src/spaces/ast.rs", + "old": " let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?;\n Ok(Self {\n inner,\n name,\n provenance: None,\n })", + "new": " let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?;\n let _ = inner.documentation(\n &DocumentationContext::default(),\n &DocumentationOptions::default(),\n );\n Ok(Self {\n inner,\n name,\n provenance: None,\n })", + "expect": ["documentation_facade::the_other_ast_operations_neither_collect_nor_change_what_is_collected"] + }, + { + "name": "adoption-runs-the-collector", + "file": "src/spaces/ast.rs", + "old": " let inner = AnyParser::from_tree(lang, tree, code)?;\n Ok(Self {\n inner,\n name,\n provenance: None,\n })", + "new": " let inner = AnyParser::from_tree(lang, tree, code)?;\n let _ = inner.documentation(\n &DocumentationContext::default(),\n &DocumentationOptions::default(),\n );\n Ok(Self {\n inner,\n name,\n provenance: None,\n })", + "expect": ["documentation_facade::the_other_ast_operations_neither_collect_nor_change_what_is_collected"] + }, + { + "name": "from-path-runs-the-collector", + "file": "src/spaces/ast.rs", + "old": " ast.provenance = provenance;\n", + "new": " ast.provenance = provenance;\n let _ = ast.documentation(\n &DocumentationContext::default(),\n &DocumentationOptions::default(),\n );\n", + "expect": ["documentation_facade::the_other_ast_operations_neither_collect_nor_change_what_is_collected"] + }, + { + "name": "facade-supplied-provenance-collects-through-the-raw-seam", + "file": "src/spaces/ast.rs", + "old": " let context = match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,\n _ => context,\n };\n self.inner.documentation(context, options)\n", + "new": " match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => {\n big_code_analysis_ast::documentation::collect(\n self.inner.language(),\n self.inner.ts_tree(),\n self.inner.code(),\n read_from,\n options,\n )\n }\n _ => self.inner.documentation(context, options),\n }\n", + "expect": ["documentation_facade::a_file_read_from_a_path_is_cancelled_as_a_parsed_source_is"] + }, + { + "name": "facade-supplied-provenance-shadows-the-installed-cancel-flag", + "file": "src/spaces/ast.rs", + "old": " let context = match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => read_from,\n _ => context,\n };\n self.inner.documentation(context, options)\n", + "new": " match &self.provenance {\n Some(PathProvenance(read_from)) if context.logical_filename.is_none() => {\n crate::ParseCancel::new().run(|| self.inner.documentation(read_from, options))\n }\n _ => self.inner.documentation(context, options),\n }\n", + "expect": ["documentation_facade::a_file_read_from_a_path_is_cancelled_as_a_parsed_source_is"] } ] } From 13e4b2ea026844f77509040b14a5e8245241b17e Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:38:45 -0800 Subject: [PATCH 108/221] test(documentation): guard the legacy rows of Go members and pin what stays without an owner Guard the legacy LOC rows and documentation counters for Go member sources. Pin retained candidate ordering, unsupported member forms, pending error cases, and the Go grammar shapes used by the collector. Add a perturbation manifest that proves the legacy guard detects changes to those rows. --- .../src/documentation/collector/go_tests.rs | 736 +++++++++++++++++- src/metrics/loc/documentation_tests.rs | 301 ++++++- ...documentation-go-unit2-legacy-perturb.json | 49 ++ 3 files changed, 1083 insertions(+), 3 deletions(-) create mode 100644 utils/documentation-go-unit2-legacy-perturb.json diff --git a/big-code-analysis-ast/src/documentation/collector/go_tests.rs b/big-code-analysis-ast/src/documentation/collector/go_tests.rs index 4184edc07..ddc1a205c 100644 --- a/big-code-analysis-ast/src/documentation/collector/go_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/go_tests.rs @@ -1,8 +1,10 @@ //! Go documentation in the source view: which declaration owns a comment, the text of //! the document and where each part of that text comes from. Every source is collected -//! through both entry points, except in the last test, which collects nothing and pins +//! through both entry points, except in the grammar tests, which collect nothing and pin //! the parse-tree shapes the other tests rely on. +#![allow(clippy::single_range_in_vec_init, clippy::type_complexity)] + #[cfg(feature = "go")] use crate::documentation::*; #[cfg(feature = "go")] @@ -1183,3 +1185,735 @@ fn go_grammar_shapes_the_unit_relies_on() { ); } } + +#[cfg(feature = "go")] +const AWAITS_PROJECTION: &str = "Selected local or wrapper form awaits owner projection"; + +#[cfg(feature = "go")] +const NEEDS_PROJECTION: &str = "Recognized declaration requires a semantic projection"; + +#[cfg(feature = "go")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +/// Every document as its fragments and its text, for a parse the view does not read. +#[cfg(feature = "go")] +fn texts(index: &DocumentationIndex<'_>) -> Vec<(Vec>, String)> { + index + .documents() + .map(|document| { + let fragments = (0..document.get().fragment_count()) + .map(|at| { + let fragment = index.facts().document_fragment(document, at).unwrap(); + fragment_span(fragment.get()) + }) + .collect(); + let complete = index.complete_text(document).unwrap().unwrap(); + (fragments, complete.text().to_owned()) + }) + .collect() +} + +/// One owner as text: a node as kind and byte range; a field slot as its ordinal, the +/// byte range of each piece of its name, and the node that encloses it; the file. +#[cfg(feature = "go")] +fn owner_text<'s>(index: &DocumentationIndex<'s>, owner: FactRef<'_, Owner<'s>>) -> String { + match owner.get() { + Owner::Node(declared) => { + let (kind, range) = site(declared.node()); + format!("{kind} {}..{}", range.start, range.end) + } + Owner::Slot(slot) => { + assert_eq!(slot.role, SlotRole::Field); + assert!(!slot.source.has_excluded_gap()); + let pieces: Vec<_> = slot + .source + .pieces() + .iter() + .map(|piece| format!("{}..{}", piece.range().start, piece.range().end)) + .collect(); + let enclosing = index.facts().slot_enclosing(owner).unwrap(); + format!( + "slot {} {} in {}", + slot.ordinal, + pieces.join(","), + owner_text(index, enclosing) + ) + } + Owner::File(file) => { + let (kind, range) = site(file.node()); + format!("file {kind} {}..{}", range.start, range.end) + } + other => panic!("a node, a field slot or the file, found {other:?}"), + } +} + +/// One association where the view does not reach: the position of its document, its +/// resolution, its owners, its binding and its lexical scope. It may have no owner. +#[cfg(feature = "go")] +type Edge = ( + usize, + Resolution, + Vec, + (&'static str, Range), + (&'static str, Range), +); + +#[cfg(feature = "go")] +fn edges(index: &DocumentationIndex<'_>) -> Vec { + let facts = index.facts(); + index + .associations() + .map(|association| { + let attachment = association.get(); + assert_eq!(attachment.convention.name(), "GoDoc"); + assert_eq!(attachment.publication, Publication::Unknown); + let document = facts.associated_document(association).unwrap(); + let owners = (0..attachment.owner_count()) + .map(|at| owner_text(index, facts.associated_owner(association, at).unwrap())) + .collect(); + ( + index + .documents() + .position(|known| known == document) + .unwrap(), + attachment.resolution, + owners, + site(attachment.binding.unwrap().node()), + site(attachment.lexical_scope.node()), + ) + }) + .collect() +} + +/// One pending assessment: its reason, its node and the position of its document. +#[cfg(feature = "go")] +type Pending = (&'static str, (&'static str, Range), Option); + +/// The pending assessments in the order of their nodes; the contract states no order +/// for them. Each one here is on the owner axis. +#[cfg(feature = "go")] +fn pending<'i, 's: 'i>( + index: &'i DocumentationIndex<'s>, + found: impl Iterator>>, +) -> Vec { + let mut all: Vec = found + .map(|assessment| { + assert_eq!(assessment.get().axis, AssessmentAxis::Owner); + let document = index.assessed_document(assessment).unwrap(); + ( + assessment.get().reason, + site(assessment.get().node.unwrap().node()), + document.map(|document| { + index + .documents() + .position(|known| known == document) + .unwrap() + }), + ) + }) + .collect(); + all.sort_by_key(|(reason, (_, range), document)| (range.start, range.end, *reason, *document)); + all +} + +/// Every retained candidate as disposition and byte range. +#[cfg(feature = "go")] +fn kept(index: &DocumentationIndex<'_>) -> Vec<(CandidateDisposition, Range)> { + index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect() +} + +#[cfg(feature = "go")] +#[test] +fn go_retained_candidates_stay_in_source_order() { + // Two comments that document nothing: one follows code on its row, the other is + // above a blank row. + let unbound: &[u8] = b"package p\nvar x = 1 // t\n\n// a\n\nfunc F() {}\n"; + let mut expected = View::default(); + assert_eq!(view(unbound), expected); + expected.evidence.extend([ + (CandidateDisposition::Unattached, 20..24), + (CandidateDisposition::Unattached, 26..30), + ]); + assert_eq!(retained(unbound, Retain::Unbound), expected); + // A comment above a blank row and the directive of a selected run: one option keeps + // each, and the list is in source order whatever the dispositions are. + let mixed: &[u8] = b"package p\n// a\n\n// b\n//go:generate tool\nfunc F() {}\n"; + let mut expected = owned( + comment(16..20, "b", [(0..1, Copied(19..20))]), + "function_declaration", + 40..51, + ); + assert_eq!(view(mixed), expected); + expected.evidence.extend([ + (CandidateDisposition::Unattached, 10..14), + (CandidateDisposition::Directive, 21..39), + ]); + assert_eq!(retained(mixed, Retain::Both), expected); +} + +/// Asserts that the source publishes nothing by default, that none of the nodes is an +/// owner, and that each comment is kept on request, in order. The kept comments show +/// that the collector saw them, so the empty view is an answer. +#[cfg(feature = "go")] +fn assert_owns_nothing(source: &[u8], nodes: &[(&str, Range)], comments: &[Range]) { + let name = source.escape_ascii(); + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + let mut expected = View::default(); + assert_eq!(agreed(&both), expected, "{name}"); + for index in &both { + for (kind, range) in nodes { + assert_eq!( + index + .node_projection(node_at(&parser, kind, range.clone())) + .err(), + Some(OwnerError::UnsupportedOwner), + "{kind} {range:?} in {name}" + ); + } + } + expected.evidence.extend( + comments + .iter() + .map(|range| (CandidateDisposition::Unattached, range.clone())), + ); + assert_eq!(retained(source, Retain::Unbound), expected, "{name}"); +} + +#[cfg(feature = "go")] +#[test] +fn go_members_declared_in_a_function_body_own_nothing() { + let cases: [(&[u8], &[(&str, Range)], &[Range]); 2] = [ + ( + b"package p\nfunc F() {\ntype T struct {\n// a\nX int\n}\n}\n", + &[("field_declaration", 42..47)], + &[37..41], + ), + ( + b"package p\nfunc F() {\ntype I interface {\n// m\nM()\n// e\nio.Reader\n}\n}\n", + &[("method_elem", 45..48), ("type_elem", 54..63)], + &[40..44, 49..53], + ), + ]; + for (source, members, comments) in cases { + assert_owns_nothing(source, members, comments); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_elements_without_a_leading_name_and_signature_parts_own_nothing() { + // An interface element that does not open with a name, a type argument and a + // parameter: Go gives none of them a lead comment, and none is an owner here. + let cases: [(&[u8], &[(&str, Range)], &[Range]); 4] = [ + ( + b"package p\ntype I interface {\n// u\n~int\n}\n", + &[("type_elem", 34..38)], + &[29..33], + ), + ( + b"package p\ntype I interface {\n// a\n~int | string\n// b\n*T\n// c\n[]int\n}\n", + &[ + ("type_elem", 34..47), + ("type_elem", 53..55), + ("type_elem", 61..66), + ], + &[29..33, 48..52, 56..60], + ), + ( + b"package p\nvar v Map[\n// c\nstring, int]\n", + &[("type_elem", 26..32), ("type_elem", 34..37)], + &[21..25], + ), + ( + b"package p\nfunc F(\n// p\nx int) {}\n", + &[("parameter_declaration", 23..28)], + &[18..22], + ), + ]; + for (source, parts, comments) in cases { + assert_owns_nothing(source, parts, comments); + } +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_member_with_a_syntax_error_stays_a_pending_owner() { + // Each member holds an error of its own: an `ERROR` node in the first four, a + // missing element type in the last. The type that holds the member has the error + // too, so the declaration and its spec are pending with it. + struct Case<'a> { + source: &'a [u8], + member: (&'static str, Range), + // The error inside the member: an `ERROR` node, or the zero-width missing node. + error: (&'static str, Range), + comment: Range, + text: &'a str, + scope: (&'static str, Range), + declaration: Range, + spec: Range, + // The comment inside the broken method, kept on request. + inside: &'a [Range], + } + let cases = [ + Case { + source: b"package p\ntype S struct {\n// a\nX %% int\n}\n", + member: ("field_declaration", 31..39), + error: ("ERROR", 33..35), + comment: 26..30, + text: "a", + scope: ("field_declaration_list", 24..41), + declaration: 10..41, + spec: 15..41, + inside: &[], + }, + Case { + source: b"package p\ntype S struct {\n// e\nio.%%Reader\n}\n", + member: ("field_declaration", 31..42), + error: ("ERROR", 34..36), + comment: 26..30, + text: "e", + scope: ("field_declaration_list", 24..44), + declaration: 10..44, + spec: 15..44, + inside: &[], + }, + Case { + source: b"package p\ntype I interface {\n// m\nM(\n// e\nio.Reader\n}\n", + member: ("method_elem", 34..51), + error: (")", 51..51), + comment: 29..33, + text: "m", + scope: ("interface_type", 17..53), + declaration: 10..53, + spec: 15..53, + inside: &[37..41], + }, + Case { + source: b"package p\ntype I interface {\n// e\nio.%%Reader\n}\n", + member: ("type_elem", 34..45), + error: ("ERROR", 37..39), + comment: 29..33, + text: "e", + scope: ("interface_type", 17..47), + declaration: 10..47, + spec: 15..47, + inside: &[], + }, + Case { + source: b"package p\ntype S struct {\n// d\nX []\n}\n", + member: ("field_declaration", 31..35), + error: ("type_identifier", 35..35), + comment: 26..30, + text: "d", + scope: ("field_declaration_list", 24..37), + declaration: 10..37, + spec: 15..37, + inside: &[], + }, + ]; + for case in cases { + let name = case.source.escape_ascii(); + let parser = AnyParser::parse(LANG::Go, case.source.to_vec(), None, None).unwrap(); + let member = node_at(&parser, case.member.0, case.member.1.clone()); + let error = node_at(&parser, case.error.0, case.error.1.clone()); + assert!(member.has_error(), "{name}"); + assert!( + error.is_error() || error.is_missing() || error.has_error(), + "{name}" + ); + assert!( + member.start_byte() <= error.start_byte() && error.end_byte() <= member.end_byte(), + "{name}" + ); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + for index in &indexes(&parser, options) { + assert_eq!( + texts(index), + [(vec![case.comment.clone()], case.text.to_owned())], + "{name}" + ); + // The error is the reason the stream gives, so the association exists; it + // has no owner, because its target is pending. + assert_eq!( + edges(index), + [( + 0, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + vec![], + case.member.clone(), + case.scope.clone(), + )], + "{name}" + ); + assert_eq!( + pending(index, index.assessments()), + [ + ( + NEEDS_PROJECTION, + ("type_declaration", case.declaration.clone()), + None + ), + (NEEDS_PROJECTION, ("type_spec", case.spec.clone()), None), + (NEEDS_PROJECTION, case.member.clone(), None), + (AWAITS_PROJECTION, case.member.clone(), Some(0)), + ], + "{name}" + ); + let inside: Vec<_> = case + .inside + .iter() + .map(|range| (CandidateDisposition::Unattached, range.clone())) + .collect(); + assert_eq!(kept(index), inside, "{name}"); + assert!(index.node_projection(member).unwrap().pending(), "{name}"); + assert_eq!( + index.node_owners(member).err(), + Some(OwnerError::PendingOwner), + "{name}" + ); + // expected: the file and the package clause. + assert_eq!(index.facts().owners().len(), 2, "{name}"); + } + } +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_member_grammar_shapes_the_unit_relies_on() { + // The names of a field declaration are its children of kind `field_identifier`, in + // order, and they are the children the grammar gives the field `name`. A field that + // embeds a type has none, and `_` is a name like any other. + let source: &[u8] = b"package p\ntype S struct {\nX, Y int `t`\n_ int\n*io.Reader\nN struct {\nA int\n}\n}\ntype I interface {\nM() int\nio.Reader\n}\n"; + let parser = clean(source); + let members: [(&str, Range, &[Range]); 7] = [ + ("field_declaration", 26..38, &[26..27, 29..30]), + ("field_declaration", 39..44, &[39..40]), + ("field_declaration", 45..55, &[]), + ("field_declaration", 56..74, &[56..57]), + ("field_declaration", 67..72, &[67..68]), + // The name of a method is a `field_identifier` as well, so the kind of the + // member decides whether such a child names a field. + ("method_elem", 96..103, &[96..97]), + ("type_elem", 104..113, &[]), + ]; + for (kind, range, names) in members { + let member = node_at(&parser, kind, range.clone()); + let mut cursor = member.walk(); + let mut by_field = Vec::new(); + let mut by_kind = Vec::new(); + assert!(cursor.goto_first_child()); + loop { + if cursor.field_name() == Some("name") { + by_field.push(cursor.node().byte_range()); + } + if cursor.node().kind() == "field_identifier" { + by_kind.push(cursor.node().byte_range()); + } + if !cursor.goto_next_sibling() { + break; + } + } + assert_eq!(by_kind, names, "{kind} {range:?}"); + assert_eq!(by_field, names, "{kind} {range:?}"); + } + assert_eq!(&source[39..40], b"_"); + // expected: the seven members above are every member of the source. + assert_eq!( + parser + .root_node() + .preorder() + .filter(|found| matches!( + found.kind(), + "field_declaration" | "method_elem" | "type_elem" + )) + .count(), + 7 + ); + + // A comment between the parts of a member is a child of the member. Only a block + // comment that holds a line feed ends on a later row than it starts on; a carriage + // return alone is no line end in Go, and the grammar counts no row for it. + let inside: [(&[u8], Range, (&str, Range), bool); 6] = [ + ( + b"package p\ntype S struct {\n// d\nX /* a\n b */ int\n}\n", + 33..43, + ("field_declaration", 31..47), + true, + ), + ( + b"package p\ntype I interface {\n// m\nM() /* a\n b */ int\n}\n", + 38..48, + ("method_elem", 34..52), + true, + ), + ( + b"package p\ntype I interface {\n// e\nA | /* a\n b */ B\n}\n", + 38..48, + ("type_elem", 34..50), + true, + ), + ( + b"package p\ntype S struct {\n// d\nX, /* c */ Y int\n}\n", + 34..41, + ("field_declaration", 31..47), + false, + ), + ( + b"package p\ntype S struct {\n// a\nX,\n// b\nY int\n}\n", + 34..38, + ("field_declaration", 31..44), + false, + ), + ( + b"package p\ntype S struct {\n// d\nX /* a\r b */ int\n}\n", + 33..43, + ("field_declaration", 31..47), + false, + ), + ]; + for (source, comment, member, breaks) in inside { + let parser = clean(source); + let comment = node_at(&parser, "comment", comment); + assert_eq!( + comment.parent().map(site), + Some(member), + "{}", + source.escape_ascii() + ); + assert_eq!( + comment.start_position().row != comment.end_position().row, + breaks, + "{}", + source.escape_ascii() + ); + } + + // A comment inside a function type is a child of that type and not of the member. + let parser = clean(b"package p\ntype S struct {\n// d\nX func() /* a\n b */ int\n}\n"); + let comment = node_at(&parser, "comment", 40..50); + assert_eq!(comment.parent().map(site), Some(("function_type", 33..54))); + assert_eq!( + comment.parent().and_then(|found| found.parent()).map(site), + Some(("field_declaration", 31..54)) + ); + + // A line feed after a name ends the member, as it does in Go: two declarations that + // each embed a type, and no field named `X`. + let parser = clean(b"package p\ntype S struct {\n// d\nX\nint\n}\n"); + let fields = named_in(node_at(&parser, "field_declaration_list", 24..38)); + assert_eq!( + shapes(&fields), + [ + ("comment", 26..30), + ("field_declaration", 31..32), + ("field_declaration", 33..36), + ] + ); + assert_eq!(shapes(&named_in(fields[1])), [("type_identifier", 31..32)]); + assert_eq!(shapes(&named_in(fields[2])), [("type_identifier", 33..36)]); +} + +/// The tokens below a node, in source order, each with whether the grammar names it: a +/// node without children, or a string literal as one token. Comments are left out. +#[cfg(feature = "go")] +fn tokens(node: tree_sitter::Node<'_>) -> Vec<(&'static str, bool)> { + let mut found = Vec::new(); + let mut open = vec![node]; + while let Some(next) = open.pop() { + let string = matches!( + next.kind(), + "raw_string_literal" | "interpreted_string_literal" + ); + if next.kind() == "comment" { + continue; + } + if next.child_count() == 0 || string { + found.push((next.kind(), next.is_named())); + } else { + let children: Vec<_> = next.children(&mut next.walk()).collect(); + open.extend(children.into_iter().rev()); + } + } + found +} + +/// The kind of every child of a node, named or not, in order. +#[cfg(feature = "go")] +fn child_kinds(node: tree_sitter::Node<'_>) -> Vec<&'static str> { + node.children(&mut node.walk()) + .map(|child| child.kind()) + .collect() +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_token_shapes_the_line_end_rule_relies_on() { + // Go ends a line after an identifier, a literal, `)`, `]` or `}`. In the pinned + // grammar the identifiers and the literals are exactly the tokens it names: every + // keyword, operator and bracket is a token without a name. + let source: &[u8] = b"package p\ntype S struct {\nX [iota + len(nil)]int `a`\nY [true]map[string]*pkg.T \"b\"\nZ [1.5 + 2i + 'c' + 3]chan<- func(a ...int) (r bool)\n_ struct{}\nW interface{ ~int | G[int, string] }\nV [false]int\n}\n"; + let parser = clean(source); + let list = node_at(&parser, "field_declaration_list", 24..198); + let mut named = std::collections::BTreeSet::new(); + let mut unnamed = std::collections::BTreeSet::new(); + for (kind, is_named) in tokens(list) { + if is_named { + named.insert(kind); + } else { + unnamed.insert(kind); + } + } + assert_eq!( + named.into_iter().collect::>(), + [ + "false", + "field_identifier", + "float_literal", + "identifier", + "imaginary_literal", + "int_literal", + "interpreted_string_literal", + "iota", + "nil", + "package_identifier", + "raw_string_literal", + "rune_literal", + "true", + "type_identifier", + ] + ); + assert_eq!( + unnamed.into_iter().collect::>(), + [ + "(", + ")", + "*", + "+", + ",", + ".", + "...", + "<-", + "[", + "]", + "chan", + "func", + "interface", + "map", + "struct", + "{", + "|", + "}", + "~", + ] + ); + + // A string literal is a node with children, also when it is empty (an empty raw + // string has a content node without a byte), so it is no token of its own accord; + // the rule takes it as one. A raw string may span rows. + let source: &[u8] = b"package p\ntype S struct {\nX int `a\nb`\nY int \"\"\nZ int ``\n}\n"; + let parser = clean(source); + let strings: [(&str, Range, &[&str]); 3] = [ + ( + "raw_string_literal", + 32..37, + &["`", "raw_string_literal_content", "`"], + ), + ("interpreted_string_literal", 44..46, &["\"", "\""]), + ( + "raw_string_literal", + 53..55, + &["`", "raw_string_literal_content", "`"], + ), + ]; + for (kind, range, children) in strings { + let string = node_at(&parser, kind, range); + assert!(string.is_named()); + assert_eq!(child_kinds(string), children); + } + let spanning = node_at(&parser, "raw_string_literal", 32..37); + assert_eq!( + (spanning.start_position().row, spanning.end_position().row), + (2, 3) + ); + + // The members of a nested struct or interface type and the statements of a function + // literal stand between a `{` and a `}` that are children of one node; in an + // interface type the keyword is a child of that node as well. + let source: &[u8] = b"package p\ntype S struct {\nA struct {\nX int\n}\nI interface {\nM()\n}\nF [len(func() int {\nreturn 1\n}())]int\n}\n"; + let parser = clean(source); + let bodies: [(&str, Range, &[&str]); 3] = [ + ( + "field_declaration_list", + 35..44, + &["{", "field_declaration", "}"], + ), + ( + "interface_type", + 47..64, + &["interface", "{", "method_elem", "}"], + ), + ("block", 83..95, &["{", "statement_list", "}"]), + ]; + for (kind, range, children) in bodies { + assert_eq!(child_kinds(node_at(&parser, kind, range)), children); + } + + // After the `]` of an array length the grammar reads on past a line end, where Go + // ends the line: one field declaration over two rows. + let parser = clean(b"package p\ntype S struct {\n// d\nX [2]\nint\n}\n"); + let field = node_at(&parser, "field_declaration", 31..40); + assert_eq!( + shapes(&named_in(field)), + [("field_identifier", 31..32), ("array_type", 33..40)] + ); + let array = node_at(&parser, "array_type", 33..40); + assert_eq!( + child_kinds(array), + ["[", "int_literal", "]", "type_identifier"] + ); + let close = array.child(2).unwrap(); + let element = array.child(3).unwrap(); + assert_eq!( + (close.end_position().row, element.start_position().row), + (3, 4) + ); + + // With a name between the brackets the grammar reads an embedded generic type, which + // ends at the line end as in Go: two field declarations. + let parser = clean(b"package p\ntype S struct {\n// d\nX [N]\nT\n}\n"); + let list = node_at(&parser, "field_declaration_list", 24..40); + assert_eq!( + shapes(&named_in(list)), + [ + ("comment", 26..30), + ("field_declaration", 31..36), + ("field_declaration", 37..38), + ] + ); + let embedded = node_at(&parser, "field_declaration", 31..36); + assert_eq!(shapes(&named_in(embedded)), [("generic_type", 31..36)]); + + // A comment after the parameters of a function type is a child of that type, below + // the member, and the result after it is read into the same type. + let parser = + clean(b"package p\ntype I interface {\n// d\nE | func() /* stop\n here */ B | C\n}\n"); + let inside = node_at(&parser, "comment", 45..61); + let function = inside.parent().unwrap(); + assert_eq!(site(function), ("function_type", 38..63)); + assert_eq!(site(function.parent().unwrap()), ("type_elem", 34..67)); +} diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index 903c43b21..793307e1a 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -607,8 +607,11 @@ fn documentation_go_source_and_legacy_views_are_independent() { source: &'a [u8], loc: [u64; 6], dloc_rows: &'a [usize], - // A run is a maximal sequence of comments in which each one starts on the row - // where the one before it ends, or on the next row. + // A run is a maximal sequence of comments with no other node between them, in + // which each one starts on the row where the one before it ends, or on the next + // row. Code before the first comment on its row does not split the run, so the + // rows `/* t1` and `{ // t` have one each; the comment after code is in the run + // and in no document. comment_runs: usize, } let counters = || { @@ -2601,3 +2604,297 @@ fn documentation_kotlin_source_and_legacy_views_are_independent() { assert_ne!(renders_total, 0); assert_ne!(evidence_total, 0); } + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn documentation_go_member_sources_keep_their_legacy_rows() { + use big_code_analysis_ast::documentation::streaming::positional::{ + evidence_built, members_materialized, positional_runs_collected, + }; + use big_code_analysis_ast::documentation::{ + DocumentationContext, DocumentationOptions, included_range_visits, observations, + }; + // Struct fields and interface elements, as the source-view tests of + // `go_tests.rs` use them. The legacy rows were measured before the collector gave + // these members owners, and they do not depend on it. + struct Row<'a> { + source: &'a [u8], + syntax_error: bool, + loc: [u64; 6], + dloc_rows: &'a [usize], + documents: usize, + // The rule of `comment_runs` in the test above. + comment_runs: usize, + } + let counters = || { + [ + observations().visits, + observations().renders, + evidence_built::observed(), + members_materialized::observed(), + positional_runs_collected::observed(), + included_range_visits::observed(), + ] + }; + let sources = [ + Row { + source: b"package p\ntype S struct {\n// audit\nX int\n}\n", + syntax_error: false, + loc: [5, 4, 0, 1, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 1, + }, + // `_ int` separates the two comments. + Row { + source: b"package p\ntype S struct {\n// pad\n_ int\n// two\n_, X int\n}\n", + syntax_error: false, + loc: [7, 5, 0, 2, 0, 2], + dloc_rows: &[2, 4], + documents: 2, + comment_runs: 2, + }, + Row { + source: b"package p\ntype S struct {\n// audit\nio.Reader\n}\n", + syntax_error: false, + loc: [5, 4, 0, 1, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 1, + }, + // An element separates each comment from the next. + Row { + source: b"package p\ntype I interface {\n// a\nint | string\n// c\nG[int]\n// d\nE\n// f\nM(x int) (int, error)\n// g\nMap[string, int]\n}\n", + syntax_error: false, + loc: [13, 8, 0, 5, 0, 5], + dloc_rows: &[2, 4, 6, 8, 10], + documents: 5, + comment_runs: 5, + }, + // The second comment is inside the method that follows the first. + Row { + source: b"package p\ntype I interface {\n// m\nM(s struct {\n// d\nX int\n})\n}\n", + syntax_error: false, + loc: [8, 6, 0, 2, 0, 2], + dloc_rows: &[2, 4], + documents: 2, + comment_runs: 2, + }, + // `// t` follows code on row 2 and `// d` is on the next row: one run, and + // only row 3 documents. + Row { + source: b"package p\ntype S struct {\nX int // t\n// d\nY int\n}\n", + syntax_error: false, + loc: [6, 5, 0, 2, 0, 1], + dloc_rows: &[3], + documents: 1, + comment_runs: 1, + }, + // A blank row separates the two comments, and another separates the second + // from the field. + Row { + source: b"package p\ntype S struct {\nX int // t\n\n// lost\n\nY int\n}\n", + syntax_error: false, + loc: [8, 5, 0, 2, 2, 0], + dloc_rows: &[], + documents: 0, + comment_runs: 2, + }, + // The second comment is inside the field that follows the first. + Row { + source: b"package p\ntype S struct {\n// d\nX, /* c */ Y int\n}\n", + syntax_error: false, + loc: [5, 4, 0, 2, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 2, + }, + Row { + source: b"package p\ntype S struct {\n// d\nX /* a\n b */ int\n}\n", + syntax_error: false, + loc: [6, 5, 0, 3, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 2, + }, + Row { + source: b"package p\ntype S struct {\n// d\nX func() /* a\n b */ int\n}\n", + syntax_error: false, + loc: [6, 5, 0, 3, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 2, + }, + Row { + source: b"package p\nfunc F() {\ntype T struct {\n// a\nX int\n}\n}\n", + syntax_error: false, + loc: [7, 6, 0, 1, 0, 0], + dloc_rows: &[], + documents: 0, + comment_runs: 1, + }, + Row { + source: b"package p\ntype I interface {\n// u\n~int\n}\n", + syntax_error: false, + loc: [5, 4, 0, 1, 0, 0], + dloc_rows: &[], + documents: 0, + comment_runs: 1, + }, + Row { + source: b"package p\ntype S struct {\n// a\nX %% int\n}\n", + syntax_error: true, + loc: [5, 4, 0, 1, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 1, + }, + // A field separates each comment from the next. + Row { + source: b"package p\ntype S struct {\n// a\nX int\n// b\nY %% int\n// c\nZ int\n}\n", + syntax_error: true, + loc: [9, 6, 0, 3, 0, 3], + dloc_rows: &[2, 4, 6], + documents: 3, + comment_runs: 3, + }, + // Members that Go ends before the end of their node, and members over several + // rows that Go reads whole. The collector keeps the first three pending. + Row { + source: b"package p\ntype S struct {\n// d\nX [2]\nint\n}\n", + syntax_error: false, + loc: [6, 5, 0, 1, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 1, + }, + // The second comment is inside the field that follows the first. + Row { + source: b"package p\ntype S struct {\n// d\nX [2] // c\nint\n}\n", + syntax_error: false, + loc: [6, 5, 0, 2, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 2, + }, + Row { + source: b"package p\ntype I interface {\n// d\nE | func() /* stop\n here */ B | C\n}\n", + syntax_error: false, + loc: [6, 5, 0, 3, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 2, + }, + Row { + source: b"package p\ntype I interface {\n// d\nM(\n\ta int,\n\tb int,\n) error\n}\n", + syntax_error: false, + loc: [8, 7, 0, 1, 0, 1], + dloc_rows: &[2], + documents: 1, + comment_runs: 1, + }, + // A field separates each comment from the next. + Row { + source: b"package p\ntype S struct {\n// d\nA struct {\n// x\nX int\n// y\nY int\n}\n}\n", + syntax_error: false, + loc: [10, 7, 0, 3, 0, 3], + dloc_rows: &[2, 4, 6], + documents: 3, + comment_runs: 3, + }, + ]; + for row in sources { + let name = row.source.escape_ascii(); + let parser = + crate::langs::AnyParser::parse(LANG::Go, row.source.to_vec(), None, None).unwrap(); + assert_eq!( + parser.ts_tree().root_node().has_error(), + row.syntax_error, + "{name}" + ); + let idle = counters(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let collected = counters(); + let space = analyze( + Source::new(LANG::Go, row.source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let analyzed = counters(); + + let loc = &space.metrics.loc; + assert_eq!( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc() + ], + row.loc, + "{name}" + ); + assert_eq!( + (0..row.source.len()) + .filter(|at| loc.dloc.lines.contains(*at)) + .collect::>(), + row.dloc_rows, + "{name}" + ); + + // The collection moves each counter on this thread, so a zero across `analyze` is + // a reading. + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| collected[at] - idle[at]); + // expected: the walk enters every node of the tree once. + assert_eq!(visits, parser.root_node().preorder().count(), "{name}"); + // expected: one render per published document. + assert_eq!(index.documents().len(), row.documents, "{name}"); + assert_eq!(renders, row.documents, "{name}"); + // expected: under default options the positional stream builds one member for + // each fragment of a selected run, and none for a trailing member. + let fragments: usize = index + .documents() + .map(|document| document.get().fragment_count()) + .sum(); + assert_eq!(built, fragments, "{name}"); + // expected: every comment is a member of exactly one run, and the source view + // materializes each run once. + let comments = parser + .root_node() + .preorder() + .filter(|node| node.kind() == "comment") + .count(); + assert_eq!(materialized, comments, "{name}"); + // expected: the source view scans every run once, at its last comment. + assert_eq!(scanned, row.comment_runs, "{name}"); + // Not exact: the number of included-range questions is the collector's own + // accounting and follows from no fact of the tree. + assert_ne!(covered, 0, "{name}"); + // expected: in these sources a document is published exactly where the legacy + // view counts a row. + assert_eq!(row.documents == 0, row.dloc_rows.is_empty(), "{name}"); + + // The same six counters across `analyze`. + let [visits, renders, built, materialized, scanned, covered] = + std::array::from_fn(|at| analyzed[at] - collected[at]); + // expected: 0 and 0, because `analyze` builds no documentation index. + assert_eq!(visits, 0, "{name}"); + assert_eq!(renders, 0, "{name}"); + // expected: 0, because the legacy view builds no source evidence. + assert_eq!(built, 0, "{name}"); + // expected: 0, because the legacy view walks members without a buffer. + assert_eq!(materialized, 0, "{name}"); + // expected: the legacy view scans every run once as well, at its last comment. + assert_eq!(scanned, row.comment_runs, "{name}"); + // expected: 0, because the legacy view has no source context to ask. + assert_eq!(covered, 0, "{name}"); + } +} diff --git a/utils/documentation-go-unit2-legacy-perturb.json b/utils/documentation-go-unit2-legacy-perturb.json new file mode 100644 index 000000000..6b690b7ca --- /dev/null +++ b/utils/documentation-go-unit2-legacy-perturb.json @@ -0,0 +1,49 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis", "--all-features", "--lib", "documentation_go_member_sources_keep_their_legacy_rows"], + "cases": [ + { + "name": "go-function-body-gate-open", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " Go::StatementList | Go::Block => 0,", + "new": " Go::StatementList | Go::Block => 1,", + "expect": ["metrics::loc::documentation_tests::documentation_go_member_sources_keep_their_legacy_rows"] + }, + { + "name": "go-negated-element-is-a-target", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " Go::TypeIdentifier | Go::QualifiedType | Go::GenericType", + "new": " Go::TypeIdentifier | Go::QualifiedType | Go::GenericType | Go::NegatedType", + "expect": ["metrics::loc::documentation_tests::documentation_go_member_sources_keep_their_legacy_rows"] + }, + { + "name": "leading-run-bills-no-documentation-row", + "file": "src/metrics/loc/shared.rs", + "old": " stats.dloc.lines.insert_range(first, last);", + "new": " let _ = (first, last);", + "expect": ["metrics::loc::documentation_tests::documentation_go_member_sources_keep_their_legacy_rows"] + }, + { + "name": "leading-run-documentation-rows-move-up", + "file": "src/metrics/loc/shared.rs", + "old": " stats.dloc.lines.insert_range(first, last);", + "new": " stats\n .dloc\n .lines\n .insert_range(first.saturating_sub(1), last.saturating_sub(1));", + "expect": ["metrics::loc::documentation_tests::documentation_go_member_sources_keep_their_legacy_rows"] + }, + { + "name": "trailing-comment-seeds-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " if prev.end_row() >= row_first.start_row() {", + "new": " if prev.end_row() > row_first.start_row() {", + "expect": ["metrics::loc::documentation_tests::documentation_go_member_sources_keep_their_legacy_rows"] + }, + { + "name": "observation-counters-do-not-count", + "file": "big-code-analysis-ast/src/observation.rs", + "old": " COUNT.with(|count| count.set(count.get() + 1));", + "new": " COUNT.with(|count| count.set(count.get()));", + "expect": ["metrics::loc::documentation_tests::documentation_go_member_sources_keep_their_legacy_rows"] + } + ] +} From d44696e240c1f258d388ef4b65da98f667e5130e Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:44:13 -0800 Subject: [PATCH 109/221] feat(documentation): give Go struct fields and interface elements owners Project Go struct field names to field slots and embedded fields and interface elements to node owners. Leave a member pending when Go ends it before the grammar node or a comment or syntax boundary makes ownership uncertain. Add owner, cost, and recovery tests, provenance and perturbation cases, and regenerate the self-scan baseline. Legacy documentation rows are unchanged. --- .bca-baseline.toml | 12 +- CHANGELOG.md | 11 + .../collector/assessment_tests.rs | 2 +- .../src/documentation/collector/go_tests.rs | 2639 ++++++++++++++++- .../documentation/collector/projections.rs | 122 + .../documentation/go-unit2-provenance.json | 32 + utils/documentation-form-matrix.json | 4 +- utils/documentation-go-unit2-perturb.json | 413 +++ 8 files changed, 3213 insertions(+), 22 deletions(-) create mode 100644 tests/fixtures/documentation/go-unit2-provenance.json create mode 100644 utils/documentation-go-unit2-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index c74105c26..030a57f04 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -665,7 +665,7 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>" metric = "wmc" -value = 73.0 +value = 81.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" @@ -695,31 +695,31 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "abc" -value = 46.75467891024384 +value = 48.14561246884289 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cognitive" -value = 29.0 +value = 30.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "cyclomatic" -value = 32.0 +value = 33.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "halstead.effort" -value = 223608.98282915083 +value = 233674.53241031803 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" qualified = "Builder<'_>::finalize_projection" metric = "nexits" -value = 12.0 +value = 13.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/projections.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index fe52b2766..5d3325891 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -58,6 +58,17 @@ for historical reference. error, excluded bytes or an unnamed (`_`) declarator stays a pending owner. Legacy documentation rows are unchanged. (#1666) +- The unstable AST documentation collector now gives Go struct fields and + interface elements owners. A field declaration with names has the declaration + and one field slot per name, spelled by the name; a comment above it is one + document associated with every slot, as go/ast attaches it. A field that + embeds a type, a method element and an interface element that opens with a + name own as their nodes. A member stays a pending owner when it holds a + syntax error, excluded bytes or a comment with a line break among its + children, and when Go ends it at a line end before the end of its node, as + it ends `X [2]` before a line end. Legacy documentation rows are unchanged. + (#1672) + - Added unstable AST-crate source-marker `Checker` hooks and streaming requests that retain selection, source pieces and attachment uncertainty. The separate legacy event stream preserves existing metric behavior. (#1658) diff --git a/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs index e8f9260ff..506892780 100644 --- a/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs @@ -66,7 +66,7 @@ fn kotlin_local_pending_owner_keeps_complete_text_and_known_leading_association( fn pending_go_field_query_exposes_assessment_instead_of_unusable_error() { let parser = AnyParser::parse( LANG::Go, - b"package p\ntype S struct {\n// both\nX, Y int\n}".to_vec(), + b"package p\ntype S struct {\n// both\nX, Y %% int\n}".to_vec(), None, None, ) diff --git a/big-code-analysis-ast/src/documentation/collector/go_tests.rs b/big-code-analysis-ast/src/documentation/collector/go_tests.rs index ddc1a205c..a6fe62748 100644 --- a/big-code-analysis-ast/src/documentation/collector/go_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/go_tests.rs @@ -1,7 +1,10 @@ -//! Go documentation in the source view: which declaration owns a comment, the text of -//! the document and where each part of that text comes from. Every source is collected -//! through both entry points, except in the grammar tests, which collect nothing and pin -//! the parse-tree shapes the other tests rely on. +//! Go documentation in the source view: which declaration, field name or interface +//! element owns a comment, the text of the document and where each part of that text +//! comes from. Every source is collected through both entry points, with three +//! exceptions. The grammar tests collect nothing and pin the parse-tree shapes the +//! other tests rely on. A tree parsed with excluded ranges goes through `collect`, the +//! one entry point that takes such a tree. The cost tests read the counters around one +//! collection through the typed entry point. #![allow(clippy::single_range_in_vec_init, clippy::type_complexity)] @@ -12,6 +15,11 @@ use crate::{AnyParser, LANG}; #[cfg(feature = "go")] use std::ops::Range; +#[cfg(feature = "go")] +use crate::documentation::budget::WorkBudget; +#[cfg(feature = "go")] +use std::cell::Cell; + #[cfg(feature = "go")] use Run::{Copied, Decoded, Synthetic}; @@ -39,14 +47,18 @@ struct Doc { /// What one collection published: the documents, the owner of each association as /// resolution, node kind and byte range, each retained candidate as disposition and byte -/// range, and the number of pending assessments. The default value is an index that -/// holds none of them. What is the same for every source here is asserted by -/// `published` and is in no expected value. Node queries are not part of it. +/// range, and the number of pending assessments. Where field slots own an association, +/// `owners` holds the declaration that encloses them, and `slots` holds the position of +/// the association and the byte range of each name, in the association's order. The +/// default value is an index that holds none of them. What is the same for every source +/// here is asserted by `published` and is in no expected value. Node queries are not +/// part of it. #[cfg(feature = "go")] #[derive(Debug, Default, PartialEq, Eq)] struct View { documents: Vec, owners: Vec<(Resolution, &'static str, Range)>, + slots: Vec<(usize, Vec>)>, evidence: Vec<(CandidateDisposition, Range)>, assessments: usize, } @@ -128,6 +140,15 @@ fn owned(document: Doc, kind: &'static str, owner: Range) -> View { owned_in_order([document], [(kind, owner)]) } +/// The expected view of one document that the names of one field declaration own. +#[cfg(feature = "go")] +fn named(document: Doc, declaration: Range, names: &[Range]) -> View { + View { + slots: vec![(0, names.to_vec())], + ..owned(document, "field_declaration", declaration) + } +} + /// The byte range of a spelling that is one included piece, as every spelling here is. #[cfg(feature = "go")] fn span(pieces: &SourcePieces<'_>) -> Range { @@ -162,20 +183,60 @@ fn fragment_span(fragment: &Fragment<'_>) -> Range { range } -/// The node that alone owns the association, as every owner here is. +/// The node that alone owns the association, or the declaration that encloses the field +/// slots that own it. #[cfg(feature = "go")] fn owner_node<'s>( facts: &Facts<'s>, association: FactRef<'_, Association<'s>>, ) -> tree_sitter::Node<'s> { - assert_eq!(association.get().owner_count(), 1); let owner = facts.associated_owner(association, 0).unwrap(); - let Owner::Node(declared) = owner.get() else { - panic!("a node owner, found {:?}", owner.get()) + let around = match owner.get() { + Owner::Node(_) => { + assert_eq!(association.get().owner_count(), 1); + owner + } + Owner::Slot(_) => facts.slot_enclosing(owner).unwrap(), + other => panic!("a node or a field slot, found {other:?}"), + }; + let Owner::Node(declared) = around.get() else { + panic!("a node around the slot, found {:?}", around.get()) }; declared.node() } +/// The byte range of the name of each field slot that owns the association, in its +/// order; nothing where a node owns it. The same holds for every slot here, so no +/// expected view states it: the role is `Field`, the ordinal is the position among the +/// owners, the name is one included piece, every slot of the association has the same +/// enclosing owner, and no qualification record names a slot. +#[cfg(feature = "go")] +fn slot_names( + index: &DocumentationIndex<'_>, + association: FactRef<'_, Association<'_>>, +) -> Vec> { + let facts = index.facts(); + let first = facts.associated_owner(association, 0).unwrap(); + if !matches!(first.get(), Owner::Slot(_)) { + return Vec::new(); + } + let around = facts.slot_enclosing(first).unwrap(); + (0..association.get().owner_count()) + .map(|at| { + let owner = facts.associated_owner(association, at).unwrap(); + let Owner::Slot(slot) = owner.get() else { + panic!("a field slot, found {:?}", owner.get()) + }; + assert_eq!((slot.role, slot.ordinal), (SlotRole::Field, at)); + assert!(!slot.source.has_excluded_gap()); + assert_eq!(facts.slot_enclosing(owner).unwrap(), around); + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.qualifications().len(), 0); + span(&slot.source) + }) + .collect() +} + #[cfg(feature = "go")] fn published(index: &DocumentationIndex<'_>) -> View { // bca: suppress(halstead) -- one flat reading of everything the index publishes, in the order of the view's fields. @@ -204,20 +265,26 @@ fn published(index: &DocumentationIndex<'_>) -> View { } }) .collect(); + let mut slots = Vec::new(); let owners = index .associations() .enumerate() .map(|(position, association)| { let attachment = association.get(); let declaration = owner_node(facts, association); + let names = slot_names(index, association); + if !names.is_empty() { + slots.push((position, names)); + } // The same for every association here, so no expected view states them. Each // document has one association, at the document's own position. assert_eq!(attachment.convention.name(), "GoDoc"); assert_eq!(attachment.publication, Publication::Unknown); let document = facts.associated_document(association).unwrap(); assert_eq!(index.documents().nth(position), Some(document)); - // Both follow from the tree: the binding is the owner itself, and the lexical - // scope is the parent of the first comment of the document. + // Both follow from the tree: the binding is the owner node, or the declaration + // around the owning slots, and the lexical scope is the parent of the first + // comment of the document. assert_eq!( attachment.binding.map(NodeEvidence::node), Some(declaration) @@ -250,6 +317,7 @@ fn published(index: &DocumentationIndex<'_>) -> View { View { documents, owners, + slots, evidence, assessments: index.assessments().len(), } @@ -1917,3 +1985,2548 @@ fn go_token_shapes_the_line_end_rule_relies_on() { assert_eq!(site(function), ("function_type", 38..63)); assert_eq!(site(function.parent().unwrap()), ("type_elem", 34..67)); } + +/// A tree parsed with those included ranges. Only `collect` takes such a tree. +#[cfg(feature = "go")] +fn restricted(source: &[u8], included: &[Range]) -> tree_sitter::Tree { + // The row is the number of line feeds before the offset, and the column the number + // of bytes after the last of them. + let point = |offset: usize| { + let mut rows = source[..offset].split(|byte| *byte == b'\n'); + let last = rows.next_back().unwrap(); + tree_sitter::Point::new(rows.count(), last.len()) + }; + let ranges: Vec<_> = included + .iter() + .map(|range| tree_sitter::Range { + start_byte: range.start, + end_byte: range.end, + start_point: point(range.start), + end_point: point(range.end), + }) + .collect(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Go.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + parser.parse(source, None).unwrap() +} + +/// The one node of that kind and byte range in a tree that no `AnyParser` holds. +#[cfg(feature = "go")] +fn node_in<'t>( + tree: &'t tree_sitter::Tree, + kind: &str, + range: Range, +) -> tree_sitter::Node<'t> { + let mut found = Vec::new(); + let mut stack = vec![tree.root_node()]; + while let Some(current) = stack.pop() { + if current.kind() == kind && current.byte_range() == range { + found.push(current); + } + stack.extend(current.children(&mut current.walk())); + } + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +/// The owners a node projects to, as text. +#[cfg(feature = "go")] +fn owners_of(index: &DocumentationIndex<'_>, node: tree_sitter::Node<'_>) -> Vec { + index + .node_owners(node) + .unwrap() + .map(|owner| owner_text(index, owner)) + .collect() +} + +#[cfg(feature = "go")] +#[test] +fn go_names_of_a_field_declaration_each_own_a_field_slot() { + let fields: [(&[u8], Doc, Range, &[Range]); 6] = [ + ( + b"package p\ntype S struct {\n// both\nX, Y int\n}\n", + comment(26..33, "both", [(0..4, Copied(29..33))]), + 34..42, + &[34..35, 37..38], + ), + ( + b"package p\ntype S struct {\n// audit\nX int\n}\n", + comment(26..34, "audit", [(0..5, Copied(29..34))]), + 35..40, + &[35..36], + ), + // A tag is no name. + ( + b"package p\ntype S struct {\n// d\nX, Y int `json:\"x\"`\n}\n", + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..50, + &[31..32, 34..35], + ), + // A line feed after the comma does not end the declaration. + ( + b"package p\ntype S struct {\n// d\nX,\nY int\n}\n", + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..39, + &[31..32, 34..35], + ), + ( + b"package p\r\ntype S struct {\r\n// both\r\nX, Y int\r\n}\r\n", + comment(28..35, "both", [(0..4, Copied(31..35))]), + 37..45, + &[37..38, 40..41], + ), + // A block comment that ends on the row above the field documents it. + ( + b"package p\ntype S struct {\n/* a\n b */\nX int\n}\n", + comment( + 26..36, + "a\n b", + [ + (0..1, Copied(29..30)), + (1..2, Copied(30..31)), + (2..4, Copied(31..33)), + ], + ), + 37..42, + &[37..38], + ), + ]; + for (source, document, declaration, names) in fields { + assert_eq!( + view(source), + named(document, declaration, names), + "{}", + source.escape_ascii() + ); + } + + // Two documents in one struct, and `_` is a name like any other. + assert_eq!( + view(b"package p\ntype S struct {\n// pad\n_ int\n// two\n_, X int\n}\n"), + View { + slots: vec![(0, vec![33..34]), (1, vec![46..47, 49..50])], + ..owned_in_order( + [ + comment(26..32, "pad", [(0..3, Copied(29..32))]), + comment(39..45, "two", [(0..3, Copied(42..45))]), + ], + [("field_declaration", 33..38), ("field_declaration", 46..54)] + ) + } + ); + + // A directive above the document is no part of it, and is kept on request. + assert_default_then_retained( + b"package p\ntype S struct {\n//go:notinheap\n// audit\nX int\n}\n", + named( + comment(41..49, "audit", [(0..5, Copied(44..49))]), + 50..55, + &[50..51], + ), + Retain::Directives, + (CandidateDisposition::Directive, 26..40), + ); + + // The slots are spelled by the names and by nothing else of the declaration. + let parser = clean(b"package p\ntype S struct {\n// both\nX, Y int\n}\n"); + for index in &indexes(&parser, DocumentationOptions::default()) { + let association = index.associations().next().unwrap(); + let spelled: Vec<_> = (0..association.get().owner_count()) + .map(|at| { + let owner = index.facts().associated_owner(association, at).unwrap(); + let Owner::Slot(slot) = owner.get() else { + panic!("a field slot, found {:?}", owner.get()) + }; + slot.source.pieces()[0].bytes().to_vec() + }) + .collect(); + assert_eq!(spelled, [b"X".to_vec(), b"Y".to_vec()]); + // expected: the file, the package clause, the type declaration and its spec, + // the field declaration, and one slot for each of the two names. + assert_eq!(index.facts().owners().len(), 7); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_inventory_row_gives_one_document_to_both_names() { + // The source of the case inventory, which has no final line end. The pinned grammar + // flags the root of such a file and no node below it. + let parser = parsed(b"package p\ntype S struct {\n// both\nX, Y int\n}"); + assert!(parser.root_node().has_error()); + assert_eq!( + agreed(&indexes(&parser, DocumentationOptions::default())), + named( + comment(26..33, "both", [(0..4, Copied(29..33))]), + 34..42, + &[34..35, 37..38], + ) + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_field_queries_answer_per_slot_and_per_declaration() { + let parser = clean(b"package p\ntype S struct {\n// audit\nX int\n}\n"); + let field = node_at(&parser, "field_declaration", 35..40); + for index in &indexes(&parser, DocumentationOptions::default()) { + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let projection = index.node_projection(field).unwrap(); + assert!(!projection.pending()); + assert!(projection.owners().eq([owner])); + assert!(index.node_owners(field).unwrap().eq([owner])); + let query = index.node_associations(field).unwrap(); + assert!(!query.projection_pending()); + assert!(query.associations().eq([association])); + assert_eq!(query.assessments().count(), 0); + let slot = index.owner_associations(owner).unwrap(); + assert!(slot.associations().eq([association])); + // The declaration is an owner of its own; the document is not listed under it. + let enclosing = index.facts().slot_enclosing(owner).unwrap(); + assert_eq!(owner_text(index, enclosing), "field_declaration 35..40"); + let declaration = index.owner_associations(enclosing).unwrap(); + assert_eq!(declaration.associations().len(), 0); + assert_eq!(declaration.assessments().count(), 0); + // The name and the type of the field are no owners. + for (kind, range) in [("field_identifier", 35..36), ("type_identifier", 37..40)] { + let part = node_at(&parser, kind, range); + assert_eq!( + index.node_projection(part).err(), + Some(OwnerError::UnsupportedOwner), + "{kind}" + ); + assert_eq!( + index.node_associations(part).err(), + Some(OwnerError::UnsupportedOwner), + "{kind}" + ); + assert_eq!( + index.node_owners(part).err(), + Some(OwnerError::UnsupportedOwner), + "{kind}" + ); + } + } + + let parser = clean(b"package p\ntype S struct {\n// both\nX, Y int\n}\n"); + let field = node_at(&parser, "field_declaration", 34..42); + for index in &indexes(&parser, DocumentationOptions::default()) { + let association = index.associations().next().unwrap(); + let owners = [ + index.facts().associated_owner(association, 0).unwrap(), + index.facts().associated_owner(association, 1).unwrap(), + ]; + assert_ne!(owners[0], owners[1]); + // Two names: the declaration has no single owner to answer for. + assert_eq!( + index.node_associations(field).err(), + Some(OwnerError::MultipleOwners) + ); + assert!(index.node_owners(field).unwrap().eq(owners)); + let projection = index.node_projection(field).unwrap(); + assert!(!projection.pending()); + assert!(projection.owners().eq(owners)); + assert_eq!(projection.assessments().count(), 0); + for owner in owners { + let query = index.owner_associations(owner).unwrap(); + assert!(query.associations().eq([association])); + assert_eq!(query.assessments().count(), 0); + } + for (kind, range) in [("field_identifier", 34..35), (",", 35..36)] { + assert_eq!( + index.node_projection(node_at(&parser, kind, range)).err(), + Some(OwnerError::UnsupportedOwner), + "{kind}" + ); + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_fields_of_a_nested_struct_own_slots_in_their_own_declaration() { + let source: &[u8] = + b"package p\ntype S struct {\n// same\nN struct {\n// same\nX, Y int\n}\n}\n"; + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + // The two documents have equal text, and each keeps its own lexical scope: the + // field list its comment is in, which `published` reads from the tree. + assert_eq!( + agreed(&both), + View { + slots: vec![(0, vec![34..35]), (1, vec![53..54, 56..57])], + ..owned_in_order( + [ + comment(26..33, "same", [(0..4, Copied(29..33))]), + comment(45..52, "same", [(0..4, Copied(48..52))]), + ], + [("field_declaration", 34..63), ("field_declaration", 53..61)] + ) + } + ); + for index in &both { + let documents: Vec<_> = index.documents().collect(); + assert_ne!(documents[0], documents[1]); + let associations: Vec<_> = index.associations().collect(); + // The slot of `N` answers with the outer document only. + let outer = index.facts().associated_owner(associations[0], 0).unwrap(); + let query = index.owner_associations(outer).unwrap(); + assert!(query.associations().eq([associations[0]])); + // The walk leaves the inner declaration first, so its owners come first. + let owners: Vec<_> = index + .facts() + .owners() + .map(|owner| owner_text(index, owner)) + .collect(); + assert_eq!( + owners, + [ + "file source_file 0..66", + "package_clause 0..9", + "type_declaration 10..65", + "type_spec 15..65", + "field_declaration 53..61", + "slot 0 53..54 in field_declaration 53..61", + "slot 1 56..57 in field_declaration 53..61", + "field_declaration 34..63", + "slot 0 34..35 in field_declaration 34..63", + ] + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_embedded_field_owns_as_its_declaration() { + assert_eq!( + view(b"package p\ntype S struct {\n// audit\nio.Reader\n}\n"), + owned( + comment(26..34, "audit", [(0..5, Copied(29..34))]), + "field_declaration", + 35..44 + ) + ); + // A type name, a pointer to one, a qualified one, an instantiated one, and one with + // a tag: none has a name of its own, so none has a slot. + let source: &[u8] = + b"package p\ntype S struct {\n// a\nT\n// b\n*T\n// c\n*io.Reader\n// d\nG[int]\n// e\nT `json:\"t\"`\n}\n"; + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both), + owned_in_order( + [ + comment(26..30, "a", [(0..1, Copied(29..30))]), + comment(33..37, "b", [(0..1, Copied(36..37))]), + comment(41..45, "c", [(0..1, Copied(44..45))]), + comment(57..61, "d", [(0..1, Copied(60..61))]), + comment(69..73, "e", [(0..1, Copied(72..73))]), + ], + [ + ("field_declaration", 31..32), + ("field_declaration", 38..40), + ("field_declaration", 46..56), + ("field_declaration", 62..68), + ("field_declaration", 74..86), + ] + ) + ); + for index in &both { + // expected: the file, the package clause, the type declaration and its spec, + // and the five field declarations; no slot. + assert_eq!(index.facts().owners().len(), 9); + let field = node_at(&parser, "field_declaration", 46..56); + assert_eq!(owners_of(index, field), ["field_declaration 46..56"]); + let query = index.node_associations(field).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 1); + assert_eq!(query.assessments().count(), 0); + // The type argument of the instantiated type is no owner. + assert_eq!( + index + .node_projection(node_at(&parser, "type_elem", 64..67)) + .err(), + Some(OwnerError::UnsupportedOwner) + ); + } + + // A line feed after a lone name ends the declaration, in Go as in the grammar: `X` + // and `int` are two embedded fields, and the document belongs to the first. + let source: &[u8] = b"package p\ntype S struct {\n// d\nX\nint\n}\n"; + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both), + owned( + comment(26..30, "d", [(0..1, Copied(29..30))]), + "field_declaration", + 31..32 + ) + ); + for index in &both { + let second = node_at(&parser, "field_declaration", 33..36); + assert_eq!(owners_of(index, second), ["field_declaration 33..36"]); + let query = index.node_associations(second).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 0); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_interface_elements_own_as_their_nodes() { + // A method and an embedded name own their comments. `~int` opens with no name: + // its comment is in no document, and the element is no owner. + let source: &[u8] = + b"package p\ntype I interface {\n// m\nM()\n// e\nio.Reader\n// u\n~int\n}\n"; + assert_default_then_retained( + source, + owned_in_order( + [ + comment(29..33, "m", [(0..1, Copied(32..33))]), + comment(38..42, "e", [(0..1, Copied(41..42))]), + ], + [("method_elem", 34..37), ("type_elem", 43..52)], + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 53..57), + ); + let parser = clean(source); + for index in &indexes(&parser, DocumentationOptions::default()) { + for (kind, range) in [("method_elem", 34..37), ("type_elem", 43..52)] { + let element = node_at(&parser, kind, range.clone()); + assert_eq!( + owners_of(index, element), + [format!("{kind} {}..{}", range.start, range.end)] + ); + let query = index.node_associations(element).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 1); + assert_eq!(query.assessments().count(), 0); + } + assert_eq!( + index + .node_projection(node_at(&parser, "type_elem", 58..62)) + .err(), + Some(OwnerError::UnsupportedOwner) + ); + // The name of a method is no field slot. + assert_eq!( + index + .node_projection(node_at(&parser, "field_identifier", 34..35)) + .err(), + Some(OwnerError::UnsupportedOwner) + ); + // expected: the file, the package clause, the type declaration and its spec, + // the method and the embedded name. + assert_eq!(index.facts().owners().len(), 6); + } + + // A union, an instantiated type, a single name, a method with parameters and + // results, and a type with two arguments. + let source: &[u8] = b"package p\ntype I interface {\n// a\nint | string\n// c\nG[int]\n// d\nE\n// f\nM(x int) (int, error)\n// g\nMap[string, int]\n}\n"; + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + assert_eq!( + agreed(&both), + owned_in_order( + [ + comment(29..33, "a", [(0..1, Copied(32..33))]), + comment(47..51, "c", [(0..1, Copied(50..51))]), + comment(59..63, "d", [(0..1, Copied(62..63))]), + comment(66..70, "f", [(0..1, Copied(69..70))]), + comment(93..97, "g", [(0..1, Copied(96..97))]), + ], + [ + ("type_elem", 34..46), + ("type_elem", 52..58), + ("type_elem", 64..65), + ("method_elem", 71..92), + ("type_elem", 98..114), + ] + ) + ); + for index in &both { + // The arguments of an instantiated type are type elements of the grammar and + // no owners. + for range in [54..57, 102..108, 110..113] { + assert_eq!( + index + .node_projection(node_at(&parser, "type_elem", range.clone())) + .err(), + Some(OwnerError::UnsupportedOwner), + "{range:?}" + ); + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_members_own_wherever_their_type_is_written() { + // A struct type of a variable, of a parameter, of a composite literal and of a + // generic type, all outside a function body. + let structs: [(&[u8], Range, usize, Range); 4] = [ + ( + b"package p\nvar v struct {\n// d\nX int\n}\n", + 25..29, + 28, + 30..35, + ), + ( + b"package p\nfunc F(s struct {\n// d\nX int\n}) {}\n", + 28..32, + 31, + 33..38, + ), + ( + b"package p\nvar v = struct {\n// d\nX int\n}{}\n", + 27..31, + 30, + 32..37, + ), + ( + b"package p\ntype S[T any] struct {\n// d\nX T\n}\n", + 33..37, + 36, + 38..41, + ), + ]; + for (source, fragment, text, field) in structs { + let name = field.start..field.start + 1; + assert_eq!( + view(source), + named( + comment(fragment, "d", [(0..1, Copied(text..text + 1))]), + field, + &[name] + ), + "{}", + source.escape_ascii() + ); + } + + // An interface that is the type of a field: the field has a slot, and the method + // inside owns as its node. + assert_eq!( + view(b"package p\ntype S struct {\n// f\nI interface {\n// m\nM()\n}\n}\n"), + View { + slots: vec![(0, vec![31..32])], + ..owned_in_order( + [ + comment(26..30, "f", [(0..1, Copied(29..30))]), + comment(45..49, "m", [(0..1, Copied(48..49))]), + ], + [("field_declaration", 31..55), ("method_elem", 50..53)] + ) + } + ); + // An interface that constrains a type parameter. + assert_eq!( + view(b"package p\nfunc F[T interface {\n// c\nint\n}]() {}\n"), + owned( + comment(31..35, "c", [(0..1, Copied(34..35))]), + "type_elem", + 36..39 + ) + ); + // A struct that is the type of a parameter of a method. + assert_eq!( + view(b"package p\ntype I interface {\n// m\nM(s struct {\n// d\nX int\n})\n}\n"), + View { + slots: vec![(1, vec![52..53])], + ..owned_in_order( + [ + comment(29..33, "m", [(0..1, Copied(32..33))]), + comment(47..51, "d", [(0..1, Copied(50..51))]), + ], + [("method_elem", 34..60), ("field_declaration", 52..57)] + ) + } + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_undocumented_members_have_owners_and_no_assessment() { + let source: &[u8] = + b"package p\ntype S struct {\nX int\nA, B string\nio.Reader\n}\ntype I interface {\nM()\nE\n}\n"; + let parser = clean(source); + let both = indexes(&parser, DocumentationOptions::default()); + // Nothing is published and nothing is pending. + assert_eq!(agreed(&both), View::default()); + for index in &both { + // A node owner is registered when the walk enters it, a member when the walk + // leaves it. + let owners: Vec<_> = index + .facts() + .owners() + .map(|owner| owner_text(index, owner)) + .collect(); + assert_eq!( + owners, + [ + "file source_file 0..83", + "package_clause 0..9", + "type_declaration 10..55", + "type_spec 15..55", + "field_declaration 26..31", + "slot 0 26..27 in field_declaration 26..31", + "field_declaration 32..43", + "slot 0 32..33 in field_declaration 32..43", + "slot 1 35..36 in field_declaration 32..43", + "field_declaration 44..53", + "type_declaration 56..82", + "type_spec 61..82", + "method_elem 75..78", + "type_elem 79..80", + ] + ); + for owner in index.facts().owners() { + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.associations().len(), 0); + assert_eq!(query.assessments().count(), 0); + } + let single: [(&str, Range); 4] = [ + ("field_declaration", 26..31), + ("field_declaration", 44..53), + ("method_elem", 75..78), + ("type_elem", 79..80), + ]; + for (kind, range) in single { + let member = node_at(&parser, kind, range); + let projection = index.node_projection(member).unwrap(); + assert!(!projection.pending(), "{kind}"); + assert_eq!(projection.assessments().count(), 0, "{kind}"); + let query = index.node_associations(member).unwrap(); + assert!(!query.projection_pending(), "{kind}"); + assert_eq!(query.associations().len(), 0, "{kind}"); + assert_eq!(query.assessments().count(), 0, "{kind}"); + } + let two = node_at(&parser, "field_declaration", 32..43); + assert!(!index.node_projection(two).unwrap().pending()); + assert_eq!( + index.node_associations(two).err(), + Some(OwnerError::MultipleOwners) + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_comments_that_document_no_member_leave_it_its_owners() { + // `// t` follows the field `X` on its row. It documents nothing, and `X` has its + // slot all the same. + let trailing: &[u8] = b"package p\ntype S struct {\nX int // t\n// d\nY int\n}\n"; + assert_default_then_retained( + trailing, + named( + comment(37..41, "d", [(0..1, Copied(40..41))]), + 42..47, + &[42..43], + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 32..36), + ); + let parser = clean(trailing); + for index in &indexes(&parser, DocumentationOptions::default()) { + let field = node_at(&parser, "field_declaration", 26..31); + assert_eq!( + owners_of(index, field), + ["slot 0 26..27 in field_declaration 26..31"] + ); + let query = index.node_associations(field).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 0); + assert_eq!(query.assessments().count(), 0); + } + + // A comment after the field on its row and a comment between two blank rows: two + // candidates, no document, and both fields have their slots. + let detached: &[u8] = b"package p\ntype S struct {\nX int // t\n\n// lost\n\nY int\n}\n"; + let mut expected = View::default(); + assert_eq!(view(detached), expected); + expected.evidence.extend([ + (CandidateDisposition::Unattached, 32..36), + (CandidateDisposition::Unattached, 38..45), + ]); + assert_eq!(retained(detached, Retain::Unbound), expected); + let parser = clean(detached); + for index in &indexes(&parser, DocumentationOptions::default()) { + for (field, name) in [(26..31, "26..27"), (47..52, "47..48")] { + let text = format!( + "slot 0 {name} in field_declaration {}..{}", + field.start, field.end + ); + assert_eq!( + owners_of(index, node_at(&parser, "field_declaration", field)), + [text] + ); + } + } + + // A block comment that ends on the row of the field is no lead comment. + assert_default_then_retained( + b"package p\ntype S struct {\n/* a\n b */ X int\n}\n", + View::default(), + Retain::Unbound, + (CandidateDisposition::Unattached, 26..36), + ); + + // The same in an interface: `// t` follows the method on its row. + assert_default_then_retained( + b"package p\ntype I interface {\nM() // t\n// e\nio.Reader\n}\n", + owned( + comment(38..42, "e", [(0..1, Copied(41..42))]), + "type_elem", + 43..52, + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 33..37), + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_comment_inside_a_member_documents_nothing() { + // A comment between the parts of a member is a child of the member. It has no + // target, and the member has its owners. + assert_default_then_retained( + b"package p\ntype S struct {\n// d\nX, /* c */ Y int\n}\n", + named( + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..47, + &[31..32, 42..43], + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 34..41), + ); + assert_default_then_retained( + b"package p\ntype S struct {\n// a\nX,\n// b\nY int\n}\n", + named( + comment(26..30, "a", [(0..1, Copied(29..30))]), + 31..44, + &[31..32, 39..40], + ), + Retain::Unbound, + (CandidateDisposition::Unattached, 34..38), + ); + // Two comments inside one method, kept in source order. + let method: &[u8] = b"package p\ntype I interface {\n// m\nM( /* in */ ) /* out */ int\n}\n"; + let mut expected = owned( + comment(29..33, "m", [(0..1, Copied(32..33))]), + "method_elem", + 34..61, + ); + assert_eq!(view(method), expected); + expected.evidence.extend([ + (CandidateDisposition::Unattached, 37..45), + (CandidateDisposition::Unattached, 48..57), + ]); + assert_eq!(retained(method, Retain::Unbound), expected); +} + +#[cfg(feature = "go")] +#[test] +fn go_member_with_a_comment_that_ends_a_line_stays_a_pending_owner() { + // Go ends a line at a comment that holds a line break. In the first source Go reads + // two embedded fields, `X` and `int`, and in the second a method without a result + // and an embedded `int`; the grammar reads one member each time. In the last three + // Go reads what the grammar reads, and the member stays pending all the same: the + // rule looks at the comment and not at the token before it. + let members: [(&[u8], &str, Range, Doc, Range); 5] = [ + ( + b"package p\ntype S struct {\n// d\nX /* a\n b */ int\n}\n", + "field_declaration", + 31..47, + comment(26..30, "d", [(0..1, Copied(29..30))]), + 33..43, + ), + ( + b"package p\ntype I interface {\n// m\nM() /* a\n b */ int\n}\n", + "method_elem", + 34..52, + comment(29..33, "m", [(0..1, Copied(32..33))]), + 38..48, + ), + ( + b"package p\ntype I interface {\n// e\nA | /* a\n b */ B\n}\n", + "type_elem", + 34..50, + comment(29..33, "e", [(0..1, Copied(32..33))]), + 38..48, + ), + ( + b"package p\ntype S struct {\n// d\nX, /* a\n b */ Y int\n}\n", + "field_declaration", + 31..50, + comment(26..30, "d", [(0..1, Copied(29..30))]), + 34..44, + ), + ( + b"package p\ntype S struct {\n// d\n* /* a\n b */ T\n}\n", + "field_declaration", + 31..45, + comment(26..30, "d", [(0..1, Copied(29..30))]), + 33..43, + ), + ]; + for (source, kind, range, document, inside) in members { + let name = source.escape_ascii(); + // The document is published with its text and has no association. + let expected = View { + documents: vec![document], + assessments: 2, + ..View::default() + }; + assert_default_then_retained( + source, + expected, + Retain::Unbound, + (CandidateDisposition::Unattached, inside), + ); + let parser = clean(source); + let member = node_at(&parser, kind, range.clone()); + for index in &indexes(&parser, DocumentationOptions::default()) { + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, (kind, range.clone()), None), + (AWAITS_PROJECTION, (kind, range.clone()), Some(0)), + ], + "{name}" + ); + assert!(index.node_projection(member).unwrap().pending(), "{name}"); + assert_eq!( + index.node_owners(member).err(), + Some(OwnerError::PendingOwner), + "{name}" + ); + let query = index.node_associations(member).unwrap(); + assert!(query.projection_pending(), "{name}"); + assert_eq!(query.associations().len(), 0, "{name}"); + // expected: the file, the package clause, the type declaration and its + // spec; the member is no owner. + assert_eq!(index.facts().owners().len(), 4, "{name}"); + } + } +} + +/// Asserts that the member is a pending owner in both indexes, as at the evidence base. +/// Its document is published with its text and has no association, the member carries +/// both `Owner` assessments, and the index has the four owners around it and no other. +/// `inside` are the comments inside the member: the retention keeps each as an +/// unattached candidate, in order. +#[cfg(feature = "go")] +fn assert_stays_pending( + source: &[u8], + kind: &'static str, + range: Range, + document: Doc, + inside: &[Range], +) { + let name = source.escape_ascii(); + let mut expected = View { + documents: vec![document], + assessments: 2, + ..View::default() + }; + assert_eq!(view(source), expected, "{name}"); + expected.evidence = inside + .iter() + .map(|comment| (CandidateDisposition::Unattached, comment.clone())) + .collect(); + assert_eq!(retained(source, Retain::Unbound), expected, "{name}"); + let parser = clean(source); + let member = node_at(&parser, kind, range.clone()); + for index in &indexes(&parser, DocumentationOptions::default()) { + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, (kind, range.clone()), None), + (AWAITS_PROJECTION, (kind, range.clone()), Some(0)), + ], + "{name}" + ); + assert!(index.node_projection(member).unwrap().pending(), "{name}"); + assert_eq!( + index.node_owners(member).err(), + Some(OwnerError::PendingOwner), + "{name}" + ); + let query = index.node_associations(member).unwrap(); + assert!(query.projection_pending(), "{name}"); + assert_eq!(query.associations().len(), 0, "{name}"); + // expected: the file, the package clause, the type declaration and its spec; + // the member is no owner. + assert_eq!(index.facts().owners().len(), 4, "{name}"); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_line_end_below_a_child_keeps_the_member_pending() { + // The comment holds a line break and stands below a child of the member, after the + // `)` of a function type. Go ends the line there, so it ends the member before the + // comment (`X func()`, `M() func()`, `E | func()`, `X []func()`, `M() <-chan func()`, + // `X *func()`, `X map[string]func()`) and reads what follows as one more embedded + // member. The grammar reads one member to the end of the row. That node is not the + // member Go reads, so it stays a pending owner. + let members: [(&[u8], &str, Range, Range); 8] = [ + ( + b"package p\ntype S struct {\n// d\nX func() /* a\n b */ int\n}\n", + "field_declaration", + 31..54, + 40..50, + ), + ( + b"package p\ntype I interface {\n// d\nM() func() /* a\n b */ int\n}\n", + "method_elem", + 34..59, + 45..55, + ), + ( + b"package p\ntype I interface {\n// d\nE | func() /* a\n b */ int\n}\n", + "type_elem", + 34..59, + 45..55, + ), + ( + b"package p\ntype I interface {\n// d\nE | func() /* stop\n here */ B | C\n}\n", + "type_elem", + 34..67, + 45..61, + ), + ( + b"package p\ntype S struct {\n// d\nX []func() /* a\n b */ int\n}\n", + "field_declaration", + 31..56, + 42..52, + ), + ( + b"package p\ntype I interface {\n// d\nM() <-chan func() /* a\n b */ int\n}\n", + "method_elem", + 34..66, + 52..62, + ), + ( + b"package p\ntype S struct {\n// d\nX *func() /* a\n b */ int\n}\n", + "field_declaration", + 31..55, + 41..51, + ), + ( + b"package p\ntype S struct {\n// d\nX map[string]func() /* a\n b */ int\n}\n", + "field_declaration", + 31..65, + 51..61, + ), + ]; + for (source, kind, range, inside) in members { + // expected: the comment `// d` ends one byte before the member starts. + let above = range.start - 5..range.start - 1; + let document = comment( + above.clone(), + "d", + [(0..1, Copied(above.end - 1..above.end))], + ); + assert_stays_pending(source, kind, range, document, &[inside]); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_line_end_after_a_closing_bracket_keeps_the_member_pending() { + // After a `]` the grammar reads on past a line end where an element type has to + // follow, and Go ends the line. In the first three sources Go reads two embedded + // fields, `X[2]` or `X[N]` and the name on the next row, and no field named `X`; + // the third has its line end in a comment below the array type, the second in a + // `//` comment on one row. Go rejects the last four files. In each the node is not + // a member Go reads, so it stays a pending owner. + let members: [(&[u8], &str, Range, &[Range]); 7] = [ + ( + b"package p\ntype S struct {\n// d\nX [2]\nint\n}\n", + "field_declaration", + 31..40, + &[], + ), + ( + b"package p\ntype S struct {\n// d\nX [2] // c\nint\n}\n", + "field_declaration", + 31..45, + &[37..41], + ), + ( + b"package p\ntype S struct {\n// d\nX [N] /* a\n b */ T\n}\n", + "field_declaration", + 31..49, + &[37..47], + ), + ( + b"package p\ntype S struct {\n// d\nX map[string]\nint\n}\n", + "field_declaration", + 31..48, + &[], + ), + ( + b"package p\ntype S struct {\n// d\nX []\nint\n}\n", + "field_declaration", + 31..39, + &[], + ), + ( + b"package p\ntype I interface {\n// d\nM() [2]\nint\n}\n", + "method_elem", + 34..45, + &[], + ), + ( + b"package p\ntype S struct {\n// d\nX, Y [2]\nint\n}\n", + "field_declaration", + 31..43, + &[], + ), + ]; + for (source, kind, range, inside) in members { + // expected: the comment `// d` ends one byte before the member starts. + let above = range.start - 5..range.start - 1; + let document = comment( + above.clone(), + "d", + [(0..1, Copied(above.end - 1..above.end))], + ); + assert_stays_pending(source, kind, range, document, inside); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending() { + // The other tokens after which Go ends a line, each before a line end that the + // grammar reads past: the `}` of a struct type in a map key, a parameter name, a + // string literal of each kind and a number. Go rejects every one of these files, so + // there is no member of Go to follow, and the member stays a pending owner. + let members: [(&[u8], &str, Range, &[Range]); 5] = [ + ( + b"package p\ntype S struct {\n// d\nX map[struct{}\n]int\n}\n", + "field_declaration", + 31..50, + &[], + ), + ( + b"package p\ntype I interface {\n// d\nM(a /* x\n y */ int)\n}\n", + "method_elem", + 34..53, + &[38..48], + ), + ( + b"package p\ntype S struct {\n// d\nX [len(\"s\" /* a\n b */ )]int\n}\n", + "field_declaration", + 31..58, + &[42..52], + ), + ( + b"package p\ntype S struct {\n// d\nX [len(`s` /* a\n b */ )]int\n}\n", + "field_declaration", + 31..58, + &[42..52], + ), + ( + b"package p\ntype S struct {\n// d\nX [2 /* a\n b */ ]int\n}\n", + "field_declaration", + 31..51, + &[36..46], + ), + ]; + for (source, kind, range, inside) in members { + // expected: the comment `// d` ends one byte before the member starts. + let above = range.start - 5..range.start - 1; + let document = comment( + above.clone(), + "d", + [(0..1, Copied(above.end - 1..above.end))], + ); + assert_stays_pending(source, kind, range, document, inside); + } +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_members_over_several_rows_keep_their_owners() { + // Controls: a line end inside a member where Go ends no line, because the token + // before it is none of an identifier, a literal, `)`, `]` and `}`, or because the + // line end lies inside one token. Go reads each of these members as the grammar + // does, and each keeps its owners. + let d = || comment(26..30, "d", [(0..1, Copied(29..30))]); + let e = || comment(29..33, "d", [(0..1, Copied(32..33))]); + let plain: [(&[u8], View); 18] = [ + // A parameter list over rows. + ( + b"package p\ntype I interface {\n// d\nM(\n\ta int,\n\tb int,\n) error\n}\n", + owned(e(), "method_elem", 34..60), + ), + // A parameter list and a result list over rows. + ( + b"package p\ntype S struct {\n// d\nF func(\n\ta int,\n) (\n\tint,\n\terror,\n)\n}\n", + named(d(), 31..66, &[31..32]), + ), + // A type argument list over rows. + ( + b"package p\ntype S struct {\n// d\nX G[\n\tint,\n\tstring,\n]\n}\n", + named(d(), 31..52, &[31..32]), + ), + // A union with `|` at the row ends. + ( + b"package p\ntype I interface {\n// d\nA |\n\tB |\n\tC\n}\n", + owned(e(), "type_elem", 34..45), + ), + // Names after a comma. + ( + b"package p\ntype S struct {\n// d\nX,\n\tY int\n}\n", + named(d(), 31..40, &[31..32, 35..36]), + ), + // A tag in back quotes over rows: the line end is inside one token. + ( + b"package p\ntype S struct {\n// d\nX int `a\nb`\n}\n", + named(d(), 31..42, &[31..32]), + ), + // `X [N]` before the closing brace: an embedded generic type, for Go as well. + ( + b"package p\ntype S struct {\n// d\nX [N]\n}\n", + owned(d(), "field_declaration", 31..36), + ), + // The same before a name on the next row: two embedded fields, for Go as well. + ( + b"package p\ntype S struct {\n// d\nX [N]\nT\n}\n", + owned(d(), "field_declaration", 31..36), + ), + // After `chan`, `*`, `.`, `struct`, `map` and `func`. + ( + b"package p\ntype S struct {\n// d\nX chan\nint\n}\n", + named(d(), 31..41, &[31..32]), + ), + ( + b"package p\ntype S struct {\n// d\nX *\nint\n}\n", + named(d(), 31..38, &[31..32]), + ), + ( + b"package p\ntype S struct {\n// d\nio.\nReader\n}\n", + owned(d(), "field_declaration", 31..41), + ), + ( + b"package p\ntype S struct {\n// d\nX struct\n{}\n}\n", + named(d(), 31..42, &[31..32]), + ), + ( + b"package p\ntype S struct {\n// d\nX map\n[string]int\n}\n", + named(d(), 31..48, &[31..32]), + ), + ( + b"package p\ntype S struct {\n// d\nX func\n()\n}\n", + named(d(), 31..40, &[31..32]), + ), + // A raw string over rows in an array length: the line end is inside one token, + // and the token ends on the row of the `)` after it. + ( + b"package p\ntype S struct {\n// d\nX [len(`a\nb`)]int\n}\n", + named(d(), 31..48, &[31..32]), + ), + // The statements of a function literal are no tokens of the member. + ( + b"package p\ntype S struct {\n// d\nX [len(func() []int {\nreturn nil\n}())]int\n}\n", + named(d(), 31..72, &[31..32]), + ), + // After an operator. + ( + b"package p\ntype S struct {\n// d\nX [1 +\n2]int\n}\n", + named(d(), 31..43, &[31..32]), + ), + // A nested struct with documented members on their own rows. + ( + b"package p\ntype S struct {\n// d\nA struct {\n// x\nX int\n// y\nY int\n}\n}\n", + View { + documents: vec![ + d(), + comment(42..46, "x", [(0..1, Copied(45..46))]), + comment(53..57, "y", [(0..1, Copied(56..57))]), + ], + owners: vec![ + (Resolution::Resolved, "field_declaration", 31..65), + (Resolution::Resolved, "field_declaration", 47..52), + (Resolution::Resolved, "field_declaration", 58..63), + ], + slots: vec![(0, vec![31..32]), (1, vec![47..48]), (2, vec![58..59])], + ..View::default() + }, + ), + ]; + for (source, expected) in plain { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + } + // A nested interface with documented members on their own rows. + assert_eq!( + view(b"package p\ntype S struct {\n// d\nI interface {\n// m\nM()\n// n\nN()\n}\n}\n"), + View { + documents: vec![ + d(), + comment(45..49, "m", [(0..1, Copied(48..49))]), + comment(54..58, "n", [(0..1, Copied(57..58))]), + ], + owners: vec![ + (Resolution::Resolved, "field_declaration", 31..64), + (Resolution::Resolved, "method_elem", 50..53), + (Resolution::Resolved, "method_elem", 59..62), + ], + slots: vec![(0, vec![31..32])], + ..View::default() + } + ); + // A comment at a line end after a comma, and a comment that holds a line break + // after a comma or an opening bracket: Go ends no line there. + assert_default_then_retained( + b"package p\ntype I interface {\n// d\nM(a int, // first\n\tb int) error\n}\n", + owned(e(), "method_elem", 34..65), + Retain::Unbound, + (CandidateDisposition::Unattached, 43..51), + ); + assert_default_then_retained( + b"package p\ntype S struct {\n// d\nF func(a, /* a\n b */ b int)\n}\n", + named(d(), 31..58, &[31..32]), + Retain::Unbound, + (CandidateDisposition::Unattached, 41..51), + ); + assert_default_then_retained( + b"package p\ntype S struct {\n// d\nX map[ /* a\n b */ string]int\n}\n", + named(d(), 31..59, &[31..32]), + Retain::Unbound, + (CandidateDisposition::Unattached, 38..48), + ); + // The second embedded field of `X [N]\nT` has its owner too. + let parser = clean(b"package p\ntype S struct {\n// d\nX [N]\nT\n}\n"); + for index in &indexes(&parser, DocumentationOptions::default()) { + assert_eq!( + owners_of(index, node_at(&parser, "field_declaration", 37..38)), + ["field_declaration 37..38"] + ); + } +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_nested_members_are_read_on_their_own() { + // The members between the braces of a nested struct or interface type are no tokens + // of the member around them. Each is read on its own: one may stay pending while + // the other has its owners. + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + + // The inner field ends early for Go (`X[2]` and `int`, two embedded fields); the + // outer field is the member Go reads. + let source: &[u8] = b"package p\ntype S struct {\n// d\nA struct {\n// i\nX [2]\nint\n}\n}\n"; + let parser = clean(source); + for index in &indexes(&parser, options) { + assert_eq!( + texts(index), + [ + (vec![26..30], "d".to_owned()), + (vec![42..46], "i".to_owned()) + ] + ); + assert_eq!( + edges(index), + [( + 0, + Resolution::Resolved, + vec!["slot 0 31..32 in field_declaration 31..58".to_owned()], + ("field_declaration", 31..58), + ("field_declaration_list", 24..60), + )] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("field_declaration", 47..56), None), + (AWAITS_PROJECTION, ("field_declaration", 47..56), Some(1)), + ] + ); + assert_eq!(kept(index), []); + assert_eq!( + index + .node_owners(node_at(&parser, "field_declaration", 47..56)) + .err(), + Some(OwnerError::PendingOwner) + ); + } + + // The outer method ends early for Go, which reads `M() func()` and then the + // interface as an embedded element; the method `N` inside is the member Go reads. + let source: &[u8] = b"package p\ntype I interface {\n// d\nM() func() /* a\n b */ interface {\n// i\nN()\n}\n}\n"; + let parser = clean(source); + for index in &indexes(&parser, options) { + assert_eq!( + texts(index), + [ + (vec![29..33], "d".to_owned()), + (vec![68..72], "i".to_owned()) + ] + ); + assert_eq!( + edges(index), + [( + 1, + Resolution::Resolved, + vec!["method_elem 73..76".to_owned()], + ("method_elem", 73..76), + ("interface_type", 56..78), + )] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("method_elem", 34..78), None), + (AWAITS_PROJECTION, ("method_elem", 34..78), Some(0)), + ] + ); + assert_eq!(kept(index), [(CandidateDisposition::Unattached, 45..55)]); + } + + // Go rejects the next two files, so these two outcomes are what the grammar reads + // and no reading of Go. The outer field ends early and the inner field has its slot. + let source: &[u8] = b"package p\ntype S struct {\n// d\nX [2]\nstruct {\n// i\nA int\n}\n}\n"; + let parser = clean(source); + for index in &indexes(&parser, options) { + assert_eq!( + edges(index), + [( + 1, + Resolution::Resolved, + vec!["slot 0 51..52 in field_declaration 51..56".to_owned()], + ("field_declaration", 51..56), + ("field_declaration_list", 44..58), + )] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("field_declaration", 31..58), None), + (AWAITS_PROJECTION, ("field_declaration", 31..58), Some(0)), + ] + ); + } + // The inner method has a comment with a line break among its children and stays + // pending; the outer field has its slot. + let source: &[u8] = + b"package p\ntype S struct {\n// d\nX interface {\n// i\nM /* a\n b */ ()\n}\n}\n"; + let parser = clean(source); + for index in &indexes(&parser, options) { + assert_eq!( + edges(index), + [( + 0, + Resolution::Resolved, + vec!["slot 0 31..32 in field_declaration 31..67".to_owned()], + ("field_declaration", 31..67), + ("field_declaration_list", 24..69), + )] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("method_elem", 50..65), None), + (AWAITS_PROJECTION, ("method_elem", 50..65), Some(1)), + ] + ); + assert_eq!(kept(index), [(CandidateDisposition::Unattached, 52..62)]); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_line_end_and_excluded_ranges() { + let context = DocumentationContext::default(); + let unbound = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + let source: &[u8] = b"package p\ntype S struct {\n// d\nX [2]\nint\n}\n"; + + // No excluded byte: two adjacent included ranges meet at the line feed after `]`. + // The field is whole, the rows of its tokens are those of the bytes, and Go ends it + // at that line end: it stays pending, and its document has no association. + let tree = restricted(source, &[0..36, 36..43]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, source, &context, &unbound).unwrap(); + let field = node_in(&tree, "field_declaration", 31..40); + assert_eq!(texts(&index), [(vec![26..30], "d".to_owned())]); + assert_eq!(edges(&index), []); + assert_eq!(kept(&index), []); + assert_eq!( + pending(&index, index.assessments()), + [ + (NEEDS_PROJECTION, ("field_declaration", 31..40), None), + (AWAITS_PROJECTION, ("field_declaration", 31..40), Some(0)), + ] + ); + assert_eq!( + index.node_owners(field).err(), + Some(OwnerError::PendingOwner) + ); + + // The line feed excluded: the field holds an excluded byte, so the existing guard + // keeps it pending before any token is read, as it keeps every node that holds the + // byte, and the comment reaches no target. + let tree = restricted(source, &[0..36, 37..43]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, source, &context, &unbound).unwrap(); + assert_eq!(texts(&index), []); + assert_eq!(kept(&index), [(CandidateDisposition::Unattached, 26..30)]); + assert_eq!( + pending(&index, index.assessments()), + [ + (NEEDS_PROJECTION, ("type_declaration", 10..42), None), + (NEEDS_PROJECTION, ("type_spec", 15..42), None), + (NEEDS_PROJECTION, ("struct_type", 17..42), None), + (NEEDS_PROJECTION, ("field_declaration_list", 24..42), None), + (NEEDS_PROJECTION, ("field_declaration", 31..40), None), + (NEEDS_PROJECTION, ("array_type", 33..40), None), + ] + ); + + // The control: two adjacent ranges meet at a line feed after `chan`, where Go ends + // no line. The field has its slot and its document. + let source: &[u8] = b"package p\ntype S struct {\n// d\nX chan\nint\n}\n"; + let tree = restricted(source, &[0..37, 37..44]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, source, &context, &unbound).unwrap(); + assert_eq!( + edges(&index), + [( + 0, + Resolution::Resolved, + vec!["slot 0 31..32 in field_declaration 31..41".to_owned()], + ("field_declaration", 31..41), + ("field_declaration_list", 24..43), + )] + ); + assert_eq!(pending(&index, index.assessments()), []); +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_member_beside_recovery_keeps_its_owners() { + let unbound = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + let parse = |source: &[u8]| AnyParser::parse(LANG::Go, source.to_vec(), None, None).unwrap(); + let boundary = Resolution::Unresolved(UnresolvedReason::GrammarBoundary); + + // An unclosed struct: the grammar gives an `ERROR` that holds the field. The field + // has no error of its own and gets its slot. The `ERROR` above it makes the + // association unresolved, and the slot is its candidate. + let parser = parse(b"package p\ntype S struct {\n// d\nX int\n"); + let field = node_at(&parser, "field_declaration", 31..36); + assert!(!field.has_error()); + assert_eq!(field.parent().map(site), Some(("ERROR", 10..37))); + for index in &indexes(&parser, unbound) { + assert_eq!(texts(index), [(vec![26..30], "d".to_owned())]); + assert_eq!( + edges(index), + [( + 0, + boundary, + vec!["slot 0 31..32 in field_declaration 31..36".to_owned()], + ("field_declaration", 31..36), + ("ERROR", 10..37), + )] + ); + assert_eq!(pending(index, index.assessments()), []); + assert_eq!(kept(index), []); + } + + // The same for a method of an unclosed interface. + let parser = parse(b"package p\ntype I interface {\n// m\nM()\n"); + let method = node_at(&parser, "method_elem", 34..37); + assert!(!method.has_error()); + assert_eq!(method.parent().map(site), Some(("ERROR", 10..38))); + for index in &indexes(&parser, unbound) { + assert_eq!(texts(index), [(vec![29..33], "m".to_owned())]); + assert_eq!( + edges(index), + [( + 0, + boundary, + vec!["method_elem 34..37".to_owned()], + ("method_elem", 34..37), + ("ERROR", 10..38), + )] + ); + assert_eq!(pending(index, index.assessments()), []); + } + + // An error in one field leaves the fields beside it their slots. The broken field + // stays pending, and so do the type declaration and its spec, which hold the error. + let parser = + parse(b"package p\ntype S struct {\n// a\nX int\n// b\nY %% int\n// c\nZ int\n}\n"); + let list = ("field_declaration_list", 24..63); + let broken = node_at(&parser, "field_declaration", 42..50); + assert!(broken.has_error()); + for index in &indexes(&parser, unbound) { + assert_eq!( + texts(index), + [ + (vec![26..30], "a".to_owned()), + (vec![37..41], "b".to_owned()), + (vec![51..55], "c".to_owned()), + ] + ); + assert_eq!( + edges(index), + [ + ( + 0, + Resolution::Resolved, + vec!["slot 0 31..32 in field_declaration 31..36".to_owned()], + ("field_declaration", 31..36), + list.clone(), + ), + ( + 1, + boundary, + vec![], + ("field_declaration", 42..50), + list.clone() + ), + ( + 2, + Resolution::Resolved, + vec!["slot 0 56..57 in field_declaration 56..61".to_owned()], + ("field_declaration", 56..61), + list.clone(), + ), + ] + ); + let above = [ + (NEEDS_PROJECTION, ("type_declaration", 10..63), None), + (NEEDS_PROJECTION, ("type_spec", 15..63), None), + ]; + let mut all = above.to_vec(); + all.extend([ + (NEEDS_PROJECTION, ("field_declaration", 42..50), None), + (AWAITS_PROJECTION, ("field_declaration", 42..50), Some(1)), + ]); + assert_eq!(pending(index, index.assessments()), all); + assert_eq!( + index.node_owners(broken).err(), + Some(OwnerError::PendingOwner) + ); + // The query of a clean field reaches the pending declarations above it. + let clean = node_at(&parser, "field_declaration", 31..36); + let query = index.node_associations(clean).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 1); + assert_eq!(pending(index, query.assessments()), above); + } + + // An `ERROR` after a method on its row is a sibling of the method. Both elements + // have no error of their own and own their comments. + let parser = parse(b"package p\ntype I interface {\n// m\nM() %%\n// e\nio.Reader\n}\n"); + assert!(node_at(&parser, "ERROR", 38..40).is_error()); + for index in &indexes(&parser, unbound) { + assert_eq!( + edges(index), + [ + ( + 0, + Resolution::Resolved, + vec!["method_elem 34..37".to_owned()], + ("method_elem", 34..37), + ("interface_type", 17..57), + ), + ( + 1, + Resolution::Resolved, + vec!["type_elem 46..55".to_owned()], + ("type_elem", 46..55), + ("interface_type", 17..57), + ), + ] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("type_declaration", 10..57), None), + (NEEDS_PROJECTION, ("type_spec", 15..57), None), + ] + ); + } + + // What the rule gives for two recovered shapes, pinned as it is and not as a + // design. An unclosed method `M(` is read as a type element `M` beside an `ERROR`, + // and that element owns the comment. + let parser = parse(b"package p\ntype I interface {\n// m\nM(\n}\n"); + assert!(node_at(&parser, "ERROR", 35..36).is_error()); + assert!(!node_at(&parser, "type_elem", 34..35).has_error()); + for index in &indexes(&parser, unbound) { + assert_eq!(texts(index), [(vec![29..33], "m".to_owned())]); + assert_eq!( + edges(index), + [( + 0, + Resolution::Resolved, + vec!["type_elem 34..35".to_owned()], + ("type_elem", 34..35), + ("interface_type", 17..38), + )] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("type_declaration", 10..38), None), + (NEEDS_PROJECTION, ("type_spec", 15..38), None), + ] + ); + } + // A function after an unclosed struct: `func` is an `ERROR`, and `F` is read as a + // field that embeds a type. It is an owner without a document; the comment above + // `func` reaches no member. + let parser = parse(b"package p\ntype S struct {\nX int\n// d\nfunc F() {}\n"); + assert!(node_at(&parser, "ERROR", 37..41).is_error()); + for index in &indexes(&parser, unbound) { + assert_eq!(texts(index), []); + assert_eq!(edges(index), []); + assert_eq!(kept(index), [(CandidateDisposition::Unattached, 32..36)]); + assert_eq!( + owners_of(index, node_at(&parser, "field_declaration", 26..31)), + ["slot 0 26..27 in field_declaration 26..31"] + ); + assert_eq!( + owners_of(index, node_at(&parser, "field_declaration", 42..43)), + ["field_declaration 42..43"] + ); + assert_eq!( + pending(index, index.assessments()), + [ + (NEEDS_PROJECTION, ("type_declaration", 10..48), None), + (NEEDS_PROJECTION, ("type_spec", 15..48), None), + ] + ); + } +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_member_and_excluded_ranges() { + let context = DocumentationContext::default(); + let unbound = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + let field_source: &[u8] = b"package p\ntype S struct {\n// both\n\tX, Y int\n}\n"; + let above_field = [ + (NEEDS_PROJECTION, ("type_declaration", 10..45), None), + (NEEDS_PROJECTION, ("type_spec", 15..45), None), + (NEEDS_PROJECTION, ("struct_type", 17..45), None), + (NEEDS_PROJECTION, ("field_declaration_list", 24..45), None), + ]; + + // An excluded byte inside the declaration, the space after the comma: the field is + // pending, as every node that holds the byte is, and the comment reaches no target. + let tree = restricted(field_source, &[0..37, 38..46]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, field_source, &context, &unbound).unwrap(); + let field = node_in(&tree, "field_declaration", 35..43); + assert_eq!(texts(&index), []); + assert_eq!(edges(&index), []); + assert_eq!(kept(&index), [(CandidateDisposition::Unattached, 26..33)]); + assert!(index.node_projection(field).unwrap().pending()); + assert_eq!( + index.node_owners(field).err(), + Some(OwnerError::PendingOwner) + ); + // expected: the file and the package clause. + assert_eq!(index.facts().owners().len(), 2); + let mut all = above_field.to_vec(); + all.push((NEEDS_PROJECTION, ("field_declaration", 35..43), None)); + assert_eq!(pending(&index, index.assessments()), all); + + // An excluded byte between the comment and the declaration, the tab: the field is + // whole and gets its slots, and the comment is not attached across the gap. + let tree = restricted(field_source, &[0..34, 35..46]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, field_source, &context, &unbound).unwrap(); + let field = node_in(&tree, "field_declaration", 35..43); + assert_eq!(texts(&index), []); + assert_eq!(edges(&index), []); + assert_eq!(kept(&index), [(CandidateDisposition::Unattached, 26..33)]); + assert_eq!( + owners_of(&index, field), + [ + "slot 0 35..36 in field_declaration 35..43", + "slot 1 38..39 in field_declaration 35..43", + ] + ); + for owner in index.node_owners(field).unwrap() { + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.associations().len(), 0); + } + assert_eq!(pending(&index, index.assessments()), above_field); + + // No excluded byte: two adjacent included ranges meet inside the name, after `al`. + let source: &[u8] = b"package p\ntype S struct {\n// d\nalpha int\n}\n"; + let tree = restricted(source, &[0..33, 33..43]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, source, &context, &unbound).unwrap(); + assert_eq!(texts(&index), [(vec![26..30], "d".to_owned())]); + assert_eq!( + edges(&index), + [( + 0, + Resolution::Resolved, + vec!["slot 0 31..33,33..36 in field_declaration 31..40".to_owned()], + ("field_declaration", 31..40), + ("field_declaration_list", 24..42), + )] + ); + assert_eq!(pending(&index, index.assessments()), []); + assert_eq!(kept(&index), []); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Slot(slot) = owner.get() else { + panic!("a field slot, found {:?}", owner.get()) + }; + let spelled: Vec<_> = slot + .source + .pieces() + .iter() + .map(SourcePiece::bytes) + .collect(); + assert_eq!(spelled, [&b"al"[..], &b"pha"[..]]); + + // The same two gaps for an interface element. + let method_source: &[u8] = b"package p\ntype I interface {\n// m\n\tM(a, b int)\n}\n"; + let above_method = [ + (NEEDS_PROJECTION, ("type_declaration", 10..48), None), + (NEEDS_PROJECTION, ("type_spec", 15..48), None), + (NEEDS_PROJECTION, ("interface_type", 17..48), None), + ]; + let tree = restricted(method_source, &[0..39, 40..49]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, method_source, &context, &unbound).unwrap(); + let method = node_in(&tree, "method_elem", 35..46); + assert_eq!(texts(&index), []); + assert_eq!(kept(&index), [(CandidateDisposition::Unattached, 29..33)]); + assert!(index.node_projection(method).unwrap().pending()); + let mut all = above_method.to_vec(); + all.extend([ + (NEEDS_PROJECTION, ("method_elem", 35..46), None), + (NEEDS_PROJECTION, ("parameter_list", 36..46), None), + (NEEDS_PROJECTION, ("parameter_declaration", 37..45), None), + ]); + assert_eq!(pending(&index, index.assessments()), all); + + let tree = restricted(method_source, &[0..34, 35..49]); + assert!(!tree.root_node().has_error()); + let index = collect(LANG::Go, &tree, method_source, &context, &unbound).unwrap(); + let method = node_in(&tree, "method_elem", 35..46); + assert_eq!(texts(&index), []); + assert_eq!(kept(&index), [(CandidateDisposition::Unattached, 29..33)]); + assert_eq!(owners_of(&index, method), ["method_elem 35..46"]); + assert_eq!(pending(&index, index.assessments()), above_method); +} + +#[cfg(feature = "go")] +#[derive(Default)] +struct Counting { + steps: Cell, + bytes: Cell, + fail_at: Option, +} + +#[cfg(feature = "go")] +impl WorkBudget for Counting { + type Error = SourceError; + #[cfg(feature = "go")] + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + fn step(&self) -> Result<(), SourceError> { + self.steps.set(self.steps.get() + 1); + if self.fail_at == Some(self.steps.get()) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + #[cfg(feature = "go")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + Ok(()) + } +} + +/// A struct whose one documented field declaration has that many names. +#[cfg(feature = "go")] +fn wide_names(width: usize) -> String { + let names: Vec<_> = (0..width).map(|at| format!("v{at}")).collect(); + format!( + "package p\ntype S struct {{\n// audit\n{} int\n}}\n", + names.join(", ") + ) +} + +/// A struct with that many documented fields of one name each. +#[cfg(feature = "go")] +fn many_fields(count: usize) -> String { + let fields: Vec<_> = (0..count) + .map(|at| format!("// d{at}\nv{at} int\n")) + .collect(); + format!("package p\ntype S struct {{\n{}}}\n", fields.concat()) +} + +/// An interface with that many documented methods. +#[cfg(feature = "go")] +fn many_methods(count: usize) -> String { + let methods: Vec<_> = (0..count) + .map(|at| format!("// d{at}\nM{at}()\n")) + .collect(); + format!("package p\ntype I interface {{\n{}}}\n", methods.concat()) +} + +/// What one call of the member scan charged and returned: steps and bytes, and the byte +/// range of each name. +#[cfg(feature = "go")] +type Scan = ( + (usize, usize), + Result>>, SourceError>, +); + +/// The member scan on the one node of that kind and range, once per budget: `None` is a +/// budget that never fails, `Some(k)` one that fails at step k. +#[cfg(feature = "go")] +fn scanned(source: &str, kind: &str, range: Range, budgets: &[Option]) -> Vec { + let parser = AnyParser::parse(LANG::Go, source.as_bytes().to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let id = index + .canonical + .lookup(node_at(&parser, kind, range)) + .unwrap(); + budgets + .iter() + .map(|fail_at| { + let budget = Counting { + fail_at: *fail_at, + ..Counting::default() + }; + let found = super::projections::go_member_names(&index.canonical, id, &budget); + let names = found.map(|found| { + found.map(|names| { + names + .iter() + .map(|name| index.canonical.nodes[name.0].evidence.node().byte_range()) + .collect() + }) + }); + ((budget.steps.get(), budget.bytes.get()), names) + }) + .collect() +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_member_scan_charges_one_step_per_child() { + let cases: [(&str, &str, Range, usize, Option>>); 11] = [ + ( + "package p\ntype S struct {\n// audit\nX int\n}\n", + "field_declaration", + 35..40, + // expected: the name and the type. + 2, + Some(vec![35..36]), + ), + ( + "package p\ntype S struct {\n// both\nX, Y int\n}\n", + "field_declaration", + 34..42, + // expected: name, `,`, name, type. + 4, + Some(vec![34..35, 37..38]), + ), + ( + "package p\ntype S struct {\n// d\nX, Y int `json:\"x\"`\n}\n", + "field_declaration", + 31..50, + // expected: name, `,`, name, type, tag. + 5, + Some(vec![31..32, 34..35]), + ), + ( + "package p\ntype S struct {\n// d\nX, /* c */ Y int\n}\n", + "field_declaration", + 31..47, + // expected: name, `,`, a comment on one row, name, type. + 5, + Some(vec![31..32, 42..43]), + ), + ( + "package p\ntype S struct {\n// audit\nio.Reader\n}\n", + "field_declaration", + 35..44, + // expected: the qualified type; no name. + 1, + Some(vec![]), + ), + ( + "package p\ntype I interface {\n// m\nM()\n// e\nio.Reader\n// u\n~int\n}\n", + "method_elem", + 34..37, + // expected: the name and the parameters; the name of a method is no + // field name. + 2, + Some(vec![]), + ), + ( + "package p\ntype I interface {\n// m\nM()\n// e\nio.Reader\n// u\n~int\n}\n", + "type_elem", + 43..52, + // expected: the qualified type. + 1, + Some(vec![]), + ), + ( + "package p\ntype I interface {\n// m\nM( /* in */ ) /* out */ int\n}\n", + "method_elem", + 34..61, + // expected: name, parameters, a comment on one row, result. + 4, + Some(vec![]), + ), + ( + "package p\ntype S struct {\n// d\nX /* a\n b */ int\n}\n", + "field_declaration", + 31..47, + // expected: the name and the comment that ends the scan. + 2, + None, + ), + ( + "package p\ntype I interface {\n// m\nM() /* a\n b */ int\n}\n", + "method_elem", + 34..52, + // expected: name, parameters and the comment that ends the scan. + 3, + None, + ), + ( + "package p\ntype S struct {\n// d\nX, /* a\n b */ Y int\n}\n", + "field_declaration", + 31..50, + // expected: name, `,` and the comment that ends the scan. + 3, + None, + ), + ]; + for (source, kind, range, steps, names) in cases { + let [(counted, found)] = &scanned(source, kind, range.clone(), &[None])[..] else { + panic!("one scan") + }; + assert_eq!(*counted, (steps, 0), "{kind} {range:?}"); + assert_eq!(*found, Ok(names), "{kind} {range:?}"); + } + + // A wide declaration, and a budget that fails at each step in turn. + let budgets: Vec<_> = std::iter::once(None).chain((1..=601).map(Some)).collect(); + let scans = scanned(&wide_names(300), "field_declaration", 35..1727, &budgets); + let (counted, found) = &scans[0]; + // expected: 300 names, 299 `,` and the type. + assert_eq!(*counted, (600, 0)); + let found = found.as_ref().unwrap().as_ref().unwrap(); + assert_eq!(found.len(), 300); + // expected: `v0` follows the 35 bytes before the names; the 300 names and their 299 + // separators are 1688 bytes, and the last name has four. + assert_eq!(found[0], 35..37); + assert_eq!(found[299], 1719..1723); + // expected: a budget that fails at step k stops the scan after k steps, for each of + // the 600 steps; one that would fail at step 601 is never reached. + for (fail_at, (counted, found)) in scans.iter().enumerate().skip(1).take(600) { + assert_eq!(*found, Err(SourceError::Cancelled), "{fail_at}"); + assert_eq!(*counted, (fail_at, 0), "{fail_at}"); + } + assert_eq!(scans[601].0, (600, 0)); + assert!(matches!(scans[601].1, Ok(Some(_)))); +} + +#[cfg(feature = "go")] +#[test] +fn go_field_name_width_costs_linear_work() { + for width in [64, 512, 2048] { + let source = wide_names(width); + let parser = AnyParser::parse(LANG::Go, source.into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + let index = parser.documentation(&context, &options).unwrap(); + let after = observations(); + // expected: 15 nodes beside the names (`source_file`, `package_clause`, + // `package`, `package_identifier`, `type_declaration`, `type`, `type_spec`, + // `type_identifier`, `struct_type`, `struct`, `field_declaration_list`, `{`, + // `comment`, `field_declaration`, `}`) and the type of the field, a node per + // name, and one comma less than names. + assert_eq!(parser.root_node().preorder().count(), 2 * width + 15); + // expected: one visit and one child batch per node. + assert_eq!(after.visits - before.visits, 2 * width + 15); + assert_eq!(after.child_batches - before.child_batches, 2 * width + 15); + // expected: every node but the root, which returns first. + assert_eq!( + after.target_classifications - before.target_classifications, + 2 * width + 14 + ); + // expected: the file, the package clause, the type declaration, its spec and + // the field declaration; a slot is pushed without an owner projection. + assert_eq!(after.owner_projections - before.owner_projections, 5); + // expected: one search for the comment fragment and one per slot; each is one + // comparison with one included range. + assert_eq!( + after.intersection_searches - before.intersection_searches, + width + 1 + ); + // expected: the profile requests no field name, and nothing looks one up. + assert_eq!(after.field_requests - before.field_requests, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + // expected: one document. + assert_eq!(after.renders - before.renders, 1); + // expected: the five owners above and one slot per name. + assert_eq!(index.facts().owners().len(), width + 5); + // expected: one document, with one association that lists a slot per name. + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + assert_eq!(association.get().owner_count(), width); + // expected: the first and the last slot have the ordinals 0 and n - 1 and are + // spelled by the first and the last name. + for position in [0, width - 1] { + let owner = index + .facts() + .associated_owner(association, position) + .unwrap(); + let Owner::Slot(found) = owner.get() else { + panic!("a field slot, found {:?}", owner.get()) + }; + assert_eq!(found.ordinal, position); + assert_eq!( + found.source.pieces()[0].bytes(), + format!("v{position}").as_bytes() + ); + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_member_count_costs_linear_work() { + // Per member: the nodes it adds to the tree, and whether it has a slot. + let shapes: [(fn(usize) -> String, usize, usize, usize); 2] = [ + // expected: a field adds its comment, its declaration, its name and its type; + // beside the fields the tree has the 13 nodes of the struct around them. + (many_fields, 4, 13, 1), + // expected: a method adds its comment, its element, its name, its parameter + // list and the two parentheses; beside the methods the tree has 12 nodes. + (many_methods, 6, 12, 0), + ]; + for (source, per_member, around, slots) in shapes { + for count in [64, 512, 2048] { + let parser = + AnyParser::parse(LANG::Go, source(count).into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + let index = parser.documentation(&context, &options).unwrap(); + let after = observations(); + // expected: the nodes each member adds and the nodes around them. + let nodes = per_member * count + around; + assert_eq!(parser.root_node().preorder().count(), nodes); + // expected: one visit and one child batch per node, and one classification + // for every node but the root. + assert_eq!(after.visits - before.visits, nodes); + assert_eq!(after.child_batches - before.child_batches, nodes); + assert_eq!( + after.target_classifications - before.target_classifications, + nodes - 1 + ); + // expected: the file, the package clause, the type declaration, its spec, + // and one projection per member. + assert_eq!( + after.owner_projections - before.owner_projections, + count + 4 + ); + // expected: one search per comment fragment and one per slot. + assert_eq!( + after.intersection_searches - before.intersection_searches, + count + slots * count + ); + // expected: the profile requests no field name, and nothing looks one up. + assert_eq!(after.field_requests - before.field_requests, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + // expected: one document per member, each with one association of one owner. + assert_eq!(after.renders - before.renders, count); + assert_eq!(index.documents().len(), count); + assert_eq!(index.associations().len(), count); + assert!( + index + .associations() + .all(|association| association.get().owner_count() == 1) + ); + // expected: the four owners above, each member, and each slot. + assert_eq!(index.facts().owners().len(), 4 + count + slots * count); + // expected: every member has its owners, so nothing is pending. + assert_eq!(index.assessments().len(), 0); + } + } +} + +#[cfg(feature = "go")] +#[test] +fn go_field_name_width_collection_observes_cancellation() { + let width = 2048; + let parser = AnyParser::parse(LANG::Go, wide_names(width).into_bytes(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + parser.documentation(&context, &options).unwrap(); + let polls = observations().polls - before.polls; + let mut inside = 0; + let mut scanning = 0; + for checkpoint in 1..=polls { + let before = observations(); + let result = crate::documentation::budget::cancel_after(checkpoint, || { + parser.documentation(&context, &options) + }); + let after = observations(); + assert!( + matches!(result, Err(CollectionError::Cancelled)), + "{checkpoint}" + ); + let owners = after.owner_projections - before.owner_projections; + let searches = after.intersection_searches - before.intersection_searches; + // The field declaration has its owner and the last slot has not been cut: the + // collection is in the slot loop. + if owners == 5 && searches < width + 1 { + inside += 1; + } + // Every node but the closing brace of the field list is entered and the field + // declaration has no owner yet: the walk is between the last child of the + // declaration and its slots, where only the two scans of its children are long. + if owners == 4 && after.visits - before.visits == 2 * width + 14 { + scanning += 1; + } + } + // expected: 6 checkpoints fall in the 6144 step charges of the slot loop (3 per + // slot, one checkpoint per 1024); the last may follow the last search. + assert!(inside >= 5, "{inside}"); + // expected: no more than those 6; a loop that charges more steps for a later slot + // holds more. + assert!(inside <= 6, "{inside}"); + // expected: the declaration has 4096 children (2048 names, 2047 commas and the + // type). The scan for the names and the scan for a line end each charge one step + // per child: 8192 steps, which hold 8 checkpoints, or 9 with the few steps before + // them. Without the charges of one scan 4096 steps lie there, which hold at most + // 5; a scan that charges a child twice brings them to 12 or more. + assert!((8..=9).contains(&scanning), "{scanning}"); + let index = crate::documentation::budget::cancel_after(polls + 1, || { + parser.documentation(&context, &options) + }) + .unwrap(); + assert_eq!( + index.associations().next().unwrap().get().owner_count(), + width + ); +} + +/// An interface whose one documented method has that many parameters. +#[cfg(feature = "go")] +fn wide_parameters(width: usize) -> String { + let parameters: Vec<_> = (0..width).map(|at| format!("a{at} int")).collect(); + format!( + "package p\ntype I interface {{\n// d\nM({})\n}}\n", + parameters.join(", ") + ) +} + +/// A struct whose one field holds that many struct types, each inside the one before, +/// on one row: `N0 struct { N1 struct { X int } }` for a depth of two. +#[cfg(feature = "go")] +fn deep_structs(depth: usize) -> String { + let open: Vec<_> = (0..depth).map(|at| format!("N{at} struct {{ ")).collect(); + format!( + "package p\ntype S struct {{\n{}X int{}\n}}\n", + open.concat(), + " }".repeat(depth) + ) +} + +/// What one call of the line-end scan charged, read and returned: steps and bytes, the +/// nodes it read, and whether Go ends the member early. +#[cfg(feature = "go")] +type LineEnds = ((usize, usize), usize, Result); + +/// The line-end scan on the one node of that kind and range, once per budget: `None` is +/// a budget that never fails, `Some(k)` one that fails at step k. +#[cfg(feature = "go")] +fn line_ends( + source: &[u8], + kind: &str, + range: Range, + budgets: &[Option], +) -> Vec { + let parser = AnyParser::parse(LANG::Go, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let id = index + .canonical + .lookup(node_at(&parser, kind, range)) + .unwrap(); + budgets + .iter() + .map(|fail_at| { + let budget = Counting { + fail_at: *fail_at, + ..Counting::default() + }; + let before = super::projections::member_reads::observed(); + let found = super::projections::go_ends_member_early(&index.canonical, id, &budget); + let reads = super::projections::member_reads::observed() - before; + ((budget.steps.get(), budget.bytes.get()), reads, found) + }) + .collect() +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_line_end_scan_reads_each_token_once() { + let cases: [(&[u8], &str, Range, usize, bool); 12] = [ + ( + b"package p\ntype S struct {\n// audit\nX int\n}\n", + "field_declaration", + 35..40, + // expected: the name and the type. + 2, + false, + ), + ( + b"package p\ntype S struct {\n// d\nX, Y int `json:\"x\"`\n}\n", + "field_declaration", + 31..50, + // expected: two names, the comma, the type, and the tag as one token; the + // three nodes inside the tag are not read. + 5, + false, + ), + ( + b"package p\ntype I interface {\n// d\nM(\n\ta int,\n\tb int,\n) error\n}\n", + "method_elem", + 34..60, + // expected: the name, the parameter list and the result; in the list two + // parentheses, two commas and two declarations; in each declaration a name + // and a type. + 13, + false, + ), + ( + b"package p\ntype I interface {\n// d\nM(a int, // first\n\tb int) error\n}\n", + "method_elem", + 34..65, + // expected: the name, the parameter list and the result; in the list two + // parentheses, one comma, the comment and two declarations of two tokens. + 13, + false, + ), + ( + b"package p\ntype S struct {\n// d\nA struct {\n// x\nX int\n// y\nY int\n}\n}\n", + "field_declaration", + 31..65, + // expected: the name, the struct type, `struct`, the field list and its two + // braces; the two comments and the two fields between them are not read. + 6, + false, + ), + ( + b"package p\ntype S struct {\n// d\nI interface {\n// m\nM()\n// n\nN()\n}\n}\n", + "field_declaration", + 31..64, + // expected: the name, the interface type, `interface` and the two braces. + 5, + false, + ), + ( + b"package p\ntype S struct {\n// d\nX [len(func() []int {\nreturn nil\n}())]int\n}\n", + "field_declaration", + 31..72, + // expected: the name and the array type (2); `[`, the outer call, `len` and + // its argument list (4); `(`, the inner call and the function literal (3); + // `func`, the parameter list and its two parentheses (4); the slice type + // with `[`, `]` and `int` (4); the block and its two braces (3); the inner + // argument list with two parentheses (3); `)`, `]` and `int` (3). + 26, + false, + ), + ( + b"package p\ntype S struct {\n// d\nX [2]\nint\n}\n", + "field_declaration", + 31..40, + // expected: the name, the array type, `[`, `2`, `]`, and the `int` on the + // next row, at which the scan returns. + 6, + true, + ), + ( + b"package p\ntype S struct {\n// d\nX func() /* a\n b */ int\n}\n", + "field_declaration", + 31..54, + // expected: the name, the function type, `func`, the parameter list, two + // parentheses, the comment, and the `int` at which the scan returns. + 8, + true, + ), + ( + b"package p\ntype I interface {\n// d\nE | func() /* stop\n here */ B | C\n}\n", + "type_elem", + 34..67, + // expected: `E`, `|`, the function type, `func`, the parameter list, two + // parentheses, the comment, and the `B` at which the scan returns; the + // second `|` and `C` are not read. + 9, + true, + ), + ( + b"package p\ntype S struct {\n// d\nX [len(\"s\" /* a\n b */ )]int\n}\n", + "field_declaration", + 31..58, + // expected: the name, the array type, `[`, the call, `len`, the argument + // list, `(`, the string as one token, the comment, and the `)` at which the + // scan returns. + 10, + true, + ), + ( + b"package p\ntype S struct {\n// d\nX map[struct{}\n]int\n}\n", + "field_declaration", + 31..50, + // expected: the name, the map type, `map`, `[`, the struct type, `struct`, + // the field list, its two braces, and the `]` at which the scan returns. + 10, + true, + ), + ]; + for (source, kind, range, steps, early) in cases { + // expected: one step and one counted read per node read, and no byte charge. + assert_eq!( + line_ends(source, kind, range, &[None]), + [((steps, 0), steps, Ok(early))], + "{}", + source.escape_ascii() + ); + } + // expected: 4 * 300 + 3 nodes (the name, the parameter list and its two + // parentheses; per parameter the declaration, its name and its type; 299 commas). + // A budget that fails at step k stops the scan after k steps, before the k-th read. + let wide = wide_parameters(300); + let member = ("method_elem", 34..wide.len() - 3); + let budgets: Vec<_> = std::iter::once(None).chain((1..=1204).map(Some)).collect(); + let found = line_ends(wide.as_bytes(), member.0, member.1, &budgets); + assert_eq!(found[0], ((1203, 0), 1203, Ok(false))); + for (fail_at, scan) in (1..=1203).zip(&found[1..]) { + assert_eq!( + *scan, + ((fail_at, 0), fail_at - 1, Err(SourceError::Cancelled)), + "{fail_at}" + ); + } + assert_eq!(found[1204], ((1203, 0), 1203, Ok(false))); +} + +/// The nodes the line-end scan read during one typed collection of a Go source, and +/// the index. +#[cfg(feature = "go")] +fn member_reads_of(parser: &AnyParser) -> (usize, DocumentationIndex<'_>) { + let before = super::projections::member_reads::observed(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + (super::projections::member_reads::observed() - before, index) +} + +#[cfg(feature = "go")] +#[test] +#[allow(clippy::too_many_lines)] +fn go_line_end_scan_costs_linear_work() { + // A wide parameter list: every token of the method is read once. + for width in [64, 512, 2048] { + let parser = + AnyParser::parse(LANG::Go, wide_parameters(width).into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let before = observations(); + let (reads, index) = member_reads_of(&parser); + let after = observations(); + // expected: the name, the parameter list and its two parentheses; per parameter + // the declaration, its name and its type; one comma less than parameters. + assert_eq!(reads, 4 * width + 3); + // expected: those nodes, the method itself, and 13 around it (`source_file`, + // `package_clause`, `package`, `package_identifier`, `type_declaration`, `type`, + // `type_spec`, `type_identifier`, `interface_type`, `interface`, `{`, `comment`, + // `}`). + let nodes = 4 * width + 17; + assert_eq!(parser.root_node().preorder().count(), nodes); + // expected: the scan moves no other counter. One visit and one child batch per + // node, one classification for every node but the root, one search for the + // comment fragment, no field name requested or looked up. + assert_eq!(after.visits - before.visits, nodes); + assert_eq!(after.child_batches - before.child_batches, nodes); + assert_eq!( + after.target_classifications - before.target_classifications, + nodes - 1 + ); + assert_eq!( + after.intersection_searches - before.intersection_searches, + 1 + ); + assert_eq!(after.field_requests - before.field_requests, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + // expected: the method has its owner and its document. + assert_eq!(index.facts().owners().len(), 5); + assert_eq!(index.associations().len(), 1); + assert_eq!(index.assessments().len(), 0); + } + + // Many members: the reads grow with the number of members. + for count in [64, 512, 2048] { + let parser = + AnyParser::parse(LANG::Go, many_fields(count).into_bytes(), None, None).unwrap(); + // expected: per field its name and its type. + assert_eq!(member_reads_of(&parser).0, 2 * count); + let parser = + AnyParser::parse(LANG::Go, many_methods(count).into_bytes(), None, None).unwrap(); + // expected: per method its name, its parameter list and the two parentheses. + assert_eq!(member_reads_of(&parser).0, 4 * count); + } + + // Structs nested many levels deep, on one row: no line end is inside, so every + // field has its owners whether or not a nested body is read again, and only the + // count tells. Each node is read for one member. + for depth in [16, 64, 256] { + let parser = + AnyParser::parse(LANG::Go, deep_structs(depth).into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let (reads, index) = member_reads_of(&parser); + // expected: per nesting field its name, the struct type, `struct`, the field + // list and its two braces; for the innermost field its name and its type. + assert_eq!(reads, 6 * depth + 2); + // expected: per nesting field 7 nodes (those six and the declaration), 3 for + // the innermost field, and 13 around them. + assert_eq!(parser.root_node().preorder().count(), 7 * depth + 16); + // expected: the file, the package clause, the type declaration and its spec; + // per field its declaration and one slot. + assert_eq!(index.facts().owners().len(), 4 + 2 * (depth + 1)); + assert_eq!(index.assessments().len(), 0); + } + + // A Go file without a member: the same wide parameter list on a function. The scan + // reads nothing; the collections above are the control that the counter counts. + let parameters: Vec<_> = (0..2048).map(|at| format!("a{at} int")).collect(); + let source = format!("package p\n// d\nfunc F({}) {{}}\n", parameters.join(", ")); + let parser = AnyParser::parse(LANG::Go, source.into_bytes(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let (reads, index) = member_reads_of(&parser); + assert_eq!(reads, 0); + // expected: the file, the package clause and the function; one document. + assert_eq!(index.facts().owners().len(), 3); + assert_eq!(index.documents().len(), 1); +} + +#[cfg(all(feature = "go", feature = "java"))] +#[test] +fn go_line_end_scan_reads_nothing_for_another_profile() { + // The control: a Go field with two names moves the counter by its four tokens. + let parser = clean(b"package p\ntype S struct {\n// both\nX, Y int\n}\n"); + assert_eq!(member_reads_of(&parser).0, 4); + // A Java field declaration with two names has the same owners, a declaration and + // two field slots, and the scan reads nothing for it. + let source = b"class C {\n/** d */\nint x, y;\n}\n"; + let parser = AnyParser::parse(LANG::Java, source.to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + let (reads, index) = member_reads_of(&parser); + assert_eq!(reads, 0); + assert_eq!(index.associations().len(), 1); + assert_eq!(index.associations().next().unwrap().get().owner_count(), 2); +} + +#[cfg(feature = "go")] +#[test] +fn go_wide_parameter_list_collection_observes_cancellation() { + let width = 2048; + let parser = + AnyParser::parse(LANG::Go, wide_parameters(width).into_bytes(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + parser.documentation(&context, &options).unwrap(); + let polls = observations().polls - before.polls; + let mut scanning = 0; + for checkpoint in 1..=polls { + let before = observations(); + let result = crate::documentation::budget::cancel_after(checkpoint, || { + parser.documentation(&context, &options) + }); + let after = observations(); + assert!( + matches!(result, Err(CollectionError::Cancelled)), + "{checkpoint}" + ); + // Every node but the closing brace of the interface is entered and the method + // has no owner yet: the walk is between the last token of the method and its + // owner, where only the line-end scan is long. + if after.owner_projections - before.owner_projections == 4 + && after.visits - before.visits == 4 * width + 16 + { + scanning += 1; + } + } + // expected: the scan charges one step for each of the 4 * 2048 + 3 = 8195 nodes it + // reads, which hold 8 checkpoints, or 9 with the few steps before it. Without those + // charges fewer than 1024 steps lie there, which hold at most one. + assert!(scanning >= 8, "{scanning}"); + // expected: no more than 9; a scan that charges a node twice holds 16. + assert!(scanning <= 9, "{scanning}"); + let index = crate::documentation::budget::cancel_after(polls + 1, || { + parser.documentation(&context, &options) + }) + .unwrap(); + assert_eq!(index.associations().len(), 1); +} diff --git a/big-code-analysis-ast/src/documentation/collector/projections.rs b/big-code-analysis-ast/src/documentation/collector/projections.rs index 10ea5a9fa..0ac03a9a1 100644 --- a/big-code-analysis-ast/src/documentation/collector/projections.rs +++ b/big-code-analysis-ast/src/documentation/collector/projections.rs @@ -49,6 +49,9 @@ impl Builder<'_> { { return self.java_field_slots(id, budget); } + if self.index.profile == Profile::GoDoc { + return self.go_member_owners(id, budget); + } if !is_wrapper(self.index.profile, node.kind()) || !matches!( self.index.canonical.nodes[id.0].projection, @@ -225,6 +228,45 @@ impl Builder<'_> { let Some(names) = java_declarator_names(&self.index.canonical, id, budget)? else { return Ok(()); }; + self.field_slots(id, names, budget) + } + + fn go_member_owners( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let record = &self.index.canonical.nodes[id.0]; + if !matches!(record.projection, Projection::Pending) + || !matches!( + record.evidence.node().kind(), + "field_declaration" | "method_elem" | "type_elem" + ) + { + return Ok(()); + } + let Some(names) = go_member_names(&self.index.canonical, id, budget)? else { + return Ok(()); + }; + if go_ends_member_early(&self.index.canonical, id, budget)? { + // The node is not the member Go reads: it stays a pending owner. + Ok(()) + } else if names.is_empty() { + // An interface element, or a field that embeds a type and has no name. + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + Ok(()) + } else { + self.field_slots(id, names, budget) + } + } + + // The declaration owns as a node, and each name owns as a field slot in it. + fn field_slots( + &mut self, + id: NodeId, + names: Vec, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { let declaration = OwnerId(self.index.facts.owners.len()); self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); let mut fields = Vec::new(); @@ -397,3 +439,83 @@ pub(super) fn java_declarator_names( // The grammar requires one declarator; an empty list is not reachable either. Ok((!names.is_empty()).then_some(names)) } + +// Go ends a line at a comment that holds a line break, and a line end after a name, a +// type or a closing bracket ends the member. The grammar reads on, so a member with +// such a comment among its children may not be the member Go reads: `None`. Otherwise +// the names of a field declaration, in order; none for a field that embeds a type or +// for an interface element. +pub(super) fn go_member_names( + canonical: &CanonicalNodes<'_>, + member: NodeId, + budget: &B, +) -> Result>, B::Error> { + let field = canonical.nodes[member.0].evidence.node().kind() == "field_declaration"; + let mut names = Vec::new(); + for &child in &canonical.children[canonical.nodes[member.0].children.clone()] { + budget.step()?; + let node = canonical.nodes[child.0].evidence.node(); + match node.kind() { + "comment" if node.start_position().row != node.end_position().row => { + return Ok(None); + } + "field_identifier" if field => names.push(child), + _ => {} + } + } + Ok(Some(names)) +} + +// Counts the nodes `go_ends_member_early` reads. No assertion on an index can tell +// whether a nested body is read once or once for every member around it. +crate::observation::counter!(member_reads); + +// Go puts a semicolon at a line end after a name, a literal or a closing bracket, and a +// comment that ends a line is such a line end. The grammar reads some members on past +// it (`X [2]\nint`, `X func() /* a\n b */ int`), and then the node is not the member Go +// reads. A token is a node without children, or a string literal. The members between +// the braces of a nested struct or interface type and the statements of a function +// literal are not tokens of this member, so no node is read for two members. +pub(super) fn go_ends_member_early( + canonical: &CanonicalNodes<'_>, + member: NodeId, + budget: &B, +) -> Result { + let mut open = vec![(canonical.nodes[member.0].children.clone(), false)]; + let mut line_end = None; + while let Some((children, body)) = open.last_mut() { + let Some(at) = children.next() else { + open.pop(); + continue; + }; + budget.step()?; + member_reads::record(); + let record = &canonical.nodes[canonical.children[at].0]; + let node = record.evidence.node(); + let kind = node.kind(); + if kind == "comment" { + continue; + } + if !record.children.is_empty() + && !matches!(kind, "raw_string_literal" | "interpreted_string_literal") + { + let body = matches!(kind, "field_declaration_list" | "interface_type" | "block"); + open.push((record.children.clone(), body)); + continue; + } + if line_end.is_some_and(|row| row < node.start_position().row) { + return Ok(true); + } + line_end = go_line_end(node); + if *body && kind == "{" { + children.start = children.start.max(children.end.saturating_sub(1)); + } + } + Ok(false) +} + +// The row on which a token ends, if Go ends a line after it: an identifier or a literal, +// which are the named tokens of the grammar, or a closing bracket. +fn go_line_end(token: tree_sitter::Node<'_>) -> Option { + (token.is_named() || matches!(token.kind(), ")" | "]" | "}")).then(|| token.end_position().row) +} diff --git a/tests/fixtures/documentation/go-unit2-provenance.json b/tests/fixtures/documentation/go-unit2-provenance.json new file mode 100644 index 000000000..50e5cadf6 --- /dev/null +++ b/tests/fixtures/documentation/go-unit2-provenance.json @@ -0,0 +1,32 @@ +{ + "scope": "Go struct field and interface element owners: field slots for the names of a field declaration, node owners for an embedded field, a method element and a name-led type element; Unit 2 of #1672", + "base": "6b72972d9743ba512042373b8599096bfae09696", + "grammar": {"runtime": "0.26.13", "go": "0.25.0"}, + "production_oracles": "big-code-analysis-ast/src/documentation/collector/go_tests.rs", + "legacy_oracles": "src/metrics/loc/documentation_tests.rs", + "mutation_manifest": "utils/documentation-go-unit2-perturb.json", + "legacy_mutation_manifest": "utils/documentation-go-unit2-legacy-perturb.json", + "reference": {"tool": "Go", "version": "go1.26.1 linux/arm64", "configuration": "go/parser.ParseFile with ParseComments|AllErrors|SkipObjectResolution on each source as one file; ast.Field Doc and Comment per struct field and interface element, with names and byte offsets; go/doc.NewFromFiles with AllDecls|AllMethods|PreserveAST for sources without a parse error. Run under env -i with GOPROXY=off, GOTOOLCHAIN=local, GOENV=off and every cache inside the run directory", "evidence": "Executed on 2026-11-25 for every source of the production oracles; the Doc group of each field and element, its names and the extent of each member were compared with the expected owners. Also for 1,664 generated sources with a line end at every gap of 81 member forms, and for 2,031 files of the Go 1.26.1 standard library, read only", "qualification": "Source attachment only. No gofmt, go vet or type check; publication is not claimed."}, + "legacy_measurement": {"binary": "bca 2.6.1 built from the base commit, debug profile", "command": "bca metrics --no-config --no-ignore --no-skip-generated --language go --format json --metrics loc ", "qualification": "Each measured file holds exactly the bytes of one legacy oracle source: no CR and one final LF, so file normalization changes nothing."}, + "known_differences": [ + "A member whose children include a comment with a line break stays a pending owner. Go ends a line at such a comment: for X /* a\n b */ int it reads two embedded fields, and for M() /* a\n b */ int a method and an embedded element. Where the comment follows a comma, a bar or a star, Go reads what the grammar reads and the member is pending all the same.", + "A member that Go ends at a line end before the end of its node stays a pending owner. Go puts a semicolon at a line end after an identifier, a literal, ), ] or }, also where a comment ends the line; the pinned grammar reads some members on past it. X [2]\nint is one field for the grammar and two embedded fields for Go; X func() /* a\n b */ int is one field for the grammar, and a field and an embedded field for Go.", + "The members between the braces of a nested struct or interface type are read on their own. In a file Go rejects, a member can have its owners inside or around a member that stays pending (X [2]\nstruct { A int }).", + "A field of a struct declared in a function body, and an element of an interface declared there, has no owner and its comment is no document; go/ast attaches the comment as Doc.", + "A member with a syntax error of its own stays a pending owner; go/parser recovers and attaches the comment.", + "A member without an error of its own gets its owners beside an ERROR node. An unclosed method M( is read by the pinned grammar as a type element M, which owns the comment; a function after an unclosed struct is read as an embedded field.", + "The pinned grammar accepts a line feed inside a field type where Go ends the line and rejects the file (X map[string]\nint); the field stays a pending owner.", + "The local text of // a is a; CommentGroup.Text returns a with a final line feed.", + "The statements between the braces of a function literal are not read for a member, as the members of a nested struct or interface type are not. Where Go rejects a line end there (X [len(func() int {\nif true\n{\nreturn 1\n}\nreturn 0\n}())]int), the member keeps its owners as the grammar reads; Go gives no reading of the file.", + "The pinned grammar reads a form feed and a vertical tab as white space, and Go rejects both bytes. A member with one of them between two of its tokens (X [2]\fint) keeps its owners as the grammar reads." + ], + "pending": [ + "Names of var and const specs and the relation of a group to its members", + "Role and owner of package documentation", + "Directive-only groups", + "The block comment after a multi-row trailing block", + "Recovery shapes beside a member", + "Imports, parameters and type arguments", + "Benchmark workloads and fuzz seeds for member owners" + ] +} diff --git a/utils/documentation-form-matrix.json b/utils/documentation-form-matrix.json index 6a78afc8c..0c1735d9f 100644 --- a/utils/documentation-form-matrix.json +++ b/utils/documentation-form-matrix.json @@ -73,9 +73,9 @@ "pending": ["page/group/other structural targets", "signature/in-body ownership", "conditional/recovery projections", "complex declarators", "publication"] }, "Go": { - "implemented": ["basic function/package", "declaration group and spec", "positional runs", "directive filtering", "literal block stars"], + "implemented": ["basic function/package", "declaration group and spec", "positional runs", "directive filtering", "literal block stars", "field name slots", "embedded field and interface element owners"], "ineligible": ["local declarations", "ordinary trailing comments", "source blank-line-separated run", "directive-only prose"], - "pending": ["multi-name field slots", "interface elements", "publication"] + "pending": ["members with a syntax error, a line-ending comment among their children, or a line end at which Go ends them early", "publication"] }, "Ruby": { "implemented": ["basic method/type", "modifier/body wrapper projections", "native YARD scope", "magic/directive filtering", "begin/end block cleanup"], diff --git a/utils/documentation-go-unit2-perturb.json b/utils/documentation-go-unit2-perturb.json new file mode 100644 index 000000000..dd718a5ae --- /dev/null +++ b/utils/documentation-go-unit2-perturb.json @@ -0,0 +1,413 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": ["cargo", "test", "-p", "big-code-analysis-ast", "--all-features", "--lib", "documentation::"], + "cases": [ + { + "name": "go-member-projection-disabled", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::GoDoc {\n return self.go_member_owners(id, budget);", + "new": " if false && self.index.profile == Profile::GoDoc {\n return self.go_member_owners(id, budget);", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_inventory_row_gives_one_document_to_both_names", "documentation::collector::go_tests::go_interface_elements_own_as_their_nodes", "documentation::collector::go_tests::go_undocumented_members_have_owners_and_no_assessment", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners"] + }, + { + "name": "go-member-projection-reaches-groovy", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if self.index.profile == Profile::GoDoc {", + "new": " if matches!(self.index.profile, Profile::GoDoc | Profile::Groovydoc) {", + "expect": ["documentation::collector::form_tests::groovy_field_form_is_pending_in_default_queries"] + }, + { + "name": "go-field-declaration-not-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"field_declaration\" | \"method_elem\" | \"type_elem\"", + "new": " \"method_elem\" | \"type_elem\"", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_inventory_row_gives_one_document_to_both_names", "documentation::collector::go_tests::go_embedded_field_owns_as_its_declaration", "documentation::collector::go_tests::go_members_own_wherever_their_type_is_written"] + }, + { + "name": "go-method-element-not-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"field_declaration\" | \"method_elem\" | \"type_elem\"", + "new": " \"field_declaration\" | \"type_elem\"", + "expect": ["documentation::collector::go_tests::go_interface_elements_own_as_their_nodes", "documentation::collector::go_tests::go_members_own_wherever_their_type_is_written", "documentation::collector::go_tests::go_member_count_costs_linear_work"] + }, + { + "name": "go-type-element-not-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"field_declaration\" | \"method_elem\" | \"type_elem\"", + "new": " \"field_declaration\" | \"method_elem\"", + "expect": ["documentation::collector::go_tests::go_interface_elements_own_as_their_nodes", "documentation::collector::go_tests::go_members_own_wherever_their_type_is_written"] + }, + { + "name": "go-member-need-not-be-a-pending-target", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if !matches!(record.projection, Projection::Pending)\n || !matches!(", + "new": " if false\n || !matches!(", + "expect": ["documentation::collector::go_tests::go_members_declared_in_a_function_body_own_nothing", "documentation::collector::go_tests::go_elements_without_a_leading_name_and_signature_parts_own_nothing"] + }, + { + "name": "go-error-member-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if node.has_error()\n || node.is_missing()\n || !self", + "new": " if (node.has_error() && self.index.profile != Profile::GoDoc)\n || node.is_missing()\n || !self", + "expect": ["documentation::collector::go_tests::go_member_with_a_syntax_error_stays_a_pending_owner", "documentation::collector::go_tests::go_member_beside_recovery_keeps_its_owners", "documentation::collector::assessment_tests::pending_go_field_query_exposes_assessment_instead_of_unusable_error"] + }, + { + "name": "go-uncovered-member-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " .covers_with_budget(node.byte_range(), budget)?\n {\n return Ok(());", + "new": " .covers_with_budget(node.byte_range(), budget)?\n && self.index.profile != Profile::GoDoc\n {\n return Ok(());", + "expect": ["documentation::collector::go_tests::go_member_and_excluded_ranges"] + }, + { + "name": "go-comment-line-end-is-ignored", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"comment\" if node.start_position().row != node.end_position().row => {", + "new": " \"comment\" if node.start_position().row > node.end_position().row => {", + "expect": ["documentation::collector::go_tests::go_member_with_a_comment_that_ends_a_line_stays_a_pending_owner", "documentation::collector::go_tests::go_member_scan_charges_one_step_per_child"] + }, + { + "name": "go-any-comment-child-keeps-the-member-pending", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"comment\" if node.start_position().row != node.end_position().row => {", + "new": " \"comment\" => {", + "expect": ["documentation::collector::go_tests::go_comment_inside_a_member_documents_nothing", "documentation::collector::go_tests::go_member_scan_charges_one_step_per_child"] + }, + { + "name": "go-later-names-dropped", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"field_identifier\" if field => names.push(child),", + "new": " \"field_identifier\" if field && names.is_empty() => names.push(child),", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_inventory_row_gives_one_document_to_both_names", "documentation::collector::go_tests::go_member_scan_charges_one_step_per_child", "documentation::collector::go_tests::go_field_name_width_costs_linear_work"] + }, + { + "name": "go-method-name-is-a-field-name", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"field_identifier\" if field => names.push(child),", + "new": " \"field_identifier\" => names.push(child),", + "expect": ["documentation::collector::go_tests::go_interface_elements_own_as_their_nodes", "documentation::collector::go_tests::go_member_scan_charges_one_step_per_child"] + }, + { + "name": "go-every-named-child-is-a-name", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " \"field_identifier\" if field => names.push(child),\n _ => {}", + "new": " \"field_identifier\" if field => names.push(child),\n _ if field && node.is_named() => names.push(child),\n _ => {}", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_embedded_field_owns_as_its_declaration", "documentation::collector::go_tests::go_member_scan_charges_one_step_per_child"] + }, + { + "name": "go-embedded-field-stays-pending", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " Ok(Some(names))\n}", + "new": " Ok((!field || !names.is_empty()).then_some(names))\n}", + "expect": ["documentation::collector::go_tests::go_embedded_field_owns_as_its_declaration", "documentation::collector::go_tests::go_undocumented_members_have_owners_and_no_assessment"] + }, + { + "name": "go-element-projection-is-empty", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " } else if names.is_empty() {", + "new": " } else if names.is_empty() && self.index.profile != Profile::GoDoc {", + "expect": ["documentation::collector::go_tests::go_embedded_field_owns_as_its_declaration", "documentation::collector::go_tests::go_interface_elements_own_as_their_nodes"] + }, + { + "name": "go-slot-ordinal-off-by-one", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " ordinal: fields.len(),", + "new": " ordinal: fields.len() + 1,", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_field_name_width_costs_linear_work"] + }, + { + "name": "go-slot-role-is-binding", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " enclosing: declaration,\n role: SlotRole::Field,", + "new": " enclosing: declaration,\n role: SlotRole::Binding,", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot"] + }, + { + "name": "go-slot-enclosing-is-the-file", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let declaration = OwnerId(self.index.facts.owners.len());", + "new": " let declaration = OwnerId(0);", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_field_queries_answer_per_slot_and_per_declaration", "documentation::collector::go_tests::go_fields_of_a_nested_struct_own_slots_in_their_own_declaration"] + }, + { + "name": "go-declaration-node-stays-the-owner", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " self.index.canonical.nodes[id.0].projection = Projection::Ready(fields);", + "new": " let _ = fields;", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_field_queries_answer_per_slot_and_per_declaration"] + }, + { + "name": "go-slot-owner-node-is-the-root", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " self.index.owner_nodes.push(id);\n fields.push(field);", + "new": " self.index.owner_nodes.push(NodeId(0));\n fields.push(field);", + "expect": ["documentation::collector::go_tests::go_member_beside_recovery_keeps_its_owners"] + }, + { + "name": "go-name-across-adjacent-ranges-is-not-a-slot", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let source = self.index.source.pieces_with_budget(spelling, budget)?;", + "new": " let source = self.index.source.pieces_with_budget(spelling, budget)?;\n if source.pieces().len() != 1 {\n return Ok(());\n }", + "expect": ["documentation::collector::go_tests::go_member_and_excluded_ranges"] + }, + { + "name": "go-member-scan-unbudgeted", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " for &child in &canonical.children[canonical.nodes[member.0].children.clone()] {\n budget.step()?;", + "new": " for &child in &canonical.children[canonical.nodes[member.0].children.clone()] {\n let _ = budget;", + "expect": ["documentation::collector::go_tests::go_member_scan_charges_one_step_per_child"] + }, + { + "name": "go-member-scan-charges-per-earlier-name", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " for &child in &canonical.children[canonical.nodes[member.0].children.clone()] {\n budget.step()?;", + "new": " for &child in &canonical.children[canonical.nodes[member.0].children.clone()] {\n for _ in 0..=names.len() {\n budget.step()?;\n }", + "expect": ["documentation::collector::go_tests::go_member_scan_charges_one_step_per_child", "documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-member-scan-ignores-the-collection-budget", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let Some(names) = go_member_names(&self.index.canonical, id, budget)? else {", + "new": " let Some(names) = crate::documentation::budget::infallible(go_member_names(\n &self.index.canonical,\n id,\n &crate::documentation::budget::NoBudget,\n )) else {", + "expect": ["documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-slot-loop-unbudgeted", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " for name in names {\n budget.step()?;", + "new": " for name in names {", + "expect": ["documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-slot-loop-charges-per-earlier-slot", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " for name in names {\n budget.step()?;", + "new": " for name in names {\n for _ in 0..=fields.len() {\n budget.step()?;\n }", + "expect": ["documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-slot-pieces-ignore-the-collection-budget", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let source = self.index.source.pieces_with_budget(spelling, budget)?;", + "new": " let source = self\n .index\n .source\n .pieces_with_budget(spelling, &crate::documentation::budget::NoBudget)?;", + "expect": ["documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-field-names-requested-from-the-cursor", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " || (profile == Profile::Yard && matches!(kind, \"if_modifier\" | \"unless_modifier\"))", + "new": " || (profile == Profile::Yard && matches!(kind, \"if_modifier\" | \"unless_modifier\"))\n || (profile == Profile::GoDoc && kind == \"field_declaration\")", + "expect": ["documentation::collector::go_tests::go_field_name_width_costs_linear_work", "documentation::collector::go_tests::go_member_count_costs_linear_work"] + }, + { + "name": "go-retained-candidates-in-reverse-order", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " self.index.evidence.push(CandidateEvidence {\n fragment,\n disposition: if member.directive {\n CandidateDisposition::Directive\n } else {\n CandidateDisposition::Unattached\n },\n });", + "new": " self.index.evidence.insert(\n 0,\n CandidateEvidence {\n fragment,\n disposition: if member.directive {\n CandidateDisposition::Directive\n } else {\n CandidateDisposition::Unattached\n },\n },\n );", + "expect": ["documentation::collector::go_tests::go_retained_candidates_stay_in_source_order", "documentation::collector::go_tests::go_comments_that_document_no_member_leave_it_its_owners", "documentation::collector::go_tests::go_comment_inside_a_member_documents_nothing"] + }, + { + "name": "go-function-body-gate-open", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " Go::StatementList | Go::Block => 0,", + "new": " Go::StatementList | Go::Block => 1,", + "expect": ["documentation::collector::go_tests::go_members_declared_in_a_function_body_own_nothing"] + }, + { + "name": "go-negated-element-is-a-target", + "file": "big-code-analysis-ast/src/roles/go.rs", + "old": " Go::TypeIdentifier | Go::QualifiedType | Go::GenericType", + "new": " Go::TypeIdentifier | Go::QualifiedType | Go::GenericType | Go::NegatedType", + "expect": ["documentation::collector::go_tests::go_elements_without_a_leading_name_and_signature_parts_own_nothing", "documentation::collector::go_tests::go_interface_elements_own_as_their_nodes"] + }, + { + "name": "trailing-comment-seeds-run", + "file": "big-code-analysis-ast/src/lang_helpers/doc_comment.rs", + "old": " if prev.end_row() >= row_first.start_row() {", + "new": " if prev.end_row() > row_first.start_row() {", + "expect": ["documentation::collector::go_tests::go_comments_that_document_no_member_leave_it_its_owners"] + }, + { + "name": "error-ancestor-leaves-the-association-resolved", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " if node.is_error() || node.is_missing() {\n record\n .qualification\n .insert(UnresolvedReason::GrammarBoundary);\n }", + "new": " if node.is_error() || node.is_missing() {\n let _ = &record;\n }", + "expect": ["documentation::collector::go_tests::go_member_beside_recovery_keeps_its_owners"] + }, + { + "name": "go-line-end-below-a-child-is-not-read", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " open.push((record.children.clone(), body));", + "new": " let _ = body;", + "expect": ["documentation::collector::go_tests::go_line_end_below_a_child_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_after_a_closing_bracket_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending", "documentation::collector::go_tests::go_nested_members_are_read_on_their_own", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-error-method-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if node.has_error()\n || node.is_missing()\n || !self", + "new": " if (node.has_error() && node.kind() != \"method_elem\")\n || node.is_missing()\n || !self", + "expect": ["documentation::collector::go_tests::go_member_with_a_syntax_error_stays_a_pending_owner"] + }, + { + "name": "go-error-type-element-is-projected", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if node.has_error()\n || node.is_missing()\n || !self", + "new": " if (node.has_error() && node.kind() != \"type_elem\")\n || node.is_missing()\n || !self", + "expect": ["documentation::collector::go_tests::go_member_with_a_syntax_error_stays_a_pending_owner"] + }, + { + "name": "go-line-end-rule-disabled", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if go_ends_member_early(&self.index.canonical, id, budget)? {", + "new": " if false && go_ends_member_early(&self.index.canonical, id, budget)? {", + "expect": ["documentation::collector::go_tests::go_line_end_below_a_child_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_after_a_closing_bracket_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending", "documentation::collector::go_tests::go_nested_members_are_read_on_their_own", "documentation::collector::go_tests::go_line_end_and_excluded_ranges"] + }, + { + "name": "go-closing-square-bracket-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "matches!(token.kind(), \")\" | \"]\" | \"}\")", + "new": "matches!(token.kind(), \")\" | \"}\")", + "expect": ["documentation::collector::go_tests::go_line_end_after_a_closing_bracket_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-closing-parenthesis-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "matches!(token.kind(), \")\" | \"]\" | \"}\")", + "new": "matches!(token.kind(), \"]\" | \"}\")", + "expect": ["documentation::collector::go_tests::go_line_end_below_a_child_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-closing-brace-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "matches!(token.kind(), \")\" | \"]\" | \"}\")", + "new": "matches!(token.kind(), \")\" | \"]\")", + "expect": ["documentation::collector::go_tests::go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-name-or-literal-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " (token.is_named() || matches!(token.kind(), \")\" | \"]\" | \"}\")).then(|| token.end_position().row)", + "new": " matches!(token.kind(), \")\" | \"]\" | \"}\").then(|| token.end_position().row)", + "expect": ["documentation::collector::go_tests::go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-every-token-ends-a-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " (token.is_named() || matches!(token.kind(), \")\" | \"]\" | \"}\")).then(|| token.end_position().row)", + "new": " Some(token.end_position().row)", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners"] + }, + { + "name": "go-line-end-is-never-cleared", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " line_end = go_line_end(node);", + "new": " line_end = go_line_end(node).or(line_end);", + "expect": ["documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners"] + }, + { + "name": "go-token-on-the-same-row-ends-the-member", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if line_end.is_some_and(|row| row < node.start_position().row) {", + "new": " if line_end.is_some_and(|row| row <= node.start_position().row) {", + "expect": ["documentation::collector::go_tests::go_names_of_a_field_declaration_each_own_a_field_slot", "documentation::collector::go_tests::go_interface_elements_own_as_their_nodes", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners"] + }, + { + "name": "go-token-ends-on-its-first-row", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": ".then(|| token.end_position().row)", + "new": ".then(|| token.start_position().row)", + "expect": ["documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners"] + }, + { + "name": "go-comment-is-a-token", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if kind == \"comment\" {\n continue;\n }\n if !record.children.is_empty()", + "new": " if !record.children.is_empty()", + "expect": ["documentation::collector::go_tests::go_comment_inside_a_member_documents_nothing", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-raw-string-is-read-token-by-token", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " && !matches!(kind, \"raw_string_literal\" | \"interpreted_string_literal\")", + "new": " && !matches!(kind, \"interpreted_string_literal\")", + "expect": ["documentation::collector::go_tests::go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-interpreted-string-is-read-token-by-token", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " && !matches!(kind, \"raw_string_literal\" | \"interpreted_string_literal\")", + "new": " && !matches!(kind, \"raw_string_literal\")", + "expect": ["documentation::collector::go_tests::go_line_end_after_a_name_a_literal_or_a_brace_keeps_the_member_pending", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-nested-struct-body-is-read", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "matches!(kind, \"field_declaration_list\" | \"interface_type\" | \"block\")", + "new": "matches!(kind, \"interface_type\" | \"block\")", + "expect": ["documentation::collector::go_tests::go_fields_of_a_nested_struct_own_slots_in_their_own_declaration", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners", "documentation::collector::go_tests::go_nested_members_are_read_on_their_own", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once", "documentation::collector::go_tests::go_line_end_scan_costs_linear_work"] + }, + { + "name": "go-nested-interface-body-is-read", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "matches!(kind, \"field_declaration_list\" | \"interface_type\" | \"block\")", + "new": "matches!(kind, \"field_declaration_list\" | \"block\")", + "expect": ["documentation::collector::go_tests::go_members_own_wherever_their_type_is_written", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-function-literal-body-is-read", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "matches!(kind, \"field_declaration_list\" | \"interface_type\" | \"block\")", + "new": "matches!(kind, \"field_declaration_list\" | \"interface_type\")", + "expect": ["documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-nested-bodies-are-read-again", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if *body && kind == \"{\" {", + "new": " if false && *body && kind == \"{\" {", + "expect": ["documentation::collector::go_tests::go_line_end_scan_costs_linear_work", "documentation::collector::go_tests::go_members_over_several_rows_keep_their_owners", "documentation::collector::go_tests::go_line_end_scan_reads_each_token_once"] + }, + { + "name": "go-line-end-scan-unbudgeted", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " budget.step()?;\n member_reads::record();", + "new": " let _ = budget;\n member_reads::record();", + "expect": ["documentation::collector::go_tests::go_line_end_scan_reads_each_token_once", "documentation::collector::go_tests::go_wide_parameter_list_collection_observes_cancellation", "documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-line-end-scan-charges-twice", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " budget.step()?;\n member_reads::record();", + "new": " budget.step()?;\n budget.step()?;\n member_reads::record();", + "expect": ["documentation::collector::go_tests::go_line_end_scan_reads_each_token_once", "documentation::collector::go_tests::go_wide_parameter_list_collection_observes_cancellation", "documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-line-end-scan-ignores-the-collection-budget", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " if go_ends_member_early(&self.index.canonical, id, budget)? {", + "new": " if crate::documentation::budget::infallible(go_ends_member_early(\n &self.index.canonical,\n id,\n &crate::documentation::budget::NoBudget,\n )) {", + "expect": ["documentation::collector::go_tests::go_wide_parameter_list_collection_observes_cancellation", "documentation::collector::go_tests::go_field_name_width_collection_observes_cancellation"] + }, + { + "name": "go-line-end-reads-are-not-counted", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " member_reads::record();", + "new": " let _ = member_reads::record;", + "expect": ["documentation::collector::go_tests::go_line_end_scan_reads_each_token_once", "documentation::collector::go_tests::go_line_end_scan_costs_linear_work", "documentation::collector::go_tests::go_line_end_scan_reads_nothing_for_another_profile"] + }, + { + "name": "java-fields-are-read-for-go-line-ends", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " self.field_slots(id, names, budget)\n }\n\n fn go_member_owners(", + "new": " go_ends_member_early(&self.index.canonical, id, budget)?;\n self.field_slots(id, names, budget)\n }\n\n fn go_member_owners(", + "expect": ["documentation::collector::go_tests::go_line_end_scan_reads_nothing_for_another_profile"] + }, + { + "name": "go-every-node-is-read-for-line-ends", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let record = &self.index.canonical.nodes[id.0];\n if !matches!(record.projection, Projection::Pending)", + "new": " go_ends_member_early(&self.index.canonical, id, budget)?;\n let record = &self.index.canonical.nodes[id.0];\n if !matches!(record.projection, Projection::Pending)", + "expect": ["documentation::collector::go_tests::go_line_end_scan_costs_linear_work"] + } + ] +} From a9261638fca5c1f3569f624e1c0c2c8d569c2b6f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:00:28 -0800 Subject: [PATCH 110/221] test(documentation): close the gaps an audit found in the Go member tests Test a field name that is not ASCII and the remaining token kinds that end a Go line inside a member. Pin four tokens that do not end a Go line, and add perturbations that prove the tests detect these regressions. No production code changes. --- .../src/documentation/collector/go_tests.rs | 163 ++++++++++++++++++ utils/documentation-go-unit2-perturb.json | 126 ++++++++++++++ 2 files changed, 289 insertions(+) diff --git a/big-code-analysis-ast/src/documentation/collector/go_tests.rs b/big-code-analysis-ast/src/documentation/collector/go_tests.rs index a6fe62748..edac22bbf 100644 --- a/big-code-analysis-ast/src/documentation/collector/go_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/go_tests.rs @@ -4530,3 +4530,166 @@ fn go_wide_parameter_list_collection_observes_cancellation() { .unwrap(); assert_eq!(index.associations().len(), 1); } + +#[cfg(feature = "go")] +#[test] +fn go_non_ascii_field_name_keeps_its_entire_slot() { + // Go 1.26.1 reads one named field, `Δ`, at 31..37; its name occupies two bytes. + let source = b"package p\ntype S struct {\n// d\n\xce\x94 int\n}\n"; + assert_eq!( + view(source), + named( + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..37, + &[31..33] + ) + ); + let parser = clean(source); + for index in &indexes(&parser, DocumentationOptions::default()) { + let association = index.associations().next().unwrap(); + let slot = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Slot(slot) = slot.get() else { + panic!("expected a field slot") + }; + assert_eq!(slot.source.pieces()[0].bytes(), "Δ".as_bytes()); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_type_argument_name_at_a_line_end_stays_pending() { + // Go reports a missing comma before the newline inside G[int\n]; the grammar + // gives one field node. The name token ends a line before `]`, so no owner is safe. + let source = b"package p\ntype S struct {\n// d\nX G[int\n]\n}\n"; + assert_stays_pending( + source, + "field_declaration", + 31..40, + comment(26..30, "d", [(0..1, Copied(29..30))]), + &[], + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_package_name_before_multiline_comment_stays_pending() { + // Go 1.26.1 stops this member at the end of `io` and rejects the dot. + // The grammar instead has one qualified type 31..52 and no ERROR node. + let source = b"package p\ntype S struct {\n// d\nio /* a\n b */ .Reader\n}\n"; + assert_stays_pending( + source, + "field_declaration", + 31..52, + comment(26..30, "d", [(0..1, Copied(29..30))]), + &[34..44], + ); +} + +#[cfg(feature = "go")] +#[test] +fn go_literals_before_a_line_end_stay_pending() { + // Go 1.26.1 reports a missing comma before the newline in each call; + // the grammar keeps one field per source. The literal ends the Go line. + let sources: [(&[u8], Range); 3] = [ + ( + b"package p\ntype S struct {\n// d\nX [int(1.5\n)]int\n}\n", + 31..47, + ), + ( + b"package p\ntype S struct {\n// d\nX [int(2i\n)]int\n}\n", + 31..46, + ), + ( + b"package p\ntype S struct {\n// d\nX [int('c'\n)]int\n}\n", + 31..47, + ), + ]; + for (source, range) in sources { + assert_stays_pending( + source, + "field_declaration", + range, + comment(26..30, "d", [(0..1, Copied(29..30))]), + &[], + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_keyword_literals_before_a_line_end_stay_pending() { + // Go 1.26.1 reports a missing comma before the newline for each argument. + // The grammar keeps a full field; the named token must still end the Go line. + let sources: [(&[u8], Range); 4] = [ + ( + b"package p\ntype S struct {\n// d\nX [len(nil\n)]int\n}\n", + 31..47, + ), + ( + b"package p\ntype S struct {\n// d\nX [int(true\n)]int\n}\n", + 31..48, + ), + ( + b"package p\ntype S struct {\n// d\nX [int(false\n)]int\n}\n", + 31..49, + ), + ( + b"package p\ntype S struct {\n// d\nX [int(iota\n)]int\n}\n", + 31..48, + ), + ]; + for (source, range) in sources { + assert_stays_pending( + source, + "field_declaration", + range, + comment(26..30, "d", [(0..1, Copied(29..30))]), + &[], + ); + } +} + +#[cfg(feature = "go")] +#[test] +fn go_line_ends_after_other_nonterminators_keep_the_member() { + // Go and the grammar both read the full field or element after `<-`, `~`, + // `...`, and `interface`. A newline at any of them inserts no semicolon. + let cases: [(&[u8], View); 3] = [ + ( + b"package p\ntype S struct {\n// d\nX chan<-\nint\n}\n", + named( + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..43, + &[31..32], + ), + ), + ( + b"package p\ntype S struct {\n// d\nF func(a ...\nint)\n}\n", + named( + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..48, + &[31..32], + ), + ), + ( + b"package p\ntype S struct {\n// d\nX interface\n{}\n}\n", + named( + comment(26..30, "d", [(0..1, Copied(29..30))]), + 31..45, + &[31..32], + ), + ), + ]; + for (source, expected) in cases { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + } + let source = b"package p\ntype I interface {\n// d\nA | ~\nint\n}\n"; + assert_eq!( + view(source), + owned( + comment(29..33, "d", [(0..1, Copied(32..33))]), + "type_elem", + 34..43 + ) + ); +} diff --git a/utils/documentation-go-unit2-perturb.json b/utils/documentation-go-unit2-perturb.json index dd718a5ae..aa9fd4130 100644 --- a/utils/documentation-go-unit2-perturb.json +++ b/utils/documentation-go-unit2-perturb.json @@ -408,6 +408,132 @@ "old": " let record = &self.index.canonical.nodes[id.0];\n if !matches!(record.projection, Projection::Pending)", "new": " go_ends_member_early(&self.index.canonical, id, budget)?;\n let record = &self.index.canonical.nodes[id.0];\n if !matches!(record.projection, Projection::Pending)", "expect": ["documentation::collector::go_tests::go_line_end_scan_costs_linear_work"] + }, + { + "name": "go-non-ascii-field-name-is-discarded", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": " let Some(names) = go_member_names(&self.index.canonical, id, budget)? else {\n return Ok(());\n };", + "new": " let Some(mut names) = go_member_names(&self.index.canonical, id, budget)? else {\n return Ok(());\n };\n names.retain(|name| self.index.source.bytes()[self.index.canonical.nodes[name.0].evidence.node().byte_range()].is_ascii());", + "expect": [ + "documentation::collector::go_tests::go_non_ascii_field_name_keeps_its_entire_slot" + ] + }, + { + "name": "go-type-identifier-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"type_identifier\")", + "expect": [ + "documentation::collector::go_tests::go_type_argument_name_at_a_line_end_stays_pending" + ] + }, + { + "name": "go-package-identifier-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"package_identifier\")", + "expect": [ + "documentation::collector::go_tests::go_package_name_before_multiline_comment_stays_pending" + ] + }, + { + "name": "go-float-literal-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"float_literal\")", + "expect": [ + "documentation::collector::go_tests::go_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-imaginary-literal-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"imaginary_literal\")", + "expect": [ + "documentation::collector::go_tests::go_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-rune-literal-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"rune_literal\")", + "expect": [ + "documentation::collector::go_tests::go_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-nil-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"nil\")", + "expect": [ + "documentation::collector::go_tests::go_keyword_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-true-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"true\")", + "expect": [ + "documentation::collector::go_tests::go_keyword_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-false-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"false\")", + "expect": [ + "documentation::collector::go_tests::go_keyword_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-iota-ends-no-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named()", + "new": "(token.is_named() && token.kind() != \"iota\")", + "expect": [ + "documentation::collector::go_tests::go_keyword_literals_before_a_line_end_stay_pending" + ] + }, + { + "name": "go-arrow-ends-a-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named() || ", + "new": "token.is_named() || token.kind() == \"<-\" || ", + "expect": [ + "documentation::collector::go_tests::go_line_ends_after_other_nonterminators_keep_the_member" + ] + }, + { + "name": "go-tilde-ends-a-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named() || ", + "new": "token.is_named() || token.kind() == \"~\" || ", + "expect": [ + "documentation::collector::go_tests::go_line_ends_after_other_nonterminators_keep_the_member" + ] + }, + { + "name": "go-ellipsis-ends-a-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named() || ", + "new": "token.is_named() || token.kind() == \"...\" || ", + "expect": [ + "documentation::collector::go_tests::go_line_ends_after_other_nonterminators_keep_the_member" + ] + }, + { + "name": "go-interface-keyword-ends-a-line", + "file": "big-code-analysis-ast/src/documentation/collector/projections.rs", + "old": "token.is_named() || ", + "new": "token.is_named() || token.kind() == \"interface\" || ", + "expect": [ + "documentation::collector::go_tests::go_line_ends_after_other_nonterminators_keep_the_member" + ] } ] } From 0ccc56b9e488675b03ca3b905b0a21e997c5d9e5 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:31:39 -0800 Subject: [PATCH 111/221] docs(documentation): correct the size of the generated sweep in the Go unit 2 provenance record The record gave the size of an earlier, smaller generated sweep. --- tests/fixtures/documentation/go-unit2-provenance.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fixtures/documentation/go-unit2-provenance.json b/tests/fixtures/documentation/go-unit2-provenance.json index 50e5cadf6..20f6ce4ea 100644 --- a/tests/fixtures/documentation/go-unit2-provenance.json +++ b/tests/fixtures/documentation/go-unit2-provenance.json @@ -6,7 +6,7 @@ "legacy_oracles": "src/metrics/loc/documentation_tests.rs", "mutation_manifest": "utils/documentation-go-unit2-perturb.json", "legacy_mutation_manifest": "utils/documentation-go-unit2-legacy-perturb.json", - "reference": {"tool": "Go", "version": "go1.26.1 linux/arm64", "configuration": "go/parser.ParseFile with ParseComments|AllErrors|SkipObjectResolution on each source as one file; ast.Field Doc and Comment per struct field and interface element, with names and byte offsets; go/doc.NewFromFiles with AllDecls|AllMethods|PreserveAST for sources without a parse error. Run under env -i with GOPROXY=off, GOTOOLCHAIN=local, GOENV=off and every cache inside the run directory", "evidence": "Executed on 2026-11-25 for every source of the production oracles; the Doc group of each field and element, its names and the extent of each member were compared with the expected owners. Also for 1,664 generated sources with a line end at every gap of 81 member forms, and for 2,031 files of the Go 1.26.1 standard library, read only", "qualification": "Source attachment only. No gofmt, go vet or type check; publication is not claimed."}, + "reference": {"tool": "Go", "version": "go1.26.1 linux/arm64", "configuration": "go/parser.ParseFile with ParseComments|AllErrors|SkipObjectResolution on each source as one file; ast.Field Doc and Comment per struct field and interface element, with names and byte offsets; go/doc.NewFromFiles with AllDecls|AllMethods|PreserveAST for sources without a parse error. Run under env -i with GOPROXY=off, GOTOOLCHAIN=local, GOENV=off and every cache inside the run directory", "evidence": "Executed on 2026-11-25 for every source of the production oracles; the Doc group of each field and element, its names and the extent of each member were compared with the expected owners. Also for 1,948 generated sources with a line end at every gap of 99 member forms, and for 2,031 files of the Go 1.26.1 standard library, read only", "qualification": "Source attachment only. No gofmt, go vet or type check; publication is not claimed."}, "legacy_measurement": {"binary": "bca 2.6.1 built from the base commit, debug profile", "command": "bca metrics --no-config --no-ignore --no-skip-generated --language go --format json --metrics loc ", "qualification": "Each measured file holds exactly the bytes of one legacy oracle source: no CR and one final LF, so file normalization changes nothing."}, "known_differences": [ "A member whose children include a comment with a line break stays a pending owner. Go ends a line at such a comment: for X /* a\n b */ int it reads two embedded fields, and for M() /* a\n b */ int a method and an embedded element. Where the comment follows a comma, a bar or a star, Go reads what the grammar reads and the member is pending all the same.", From 73bad225a4e5e760145fb1419faaf27efcc26b2d Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:40:32 -0800 Subject: [PATCH 112/221] fix(fuzz): compare captured events with an empty list in the remediation test A newer nightly clippy rejects assert!(events.is_empty()) under clippy::assert_is_empty, which failed the 'Build and smoke targets' job of the first CI run. assert_eq! also prints the events when the test fails. --- fuzz/src/documentation/tests/remediation.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fuzz/src/documentation/tests/remediation.rs b/fuzz/src/documentation/tests/remediation.rs index 606cec9d0..b1766c3c1 100644 --- a/fuzz/src/documentation/tests/remediation.rs +++ b/fuzz/src/documentation/tests/remediation.rs @@ -219,7 +219,7 @@ fn observation_scope_restores_on_rejection_skip_and_unwind() { for bytes in [&[25, 0, 0][..], &[0, 4, 0], &[0, 4, 0, 0]] { let (result, events) = observation::capture(|| exercise(bytes)); assert!(matches!(result, Ok(Outcome::Skipped(_)))); - assert!(events.is_empty()); + assert_eq!(events, []); } let (result, events) = observation::capture(|| exercise(&[1, 0, 0])); let error = CollectionError::AdapterUnavailable { From 82a53983e64d84af23399b38c4a3219e3f243175 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:40:32 -0800 Subject: [PATCH 113/221] test(documentation): record the capture root of the reference manifest as a repository path The manifest named the absolute path of the checkout it was captured in. No test or tool reads the key; the comparison reads keys, views and outputs. --- tests/fixtures/documentation/reference/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/fixtures/documentation/reference/manifest.json b/tests/fixtures/documentation/reference/manifest.json index c85cf6b6b..9c7ffbfb3 100644 --- a/tests/fixtures/documentation/reference/manifest.json +++ b/tests/fixtures/documentation/reference/manifest.json @@ -23,7 +23,7 @@ "verbatim_metrics_only_mi_exclude_tests_no_count_try_mi_charges_docs_true" ], "roots": { - "documentation": "/home/elijah/Development/Open_Source/big-code-analysis-docs-1657/tests/fixtures/documentation/sources" + "documentation": "tests/fixtures/documentation/sources" }, "metrics_options": { "verbatim_metrics_mi_charges_docs_false": [ From 1ef77ce1930c0a9fbadba57ef57c56ceabb682bd Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:46:56 -0800 Subject: [PATCH 114/221] test(documentation): anchor six CRLF defects in SourceCursor::newline The Rust unit moved the decision whether a two-byte line end is decoded from text/comments.rs to SourceCursor::newline. Six deliberate defects of the groovy, js, kotlin, lua, php and ts unit manifests anchored on the old line and matched nothing after the merge. --- utils/documentation-groovy-unit1-perturb.json | 6 +++--- utils/documentation-js-unit1-perturb.json | 6 +++--- utils/documentation-kotlin-unit1-perturb.json | 6 +++--- utils/documentation-lua-unit1-perturb.json | 6 +++--- utils/documentation-php-unit1-perturb.json | 6 +++--- utils/documentation-ts-unit1-perturb.json | 6 +++--- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/utils/documentation-groovy-unit1-perturb.json b/utils/documentation-groovy-unit1-perturb.json index d3abefcff..46c59f46d 100644 --- a/utils/documentation-groovy-unit1-perturb.json +++ b/utils/documentation-groovy-unit1-perturb.json @@ -180,9 +180,9 @@ }, { "name": "crlf-inside-block-is-copied", - "file": "big-code-analysis-ast/src/documentation/text/comments.rs", - "old": " if line.ending.len() == 2 {", - "new": " if line.ending.len() == 3 {", + "file": "big-code-analysis-ast/src/documentation/text/source_cursor.rs", + "old": " if range.len() == 2 {", + "new": " if range.len() == 3 {", "expect": ["documentation::collector::groovy_tests::groovy_block_with_crlf_line_endings"] }, { diff --git a/utils/documentation-js-unit1-perturb.json b/utils/documentation-js-unit1-perturb.json index 1d319e548..db1a327c1 100644 --- a/utils/documentation-js-unit1-perturb.json +++ b/utils/documentation-js-unit1-perturb.json @@ -549,9 +549,9 @@ }, { "name": "crlf-copied-not-decoded", - "file": "big-code-analysis-ast/src/documentation/text/comments.rs", - "old": " if line.ending.len() == 2 {", - "new": " if line.ending.len() == 3 {", + "file": "big-code-analysis-ast/src/documentation/text/source_cursor.rs", + "old": " if range.len() == 2 {", + "new": " if range.len() == 3 {", "expect": [ "documentation::collector::js_tests::javascript_crlf_line_endings_keep_byte_ranges_and_decode_to_lf", "documentation::collector::js_tests::mozjs_crlf_line_endings_keep_byte_ranges_and_decode_to_lf" diff --git a/utils/documentation-kotlin-unit1-perturb.json b/utils/documentation-kotlin-unit1-perturb.json index e6f4df746..be4852348 100644 --- a/utils/documentation-kotlin-unit1-perturb.json +++ b/utils/documentation-kotlin-unit1-perturb.json @@ -412,9 +412,9 @@ }, { "name": "crlf-inside-block-is-copied", - "file": "big-code-analysis-ast/src/documentation/text/comments.rs", - "old": " if line.ending.len() == 2 {", - "new": " if line.ending.len() == 3 {", + "file": "big-code-analysis-ast/src/documentation/text/source_cursor.rs", + "old": " if range.len() == 2 {", + "new": " if range.len() == 3 {", "expect": [ "documentation::collector::kotlin_tests::kotlin_kdoc_with_crlf_line_endings" ] diff --git a/utils/documentation-lua-unit1-perturb.json b/utils/documentation-lua-unit1-perturb.json index f0effa959..c70bf814e 100644 --- a/utils/documentation-lua-unit1-perturb.json +++ b/utils/documentation-lua-unit1-perturb.json @@ -220,9 +220,9 @@ }, { "name": "crlf-in-block-copied-raw", - "file": "big-code-analysis-ast/src/documentation/text/comments.rs", - "old": " if line.ending.len() == 2 {", - "new": " if line.ending.len() == 3 {", + "file": "big-code-analysis-ast/src/documentation/text/source_cursor.rs", + "old": " if range.len() == 2 {", + "new": " if range.len() == 3 {", "expect": [ "documentation::collector::lua_tests::lua_crlf_rows_keep_owners_fragments_and_text" ] diff --git a/utils/documentation-php-unit1-perturb.json b/utils/documentation-php-unit1-perturb.json index 866c41373..d122f5bc5 100644 --- a/utils/documentation-php-unit1-perturb.json +++ b/utils/documentation-php-unit1-perturb.json @@ -373,9 +373,9 @@ }, { "name": "crlf-inside-block-is-copied", - "file": "big-code-analysis-ast/src/documentation/text/comments.rs", - "old": " if line.ending.len() == 2 {", - "new": " if line.ending.len() == 3 {", + "file": "big-code-analysis-ast/src/documentation/text/source_cursor.rs", + "old": " if range.len() == 2 {", + "new": " if range.len() == 3 {", "expect": [ "documentation::collector::php_tests::php_docblock_with_crlf_line_endings" ] diff --git a/utils/documentation-ts-unit1-perturb.json b/utils/documentation-ts-unit1-perturb.json index 1fb7f2349..ecf6b5086 100644 --- a/utils/documentation-ts-unit1-perturb.json +++ b/utils/documentation-ts-unit1-perturb.json @@ -432,9 +432,9 @@ }, { "name": "crlf-not-decoded", - "file": "big-code-analysis-ast/src/documentation/text/comments.rs", - "old": " if line.ending.len() == 2 {", - "new": " if line.ending.len() == 3 {", + "file": "big-code-analysis-ast/src/documentation/text/source_cursor.rs", + "old": " if range.len() == 2 {", + "new": " if range.len() == 3 {", "expect": [ "documentation::collector::ts_tests::typescript_block_text_is_cleaned_and_mapped_to_its_source", "documentation::collector::ts_tests::tsx_block_text_is_cleaned_and_mapped_to_its_source" From ebb5df1be6c92d048a6777ad573857d814b66342 Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:29:34 -0800 Subject: [PATCH 115/221] test(documentation): collect every LANG variant's primary row through the root Ast (#1681) --- tests/api/documentation_variants.rs | 449 ++++++++++++++++++ tests/api/main.rs | 1 + .../documentation-variants-unit1-perturb.json | 144 ++++++ 3 files changed, 594 insertions(+) create mode 100644 tests/api/documentation_variants.rs create mode 100644 utils/documentation-variants-unit1-perturb.json diff --git a/tests/api/documentation_variants.rs b/tests/api/documentation_variants.rs new file mode 100644 index 000000000..811e42f12 --- /dev/null +++ b/tests/api/documentation_variants.rs @@ -0,0 +1,449 @@ +//! Collects every enabled LANG variant's primary documentation through the root Ast +//! and checks independent inventory rows and discriminating in-memory controls. + +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +use big_code_analysis::{Ast, LANG, Source}; +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +use big_code_analysis_ast::documentation::{ + Capability, CollectionError, DocumentationContext, DocumentationIndex, DocumentationOptions, + Owner, Profile, Resolution, +}; +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +use big_code_analysis_ast::test_support::documentation::{ + assert_primary_extraction, primary, source, +}; + +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +fn projection(index: &DocumentationIndex<'_>) -> serde_json::Value { + let facts = index.facts(); + serde_json::Value::Array( + index + .documents() + .map(|document| { + let fragments: Vec<_> = (0..document.get().fragment_count()) + .map(|at| { + let fragment = facts.document_fragment(document, at).unwrap(); + let [piece] = fragment.get().source().pieces() else { + panic!("one source piece per fragment") + }; + let range = piece.range(); + serde_json::json!([range.start, range.end]) + }) + .collect(); + let text = index + .complete_text(document) + .unwrap() + .map(|complete| complete.text().to_owned()); + let associations: Vec<_> = index + .associations() + .filter(|association| { + facts.associated_document(*association).unwrap() == document + }) + .collect(); + let [association] = associations.as_slice() else { + panic!("one association per document") + }; + let node = if association.get().resolution == Resolution::Resolved + && association.get().owner_count() == 1 + { + match facts.associated_owner(*association, 0).unwrap().get() { + Owner::Node(declared) => Some(declared.node()), + _ => None, + } + } else { + None + }; + let owner = node.map(|node| { + let range = node.byte_range(); + serde_json::json!([range.start, range.end]) + }); + let owner_kind = node.map(|node| node.kind()); + serde_json::json!({ + "fragments": fragments, + "text": text, + "owner": owner, + "owner_kind": owner_kind, + }) + }) + .collect(), + ) +} + +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +#[derive(Clone, Copy)] +enum Expectation { + Row(Profile), + Rejected(Profile), + Helper, +} + +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +fn check_policy(ast: &Ast, lang: LANG, expected: Expectation, filename: Option<&str>) { + let result = ast.documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ); + match expected { + Expectation::Row(profile) => { + let index = result.unwrap(); + assert_eq!(index.profile(), profile, "{lang}"); + assert_eq!(index.capability(), Capability::Partial, "{lang}"); + assert_eq!(index.assessments().len(), 0, "{lang}"); + if let Some(filename) = filename { + assert_eq!( + index.context().logical_filename.as_deref(), + Some(filename), + "{lang}" + ); + } + assert_primary_extraction(lang, Ok(projection(&index))); + } + Expectation::Rejected(profile) => { + assert_eq!( + result.err(), + Some(CollectionError::AdapterUnavailable { + language: lang, + profile + }), + "{lang}" + ); + } + Expectation::Helper => { + let index = result.unwrap(); + assert_eq!(index.profile(), Profile::Helper, "{lang}"); + assert_eq!(index.capability(), Capability::NoDeclarationModel, "{lang}"); + assert_eq!(index.documents().len(), 0, "{lang}"); + assert_eq!(index.associations().len(), 0, "{lang}"); + assert_eq!(index.assessments().len(), 0, "{lang}"); + assert_primary_extraction(lang, Err("NoDeclarationModel")); + } + } +} + +#[cfg(any( + feature = "bash", + feature = "c", + feature = "cpp", + feature = "csharp", + feature = "elixir", + feature = "go", + feature = "groovy", + feature = "irules", + feature = "java", + feature = "javascript", + feature = "kotlin", + feature = "lua", + feature = "mozcpp", + feature = "mozjs", + feature = "objc", + feature = "perl", + feature = "php", + feature = "python", + feature = "ruby", + feature = "rust", + feature = "tcl", + feature = "typescript", + feature = "c-family-helpers" +))] +#[test] +fn every_language_variant_meets_its_documentation_policy_through_the_root_ast() { + use Expectation::{Helper, Rejected, Row}; + let directory = tempfile::tempdir().unwrap(); + let mut counts = (0, 0, 0); + for lang in LANG::into_enum_iter().filter(LANG::is_enabled) { + let expected = match lang { + LANG::Rust => Row(Profile::Rust), + LANG::Python => Rejected(Profile::Python), + LANG::Java => Row(Profile::Javadoc), + LANG::Kotlin => Row(Profile::Kdoc), + LANG::Groovy => Row(Profile::Groovydoc), + LANG::Csharp => Row(Profile::CsharpXml), + LANG::Php => Row(Profile::BcaPhpSource), + LANG::Javascript | LANG::Mozjs => Row(Profile::Jsdoc), + LANG::Typescript | LANG::Tsx => Row(Profile::BcaTypescriptSource), + LANG::C | LANG::Cpp | LANG::Mozcpp | LANG::Objc => Row(Profile::Doxygen), + LANG::Go => Row(Profile::GoDoc), + LANG::Ruby => Row(Profile::Yard), + LANG::Lua => Row(Profile::Ldoc), + LANG::Perl => Rejected(Profile::Pod), + LANG::Elixir => Rejected(Profile::Elixir), + LANG::Bash => Rejected(Profile::Shdoc), + LANG::Tcl => Rejected(Profile::Ruff), + LANG::Irules => Rejected(Profile::Irules), + LANG::Ccomment | LANG::Preproc => Helper, + }; + match expected { + Row(_) => counts.0 += 1, + Rejected(_) => counts.1 += 1, + Helper => counts.2 += 1, + } + let filename = primary(lang); + let bytes = source(filename); + let ast = Ast::parse(Source::new(lang, &bytes)).unwrap(); + assert_eq!(ast.language(), lang); + check_policy(&ast, lang, expected, None); + // Mozjs, Mozcpp, Ccomment and Preproc have no filename that selects their grammar. + if !matches!( + lang, + LANG::Mozjs | LANG::Mozcpp | LANG::Ccomment | LANG::Preproc + ) { + let path = directory.path().join(filename); + std::fs::write(&path, &bytes).unwrap(); + let from_path = Ast::from_path(&path).unwrap(); + assert_eq!(from_path.language(), lang); + check_policy(&from_path, lang, expected, Some(filename)); + } + } + let ran = counts.0 + counts.1 + counts.2; + assert_eq!(ran, LANG::into_enum_iter().filter(LANG::is_enabled).count()); + assert!(ran > 0); + #[cfg(feature = "all-languages")] + assert_eq!(counts, (17, 6, 2)); +} + +#[cfg(feature = "rust")] +#[test] +fn the_projection_tells_rust_results_apart() { + let controls = [ + // expected: the primary comment is owned by the following function. + ( + "///audit\nfn f() {}", + serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"owner_kind":"function_item","text":"audit"}]), + ), + // expected: the same ranges but other comment text. + ( + "///other\nfn f() {}", + serde_json::json!([{"fragments":[[0,8]],"owner":[9,18],"owner_kind":"function_item","text":"other"}]), + ), + // expected: a longer declaration moves the owner's end to byte 23. + ( + "///audit\nfn g(a: u8) {}", + serde_json::json!([{"fragments":[[0,8]],"owner":[9,23],"owner_kind":"function_item","text":"audit"}]), + ), + // expected: two distinct documents are returned in source order. + ( + "///audit\nfn f() {}\n///b\nfn g() {}", + serde_json::json!([ + {"fragments":[[0,8]],"owner":[9,18],"owner_kind":"function_item","text":"audit"}, + {"fragments":[[19,23]],"owner":[24,33],"owner_kind":"function_item","text":"b"} + ]), + ), + // expected: no comment means no document. + ("fn f() {}", serde_json::json!([])), + // expected: the computed #[doc = concat!("a")] value has no complete text. + ( + "#[doc = concat!(\"a\")]\nfn f() {}", + serde_json::json!([{"fragments":[[0,21]],"owner":[22,31],"owner_kind":"function_item","text":null}]), + ), + // expected: the inner comment belongs to the file, not a node owner. + ( + "//!audit\nfn f() {}", + serde_json::json!([{"fragments":[[0,8]],"owner":null,"owner_kind":null,"text":"audit"}]), + ), + // expected: two comment rows make two fragments but one complete text. + ( + "///audit\n///b\nfn f() {}", + serde_json::json!([{"fragments":[[0,8],[9,13]],"owner":[14,23],"owner_kind":"function_item","text":"audit\nb"}]), + ), + ]; + for (bytes, expected) in controls { + let ast = Ast::parse(Source::new(LANG::Rust, bytes.as_bytes())).unwrap(); + let index = ast + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(projection(&index), expected, "{bytes}"); + } +} + +#[cfg(feature = "cpp")] +#[test] +fn the_projection_names_no_owner_for_an_unresolved_or_slot_association() { + use big_code_analysis_ast::documentation::UnresolvedReason; + let controls = [ + ( + "/**@fn void g()\n * audit*/\nvoid f();", + serde_json::json!([{"fragments":[[0,26]],"owner":null,"owner_kind":null,"text":"@fn void g()\naudit"}]), + ), + ( + "/**a*/\nint x, y;", + serde_json::json!([{"fragments":[[0,6]],"owner":null,"owner_kind":null,"text":"a"}]), + ), + ]; + for (at, (bytes, expected)) in controls.into_iter().enumerate() { + let ast = Ast::parse(Source::new(LANG::Cpp, bytes.as_bytes())).unwrap(); + let index = ast + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(projection(&index), expected, "{bytes}"); + let associations: Vec<_> = index.associations().collect(); + let [association] = associations.as_slice() else { + panic!("one association per C++ control") + }; + if at == 0 { + assert_eq!( + association.get().resolution, + Resolution::Unresolved(UnresolvedReason::MissingName) + ); + } else { + assert_eq!(association.get().resolution, Resolution::Resolved); + assert_eq!(association.get().owner_count(), 2); + for ordinal in 0..2 { + let owner = index + .facts() + .associated_owner(*association, ordinal) + .unwrap(); + assert!(matches!(owner.get(), Owner::Slot(_))); + } + } + } +} diff --git a/tests/api/main.rs b/tests/api/main.rs index 57cb70629..b503f4452 100644 --- a/tests/api/main.rs +++ b/tests/api/main.rs @@ -37,6 +37,7 @@ mod derive_eq_hash_ord; // to read; the grammar is named inside the file it points at #[cfg(feature = "rust")] mod documentation_facade; +mod documentation_variants; // The feature gate moved here from the `mod parser_reuse` wrapper the // file used to carry: as a module it can be gated at the declaration, // and keeping the wrapper would have nested `parser_reuse` inside diff --git a/utils/documentation-variants-unit1-perturb.json b/utils/documentation-variants-unit1-perturb.json new file mode 100644 index 000000000..b90d6a37c --- /dev/null +++ b/utils/documentation-variants-unit1-perturb.json @@ -0,0 +1,144 @@ +{ + "cwd": ".", + "runner": "cargo", + "cargo": [ + "cargo", + "test", + "-p", + "big-code-analysis", + "--all-features", + "--test", + "api", + "documentation_variants" + ], + "cases": [ + { + "name": "variants-every-error-is-reported-as-cancelled", + "file": "src/spaces/ast.rs", + "old": " self.inner.documentation(context, options)\n", + "new": " self.inner\n .documentation(context, options)\n .map_err(|_| CollectionError::Cancelled)\n", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-rejected-adapter-is-an-empty-success", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": " return Err(CollectionError::AdapterUnavailable { language, profile });", + "new": " return Ok(profile);", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-helper-capability-is-partial", + "file": "big-code-analysis-ast/src/documentation/collector.rs", + "old": " capability: if profile == Profile::Helper {", + "new": " capability: if false && profile == Profile::Helper {", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-helpers-routed-to-doxygen", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": " LANG::Ccomment | LANG::Preproc => Self::Helper,", + "new": " LANG::Ccomment | LANG::Preproc => Self::Doxygen,", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-mozjs-routed-to-the-typescript-profile", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": " LANG::Javascript | LANG::Mozjs => Self::Jsdoc,", + "new": " LANG::Javascript => Self::Jsdoc,\n LANG::Mozjs => Self::BcaTypescriptSource,", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-tsx-routed-to-the-jsdoc-profile", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": " LANG::Typescript | LANG::Tsx => Self::BcaTypescriptSource,", + "new": " LANG::Typescript => Self::BcaTypescriptSource,\n LANG::Tsx => Self::Jsdoc,", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-mozcpp-routed-to-the-helper-profile", + "file": "big-code-analysis-ast/src/documentation/options.rs", + "old": " LANG::C | LANG::Cpp | LANG::Mozcpp | LANG::Objc => Self::Doxygen,", + "new": " LANG::C | LANG::Cpp | LANG::Objc => Self::Doxygen,\n LANG::Mozcpp => Self::Helper,", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-ast-parses-mozcpp-as-cpp", + "file": "src/spaces/ast.rs", + "old": " let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?;", + "new": " let lang = if lang == LANG::Mozcpp { LANG::Cpp } else { lang };\n let inner = AnyParser::parse(lang, code.into_owned(), preproc_path, preproc)?;", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-path-provenance-not-stored", + "file": "src/spaces/ast.rs", + "old": " ast.provenance = provenance;\n", + "new": " let _ = provenance;\n", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-text-copied-twice", + "file": "big-code-analysis-ast/src/documentation/text.rs", + "old": " self.text.push_str(valid);", + "new": " self.text.push_str(valid);\n self.text.push_str(valid);", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast", + "documentation_variants::the_projection_tells_rust_results_apart", + "documentation_variants::the_projection_names_no_owner_for_an_unresolved_or_slot_association" + ] + }, + { + "name": "variants-documents-in-reverse-order", + "file": "big-code-analysis-ast/src/documentation/index.rs", + "old": " self.documents_ordered.iter().map(|&ordinal| FactRef {", + "new": " self.documents_ordered.iter().rev().map(|&ordinal| FactRef {", + "expect": [ + "documentation_variants::the_projection_tells_rust_results_apart" + ] + }, + { + "name": "variants-inventory-ruby-owner-kind-changed", + "file": "tests/fixtures/documentation/inventory.json", + "old": " \"selected_owner_kind\": \"method\",", + "new": " \"selected_owner_kind\": \"singleton_method\",", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-inventory-csharp-text-changed", + "file": "tests/fixtures/documentation/inventory.json", + "old": " \"text\": \"audit\",", + "new": " \"text\": \"audit\",", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + }, + { + "name": "variants-helpers-required-to-have-declaration-text", + "file": "big-code-analysis-ast/src/test_support/documentation.rs", + "old": " LANG::Ccomment | LANG::Preproc => Requirement::NoDeclarationModel,", + "new": " LANG::Ccomment | LANG::Preproc => Requirement::DeclarationText,", + "expect": [ + "documentation_variants::every_language_variant_meets_its_documentation_policy_through_the_root_ast" + ] + } + ] +} From aecc87fdc11e7069734fdeff4935e0e69faad81b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:34:04 -0800 Subject: [PATCH 116/221] test(documentation): pin the Perl POD parse shapes and the legacy rows of inline POD The pinned grammar's pod_statement and data-section shapes, its reading of formats, here-documents and quote-like literals, and the legacy LOC rows of 261 Perl sources, before the collector reads any of them. No production change; Perl stays rejected. --- .../src/documentation/collector.rs | 2 + .../src/documentation/collector/perl_tests.rs | 1056 +++++++++++ src/metrics/loc/documentation_tests.rs | 1628 +++++++++++++++++ 3 files changed, 2686 insertions(+) create mode 100644 big-code-analysis-ast/src/documentation/collector/perl_tests.rs diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index da9da0321..44f831248 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -1026,6 +1026,8 @@ mod lua_tests; #[cfg(test)] mod named_tests; #[cfg(test)] +mod perl_tests; +#[cfg(test)] mod php_tests; #[cfg(test)] mod projection_tests; diff --git a/big-code-analysis-ast/src/documentation/collector/perl_tests.rs b/big-code-analysis-ast/src/documentation/collector/perl_tests.rs new file mode 100644 index 000000000..968f7e265 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/perl_tests.rs @@ -0,0 +1,1056 @@ +//! Parse shapes of the pinned Perl grammar that a reader of POD blocks relies on: where a +//! `pod_statement` and the data section start and end, where the grammar gives no block, +//! and how it reads formats, here-documents and quote-like literals. The tests parse +//! verbatim bytes and collect nothing. + +#![allow(clippy::single_range_in_vec_init, clippy::naive_bytecount)] + +#[cfg(feature = "perl")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "perl")] +use std::ops::Range; + +#[cfg(feature = "perl")] +const PRIMARY: &[u8] = b"=head2 f\n\nAudit\n\n=cut\n\nsub f {}"; +#[cfg(feature = "perl")] +const TWO_BLOCKS: &[u8] = b"my $x = 1;\n=head1 A\n\na\n\n=cut\nmy $y = 2;\n=head1 B\n\nb\n\n=cut\n"; +#[cfg(feature = "perl")] +const MIXED_FIXTURE: &[u8] = + b"=head2 f\n\nAudit\n\n=begin comment\n\nnot prose\n\n=end comment\n\n\ + =cut\n\nsub f { return 1; }\n__END__\n=head1 NAME\n\nData docs\n\n=cut\n"; + +/// A node as kind, byte range and kind of its parent. +#[cfg(feature = "perl")] +type Leaf = (&'static str, Range, &'static str); +#[cfg(feature = "perl")] +type Ranges = Vec>; + +/// A node as label, byte range and start row. The label is `ERROR` or `MISSING` for a +/// recovery node and the kind otherwise. +#[cfg(feature = "perl")] +type Shape = (&'static str, Range, usize); + +#[cfg(feature = "perl")] +fn parsed(source: &[u8]) -> AnyParser { + AnyParser::parse(LANG::Perl, source.to_vec(), None, None).unwrap() +} + +/// A raw parse that reads the given byte ranges only. +#[cfg(feature = "perl")] +fn restricted(source: &[u8], ranges: &[Range]) -> tree_sitter::Tree { + let point = |offset: usize| { + let before = &source[..offset]; + tree_sitter::Point::new( + before.iter().filter(|byte| **byte == b'\n').count(), + before + .iter() + .rev() + .take_while(|byte| **byte != b'\n') + .count(), + ) + }; + let ranges: Vec<_> = ranges + .iter() + .map(|range| tree_sitter::Range { + start_byte: range.start, + end_byte: range.end, + start_point: point(range.start), + end_point: point(range.end), + }) + .collect(); + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Perl.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + parser.parse(source, None).unwrap() +} + +/// Every node of the given kinds, in source order, with the kind of its parent. +#[cfg(feature = "perl")] +fn nodes_of(root: tree_sitter::Node<'_>, kinds: &[&str]) -> Vec { + let mut found = Vec::new(); + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + let mut cursor = node.walk(); + let children: Vec<_> = node.children(&mut cursor).collect(); + stack.extend(children.into_iter().rev()); + if kinds.contains(&node.kind()) { + assert_eq!(node.child_count(), 0, "a leaf"); + found.push(( + node.kind(), + node.byte_range(), + node.parent().unwrap().kind(), + )); + } + } + found +} + +/// Every node that the rules for literal text read, in tree order: recovery nodes, +/// blocks, the data leaf, here-document nodes, `<<` and `.` tokens, quote-like literals, +/// and identifiers spelled `format` or like a quote-like operator. +#[cfg(feature = "perl")] +fn shapes_of(root: tree_sitter::Node<'_>, source: &[u8]) -> Vec { + const KINDS: [&str; 19] = [ + "pod_statement", + "data_not_for_compiler", + "heredoc_initializer", + "heredoc_body_statement", + "heredoc_end_identifier", + "<<", + ".", + "string_single_quoted", + "string_double_quoted", + "string_qq_quoted", + "backtick_quoted", + "command_qx_quoted", + "pattern_matcher", + "pattern_matcher_m", + "regex_pattern_qr", + "substitution_pattern_s", + "transliteration_tr_or_y", + "string_q_quoted", + "word_list_qw", + ]; + let mut found = Vec::new(); + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + let mut cursor = node.walk(); + let children: Vec<_> = node.children(&mut cursor).collect(); + stack.extend(children.into_iter().rev()); + let keyword = node.kind() == "identifier" + && matches!( + &source[node.byte_range()], + b"format" | b"q" | b"qq" | b"qw" | b"qx" | b"m" | b"qr" | b"s" | b"tr" | b"y" + ); + let label = if node.is_error() { + "ERROR" + } else if node.is_missing() { + "MISSING" + } else if keyword || KINDS.contains(&node.kind()) { + node.kind() + } else { + continue; + }; + found.push((label, node.byte_range(), node.start_position().row)); + } + found +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn perl_pod_parse_shapes_the_reader_relies_on() { + // expected: a block starts at its `=`. One that a `=cut` line ends runs to the end of + // that line and holds no line feed after it, but holds the CR of a CRLF. One that no + // `=cut` line ends runs to the end of the input, final line end included. A NUL byte + // ends a block where it stands. The text after `__END__` or `__DATA__` is one leaf. + let block = |range: Range, parent: &'static str| ("pod_statement", range, parent); + let file = |range: Range| ("pod_statement", range, "source_file"); + let cases: [(&[u8], bool, Vec); 39] = [ + (PRIMARY, false, vec![file(0..21)]), + ( + b"=head1 A\r\n\r\na\r\n\r\n=cut\r\nsub f {}\r\n", + false, + vec![file(0..22)], + ), + ( + b"my $x = 1;\n\n=head1 NAME\n\nNever closed.\n", + false, + vec![file(12..39)], + ), + ( + b"my $x = 1;\n\n=head1 NAME\n\nNever closed.", + false, + vec![file(12..38)], + ), + ( + b"=head1 NAME\n\nNever closed.\n\n\n", + false, + vec![file(0..29)], + ), + (b"=pod\n\nx\n\n=cut", false, vec![file(0..13)]), + (b"=pod\r\n\r\nx\r\n", false, vec![file(0..11)]), + (b"=pod\r\n\r\nx\r\n\r\n=cut\r\n", false, vec![file(0..18)]), + (b"=pod\n", false, vec![file(0..5)]), + (b"=pod\n=cut\n", false, vec![file(0..9)]), + ( + b"=head1 A\n\na\n\n=cut here is text\nmy $y = 2;\n", + false, + vec![file(0..30)], + ), + (b"=pod\n\ny\n\n=CUT\nmy $x;\n", false, vec![file(0..21)]), + (TWO_BLOCKS, false, vec![file(11..28), file(40..57)]), + ( + b"=head1 A\n\na\n\n=cut\n=head1 B\n\nb\n\n=cut\n", + false, + vec![file(0..17), file(18..35)], + ), + ( + b"sub f {\n my $x = 1;\n\n=pod\n\nDoc.\n\n=cut\n\n return $x;\n}\n", + false, + vec![block(24..40, "block")], + ), + ( + b"sub o {\n sub i {\n=head2 i\n\nInner.\n\n=cut\n }\n}\n", + false, + vec![block(18..40, "block")], + ), + ( + MIXED_FIXTURE, + false, + vec![ + file(0..62), + ("data_not_for_compiler", 91..121, "special_literal"), + ], + ), + ( + b"__END__\n=head1 NAME\n\nAudit\n\n=cut\n", + false, + vec![("data_not_for_compiler", 7..33, "special_literal")], + ), + ( + b"__DATA__\nrow\n", + false, + vec![("data_not_for_compiler", 8..13, "special_literal")], + ), + ( + b"__END__", + false, + vec![("data_not_for_compiler", 7..7, "special_literal")], + ), + ( + b"sub f {\n__END__\n=pod\n\nx\n\n=cut\n", + true, + vec![("data_not_for_compiler", 15..30, "special_literal")], + ), + // The grammar opens a block wherever a statement may start, at any `=` word. + (b"my $x = 1;\n=cut\nmy $y = 2;\n", false, vec![file(11..27)]), + (b"my $x = 1;\n=1\ntext\n=cut\n", false, vec![file(11..23)]), + ( + b"my $x = 1;\n =head1 NAME\n\ntext\n\n=cut\n", + false, + vec![file(13..36)], + ), + ( + b"my $x = 1; =head1 NAME\n\ntext\n\n=cut\n", + false, + vec![file(11..34)], + ), + (b"\xef\xbb\xbf=pod\n\nx\n\n=cut\n", false, vec![file(3..16)]), + // `=cutting` ends a block, and the `=cut` below it opens one. + ( + b"=head1 A\n\ntext\n\n=cutting\nmy $y = 2;\n=cut\n", + false, + vec![file(0..24), file(36..41)], + ), + (b"=pod\n\na\x00b\n\n=cut\n", true, vec![file(0..7)]), + ( + b"=pod\n\nx\n\n=cut\x00foo\nmy $y;\n", + true, + vec![file(0..13)], + ), + (b"=pod\r\rx\r\r=cut\rmy $x;\r", false, vec![file(0..21)]), + (b"=pod\n\nx\n\n=cut\r", false, vec![file(0..14)]), + // Recovery beside a block leaves the node of the block as it is. + (b"%%%% (\n=pod\n\nx\n\n=cut\n", true, vec![file(7..20)]), + ( + b"my $x = 1,\n=pod\n\nx\n\n=cut\n2;\n", + true, + vec![file(11..24)], + ), + ( + b"sub f {\n=pod\n\nx\n\n=cut\n", + true, + vec![block(8..21, "block")], + ), + ( + b"sub f {\nreturn\n=pod\n\nx\n\n=cut\n1;\n}\n", + true, + vec![block(15..28, "block")], + ), + // No block where the text is part of another node. + ( + b"my $t = <<'EOT';\n=head1 NAME\n\nnot pod\n\n=cut\nEOT\n", + false, + vec![], + ), + (b"my $s = \"abc\n=pod\n\nx\n\n=cut\n", true, vec![]), + (b"my @a = (\n1,\n=pod\n\nx\n\n=cut\n2);\n", true, vec![]), + (b"=pod", true, vec![]), + ]; + for (source, recovered, expected) in cases { + let parser = parsed(source); + let root = parser.ts_tree().root_node(); + assert_eq!(root.kind(), "source_file", "{}", source.escape_ascii()); + assert_eq!(root.has_error(), recovered, "{}", source.escape_ascii()); + assert_eq!( + nodes_of(root, &["pod_statement", "data_not_for_compiler"]), + expected, + "{}", + source.escape_ascii() + ); + } + // The scanner reads the included bytes as one text: an excluded line feed after + // `=cut` joins the next row to the block, and an excluded `=cut` joins two blocks. + let cut: [(&[Range], Ranges); 8] = [ + (&[0..20, 21..58], vec![11..28, 40..57]), + (&[0..10, 11..58], vec![11..28, 40..57]), + (&[0..28, 29..58], vec![11..39, 40..57]), + (&[0..24, 28..58], vec![11..57]), + (&[0..5, 6..58], vec![11..28, 40..57]), + (&[0..57], vec![11..28, 40..57]), + (&[0..15, 15..58], vec![11..28, 40..57]), + (&[0..11, 12..58], vec![40..57]), + ]; + for (ranges, expected) in cut { + let tree = restricted(TWO_BLOCKS, ranges); + let blocks: Vec<_> = nodes_of(tree.root_node(), &["pod_statement"]) + .into_iter() + .map(|(_, range, _)| range) + .collect(); + assert_eq!(blocks, expected, "{ranges:?}"); + } +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn perl_literal_parse_shapes_the_doubt_rules_rely_on() { + // expected: per source, whether the tree holds an error, and in tree order the nodes + // that the rules for literal text read. A format is a call for the grammar: only the + // identifier `format` and, where the grammar keeps it, the `.` of its last line say + // that it is there. A here-document that the grammar reads has an initializer, and + // its body starts on the row after the initializer's row. One that it does not read + // is a `<<` operator, a recovery node, or part of a literal. A literal node holds no + // other literal node. A block is a `pod_statement` wherever a statement may start. + // Where a literal starts and ends is the grammar's claim, and the last rows show + // claims that perl does not share: `q`, `tr` and `y` behind an escaped opening + // bracket end late; `CORE::q` is a name and the lines behind it are code; a `/` + // behind `time` starts a pattern; a `'` behind a name starts a string; an operator + // word before `=>` or in a subscript starts a literal. `<<`, a blank and a quoted + // tag is a shift. Behind a literal that the grammar does not parse, a block has no + // node. + let cases: [(&[u8], bool, Vec); 69] = [ + ( + b"my $x = 1,\n=pod\n\nx\n\n=cut\n2;\n", + true, + vec![("MISSING", 10..10, 0), ("pod_statement", 11..24, 1)], + ), + ( + b"my $s = <<\"\";\n=pod\n\nprint \"MARK\";\n", + true, + vec![ + ("ERROR", 8..10, 0), + ("<<", 8..10, 0), + ("string_double_quoted", 10..12, 0), + ("pod_statement", 14..34, 1), + ], + ), + ( + b"1;\n\x04\n=pod\n\nd\n\n=cut\n", + true, + vec![ + ("ERROR", 3..4, 1), + ("ERROR", 3..4, 1), + ("pod_statement", 5..18, 2), + ], + ), + ( + b"format STDOUT =\n=pod\n.\n", + true, + vec![ + ("ERROR", 0..15, 0), + ("identifier", 0..6, 0), + ("pod_statement", 16..23, 1), + ], + ), + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + false, + vec![ + ("identifier", 0..6, 0), + ("pod_statement", 19..32, 2), + (".", 35..36, 8), + ], + ), + ( + b"format =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + false, + vec![ + ("identifier", 0..6, 0), + ("pod_statement", 12..25, 2), + (".", 28..29, 8), + ], + ), + ( + b"format STDOUT =\n1\n.\n2;\n\n=pod\n\nreal\n\n=cut\n", + false, + vec![ + ("identifier", 0..6, 0), + (".", 18..19, 2), + ("pod_statement", 24..40, 5), + ], + ), + ( + b"format STDOUT =\n1\n. \t\r\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + false, + vec![ + ("identifier", 0..6, 0), + (".", 18..19, 2), + ("pod_statement", 27..40, 5), + ("string_double_quoted", 47..53, 10), + ], + ), + ( + b"format STDOUT =\r\n1\r\n.\r\n2;\r\n\r\n=pod\r\n\r\nd\r\n\r\n=cut\r\nprint \"\ + MARK\";\r\n", + false, + vec![ + ("identifier", 0..6, 0), + (".", 20..21, 2), + ("pod_statement", 29..47, 5), + ("string_double_quoted", 54..60, 10), + ], + ), + ( + b"format A =\nformat B =\n1\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + false, + vec![ + ("identifier", 0..6, 0), + ("identifier", 11..17, 1), + (".", 24..25, 3), + ("pod_statement", 30..43, 6), + ("string_double_quoted", 50..56, 11), + ], + ), + ( + b"my $o = bless {};\nsub format { 7 }\nmy $v = $o->format;\n\n=pod\n\nd\n\n=cu\ + t\nprint \"MARK\";\n", + false, + vec![ + ("identifier", 22..28, 1), + ("identifier", 47..53, 2), + ("pod_statement", 56..69, 4), + ("string_double_quoted", 76..82, 9), + ], + ), + ( + b"FORMAT STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + false, + vec![("pod_statement", 19..32, 2), (".", 35..36, 8)], + ), + ( + b"format F =\na 'b\n.\nmy $s = ';\n=pod\n\nd\n\n=cut\n';\nprint \"MARK\";\n", + true, + vec![ + ("identifier", 0..6, 0), + ("string_single_quoted", 13..27, 1), + ("pod_statement", 29..42, 4), + ("ERROR", 43..60, 9), + ], + ), + ( + b"format F =\n1; print < 1, s => 2, q => 3);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + false, + vec![ + ("transliteration_tr_or_y", 9..28, 0), + ("pod_statement", 35..48, 2), + ("string_double_quoted", 55..61, 7), + ], + ), + ( + b"my @m = split /,/, 'a,b'; my $n = 1 if $m[0] =~ /a/; my @o = grep /b/, @m;\n\ + \n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + false, + vec![ + ("pattern_matcher", 14..17, 0), + ("string_single_quoted", 19..24, 0), + ("pattern_matcher", 48..51, 0), + ("pattern_matcher", 66..69, 0), + ("pod_statement", 76..89, 2), + ("string_double_quoted", 96..102, 7), + ], + ), + ( + b"my %k; my $v = $k{q}; my $w = { 1 };\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + true, + vec![ + ("string_q_quoted", 18..35, 0), + ("MISSING", 35..35, 0), + ("pod_statement", 38..51, 2), + ("string_double_quoted", 58..64, 7), + ], + ), + ]; + for (source, recovered, expected) in cases { + let parser = parsed(source); + let root = parser.ts_tree().root_node(); + assert_eq!(root.has_error(), recovered, "{}", source.escape_ascii()); + assert_eq!( + shapes_of(root, source), + expected, + "{}", + source.escape_ascii() + ); + } +} diff --git a/src/metrics/loc/documentation_tests.rs b/src/metrics/loc/documentation_tests.rs index e13c305c7..d3d144824 100644 --- a/src/metrics/loc/documentation_tests.rs +++ b/src/metrics/loc/documentation_tests.rs @@ -2981,3 +2981,1631 @@ fn documentation_go_member_sources_keep_their_legacy_rows() { assert_eq!(covered, 0, "{name}"); } } + +/// One Perl source of the POD unit with its legacy values, measured before the collector +/// read any of them: name, bytes, `[sloc, ploc, lloc, cloc, blank, dloc]` and the +/// zero-based documentation rows. +#[cfg(feature = "perl")] +type PerlPodSource = (&'static str, &'static [u8], [u64; 6], &'static [usize]); + +#[cfg(feature = "perl")] +static PERL_POD_SOURCES: [PerlPodSource; 261] = [ + ( + "a01_primary", + b"=head2 f\n\nAudit\n\n=cut\n\nsub f {}", + [7, 1, 0, 5, 1, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a02_two_blocks", + b"my $x = 1;\n=head1 A\n\na\n\n=cut\nmy $y = 2;\n=head1 B\n\nb\n\n=cut\nmy $z \ + = 3;\n", + [13, 3, 3, 10, 0, 10], + &[1, 2, 3, 4, 5, 7, 8, 9, 10, 11], + ), + ( + "a03_in_sub", + b"sub f {\n my $x = 1;\n\n=pod\n\nDoc.\n\n=cut\n\n return $x;\n}\n", + [11, 4, 2, 5, 2, 5], + &[3, 4, 5, 6, 7], + ), + ( + "a04_adjacent", + b"=head1 A\n\na\n\n=cut\n=head1 B\n\nb\n\n=cut\n", + [10, 0, 0, 10, 0, 10], + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + ), + ( + "a05_begin_html", + b"=begin html\n\n

x

\n\n=end html\n\n=cut\n", + [7, 0, 0, 7, 0, 7], + &[0, 1, 2, 3, 4, 5, 6], + ), + ( + "a06_cut_with_text", + b"=head1 A\n\na\n\n=cut here is text\nmy $y = 2;\n", + [6, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a07_cut_digit", + b"=head1 A\n\ntext\n\n=cut2\nmy $y = 2;\n", + [6, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a08_command_and_cut", + b"=pod\n=cut\n", + [2, 0, 0, 2, 0, 2], + &[0, 1], + ), + ( + "a09_whitespace_line", + b"=pod\n\nx\n \n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a10_blank_lines", + b"=pod\n\n\n\ny\n\n\n=cut\n", + [8, 0, 0, 8, 0, 8], + &[0, 1, 2, 3, 4, 5, 6, 7], + ), + ( + "a11_collision", + b"=head2 f\n\nAudit\n\n=cut\n\nsub f {}\nsub f {}", + [8, 2, 0, 5, 1, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a12_package", + b"package Foo;\n\n=head1 NAME\n\nFoo\n\n=cut\n\nsub new {}\n", + [9, 2, 1, 5, 2, 5], + &[2, 3, 4, 5, 6], + ), + ( + "a13_nested_sub", + b"sub o {\n sub i {\n=head2 i\n\nInner.\n\n=cut\n }\n}\n", + [9, 4, 0, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "a14_begin_colon_comment", + b"=begin :comment\n\nx\n\n=end :comment\n\n=cut\n", + [7, 0, 0, 7, 0, 7], + &[0, 1, 2, 3, 4, 5, 6], + ), + ( + "a15_item_tab", + b"=item\t*\n\ny\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a16_vertical_tab", + b"=pod\x0bx\n\ny\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a17_cut_form_feed", + b"=pod\n\nx\n\n=cut\x0cfoo\nmy $y;\n", + [6, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a18_end_marker_inside", + b"=pod\n\n__END__\n\n=cut\nmy $x;\n", + [6, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "a19_uppercase_cut", + b"=pod\n\ny\n\n=CUT\nmy $x;\n", + [6, 0, 0, 6, 0, 6], + &[0, 1, 2, 3, 4, 5], + ), + ( + "b01_crlf", + b"=head1 A\r\n\r\na\r\n\r\n=cut\r\nsub f {}\r\n", + [6, 1, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "b02_unterminated", + b"my $x = 1;\n\n=head1 NAME\n\nNever closed.\n", + [5, 1, 1, 3, 1, 3], + &[2, 3, 4], + ), + ( + "b03_unterminated_no_final_lf", + b"my $x = 1;\n\n=head1 NAME\n\nNever closed.", + [5, 1, 1, 3, 1, 3], + &[2, 3, 4], + ), + ( + "b04_unterminated_blank_rows", + b"=head1 NAME\n\nNever closed.\n\n\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "b05_cut_at_end_of_input", + b"=pod\n\nx\n\n=cut", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "b06_crlf_unterminated", + b"=pod\r\n\r\nx\r\n", + [3, 0, 0, 3, 0, 3], + &[0, 1, 2], + ), + ( + "b07_crlf_cut_at_end", + b"=pod\r\n\r\nx\r\n\r\n=cut\r\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ("b08_command_line_only", b"=pod\n", [1, 0, 0, 1, 0, 1], &[0]), + ( + "c01_comment_only", + b"=begin comment\n\nnot prose\n\n=end comment\n\n=cut\n", + [7, 0, 0, 7, 0, 0], + &[], + ), + ( + "c02_two_comment_only", + b"=begin comment\n\na\n\n=end comment\n\n=cut\n\nmy $x;\n\n=for comment b\n\n=\ + cut\n", + [13, 1, 1, 10, 2, 0], + &[], + ), + ( + "c03_comment_then_document", + b"=begin comment\n\nx\n\n=end comment\n\n=cut\n\n=head1 A\n\na\n\n=cut\n", + [13, 0, 0, 12, 1, 5], + &[8, 9, 10, 11, 12], + ), + ( + "c04_mixed", + b"=head2 f\n\nAudit\n\n=begin comment\n\nnot prose\n\n=end comment\n\n=cut\n\n\ + sub f { return 1; }\n__END__\n=head1 NAME\n\nData docs\n\n=cut\n", + [19, 2, 1, 16, 1, 16], + &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18], + ), + ( + "c05_region_first", + b"=for comment\nInternal note.\n\n=head1 NAME\n\nFoo - bar\n\n=cut\n", + [8, 0, 0, 8, 0, 8], + &[0, 1, 2, 3, 4, 5, 6, 7], + ), + ( + "c06_document_then_mixed", + b"=head1 A\n\na\n\n=cut\n\n=head1 B\n\n=for comment x\n\nb\n\n=cut\n", + [13, 0, 0, 12, 1, 12], + &[0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12], + ), + ( + "c07_command_in_paragraph", + b"=head1 A\n\ntext\n=for comment x\n\nmore\n\n=cut\n", + [8, 0, 0, 8, 0, 8], + &[0, 1, 2, 3, 4, 5, 6, 7], + ), + ( + "w01_stray_cut", + b"my $x = 1;\n=cut\nmy $y = 2;\n", + [3, 1, 1, 2, 0, 2], + &[1, 2], + ), + ( + "w02_digit_command", + b"my $x = 1;\n=1\ntext\n=cut\n", + [4, 1, 1, 3, 0, 3], + &[1, 2, 3], + ), + ( + "w03_head_dash", + b"=head-x\n\ntext\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w04_indented", + b"my $x = 1;\n =head1 NAME\n\ntext\n\n=cut\n", + [6, 1, 1, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "w05_same_row", + b"my $x = 1; =head1 NAME\n\ntext\n\n=cut\n", + [5, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w06_cutting_opens", + b"my $x;\n=cutting\ntext\n=cut\nmy $y;\n", + [5, 2, 2, 3, 0, 3], + &[1, 2, 3], + ), + ( + "w07_cutting_closes", + b"=head1 A\n\ntext\n\n=cutting\nmy $y = 2;\n=cut\n", + [7, 1, 1, 6, 0, 6], + &[0, 1, 2, 3, 4, 6], + ), + ( + "w08_nul_in_text", + b"=pod\n\na\x00b\n\n=cut\n", + [5, 2, 0, 3, 1, 3], + &[0, 1, 2], + ), + ( + "w09_nul_after_cut", + b"=pod\n\nx\n\n=cut\x00foo\nmy $y;\n", + [6, 2, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w10_carriage_returns_only", + b"=pod\r\rx\r\r=cut\rmy $x;\r", + [1, 0, 0, 1, 0, 1], + &[0], + ), + ( + "w11_carriage_return_in_text", + b"=pod\n\na\rb\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w12_carriage_return_at_end", + b"=pod\n\nx\n\n=cut\r", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w13_byte_order_mark", + b"\xef\xbb\xbf=pod\n\nx\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w14_carriage_return_before", + b"my $x;\r=pod\n\nx\n\n=cut\n", + [5, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w15_withheld_then_document", + b"my $x = 1;\n =head1 X\n\nx\n\n=cut\n=head1 A\n\na\n\n=cut\n", + [11, 1, 1, 10, 0, 10], + &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + ), + ( + "w16_underscore_command", + b"my $x = 1;\n=_x\ntext\n=cut\n", + [4, 1, 1, 3, 0, 3], + &[1, 2, 3], + ), + ( + "w17_command_with_dot", + b"=pod.\n\nx\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "w18_stray_cut_first", + b"=cut\n\nx\n\n=cut\nmy $y;\n", + [6, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "r01_error_before", + b"%%%% (\n=pod\n\nx\n\n=cut\n", + [6, 1, 0, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "r02_missing_semicolon", + b"my $x = 1,\n=pod\n\nx\n\n=cut\n2;\n", + [7, 2, 2, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "r03_unclosed_sub", + b"sub f {\n=pod\n\nx\n\n=cut\n", + [6, 2, 0, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "r04_error_after", + b"=pod\n\nx\n\n=cut\n}}}}\n", + [6, 1, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "r05_return_before", + b"sub f {\nreturn\n=pod\n\nx\n\n=cut\n1;\n}\n", + [9, 4, 1, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "s01_hash_comment", + b"# leads f\nsub f {}\n", + [2, 1, 0, 1, 0, 0], + &[], + ), + ( + "s02_heredoc", + b"my $t = <<'EOT';\n=head1 NAME\n\nnot pod\n\n=cut\nEOT\n", + [7, 7, 1, 0, 0, 0], + &[], + ), + ( + "s03_string", + b"my $s = \"\n=pod\n\nx\n\n=cut\n\";\nmy $after = 2;\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "s04_word_list", + b"my @a = qw(\n=pod\n\nx\n\n=cut\n);\nmy $after = 2;\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "s05_pattern", + b"my $r = qr/\n=pod\n\nx\n\n=cut\n/x;\nmy $after = 2;\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "s06_unclosed_string", + b"my $s = \"abc\n=pod\n\nx\n\n=cut\n", + [6, 1, 0, 0, 5, 0], + &[], + ), + ( + "s07_in_list", + b"my @a = (\n1,\n=pod\n\nx\n\n=cut\n2);\n", + [8, 4, 1, 0, 4, 0], + &[], + ), + ( + "s08_command_at_end_of_input", + b"=pod", + [1, 1, 0, 0, 0, 0], + &[], + ), + ( + "s09_no_semicolon_before", + b"my $x = 1\n=pod\n\nx\n\n=cut\n;\n", + [7, 4, 1, 0, 3, 0], + &[], + ), + ( + "d01_end", + b"__END__\n=head1 NAME\n\nAudit\n\n=cut\n", + [6, 1, 0, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ("d02_data", b"__DATA__\nrow\n", [2, 2, 0, 0, 0, 0], &[]), + ( + "d03_end_at_end_of_input", + b"__END__", + [1, 1, 0, 0, 0, 0], + &[], + ), + ( + "d04_end_in_sub", + b"sub f {\n__END__\n=pod\n\nx\n\n=cut\n", + [7, 2, 0, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "i01_invalid_utf8", + b"=head1 A\n\n\xff\n\n=cut\n", + [5, 0, 0, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ("e01_empty", b"", [0, 0, 0, 0, 0, 0], &[]), + ( + "e02_code_only", + b"sub f { return 1; }\n", + [1, 1, 1, 0, 0, 0], + &[], + ), + ( + "g01_unterminated_whitespace_rows", + b"my $x = 1;\n=pod\nabc\n \n \n", + [5, 1, 1, 4, 0, 4], + &[1, 2, 3, 4], + ), + ( + "g02_stray_cut_then_cut", + b"my $x = 1;\n=cut\nnot perl at all (\n=cut\nmy $y = 2;\n", + [5, 2, 2, 3, 0, 3], + &[1, 2, 3], + ), + ( + "g03_indented_then_code", + b"my $x = 1;\n =head1 NAME\n\ntext\n\n=cut\nmy $y = 2;\n", + [7, 2, 2, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "g04_digit_then_code", + b"my $x = 1;\n=1\ntext\n=cut\nmy $y = 2;\n", + [5, 2, 2, 3, 0, 3], + &[1, 2, 3], + ), + ( + "g05_underscore_then_code", + b"my $x = 1;\n=_x\ntext\n=cut\nmy $y = 2;\n", + [5, 2, 2, 3, 0, 3], + &[1, 2, 3], + ), + ( + "g06_head_dash_then_code", + b"my $x = 1;\n=head-x\ntext\n=cut\nmy $y = 2;\n", + [5, 2, 2, 3, 0, 3], + &[1, 2, 3], + ), + ( + "g07_cutting_closes", + b"=head1 A\n\na\n\n=cutting\nmy $y = 2;\n", + [6, 1, 1, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "g08_cutting_opens_then_code", + b"my $x = 1;\n=cutting\ntext\n=cut\nmy $y = 2;\n", + [5, 2, 2, 3, 0, 3], + &[1, 2, 3], + ), + ( + "g09_cutting_then_garbage", + b"=head1 A\n\na\n\n=cutting\nnot perl at all (\n=cut\nmy $y = 2;\n", + [8, 1, 0, 7, 0, 7], + &[0, 1, 2, 3, 4, 6, 7], + ), + ( + "g10_unterminated_whitespace_rows_data", + b"1;\n__END__\n=pod\nabc\n \n \n", + [6, 2, 1, 2, 2, 2], + &[2, 3], + ), + ( + "g11_whitespace_line_ends_region", + b"=for comment x\n \nprose\n=cut\n", + [4, 0, 0, 4, 0, 4], + &[0, 1, 2, 3], + ), + ( + "g12_digit_in_data_section", + b"1;\n__END__\n=1\ntext\n=cut\n", + [5, 5, 1, 0, 0, 0], + &[], + ), + ( + "x01_two_blocks", + b"my $x = 1;\n=head1 A\n\na\n\n=cut\nmy $y = 2;\n=head1 B\n\nb\n\n=cut\n", + [12, 2, 2, 10, 0, 10], + &[1, 2, 3, 4, 5, 7, 8, 9, 10, 11], + ), + ( + "r06_empty_tag", + b"my $s = <<\"\";\n=pod\n\nprint \"MARK\";\n", + [4, 1, 1, 3, 0, 3], + &[1, 2, 3], + ), + ( + "r07_empty_tag_single", + b"my $s = <<'';\n=pod\n\nprint \"MARK\";\n", + [4, 1, 1, 3, 0, 3], + &[1, 2, 3], + ), + ( + "r08_empty_tag_then_real", + b"my $s = <<\"\";\nlit\n\nprint \"MARK\";\n\n=pod\n\nreal\n\n=cut\n", + [10, 3, 2, 5, 2, 5], + &[5, 6, 7, 8, 9], + ), + ( + "r09_control_d", + b"1;\n\x04\n=pod\n\nd\n\n=cut\n", + [7, 2, 1, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "r10_control_z", + b"1;\n\x1a\n=pod\n\nd\n\n=cut\n", + [7, 2, 1, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "r11_format_at_opener", + b"format STDOUT =\n=pod\n.\n", + [3, 1, 0, 2, 0, 2], + &[1, 2], + ), + ( + "r12_error_then_real", + b"sub isn't { 1 }\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 1, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "r13_error_between", + b"=pod\n\nx\n\n=cut\n}}}}\n=pod\n\ny\n\n=cut\n", + [11, 1, 0, 10, 0, 10], + &[0, 1, 2, 3, 4, 6, 7, 8, 9, 10], + ), + ( + "f01_named", + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f02_default_name", + b"format =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f03_qualified", + b"format Pkg::F =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f04_no_spaces", + b"format STDOUT=\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f05_trailing_blanks", + b"format STDOUT = \t\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f06_trailing_comment", + b"format STDOUT = # c\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 6, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f07_name_next_row", + b"format\nSTDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [11, 6, 2, 5, 0, 5], + &[3, 4, 5, 6, 7], + ), + ( + "f08_equals_next_row", + b"format STDOUT\n=\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [11, 6, 2, 5, 0, 5], + &[3, 4, 5, 6, 7], + ), + ( + "f09_comments_between", + b"format # a\nSTDOUT # b\n=\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [12, 7, 2, 7, 0, 5], + &[4, 5, 6, 7, 8], + ), + ( + "f10_indented", + b" format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f11_after_statement", + b"my $q = 1; format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 3, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f12_in_sub", + b"sub g {\nformat STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n}\n", + [12, 7, 2, 5, 0, 5], + &[3, 4, 5, 6, 7], + ), + ( + "f13_carriage_return", + b"format STDOUT =\r\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f14_after_label", + b"L: format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f15_no_last_line", + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n2;\n", + [8, 3, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f16_then_real", + b"format STDOUT =\n1\n.\n2;\n\n=pod\n\nreal\n\n=cut\n", + [10, 4, 1, 5, 1, 5], + &[5, 6, 7, 8, 9], + ), + ( + "f17_real_then_format", + b"=pod\n\nd\n\n=cut\nformat STDOUT =\n1\n.\n2;\nprint \"MARK\";\n", + [10, 5, 2, 5, 0, 5], + &[0, 1, 2, 3, 4], + ), + ( + "f18_inside_and_after", + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n\n=pod\n\nreal\n\n=cut\n", + [16, 5, 2, 10, 1, 10], + &[2, 3, 4, 5, 6, 11, 12, 13, 14, 15], + ), + ( + "f19_last_line_blanks", + b"format STDOUT =\n1\n. \t\r\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [11, 5, 2, 5, 1, 5], + &[5, 6, 7, 8, 9], + ), + ( + "f20_crlf", + b"format STDOUT =\r\n1\r\n.\r\n2;\r\n\r\n=pod\r\n\r\nd\r\n\r\n=cut\r\nprint \"\ + MARK\";\r\n", + [11, 5, 2, 5, 1, 5], + &[5, 6, 7, 8, 9], + ), + ( + "f21_two_formats", + b"format A =\n1\n.\n2;\nformat B =\n3\n.\n4;\n\n=pod\n\nd\n\n=cut\nprint \"MAR\ + K\";\n", + [15, 9, 3, 5, 1, 5], + &[9, 10, 11, 12, 13], + ), + ( + "f22_opener_in_body", + b"format A =\nformat B =\n1\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [12, 6, 2, 5, 1, 5], + &[6, 7, 8, 9, 10], + ), + ( + "f23_method", + b"my $o = bless {};\nsub format { 7 }\nmy $v = $o->format;\n\n=pod\n\nd\n\n=cu\ + t\nprint \"MARK\";\n", + [10, 4, 3, 5, 1, 5], + &[4, 5, 6, 7, 8], + ), + ( + "f24_hash_key", + b"my %h = (format => 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f25_hash_key_next_row", + b"my %h = (format\n=> 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [9, 3, 2, 5, 1, 5], + &[3, 4, 5, 6, 7], + ), + ( + "f26_in_string", + b"my $s = 'format STDOUT =';\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f27_in_comment", + b"# format STDOUT =\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 1, 1, 6, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f28_upper_case", + b"FORMAT STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 5, 2, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f29_subscript", + b"my %h; $h{format} =\n1;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [9, 3, 3, 5, 1, 5], + &[3, 4, 5, 6, 7], + ), + ( + "f30_quote_in_picture", + b"format F =\na 'b\n.\nmy $s = ';\n=pod\n\nd\n\n=cut\n';\nprint \"MARK\";\n", + [11, 5, 1, 5, 1, 5], + &[4, 5, 6, 7, 8], + ), + ( + "f31_opener_in_picture", + b"format F =\n1; print <>> 1 << 2\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "h18_word_in_string", + b"my $s = \"a< < 2);\nprint \"MARK\";\n", + [9, 7, 0, 0, 2, 0], + &[], + ), + ( + "t11_q_brace", + b"my $s = q{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t12_q_paren", + b"my $s = q(\n=pod\n\nd\n\n=cut\n);\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t13_q_word_delimiter", + b"my $s = q X\n=pod\n\nd\n\n=cut\nX;\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t14_q_hash", + b"my $s = q#\n=pod\n\nd\n\n=cut\n#;\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t15_qq_brace", + b"my $s = qq{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t16_m_brace", + b"my $s = 'a' =~ m{\n=pod\n\nd\n\n=cut\n}x;\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t17_qr_slash", + b"my $s = qr/\n=pod\n\nd\n\n=cut\n/x;\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t18_s_pattern", + b"my $s = 'a'; $s =~ s/\n=pod\n\nd\n\n=cut\n/b/x;\nprint \"MARK\";\n", + [8, 8, 3, 0, 0, 0], + &[], + ), + ( + "t19_s_replacement", + b"my $s = 'a'; $s =~ s{a}{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + [8, 8, 3, 0, 0, 0], + &[], + ), + ( + "t20_tr", + b"my $s = 'a'; $s =~ tr/a/\n=pod\n\nd\n\n=cut\n/;\nprint \"MARK\";\n", + [8, 8, 3, 0, 0, 0], + &[], + ), + ( + "t21_y", + b"my $s = 'a'; $s =~ y/a/\n=pod\n\nd\n\n=cut\n/;\nprint \"MARK\";\n", + [8, 8, 3, 0, 0, 0], + &[], + ), + ( + "t22_single_quoted", + b"my $s = '\n=pod\n\nd\n\n=cut\n';\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t23_backticks", + b"my $s = `\n=pod\n\nd\n\n=cut\n`;\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t24_qx", + b"my $s = qx{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t25_heredoc_command", + b"my $s = <<`EOT`;\n=pod\n\nd\n\n=cut\nEOT\nprint \"MARK\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "t26_end_same_row", + b"1; __END__\n=pod\n\nd\n\n=cut\n", + [6, 1, 1, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "t27_end_as_key", + b"my %h = (__END__ => 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 0, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "t28_format_then_pod", + b"format STDOUT =\nline\n.\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [9, 7, 1, 0, 2, 0], + &[], + ), + ( + "t29_format_tick_name", + b"format Pkg'F =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + [10, 1, 0, 0, 9, 0], + &[], + ), + ( + "t30_bareword_assignment", + b"my $y\n=pod\n;\nprint \"MARK\";\n", + [4, 4, 2, 0, 0, 0], + &[], + ), + ( + "n01_source_filter", + b"use Filter::Util::Call;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "r14_hidden_block", + b"my $s = q'a\\'b';\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 1, 0, 0, 7, 0], + &[], + ), + ( + "r15_command_before_data", + b"my $x = (1;\nmy $s = \"\n=pod\n\";\n__END__\n=pod\n\nd\n\n=cut\n", + [10, 5, 2, 5, 0, 5], + &[5, 6, 7, 8, 9], + ), + ( + "r16_command_in_data_only", + b"my $x = (1;\n__END__\n=pod\n\nd\n\n=cut\n", + [7, 2, 1, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "r17_command_before_error", + b"my $s = '\n=pod\n';\nmy $x = (1;\n", + [4, 4, 2, 0, 0, 0], + &[], + ), + ( + "r18_no_command_line", + b"my $x = (1;\nmy $s = \"\n=1\n==\n= a\n =pod\nx=pod\n\";\n", + [8, 8, 2, 0, 0, 0], + &[], + ), + ( + "r19_error_without_pod", + b"my $x = (1;\nmy $y = 2;\n", + [2, 2, 2, 0, 0, 0], + &[], + ), + ( + "r21_block_with_a_node", + b"my $x = (1;\n\n=head1 A\n\na\n\n=cut\n", + [7, 1, 1, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "f38_value_heredoc", + b"format F =\n@x;\nqq{@{[ <format =\n1;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [10, 4, 3, 5, 1, 5], + &[4, 5, 6, 7, 8], + ), + ( + "f50_glob_assignment", + b"sub g { 7 }\n*format =\n\\&g;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [10, 4, 2, 5, 1, 5], + &[4, 5, 6, 7, 8], + ), + ( + "h45_block_handle_blanks", + b"my $fh = \\*STDOUT;\nprint {$fh} << \"EOT\";\n=pod\n\nd\n\n=cut\nEOT\nprint \ + \"MARK\";\n", + [9, 4, 3, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "h46_bare_handle_empty_tag", + b"print STDOUT << \"\";\n=pod\n\nprint \"MARK\";\n", + [4, 1, 1, 3, 0, 3], + &[1, 2, 3], + ), + ( + "h47_glob_handle_tabs", + b"print {*STDOUT} <<\t\t'EOT';\n=pod\n\nd\n\n=cut\nEOT\nprint \"MARK\";\n", + [8, 3, 2, 5, 0, 5], + &[1, 2, 3, 4, 5], + ), + ( + "h52_block_handle_command", + b"my $fh = \\*STDOUT;\nprint {$fh} << `EOT`;\n=pod\n\nd\n\n=cut\nEOT\nprint \"\ + MARK\";\n", + [9, 4, 3, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "h48_scalar_handle_blank", + b"my $fh = \\*STDOUT;\nprint $fh << \"EOT\";\n\n=pod\n\nd\n\n=cut\nprint \"MAR\ + K\";\n", + [9, 3, 3, 5, 1, 5], + &[3, 4, 5, 6, 7], + ), + ( + "h49_tilde_blank", + b"my $fh = \\*STDOUT;\nprint {$fh} <<~ \"EOT\";\n=pod\n\nd\n\n=cut\nEOT\nprint \ + \"MARK\";\n", + [9, 4, 3, 5, 0, 5], + &[2, 3, 4, 5, 6], + ), + ( + "h50_shift_by_bareword", + b"my $t = 2; my $x = $t < 1, s => 2, q => 3);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "q22_pattern_after_keyword", + b"my @m = split /,/, 'a,b'; my $n = 1 if $m[0] =~ /a/; my @o = grep /b/, @m;\n\ + \n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 4, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "q23_pattern_after_word", + b"my $m = lc /A/;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "q24_plain_division", + b"my $z = 4 / 2; my $w = $z / 2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 3, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "q25_word_in_subscript", + b"my %k; my $v = $k{q}; my $w = { 1 };\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 3, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "q26_short_identifier", + b"my $v = 1; sub go { 7 }\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 2, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), + ( + "t31_data_as_key", + b"my %h = (__DATA__ => 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + [8, 2, 0, 5, 1, 5], + &[2, 3, 4, 5, 6], + ), +]; + +#[cfg(feature = "perl")] +fn perl_loc(source: &[u8]) -> ([u64; 6], Vec) { + let space = analyze( + Source::new(LANG::Perl, source), + MetricsOptions::default().with_only(&[Metric::Loc]), + ) + .unwrap(); + let loc = &space.metrics.loc; + ( + [ + loc.sloc(), + loc.ploc(), + loc.lloc(), + loc.cloc(), + loc.blank(), + loc.dloc(), + ], + (0..=source.len()) + .filter(|row| loc.dloc.lines.contains(*row)) + .collect(), + ) +} + +#[cfg(feature = "perl")] +#[test] +fn documentation_perl_pod_legacy_rows() { + for &(name, source, loc, rows) in &PERL_POD_SOURCES { + assert_eq!(perl_loc(source), (loc, rows.to_vec()), "{name}"); + } +} From 455ef908a0d4578ee9bdb520c5ab6631cb5d4e0f Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:39:12 -0800 Subject: [PATCH 117/221] feat(documentation): collect Perl inline POD blocks as documents of the file A POD block before the data section is one document of the file under the POD profile, with its POD source as text and without its =cut line. Blocks that perl, Pod::Simple and the grammar read differently, blocks where perl may read literal text, mixed comment regions and the data section are reported as pending. Perl is switched on: Self::Pod leaves the gate list. Seven literal forms in which perl reads a block as string text and Pod::Simple reads it as POD are published; the provenance record names them as known differences and one characterization test pins today's outcome. Legacy documentation rows are unchanged. (#1675) --- .bca-baseline.toml | 20 +- CHANGELOG.md | 13 + .../src/documentation/byte_scan.rs | 8 + .../src/documentation/collector.rs | 12 + .../src/documentation/collector/assembly.rs | 1 + .../src/documentation/collector/perl_tests.rs | 4012 ++++++++++++++++- .../src/documentation/collector/pod.rs | 303 ++ .../src/documentation/collector/pod_doubt.rs | 246 + .../src/documentation/collector/pod_format.rs | 209 + .../documentation/collector/pod_literal.rs | 399 ++ .../src/documentation/collector/tests.rs | 1 - .../src/documentation/options.rs | 2 +- .../src/documentation/text/comments.rs | 72 + .../src/lang_helpers/doc_text.rs | 92 +- .../src/lang_helpers/perl.rs | 21 +- docs/development/fuzzing.md | 4 +- fuzz/documentation-perturb.json | 7 + fuzz/documentation-seeds.json | 2 +- fuzz/generate_documentation_seeds.py | 6 +- fuzz/src/documentation/header.rs | 2 +- fuzz/src/documentation/tests.rs | 29 +- src/metrics/loc/documentation_tests.rs | 58 + .../documentation/perl-unit1-provenance.json | 65 + utils/documentation-audit-perturb.json | 8 +- utils/documentation-form-matrix.json | 7 +- ...cumentation-perl-unit1-legacy-perturb.json | 63 + utils/documentation-perl-unit1-perturb.json | 2149 +++++++++ 27 files changed, 7750 insertions(+), 61 deletions(-) create mode 100644 big-code-analysis-ast/src/documentation/collector/pod.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/pod_doubt.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/pod_format.rs create mode 100644 big-code-analysis-ast/src/documentation/collector/pod_literal.rs create mode 100644 tests/fixtures/documentation/perl-unit1-provenance.json create mode 100644 utils/documentation-perl-unit1-legacy-perturb.json create mode 100644 utils/documentation-perl-unit1-perturb.json diff --git a/.bca-baseline.toml b/.bca-baseline.toml index b3f3f1c8a..7c437fbca 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -359,19 +359,19 @@ value = 5.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "" metric = "loc.ploc" -value = 966.0 +value = 978.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>" metric = "wmc" -value = 136.0 +value = 137.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::finish" metric = "nexits" -value = 5.0 +value = 6.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -455,13 +455,13 @@ value = 13.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::recognize" metric = "halstead.effort" -value = 72422.98375857045 +value = 81796.34738938176 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "Builder<'s>::recognize" metric = "nexits" -value = 7.0 +value = 8.0 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -539,13 +539,13 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "abc" -value = 58.29236656715869 +value = 60.249481325568276 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" qualified = "collect_typed" metric = "halstead.effort" -value = 99507.69266781778 +value = 102783.07983778053 [[entry]] path = "big-code-analysis-ast/src/documentation/collector.rs" @@ -581,7 +581,7 @@ value = 77507.87166066223 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "abc" -value = 53.61902647381804 +value = 54.46099521676041 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -599,7 +599,7 @@ value = 23.0 path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" qualified = "Builder<'s>::document" metric = "halstead.effort" -value = 155069.99356991026 +value = 157081.76096151394 [[entry]] path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" @@ -1079,7 +1079,7 @@ value = 10.0 path = "big-code-analysis-ast/src/documentation/text/comments.rs" qualified = "" metric = "loc.ploc" -value = 584.0 +value = 650.0 [[entry]] path = "big-code-analysis-ast/src/documentation/text/comments.rs" diff --git a/CHANGELOG.md b/CHANGELOG.md index 11cabef9d..e74ef029c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -98,6 +98,19 @@ for historical reference. root library does not re-export, and it may change in any release. Existing metric behavior is unchanged. (#1680) +- The unstable AST documentation collector now reads Perl POD. A POD block + before the data section is one document of the file, with its POD markup as + text and without its `=cut` line. A block of `comment` regions only is no + document. A block that mixes prose with a `comment` region, a block that + perl and POD processors read differently, a block where perl may read + literal text (after a syntax error, in a `format` or after one whose end is + not known, or beside a here-document or a quote-like literal that perl + reads differently from the grammar), and the data section after `__END__` + or `__DATA__` are reported as pending. So is a file with a syntax error + whose later lines look like POD that the grammar did not read. No `sub` or + `package` owns documentation yet. Legacy documentation rows are unchanged. + (#1675) + ### Changed - **(breaking), deferred to the next major (3.0):** the MI of a space diff --git a/big-code-analysis-ast/src/documentation/byte_scan.rs b/big-code-analysis-ast/src/documentation/byte_scan.rs index ce87fce0b..b97ef68f5 100644 --- a/big-code-analysis-ast/src/documentation/byte_scan.rs +++ b/big-code-analysis-ast/src/documentation/byte_scan.rs @@ -4,6 +4,14 @@ use super::budget::WorkBudget; crate::observation::counter!(bytes_read, cfg(any(test, feature = "test-support"))); +/// Charges one byte that the caller reads itself, in a scan that keeps a +/// state of its own from byte to byte. +pub(crate) fn one(budget: &B) -> Result<(), B::Error> { + budget.bytes(1)?; + bytes_read::record(); + Ok(()) +} + pub(crate) fn position( bytes: &[u8], predicate: impl Fn(u8) -> bool, diff --git a/big-code-analysis-ast/src/documentation/collector.rs b/big-code-analysis-ast/src/documentation/collector.rs index 44f831248..d406293a0 100644 --- a/big-code-analysis-ast/src/documentation/collector.rs +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -8,6 +8,10 @@ use super::*; use crate::{Ancestors, Checker, FoldCache, Node, SiblingCache}; mod assembly; +mod pod; +mod pod_doubt; +mod pod_format; +mod pod_literal; mod projections; pub(super) mod qualifications; mod rust; @@ -80,6 +84,8 @@ pub(crate) fn collect_typed<'s, T: Checker + crate::traits::LanguageInfo>( pending_attributes: Vec::new(), rust_values: std::collections::HashMap::new(), names: super::names::Names::default(), + pod_doubt: pod_doubt::Doubt::default(), + pod_hidden: pod::Hidden::default(), }; let root_id = builder .index @@ -121,6 +127,8 @@ struct Builder<'s> { pending_attributes: Vec<(NodeId, FragmentId, Option)>, rust_values: std::collections::HashMap, names: super::names::Names, + pod_doubt: pod_doubt::Doubt, + pod_hidden: pod::Hidden, } trait OwnerCandidates: Checker { @@ -435,6 +443,9 @@ impl<'s> Builder<'s> { budget: &CollectionBudget, ) -> Result<(), CollectionError> { budget.step()?; + if self.index.profile == Profile::Pod { + return self.pod_node(id, node, budget); + } if !T::is_comment(node) { return Ok(()); } @@ -829,6 +840,7 @@ impl<'s> Builder<'s> { } fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + self.pod_end(budget)?; self.coalesce_rust(budget)?; self.combine_pending(budget)?; for draft in std::mem::take(&mut self.drafts) { diff --git a/big-code-analysis-ast/src/documentation/collector/assembly.rs b/big-code-analysis-ast/src/documentation/collector/assembly.rs index 004f219e1..1a98a7385 100644 --- a/big-code-analysis-ast/src/documentation/collector/assembly.rs +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -135,6 +135,7 @@ impl<'s> Builder<'s> { role: draft.role, content, }); + self.pod_pending_text(document); let mut owners = Vec::new(); let mut pending = draft.pending; let mut named_resolution = None; diff --git a/big-code-analysis-ast/src/documentation/collector/perl_tests.rs b/big-code-analysis-ast/src/documentation/collector/perl_tests.rs index 968f7e265..bfe5176fd 100644 --- a/big-code-analysis-ast/src/documentation/collector/perl_tests.rs +++ b/big-code-analysis-ast/src/documentation/collector/perl_tests.rs @@ -1,15 +1,78 @@ -//! Parse shapes of the pinned Perl grammar that a reader of POD blocks relies on: where a -//! `pod_statement` and the data section start and end, where the grammar gives no block, -//! and how it reads formats, here-documents and quote-like literals. The tests parse -//! verbatim bytes and collect nothing. +//! Perl POD in the source view: which blocks before the data section are documents of the +//! file, where a document's fragment ends, its text and where each part of the text comes +//! from, what is reported as pending, which blocks are withheld because perl may read +//! their lines as literal text, and which files are marked because the grammar may hide +//! POD behind a syntax error. A source is collected through both entry points, except +//! in the tests of restricted parses and of cost. The first two tests collect nothing and +//! pin the parse shapes the reader relies on. Node queries are not part of the view. #![allow(clippy::single_range_in_vec_init, clippy::naive_bytecount)] +#[cfg(feature = "perl")] +use super::pod::{PodBlock, command_line, pod_block}; +#[cfg(feature = "perl")] +use super::pod_doubt::Doubt; +#[cfg(feature = "perl")] +use super::pod_format::{format_body, format_end}; +#[cfg(feature = "perl")] +use super::pod_literal::{Quote, expects_term, perl_reads}; +#[cfg(feature = "perl")] +use crate::documentation::budget::{ + BYTE_INTERVAL, STEP_INTERVAL, WorkBudget, WorkPhase, cancel_after, cancel_in_phase, +}; +#[cfg(feature = "perl")] +use crate::documentation::text::TextError; +#[cfg(feature = "perl")] +use crate::documentation::text::comments::render; +#[cfg(feature = "perl")] +use crate::documentation::*; +#[cfg(feature = "perl")] +use crate::lang_helpers::doc_text::{pod_comment_region, pod_comment_region_with_budget}; +#[cfg(feature = "perl")] +use crate::lang_helpers::perl::opens_pod_with_budget; #[cfg(feature = "perl")] use crate::{AnyParser, LANG}; #[cfg(feature = "perl")] +use std::cell::Cell; +#[cfg(feature = "perl")] use std::ops::Range; +#[cfg(feature = "perl")] +use Run::{Copied, Decoded}; + +#[cfg(feature = "perl")] +const EXCLUDED: &str = "Excluded bytes prevent reading this POD block"; +#[cfg(feature = "perl")] +const OPENER: &str = "POD block does not open with a POD command at the start of a line"; +#[cfg(feature = "perl")] +const CLOSER: &str = "POD block does not end where perl and POD processors both end it"; +#[cfg(feature = "perl")] +const LINE_END: &str = "POD block holds a carriage return that no line feed follows"; +#[cfg(feature = "perl")] +const DATA_SECTION: &str = "Perl data section is not read for POD blocks"; +#[cfg(feature = "perl")] +const MIXED: &str = "POD block mixes documentation with comment regions"; +#[cfg(feature = "perl")] +const RECOVERY: &str = "POD block follows a syntax error, where perl may read literal text"; +#[cfg(feature = "perl")] +const FORMAT: &str = "POD block lies in the body of a format, or after one whose end is not known"; +#[cfg(feature = "perl")] +const UNREAD_OPENER: &str = + "POD block follows a here-document opener that the grammar did not read"; +#[cfg(feature = "perl")] +const HEREDOC: &str = "POD block lies beside a here-document that perl may read differently"; +#[cfg(feature = "perl")] +const LITERAL: &str = "POD block follows a quote-like literal that perl may read differently"; +#[cfg(feature = "perl")] +const HIDDEN: &str = "POD may stand after a syntax error where the grammar reads no POD block"; +#[cfg(feature = "perl")] +const CUT_NODE: &str = "Recognized declaration requires a semantic projection"; +/// The explicit checkpoints of a collection that publishes no document: one on entry, two +/// in the range preparation, one at the end of each of the three orderings (documents, +/// associations, qualifications), and one before the index is returned. +#[cfg(feature = "perl")] +const EMPTY: usize = 7; + #[cfg(feature = "perl")] const PRIMARY: &[u8] = b"=head2 f\n\nAudit\n\n=cut\n\nsub f {}"; #[cfg(feature = "perl")] @@ -24,17 +87,417 @@ const MIXED_FIXTURE: &[u8] = type Leaf = (&'static str, Range, &'static str); #[cfg(feature = "perl")] type Ranges = Vec>; - +/// Steps and bytes that a reading charged. +#[cfg(feature = "perl")] +type Charged = (usize, usize); /// A node as label, byte range and start row. The label is `ERROR` or `MISSING` for a /// recovery node and the kind otherwise. #[cfg(feature = "perl")] type Shape = (&'static str, Range, usize); +/// The start of each block and the reason that withholds it. +#[cfg(feature = "perl")] +type Doubts = Vec<(usize, Option<&'static str>)>; +/// The included byte ranges of a restricted parse. +#[cfg(feature = "perl")] +type Included = &'static [Range]; +/// The line that ends a format, in its body, where the unit knows it. +// test-lang-gates: hand-written(perl) — named by the test of the scans only, which is +// built with the Perl tests +#[cfg(feature = "perl")] +type LastLine = Option>; +/// What perl makes of the spelling of a literal node: whether it ends the literal at the +/// last byte, and whether the text holds a here-document opener. +// test-lang-gates: hand-written(perl) — named by the test of the scans only, which is +// built with the Perl tests +#[cfg(feature = "perl")] +type Reading = (bool, bool); + +#[cfg(feature = "perl")] +#[derive(Debug, PartialEq, Eq)] +enum Run { + Copied(Range), + Decoded(Range), + Expanded(Range), + Synthetic, +} + +#[cfg(feature = "perl")] +#[derive(Debug, PartialEq, Eq)] +enum Text { + Complete(String, Vec<(Range, Run)>), + Pending, + Unavailable(UnavailableReason), +} + +#[cfg(feature = "perl")] +#[derive(Debug, PartialEq, Eq)] +struct Doc { + fragment: Vec>, + text: Text, +} + +#[cfg(feature = "perl")] +#[derive(Debug, PartialEq, Eq)] +struct Pending { + axis: AssessmentAxis, + reason: &'static str, + node: (&'static str, Range), + document: Option, +} + +/// The documents with their fragment pieces and text state, the retained candidates and +/// the pending assessments (sorted: the contract gives them no order) of one collection. +/// `published` asserts what is the same for every source of this file; the association of +/// a document is among that. +#[cfg(feature = "perl")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: Vec, +} + +#[cfg(feature = "perl")] +#[derive(Clone, Copy)] +enum Retain { + Nothing, + Unbound, + Directives, +} + +/// A document whose text is its fragment's bytes from the first on: one copied run for +/// each line and for each line feed between two lines. +#[cfg(feature = "perl")] +fn doc(fragment: Range, text: &str) -> Doc { + let mut map = Vec::new(); + let mut at = 0; + for line in text.split_inclusive('\n') { + let content = line.trim_end_matches('\n').len(); + for run in [at..at + content, at + content..at + line.len()] { + if !run.is_empty() { + map.push(( + run.clone(), + Copied(fragment.start + run.start..fragment.start + run.end), + )); + } + } + at += line.len(); + } + mapped(fragment, text, map) +} + +#[cfg(feature = "perl")] +fn mapped(fragment: Range, text: &str, map: Vec<(Range, Run)>) -> Doc { + Doc { + fragment: vec![fragment], + text: Text::Complete(text.to_owned(), map), + } +} + +#[cfg(feature = "perl")] +fn pending_text(fragment: Range) -> Doc { + Doc { + fragment: vec![fragment], + text: Text::Pending, + } +} + +#[cfg(feature = "perl")] +fn withheld(reason: &'static str, block: Range) -> Pending { + Pending { + axis: AssessmentAxis::Selection, + reason, + node: ("pod_statement", block), + document: None, + } +} + +#[cfg(feature = "perl")] +fn data_section(leaf: Range) -> Pending { + Pending { + axis: AssessmentAxis::Occurrence, + reason: DATA_SECTION, + node: ("data_not_for_compiler", leaf), + document: None, + } +} + +/// A node that an excluded range cuts. Today's outcome of the core, and no rule of the +/// Perl reader: the node is reported as a pending declaration. +#[cfg(feature = "perl")] +fn cut(kind: &'static str, node: Range) -> Pending { + Pending { + axis: AssessmentAxis::Owner, + reason: CUT_NODE, + node: (kind, node), + document: None, + } +} + +/// The mark of a file whose POD the grammar may hide behind a syntax error: one +/// assessment on the first recovery node of the tree. +#[cfg(feature = "perl")] +fn hidden(kind: &'static str, node: Range) -> Pending { + Pending { + axis: AssessmentAxis::Occurrence, + reason: HIDDEN, + node: (kind, node), + document: None, + } +} + +#[cfg(feature = "perl")] +fn mixed(block: Range, document: usize) -> Pending { + Pending { + axis: AssessmentAxis::Composition, + reason: MIXED, + node: ("pod_statement", block), + document: Some(document), + } +} + +#[cfg(feature = "perl")] +fn documents(documents: [Doc; N]) -> View { + View { + documents: documents.into(), + ..View::default() + } +} + +#[cfg(feature = "perl")] +fn pending(assessments: [Pending; N]) -> View { + View { + assessments: unordered(assessments), + ..View::default() + } +} + +#[cfg(feature = "perl")] +fn unordered(assessments: impl IntoIterator) -> Vec { + let mut sorted: Vec<_> = assessments.into_iter().collect(); + sorted.sort_by_cached_key(|entry| format!("{entry:?}")); + sorted +} + +#[cfg(feature = "perl")] +fn span(pieces: &SourcePieces<'_>) -> Range { + let [piece] = pieces.pieces() else { + panic!("one source piece, found {:?}", pieces.pieces()) + }; + piece.range() +} + +#[cfg(feature = "perl")] +fn origin_run(origin: &Origin<'_>) -> Run { + match origin { + Origin::Copied(pieces) => Run::Copied(span(pieces)), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "perl")] +fn site(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +/// The pieces of a POD fragment. Its node is the block that starts where it starts, and +/// between its end and the block's end lies nothing but one line end. +#[cfg(feature = "perl")] +fn fragment_pieces(fragment: &Fragment<'_>, source: &[u8]) -> Vec> { + assert!(!fragment.source().has_excluded_gap()); + let pieces: Vec<_> = fragment + .source() + .pieces() + .iter() + .map(SourcePiece::range) + .collect(); + assert_eq!(fragment.form(), FragmentForm::Pod); + let block = fragment.node().unwrap().node(); + assert_eq!( + (block.kind(), block.start_byte()), + ("pod_statement", pieces[0].start) + ); + let end = pieces.last().unwrap().end; + assert!(matches!( + &source[end..block.end_byte()], + b"" | b"\n" | b"\r" | b"\r\n" + )); + pieces +} + +#[cfg(feature = "perl")] +fn assessed<'i, 's>( + index: &'i DocumentationIndex<'s>, + ordered: &[FactRef<'i, Document<'s>>], + assessment: FactRef<'i, Assessment<'s>>, +) -> Pending { + Pending { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: site(assessment.get().node.unwrap().node()), + document: index + .assessed_document(assessment) + .unwrap() + .map(|document| ordered.iter().position(|known| *known == document).unwrap()), + } +} + +#[cfg(feature = "perl")] +fn published(index: &DocumentationIndex<'_>, root: tree_sitter::Node<'_>) -> View { + // bca: suppress(halstead) -- one reading of the published lists and their shared rules. + let facts = index.facts(); + let source = index.source(); + let ordered: Vec<_> = index.documents().collect(); + let position = |document| ordered.iter().position(|known| *known == document).unwrap(); + let documents = ordered + .iter() + .map(|&document| { + assert_eq!(document.get().role(), DocumentRole::FilePackage); + assert_eq!(document.get().composition(), Composition::Single); + assert_eq!(document.get().fragment_count(), 1); + let fragment = facts.document_fragment(document, 0).unwrap(); + Doc { + fragment: fragment_pieces(fragment.get(), source), + text: match document.get().content() { + Content::Complete { .. } => { + let complete = index.complete_text(document).unwrap().unwrap(); + Text::Complete( + complete.text().to_owned(), + complete + .mappings() + .iter() + .map(|entry| (entry.output.range(), origin_run(&entry.origin))) + .collect(), + ) + } + Content::PendingAdapter => Text::Pending, + Content::Unavailable(reason) => Text::Unavailable(*reason), + other => panic!("a POD text state, found {other:?}"), + }, + } + }) + .collect(); + // The only owner is the file, and every document belongs to it: association `i` is + // the resolved association of document `i`. + let [file] = facts.owners().collect::>()[..] else { + panic!("the file owner alone") + }; + assert!(matches!(file.get(), Owner::File(evidence) if evidence.node() == root)); + assert_eq!(index.associations().len(), ordered.len()); + for (at, association) in index.associations().enumerate() { + let attachment = association.get(); + let document = facts.associated_document(association).unwrap(); + assert_eq!(position(document), at); + assert_eq!(attachment.resolution, Resolution::Resolved); + assert_eq!(attachment.owner_count(), 1); + assert_eq!(facts.associated_owner(association, 0).unwrap(), file); + assert_eq!(attachment.convention.name(), "POD"); + assert_eq!(attachment.publication, Publication::Unknown); + assert!(attachment.binding.is_none()); + let block = facts.document_fragment(document, 0).unwrap(); + let block = block.get().node().unwrap().node(); + assert_eq!(Some(attachment.lexical_scope.node()), block.parent()); + } + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + ( + candidate.get().disposition, + span_of(&fragment_pieces(fragment.get(), source)), + ) + }) + .collect(); + let read = |assessment| assessed(index, &ordered, assessment); + let assessments = unordered(index.assessments().map(read)); + // Pending POD work is filed with the file. A node that an excluded range cuts keeps + // the core's own assessment, which is filed with that node. + let filed = index.owner_associations(file).unwrap(); + assert_eq!( + unordered(filed.assessments().map(read)), + unordered( + index + .assessments() + .map(read) + .filter(|entry| entry.reason != CUT_NODE) + ) + ); + assert_eq!(filed.associations().len(), ordered.len()); + assert_eq!(index.profile(), Profile::Pod); + assert_eq!(index.capability(), Capability::Partial); + // POD has no command that names a declaration, so no qualification record exists. + assert_eq!(index.qualifications().len(), 0); + View { + documents, + evidence, + assessments, + } +} + +#[cfg(feature = "perl")] +fn span_of(pieces: &[Range]) -> Range { + let [piece] = pieces else { + panic!("one source piece, found {pieces:?}") + }; + piece.clone() +} #[cfg(feature = "perl")] fn parsed(source: &[u8]) -> AnyParser { AnyParser::parse(LANG::Perl, source.to_vec(), None, None).unwrap() } +#[cfg(feature = "perl")] +fn options(retain: Retain) -> DocumentationOptions { + DocumentationOptions { + retain_unbound: matches!(retain, Retain::Unbound), + retain_directives: matches!(retain, Retain::Directives), + ..DocumentationOptions::default() + } +} + +#[cfg(feature = "perl")] +fn indexes(parser: &AnyParser, retain: Retain) -> [DocumentationIndex<'_>; 2] { + let context = DocumentationContext::default(); + let options = options(retain); + [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Perl, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] +} + +#[cfg(feature = "perl")] +fn retained(source: &[u8], retain: Retain) -> View { + let parser = parsed(source); + let root = parser.ts_tree().root_node(); + let [typed, raw] = indexes(&parser, retain) + .each_ref() + .map(|index| published(index, root)); + assert_eq!(typed, raw, "`AnyParser::documentation` and `collect`"); + typed +} + +#[cfg(feature = "perl")] +fn view(source: &[u8]) -> View { + retained(source, Retain::Nothing) +} + +#[cfg(feature = "perl")] +fn assert_views(cases: [(&[u8], View); N]) { + for (source, expected) in cases { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + } +} + /// A raw parse that reads the given byte ranges only. #[cfg(feature = "perl")] fn restricted(source: &[u8], ranges: &[Range]) -> tree_sitter::Tree { @@ -66,6 +529,20 @@ fn restricted(source: &[u8], ranges: &[Range]) -> tree_sitter::Tree { parser.parse(source, None).unwrap() } +#[cfg(feature = "perl")] +fn restricted_view(source: &[u8], ranges: &[Range], retain: Retain) -> View { + let tree = restricted(source, ranges); + let index = collect( + LANG::Perl, + &tree, + source, + &DocumentationContext::default(), + &options(retain), + ) + .unwrap(); + published(&index, tree.root_node()) +} + /// Every node of the given kinds, in source order, with the kind of its parent. #[cfg(feature = "perl")] fn nodes_of(root: tree_sitter::Node<'_>, kinds: &[&str]) -> Vec { @@ -138,6 +615,161 @@ fn shapes_of(root: tree_sitter::Node<'_>, source: &[u8]) -> Vec { found } +/// The state of the rules for literal text, fed every node in tree order as the +/// collector's walk feeds it: for each block the reason that withholds it. +#[cfg(feature = "perl")] +fn doubt_walk( + context: &SourceContext<'_>, + root: tree_sitter::Node<'_>, + budget: &Counting, +) -> Result { + let mut doubt = Doubt::default(); + let mut blocks = Vec::new(); + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + doubt.enter(context, node, budget)?; + if node.kind() == "pod_statement" { + blocks.push((node.start_byte(), doubt.reason(node.start_byte()))); + } + let mut cursor = node.walk(); + let children: Vec<_> = node.children(&mut cursor).collect(); + stack.extend(children.into_iter().rev()); + } + Ok(blocks) +} + +/// What a scan answers and the bytes it charges. The scan charges no step, and it is +/// cancelled once at each of its charges. +// test-lang-gates: hand-written(perl) — called by the test of the scans only, which is +// built with the Perl tests +#[cfg(feature = "perl")] +fn scan_charges( + scan: impl Fn(&Counting) -> Result, +) -> (T, usize) { + let budget = Counting::default(); + let answer = scan(&budget).unwrap(); + assert_eq!(budget.steps.get(), 0); + for fail_at in 1..=budget.charges.get() { + assert!(matches!( + scan(&failing_at(fail_at)), + Err(SourceError::Cancelled) + )); + } + assert_eq!(scan(&failing_at(budget.charges.get() + 1)).unwrap(), answer); + (answer, budget.bytes.get()) +} + +#[cfg(feature = "perl")] +fn node_at<'t>( + root: tree_sitter::Node<'t>, + kind: &str, + range: Range, +) -> tree_sitter::Node<'t> { + let mut found = Vec::new(); + let mut stack = vec![root]; + while let Some(node) = stack.pop() { + let mut cursor = node.walk(); + stack.extend(node.children(&mut cursor)); + if node.kind() == kind && node.byte_range() == range { + found.push(node); + } + } + let [found] = found[..] else { + panic!("one {kind} at {range:?}, found {found:?}") + }; + found +} + +/// Counts every charge and fails the charge numbered `fail_at`, after counting it. +#[cfg(feature = "perl")] +#[derive(Default)] +struct Counting { + steps: Cell, + bytes: Cell, + checkpoints: Cell, + charges: Cell, + fail_at: Option, +} + +#[cfg(feature = "perl")] +fn failing_at(charge: usize) -> Counting { + Counting { + fail_at: Some(charge), + ..Counting::default() + } +} + +// test-lang-gates: hand-written(perl) — called from the trait methods of `Counting` +// only, and the gate does not read the `cfg` of an `impl` block +#[cfg(feature = "perl")] +fn count_charge(budget: &Counting) -> Result<(), SourceError> { + budget.charges.set(budget.charges.get() + 1); + if budget.fail_at == Some(budget.charges.get()) { + Err(SourceError::Cancelled) + } else { + Ok(()) + } +} + +#[cfg(feature = "perl")] +fn charged_totals(budget: &Counting) -> Charged { + (budget.steps.get(), budget.bytes.get()) +} + +#[cfg(feature = "perl")] +impl WorkBudget for Counting { + type Error = SourceError; + + #[cfg(feature = "perl")] + fn checkpoint(&self) -> Result<(), SourceError> { + self.checkpoints.set(self.checkpoints.get() + 1); + Ok(()) + } + + fn step(&self) -> Result<(), SourceError> { + self.steps.set(self.steps.get() + 1); + count_charge(self) + } + + #[cfg(feature = "perl")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + count_charge(self) + } +} + +/// `pod_block` for the block that starts at `start`, with the steps and bytes it charged. +/// With `sweep`, the reading is also cancelled once at each of its charges. +#[cfg(feature = "perl")] +fn block_charges(source: &[u8], start: usize, sweep: bool) -> (PodBlock, Charged) { + let parser = parsed(source); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let (_, range, _) = nodes_of(parser.ts_tree().root_node(), &["pod_statement"]) + .into_iter() + .find(|(_, range, _)| range.start == start) + .unwrap(); + let block = node_at(parser.ts_tree().root_node(), "pod_statement", range); + let budget = Counting::default(); + let answer = pod_block(&context, block, &budget).unwrap(); + if sweep { + for fail_at in 1..=budget.charges.get() { + // expected: every charge is passed on, so each of them can cancel the reading. + assert!(matches!( + pod_block(&context, block, &failing_at(fail_at)), + Err(SourceError::Cancelled) + )); + } + let next = failing_at(budget.charges.get() + 1); + assert_eq!(pod_block(&context, block, &next).unwrap(), answer); + } + (answer, charged_totals(&budget)) +} + +#[cfg(feature = "perl")] +fn tall(rows: usize, row: &str, last: &str) -> Vec { + format!("{}{last}", row.repeat(rows)).into_bytes() +} + #[cfg(feature = "perl")] #[test] #[allow(clippy::too_many_lines)] @@ -1054,3 +1686,3373 @@ fn perl_literal_parse_shapes_the_doubt_rules_rely_on() { ); } } + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_block_documents_the_file() { + assert_views([ + (PRIMARY, documents([doc(0..21, "=head2 f\n\nAudit")])), + ( + b"=head2 f\n\nAudit\n\n=cut\n\nsub f {}\nsub f {}", + documents([doc(0..21, "=head2 f\n\nAudit")]), + ), + ( + b"package Foo;\n\n=head1 NAME\n\nFoo\n\n=cut\n\nsub new {}\n", + documents([doc(14..36, "=head1 NAME\n\nFoo")]), + ), + ( + b"=begin html\n\n

x

\n\n=end html\n\n=cut\n", + documents([doc(0..38, "=begin html\n\n

x

\n\n=end html")]), + ), + ( + b"=begin :comment\n\nx\n\n=end :comment\n\n=cut\n", + documents([doc(0..39, "=begin :comment\n\nx\n\n=end :comment")]), + ), + ( + b"=item\t*\n\ny\n\n=cut\n", + documents([doc(0..16, "=item\t*\n\ny")]), + ), + ( + b"=pod\x0bx\n\ny\n\n=cut\n", + documents([doc(0..15, "=pod\x0bx\n\ny")]), + ), + ( + b"=pod\n\n__END__\n\n=cut\nmy $x;\n", + documents([doc(0..19, "=pod\n\n__END__")]), + ), + ]); + let parser = parsed(PRIMARY); + let root = parser.ts_tree().root_node(); + for index in indexes(&parser, Retain::Nothing) { + let association = index.associations().next().unwrap(); + let file = index.node_associations(root).unwrap(); + assert!(!file.projection_pending()); + assert_eq!(file.associations().collect::>(), [association]); + assert_eq!(file.assessments().count(), 0); + // Today's outcome, expected to change: no `sub` is an owner in this unit, so a + // query for one is unsupported and not an empty answer. + let sub = node_at(root, "function_definition", 23..31); + assert!(matches!( + index.node_associations(sub), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_projection(sub), + Err(OwnerError::UnsupportedOwner) + )); + // A block is no owner either. + let block = node_at(root, "pod_statement", 0..21); + assert!(matches!( + index.node_owners(block), + Err(OwnerError::UnsupportedOwner) + )); + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_blocks_are_documents_in_source_order() { + assert_views([ + ( + b"my $x = 1;\n=head1 A\n\na\n\n=cut\nmy $y = 2;\n=head1 B\n\nb\n\n=cut\nmy $z = 3;\n", + documents([doc(11..28, "=head1 A\n\na"), doc(40..57, "=head1 B\n\nb")]), + ), + ( + b"=head1 A\n\na\n\n=cut\n=head1 B\n\nb\n\n=cut\n", + documents([doc(0..17, "=head1 A\n\na"), doc(18..35, "=head1 B\n\nb")]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_block_in_a_body_is_scoped_to_the_body() { + let cases: [(&[u8], View, Range); 2] = [ + ( + b"sub f {\n my $x = 1;\n\n=pod\n\nDoc.\n\n=cut\n\n return $x;\n}\n", + documents([doc(24..40, "=pod\n\nDoc.")]), + 6..59, + ), + ( + b"sub o {\n sub i {\n=head2 i\n\nInner.\n\n=cut\n }\n}\n", + documents([doc(18..40, "=head2 i\n\nInner.")]), + 16..45, + ), + ]; + for (source, expected, body) in cases { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + let parser = parsed(source); + for index in indexes(&parser, Retain::Nothing) { + let association = index.associations().next().unwrap(); + // expected: the body that holds the block, not the file and not the sub. + assert_eq!( + site(association.get().lexical_scope.node()), + ("block", body.clone()) + ); + } + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_fragment_ends_before_the_line_end_of_its_last_line() { + let crlf = |fragment: Range, text: &str, name: Range, body: Range| { + mapped( + fragment, + text, + vec![ + (0..name.len(), Copied(name.clone())), + (name.len()..name.len() + 1, Decoded(name.end..name.end + 2)), + ( + name.len() + 1..name.len() + 2, + Decoded(name.end + 2..name.end + 4), + ), + (name.len() + 2..text.len(), Copied(body)), + ], + ) + }; + assert_views([ + // A `=cut` line ends the block: its line end is outside the node and the fragment. + ( + b"=head1 A\n\na\n\n=cut here is text\nmy $y = 2;\n", + documents([doc(0..30, "=head1 A\n\na")]), + ), + (b"=pod\n\nx\n\n=cut", documents([doc(0..13, "=pod\n\nx")])), + // The node holds the CR of `=cut\r\n`; the fragment does not. + ( + b"=head1 A\r\n\r\na\r\n\r\n=cut\r\nsub f {}\r\n", + documents([crlf(0..21, "=head1 A\n\na", 0..8, 12..13)]), + ), + ( + b"=pod\r\n\r\nx\r\n\r\n=cut\r\n", + documents([crlf(0..17, "=pod\n\nx", 0..4, 8..9)]), + ), + // No `=cut` line: the node holds the final line end; the fragment does not. + ( + b"my $x = 1;\n\n=head1 NAME\n\nNever closed.\n", + documents([doc(12..38, "=head1 NAME\n\nNever closed.")]), + ), + ( + b"my $x = 1;\n\n=head1 NAME\n\nNever closed.", + documents([doc(12..38, "=head1 NAME\n\nNever closed.")]), + ), + ( + b"=head1 NAME\n\nNever closed.\n\n\n", + documents([doc(0..28, "=head1 NAME\n\nNever closed.")]), + ), + ( + b"=pod\r\n\r\nx\r\n", + documents([crlf(0..9, "=pod\n\nx", 0..4, 8..9)]), + ), + (b"=pod\n", documents([doc(0..4, "=pod")])), + // `=CUT` ends nothing for perl, for POD processors and for the grammar. + ( + b"=pod\n\ny\n\n=CUT\nmy $x;\n", + documents([doc(0..20, "=pod\n\ny\n\n=CUT\nmy $x;")]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_text_keeps_its_lines_and_drops_the_cut_line() { + assert_views([ + (b"=pod\n=cut\n", documents([doc(0..9, "=pod")])), + // `=cut` before a digit or a form feed ends the block for all three readers. + ( + b"=head1 A\n\ntext\n\n=cut2\nmy $y = 2;\n", + documents([doc(0..21, "=head1 A\n\ntext")]), + ), + ( + b"=pod\n\nx\n\n=cut\x0cfoo\nmy $y;\n", + documents([doc(0..17, "=pod\n\nx")]), + ), + // Only a line of no bytes is an empty boundary line: a line of one space stays. + ( + b"=pod\n\nx\n \n=cut\n", + documents([doc(0..14, "=pod\n\nx\n ")]), + ), + // Blank lines inside stay; those before the `=cut` line go. + ( + b"=pod\n\n\n\ny\n\n\n=cut\n", + documents([doc(0..16, "=pod\n\n\n\ny")]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_comment_only_pod_is_no_document() { + let sources: [(&[u8], View, Ranges); 3] = [ + ( + b"=begin comment\n\nnot prose\n\n=end comment\n\n=cut\n", + View::default(), + vec![0..45], + ), + // Two candidates, in source order. + ( + b"=begin comment\n\na\n\n=end comment\n\n=cut\n\nmy $x;\n\n=for comment b\n\n=cut\n", + View::default(), + vec![0..37, 47..67], + ), + // The comment-only block is withheld beside a block that is published. + ( + b"=begin comment\n\nx\n\n=end comment\n\n=cut\n\n=head1 A\n\na\n\n=cut\n", + documents([doc(39..56, "=head1 A\n\na")]), + vec![0..37], + ), + ]; + for (source, mut expected, candidates) in sources { + assert_eq!(view(source), expected, "{}", source.escape_ascii()); + // A comment-only block is a directive, not an unattached candidate. + assert_eq!( + retained(source, Retain::Unbound), + expected, + "{}", + source.escape_ascii() + ); + expected.evidence = candidates + .into_iter() + .map(|range| (CandidateDisposition::Directive, range)) + .collect(); + assert_eq!( + retained(source, Retain::Directives), + expected, + "{}", + source.escape_ascii() + ); + } + // A document is no candidate under either option. + for retain in [Retain::Unbound, Retain::Directives] { + assert_eq!(retained(PRIMARY, retain), view(PRIMARY)); + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_with_a_comment_region_has_pending_text() { + assert_views([ + ( + MIXED_FIXTURE, + View { + documents: vec![pending_text(0..62)], + assessments: unordered([mixed(0..62, 0), data_section(91..121)]), + ..View::default() + }, + ), + ( + b"=for comment\nInternal note.\n\n=head1 NAME\n\nFoo - bar\n\n=cut\n", + View { + documents: vec![pending_text(0..57)], + assessments: vec![mixed(0..57, 0)], + ..View::default() + }, + ), + // The assessment names the document whose text waits, here the second. + ( + b"=head1 A\n\na\n\n=cut\n\n=head1 B\n\n=for comment x\n\nb\n\n=cut\n", + View { + documents: vec![doc(0..17, "=head1 A\n\na"), pending_text(19..52)], + assessments: vec![mixed(19..52, 1)], + ..View::default() + }, + ), + // A comment command line inside a paragraph is ordinary text for `Pod::Simple`. + // This unit does not tell paragraphs apart and lets the text wait. + ( + b"=head1 A\n\ntext\n=for comment x\n\nmore\n\n=cut\n", + View { + documents: vec![pending_text(0..41)], + assessments: vec![mixed(0..41, 0)], + ..View::default() + }, + ), + ]); + // The document keeps no complete text and no source-cleaned text. + let parser = parsed(MIXED_FIXTURE); + for index in indexes(&parser, Retain::Nothing) { + let document = index.documents().next().unwrap(); + assert!(index.complete_text(document).unwrap().is_none()); + assert!(index.source_cleaned_text(document).unwrap().is_none()); + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_block_with_a_foreign_opener_is_withheld() { + // These are undecided states, not answers: perl, `Pod::Simple` and the grammar do not + // read the same block here. No option retains such a block as a candidate. + let cases: [(&[u8], Range); 11] = [ + (b"my $x = 1;\n=cut\nmy $y = 2;\n", 11..27), + (b"=cut\n\nx\n\n=cut\nmy $y;\n", 0..13), + (b"my $x = 1;\n=1\ntext\n=cut\n", 11..23), + (b"my $x = 1;\n=_x\ntext\n=cut\n", 11..24), + (b"=head-x\n\ntext\n\n=cut\n", 0..19), + (b"=pod.\n\nx\n\n=cut\n", 0..14), + (b"my $x;\n=cutting\ntext\n=cut\nmy $y;\n", 7..25), + (b"my $x = 1;\n =head1 NAME\n\ntext\n\n=cut\n", 13..36), + (b"my $x = 1; =head1 NAME\n\ntext\n\n=cut\n", 11..34), + (b"my $x;\r=pod\n\nx\n\n=cut\n", 7..20), + // perl and `Pod::Simple` skip a byte order mark at the start of the input and + // read this block. This unit does not. + (b"\xef\xbb\xbf=pod\n\nx\n\n=cut\n", 3..16), + ]; + for (source, block) in cases { + let expected = pending([withheld(OPENER, block)]); + for retain in [Retain::Nothing, Retain::Unbound, Retain::Directives] { + assert_eq!( + retained(source, retain), + expected, + "{}", + source.escape_ascii() + ); + } + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_block_with_a_disputed_end_is_withheld() { + let cases: [(&[u8], View); 3] = [ + // perl does not end a block at `=cutting`; the grammar does, and reads the + // `=cut` below it as a second block. + ( + b"=head1 A\n\ntext\n\n=cutting\nmy $y = 2;\n=cut\n", + pending([withheld(CLOSER, 0..24), withheld(OPENER, 36..41)]), + ), + // The grammar ends a block at a NUL byte; perl reads on to `=cut`. The byte is an + // `ERROR` node, and the `=cut` line behind it has no node: the file is marked. + ( + b"=pod\n\na\x00b\n\n=cut\n", + View { + assessments: unordered([withheld(CLOSER, 0..7), hidden("ERROR", 7..8)]), + ..View::default() + }, + ), + ( + b"=pod\n\nx\n\n=cut\x00foo\nmy $y;\n", + pending([withheld(CLOSER, 0..13)]), + ), + ]; + for (source, expected) in cases { + for retain in [Retain::Nothing, Retain::Unbound, Retain::Directives] { + assert_eq!( + retained(source, retain), + expected, + "{}", + source.escape_ascii() + ); + } + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_block_with_a_lone_carriage_return_is_withheld() { + assert_views([ + ( + b"=pod\r\rx\r\r=cut\rmy $x;\r", + pending([withheld(LINE_END, 0..21)]), + ), + ( + b"=pod\n\na\rb\n\n=cut\n", + pending([withheld(LINE_END, 0..15)]), + ), + (b"=pod\n\nx\n\n=cut\r", pending([withheld(LINE_END, 0..14)])), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_withheld_block_leaves_the_next_block_published() { + assert_views([( + b"my $x = 1;\n =head1 X\n\nx\n\n=cut\n=head1 A\n\na\n\n=cut\n", + View { + documents: vec![doc(31..48, "=head1 A\n\na")], + assessments: vec![withheld(OPENER, 13..30)], + ..View::default() + }, + )]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_beside_excluded_bytes_is_withheld() { + let b = || doc(40..57, "=head1 B\n\nb"); + let a = || doc(11..28, "=head1 A\n\na"); + let cases: [(&[Range], View); 6] = [ + // An excluded byte inside the block. + ( + &[0..20, 21..58], + View { + documents: vec![b()], + assessments: vec![withheld(EXCLUDED, 11..28)], + ..View::default() + }, + ), + // The byte before the block: whether the block starts a line is not known. + ( + &[0..10, 11..58], + View { + documents: vec![b()], + assessments: vec![withheld(EXCLUDED, 11..28)], + ..View::default() + }, + ), + // The line feed after `=cut`: the grammar joins the next row to the block. + ( + &[0..28, 29..58], + View { + documents: vec![b()], + assessments: vec![withheld(EXCLUDED, 11..39)], + ..View::default() + }, + ), + // The `=cut` line itself: the grammar joins both blocks. + (&[0..24, 28..58], pending([withheld(EXCLUDED, 11..57)])), + // The byte after the block, here the last byte of the input. + ( + &[0..57], + View { + documents: vec![a()], + assessments: vec![withheld(EXCLUDED, 40..57)], + ..View::default() + }, + ), + // Excluded bytes elsewhere withhold no block. Today's outcome of the core, not a + // rule of this unit: the statement that the gap cuts is reported as a pending + // declaration. + ( + &[0..5, 6..58], + View { + documents: vec![a(), b()], + assessments: vec![Pending { + axis: AssessmentAxis::Owner, + reason: CUT_NODE, + node: ("binary_expression", 0..9), + document: None, + }], + ..View::default() + }, + ), + ]; + for (ranges, expected) in cases { + for retain in [Retain::Nothing, Retain::Unbound, Retain::Directives] { + assert_eq!( + restricted_view(TWO_BLOCKS, ranges, retain), + expected, + "{ranges:?}" + ); + } + } + // Control: the same source without an excluded byte publishes both blocks. + assert_eq!(view(TWO_BLOCKS), documents([a(), b()])); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_across_adjacent_ranges_keeps_one_piece_per_range() { + let tree = restricted(TWO_BLOCKS, &[0..15, 15..58]); + let index = collect( + LANG::Perl, + &tree, + TWO_BLOCKS, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + // expected: no byte is excluded, so the block is read; its fragment and the first + // line of its text are cut where the two ranges meet. + assert_eq!( + published(&index, tree.root_node()), + documents([ + Doc { + fragment: vec![11..15, 15..28], + text: Text::Complete( + "=head1 A\n\na".to_owned(), + vec![ + (0..4, Copied(11..15)), + (4..8, Copied(15..19)), + (8..9, Copied(19..20)), + (9..10, Copied(20..21)), + (10..11, Copied(21..22)), + ] + ), + }, + doc(40..57, "=head1 B\n\nb"), + ]) + ); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_after_a_recovery_node_is_withheld() { + // After an `ERROR` or a missing node the grammar has lost its place, and perl may + // read the lines that follow as literal text. In the first three sources it does: a + // here-document with an empty tag, and a format. In the next two perl stops reading + // at a control byte. perl rejects the last four files. Every block that follows + // such a node in the tree is withheld. Each of these blocks has a node, so no file + // is marked for POD that the grammar hides. + assert_views([ + ( + b"my $s = <<\"\";\n=pod\n\nprint \"MARK\";\n", + pending([withheld(RECOVERY, 14..34)]), + ), + ( + b"my $s = <<'';\n=pod\n\nprint \"MARK\";\n", + pending([withheld(RECOVERY, 14..34)]), + ), + ( + b"format STDOUT =\n=pod\n.\n", + pending([withheld(RECOVERY, 16..23)]), + ), + ( + b"1;\n\x04\n=pod\n\nd\n\n=cut\n", + pending([withheld(RECOVERY, 5..18)]), + ), + ( + b"1;\n\x1a\n=pod\n\nd\n\n=cut\n", + pending([withheld(RECOVERY, 5..18)]), + ), + ( + b"%%%% (\n=pod\n\nx\n\n=cut\n", + pending([withheld(RECOVERY, 7..20)]), + ), + ( + b"my $x = 1,\n=pod\n\nx\n\n=cut\n2;\n", + pending([withheld(RECOVERY, 11..24)]), + ), + ( + b"sub f {\nreturn\n=pod\n\nx\n\n=cut\n1;\n}\n", + pending([withheld(RECOVERY, 15..28)]), + ), + ( + b"my $x = (1;\n\n=head1 A\n\na\n\n=cut\n", + pending([withheld(RECOVERY, 13..30)]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_before_the_first_recovery_node_is_read() { + // A recovery node says nothing about the lines before it. perl rejects each of these + // files; `Pod::Simple` reads the block, and so does this unit. In the last source the + // block after the node is withheld. + assert_views([ + ( + b"sub f {\n=pod\n\nx\n\n=cut\n", + documents([doc(8..21, "=pod\n\nx")]), + ), + ( + b"=pod\n\nx\n\n=cut\n}}}}\n", + documents([doc(0..13, "=pod\n\nx")]), + ), + ( + b"=pod\n\nx\n\n=cut\n}}}}\n=pod\n\ny\n\n=cut\n", + View { + documents: vec![doc(0..13, "=pod\n\nx")], + assessments: unordered([withheld(RECOVERY, 19..32)]), + ..View::default() + }, + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn perl_pod_in_a_format_is_withheld() { + // perl reads the lines of a format as picture text, up to a line that holds a dot and + // then only blanks, tabs or carriage returns. The grammar knows no format: it reads + // a call, and a block wherever a line starts with `=`. The opener is the keyword, + // an optional name, `=` and the end of the line, with white space and comments + // between them. A format without a last line runs to the end of the input. A + // comment-only block in a format is reported like any block there, and a block that + // the reader's own tests withhold keeps their reason. In the last four sources the + // grammar reads the picture text into the code after the format, or the format + // goes on behind a line that looks like its last. + assert_views([ + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 19..32)]), + ), + ( + b"format =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 12..25)]), + ), + ( + b"format Pkg::F =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 19..32)]), + ), + ( + b"format STDOUT=\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 18..31)]), + ), + ( + b"format STDOUT = \t\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 22..35)]), + ), + ( + b"format STDOUT = # c\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 23..36)]), + ), + ( + b"format\nSTDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 19..32)]), + ), + ( + b"format STDOUT\n=\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 19..32)]), + ), + ( + b"format # a\nSTDOUT # b\n=\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 27..40)]), + ), + ( + b" format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 21..34)]), + ), + ( + b"my $q = 1; format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 30..43)]), + ), + ( + b"sub g {\nformat STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n}\n", + pending([withheld(FORMAT, 27..40)]), + ), + ( + b"format STDOUT =\r\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 20..33)]), + ), + ( + b"L: format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 22..35)]), + ), + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n2;\n", + pending([withheld(FORMAT, 19..32)]), + ), + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n\n=pod\n\nreal\n\n=cut\n", + View { + documents: vec![doc(41..57, "=pod\n\nreal")], + assessments: unordered([withheld(FORMAT, 19..32)]), + ..View::default() + }, + ), + ( + b"format STDOUT =\n1;\n=begin comment\n\nx\n\n=end comment\n\n=cut\n1\n.\n2;\n", + pending([withheld(FORMAT, 19..56)]), + ), + ( + b"format STDOUT =\n1;\n=cut\n1\n.\n2;\n", + pending([withheld(OPENER, 19..31)]), + ), + ( + b"format F =\na 'b\n.\nmy $s = ';\n=pod\n\nd\n\n=cut\n';\nprint \"MARK\";\n", + pending([withheld(FORMAT, 29..42)]), + ), + ( + b"format F =\n1; print <format;\n\n=pod\n\nd\n\n=cu\ + t\nprint \"MARK\";\n", + documents([doc(56..69, "=pod\n\nd")]), + ), + ( + b"my %h = (format => 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(24..37, "=pod\n\nd")]), + ), + ( + b"my %h = (format\n=> 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(24..37, "=pod\n\nd")]), + ), + ( + b"my $s = 'format STDOUT =';\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(28..41, "=pod\n\nd")]), + ), + ( + b"# format STDOUT =\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(19..32, "=pod\n\nd")]), + ), + ( + b"FORMAT STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + documents([doc(19..32, "=pod\n\nd")]), + ), + ( + b"my %h; $h{format} =\n1;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(24..37, "=pod\n\nd")]), + ), + ( + b"format STDOUT =\n1\n.\n2;\nmy $k = 3;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\ + \n", + documents([doc(35..48, "=pod\n\nd")]), + ), + ( + b"forXmat STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + documents([doc(20..33, "=pod\n\nd")]), + ), + ( + b"format F =\n@x;\n$a, $b\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(28..41, "=pod\n\nd")]), + ), + ( + b"format F =\n@x\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(20..33, "=pod\n\nd")]), + ), + ( + b"format F =\n~~@x;\n$a\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(26..39, "=pod\n\nd")]), + ), + ( + b"format F =\n1\n# @x\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(24..37, "=pod\n\nd")]), + ), + ( + b"format F =\n@x;\n$a,\n@y;\n$b;\ntext\n. \n2;\n\n=pod\n\nd\n\n=cut\nprint \"M\ + ARK\";\n", + documents([doc(39..52, "=pod\n\nd")]), + ), + ( + b"format F =\r\n@x;\r\n$a\r\n.\r\n2;\r\n\r\n=pod\r\n\r\nd\r\n\r\n=cut\r\nprint \ + \"MARK\";\r\n", + documents([mapped( + 30..47, + "=pod\n\nd", + vec![ + (0..4, Copied(30..34)), + (4..5, Decoded(34..36)), + (5..6, Decoded(36..38)), + (6..7, Copied(38..39)), + ], + )]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn perl_pod_after_an_unread_here_document_opener_is_withheld() { + // perl opens a here-document inside a literal that it evaluates: a string, `qq`, + // backticks, `qx`, a pattern or a substitution. The grammar reads no code in a + // literal. It also reads the opener behind a file handle in a variable or in braces + // as a shift. In both cases the lines of the here-document are code for the grammar, + // and every later block is withheld. In the last five sources blanks or tabs stand + // between `<<` or `<<~` and a quoted tag, which may be empty. + assert_views([ + ( + b"my $s = \"@{[ <>> 1 << 2\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(29..42, "=pod\n\nd")]), + ), + ( + b"my $s = \"<<\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(15..28, "=pod\n\nd")]), + ), + ( + b"my $t = 2; my $s = $t <<$t;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(29..42, "=pod\n\nd")]), + ), + ( + b"my $s = \"a b\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(16..29, "=pod\n\nd")]), + ), + ( + b"my $s = < < 2);\nprint \"MARK\";\n", + pending([hidden("ERROR", 0..64)]), + ), + ( + b"my $s = q{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = q(\n=pod\n\nd\n\n=cut\n);\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = q X\n=pod\n\nd\n\n=cut\nX;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = q#\n=pod\n\nd\n\n=cut\n#;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = qq{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = 'a' =~ m{\n=pod\n\nd\n\n=cut\n}x;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = qr/\n=pod\n\nd\n\n=cut\n/x;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = 'a'; $s =~ s/\n=pod\n\nd\n\n=cut\n/b/x;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = 'a'; $s =~ s{a}{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = 'a'; $s =~ tr/a/\n=pod\n\nd\n\n=cut\n/;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = 'a'; $s =~ y/a/\n=pod\n\nd\n\n=cut\n/;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = '\n=pod\n\nd\n\n=cut\n';\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = `\n=pod\n\nd\n\n=cut\n`;\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = qx{\n=pod\n\nd\n\n=cut\n};\nprint \"MARK\";\n", + View::default(), + ), + ( + b"my $s = <<`EOT`;\n=pod\n\nd\n\n=cut\nEOT\nprint \"MARK\";\n", + View::default(), + ), + ( + b"1; __END__\n=pod\n\nd\n\n=cut\n", + pending([data_section(10..25)]), + ), + ( + b"format STDOUT =\nline\n.\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([hidden("ERROR", 23..27)]), + ), + ( + b"format Pkg'F =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + pending([hidden("ERROR", 0..39)]), + ), + (b"my $y\n=pod\n;\nprint \"MARK\";\n", View::default()), + ]; + for (source, expected) in cases { + for retain in [Retain::Nothing, Retain::Unbound, Retain::Directives] { + assert_eq!( + retained(source, retain), + expected, + "{}", + source.escape_ascii() + ); + } + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_end_marker_as_a_hash_key_is_pinned() { + // This test pins today's outcome, not a decision: `__END__` and `__DATA__` before + // `=>` are hash keys for perl, which compiles the lines behind them and reads the + // block as POD. The grammar gives a data leaf there, and the unit reports a data + // section that perl does not have. + assert_views([ + ( + b"my %h = (__END__ => 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([data_section(16..53)]), + ), + ( + b"my %h = (__DATA__ => 1);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([data_section(17..54)]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_pod_hidden_behind_recovery_is_reported() { + // Behind a recovery node the grammar may give no `pod_statement` for a POD block. + // The file then gets one assessment on the first recovery node of the tree, if a + // line that starts with `=` and an ASCII letter stands behind that node, before the + // data section and outside every block. First source: perl reads the block as POD; + // the grammar does not parse the literal before it. Second source: the node is a + // missing node, the line stands in a string, and the search ends at the data leaf. + assert_views([ + ( + b"my $s = q'a\\'b';\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([hidden("ERROR", 0..46)]), + ), + ( + b"my $x = (1;\nmy $s = \"\n=pod\n\";\n__END__\n=pod\n\nd\n\n=cut\n", + View { + assessments: unordered([data_section(37..52), hidden(")", 10..10)]), + ..View::default() + }, + ), + ]); + // Not marked: the only such line stands in the data section; it stands before the + // first recovery node; no line behind the node starts with `=` and a letter; there + // is no such line at all. + assert_views([ + ( + b"my $x = (1;\n__END__\n=pod\n\nd\n\n=cut\n", + pending([data_section(19..34)]), + ), + (b"my $s = '\n=pod\n';\nmy $x = (1;\n", View::default()), + ( + b"my $x = (1;\nmy $s = \"\n=1\n==\n= a\n =pod\nx=pod\n\";\n", + View::default(), + ), + (b"my $x = (1;\nmy $y = 2;\n", View::default()), + ]); + // An excluded byte behind the node is not read, and the worst case holds: the file + // is marked. The cut nodes are today's outcome of the core. + let cases: [(&[u8], Included, View); 1] = [( + b"my $x = (1;\nmy $y = 2;\n", + &[0..14, 15..23], + View { + assessments: unordered([ + cut("binary_expression", 12..21), + cut("variable_declaration", 12..17), + hidden(")", 10..10), + ]), + ..View::default() + }, + )]; + for (source, ranges, expected) in cases { + for retain in [Retain::Nothing, Retain::Unbound, Retain::Directives] { + assert_eq!( + restricted_view(source, ranges, retain), + expected, + "{ranges:?}" + ); + } + } +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn perl_known_over_withholding_is_pinned() { + // Today's outcomes, not decisions: perl reads each of these blocks as POD, and the + // unit withholds it. A real block after a here-document with an empty tag; after a + // name with the old package separator, which the grammar does not parse; after a + // string that holds `<<` and a word; after a here-document inside a literal has + // ended; after a here-document whose body the grammar starts late; and after a shift + // that is written like an opener with a digit tag. After a format with a value line + // that holds a closed string or brackets over two lines; after the word `format` as + // a method name or a glob name before `=` and a line end; after a shift by a quoted + // string or by a bareword behind a variable; after a `q` literal that the grammar + // ends late, with the string behind it closed on its row; after an operator word + // before `=>` or in a subscript, which the grammar reads as a literal; and after a + // pattern behind a word that the unit does not know as a keyword. + assert_views([ + ( + b"my $s = <<\"\";\nlit\n\nprint \"MARK\";\n\n=pod\n\nreal\n\n=cut\n", + pending([withheld(RECOVERY, 34..50)]), + ), + ( + b"sub isn't { 1 }\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([withheld(RECOVERY, 17..30)]), + ), + ( + b"my $s = \"a<format =\n1;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([withheld(FORMAT, 35..48)]), + ), + ( + b"sub g { 7 }\n*format =\n\\&g;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([withheld(FORMAT, 28..41)]), + ), + ( + b"my $fh = \\*STDOUT;\nprint $fh << \"EOT\";\n\n=pod\n\nd\n\n=cut\nprint \"MAR\ + K\";\n", + pending([withheld(UNREAD_OPENER, 40..53)]), + ), + ( + b"my $t = 2; my $x = $t < 1, s => 2, q => 3);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([withheld(LITERAL, 35..48)]), + ), + ( + b"my $m = lc /A/;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([withheld(LITERAL, 17..30)]), + ), + ( + b"my %k; my $v = $k{q}; my $w = { 1 };\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + pending([withheld(LITERAL, 38..51)]), + ), + ]); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_source_filter_is_a_named_limitation() { + // Today's outcome, not a decision: code that runs while perl compiles can change + // what perl reads after it. The unit reads the bytes of the file and publishes the + // block. + assert_views([( + b"use Filter::Util::Call;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + documents([doc(25..38, "=pod\n\nd")]), + )]); +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn perl_doubt_beside_excluded_bytes_takes_the_worst_case() { + // An excluded byte is not read. Where a rule would have to read one, the worst case + // holds: a format whose opener or body cannot be read runs to the end of the input; + // an identifier with an excluded byte may be the keyword; a shift with an excluded + // byte beside it may be an opener; a literal with an excluded byte may hold an + // opener or end elsewhere; a tag line with an excluded byte behind the tag may not end + // the here-document. The second row is the control: two ranges that touch exclude + // nothing. In the last four rows the excluded byte stands before the node: in the + // bytes before a pattern and before a single-quoted string that say whether perl + // starts a literal there; behind the blanks of a shift; and in the six bytes before + // a name of two bytes, which may be `CORE::`. The cut nodes are today's outcome of + // the core. + let cases: [(&[u8], Included, View); 12] = [ + ( + b"format STDOUT =\n1\n.\n2;\nmy $k = 3;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\ + \n", + &[0..25, 26..63], + View { + assessments: unordered([ + withheld(FORMAT, 35..48), + cut("binary_expression", 23..32), + cut("variable_declaration", 23..28), + ]), + ..View::default() + }, + ), + ( + b"format STDOUT =\n1\n.\n2;\nmy $k = 3;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\ + \n", + &[0..25, 25..63], + documents([doc(35..48, "=pod\n\nd")]), + ), + ( + b"forXmat STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + &[0..3, 4..41], + View { + assessments: unordered([ + withheld(FORMAT, 20..33), + cut("call_expression_with_spaced_args", 0..18), + cut("call_expression_with_bareword", 0..7), + cut("identifier", 0..7), + ]), + ..View::default() + }, + ), + ( + b"my $t = 2; my $s = $t <<$t;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + &[0..21, 22..57], + View { + assessments: unordered([ + withheld(UNREAD_OPENER, 29..42), + cut("binary_expression", 11..26), + cut("binary_expression", 19..26), + ]), + ..View::default() + }, + ), + ( + b"my $s = \"a b\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + &[0..10, 11..44], + View { + assessments: unordered([ + withheld(LITERAL, 16..29), + cut("binary_expression", 0..13), + cut("string_double_quoted", 8..13), + ]), + ..View::default() + }, + ), + ( + b"my $s = <, usize); 25] = [ + (b" STDOUT =\n1\n", Some(10), 13), + (b" =\n", Some(3), 6), + (b"=\n", Some(2), 5), + (b" Pkg::F =\n", Some(10), 13), + (b" A'B =\n", Some(7), 10), + (b" _f =\n", Some(6), 9), + (b" F1 =\n", Some(6), 9), + (b"\x0bSTDOUT\x0b=\n", Some(10), 13), + (b"\nSTDOUT\n=\n", Some(10), 13), + (b" # a\nSTDOUT # b\n=\n", Some(18), 25), + (b" STDOUT = # c\n", Some(14), 17), + (b" STDOUT = \t\r\n", Some(14), 17), + (b"\tSTDOUT\t=\n", Some(10), 13), + (b" STDOUT = # c", Some(13), 16), + (b" STDOUT = 1;\n", None, 13), + (b" STDOUT =\x0c\n", None, 12), + (b" STDOUT =\x0b\n", None, 12), + (b" STDOUT =;\n", None, 12), + (b" STDOUT ==\n", None, 12), + (b" STDOUT =", None, 11), + (b" => 1);\n", None, 5), + (b";\n", None, 3), + (b" { 7 }\n", None, 4), + (b" STDOUT\n", None, 10), + (b"", None, 0), + ]; + for (after, body, bytes) in openers { + assert_eq!( + scan_charges(|budget| format_body(after, budget)), + (body, bytes), + "{}", + after.escape_ascii() + ); + } + // A body, and the line that ends the format for perl 5.34.0, where the unit knows + // it. Where picture text may stand: a dot at the start of a line, then only blanks, + // tabs and carriage returns, with or without a line feed. Text, `;`, `#`, a form + // feed or a vertical tab behind the dot, a second dot, and white space before the + // dot do not end it. Behind a picture line that holds `@` or `^` perl reads values: + // there a dot ends the format only directly before the line end, and any other line + // is read only if it is a list of named variables. A comment, a string, a call, an + // expression, a bracket, a variable with a digit as name: the end is not known. + // Read: each byte once, up to and including the line that ends the format or the + // value line that is not read. First row: `1` and its line feed (2), the dot and its + // line feed (2). + let bodies: [(&[u8], LastLine, usize); 55] = [ + (b"1\n.\n2;\n", Some(2..4), 4), + (b".\n", Some(0..2), 2), + (b"1\n.", Some(2..3), 3), + (b"1\n. \t\n2;\n", Some(2..6), 6), + (b"1\n.\r\n", Some(2..5), 5), + (b"1\n. \r\r\n", Some(2..7), 7), + (b"1\r\n.\r\n2;\r\n", Some(3..6), 6), + (b"1\n. ", Some(2..4), 4), + (b"1\n. x\n.\n", Some(6..8), 8), + (b"1\n .\n", None, 5), + (b"1\n\t.\n", None, 5), + (b"1\n..\n", None, 5), + (b"1\n.;\n", None, 5), + (b"1\n.#c\n", None, 6), + (b"1\n.\x0c\n", None, 5), + (b"1\n.\x0b\n", None, 5), + (b"1\n2\n", None, 4), + (b"", None, 0), + (b"@<<<\n$a\n.\n", Some(8..10), 10), + ( + b"@<<< ^>>>\n$a, @l, %h, $P::q, $::r ;\t\r\n.\n", + Some(38..40), + 40, + ), + (b"@<<<\n.\n2;\n", Some(5..7), 7), + (b"@<<<\n.\r\n", Some(5..8), 8), + (b"@<<<\n.", None, 6), + (b"@<<<\n. \n.\n", None, 8), + (b"@<<<\n.\r\r\n.\n", None, 9), + (b"@<<<\n\n.\n", Some(6..8), 8), + (b"@<<<\n$a,\n$b\n.\n", Some(12..14), 14), + (b"~~ ^<<<\n$a\n.\n", Some(11..13), 13), + (b"# @<<<\n.\n", Some(7..9), 9), + (b"@<<<\n# c\n.\n", None, 9), + (b"@<<<\n$a # c\n.\n", None, 12), + (b"@<<<\nq(a)\n.\n", None, 10), + (b"@<<<\n\"a\"\n.\n", None, 9), + (b"@<<<\nf($a)\n.\n", None, 11), + (b"@<<<\n{ $a }\n.\n", None, 12), + (b"@<<<\n$a . $b\n.\n", None, 13), + (b"@<<<\n<>>\n$b\n.\n", Some(16..18), 18), + (b"@<<<\n$a\n@>>>\nq!\n.\n", None, 16), + (b"a@b\n$a", None, 6), + (b"@<<<\n$a:b\n.\n", Some(10..12), 12), + (b"@<<<\n$a%\n.\n", None, 9), + (b"@<<<\n@$a\n.\n", None, 9), + (b"@<<<\n$_a1\n.\n", Some(10..12), 12), + (b"^<<<\nq(a)\n.\n", None, 10), + (b"# @x\n. \n", Some(5..8), 8), + (b"@<<<\n$a\r\n.\n", Some(9..11), 11), + (b"@<<<\n$a;$b\n.\n", Some(11..13), 13), + (b"x\n@<<<\n\t\n. \t\n", Some(9..13), 13), + ]; + for (body, last, bytes) in bodies { + assert_eq!( + scan_charges(|budget| format_end(body, budget)), + (last, bytes), + "{}", + body.escape_ascii() + ); + } + // The spelling of a literal node of a kind: whether perl ends the literal at the last + // byte of the spelling, and whether its text holds `<<` and a tag. A backslash hides + // the next byte; behind an opening bracket the literal ends at the matching closing + // bracket, and brackets of that kind nest; any other delimiter ends it at its next + // occurrence; `s`, `tr` and `y` have two parts; white space and comments may stand + // before a delimiter, and a `#` directly behind the operator is the delimiter; ASCII + // letters behind the last delimiter are flags. An operator word before `=>` or + // before a closing bracket is a name. A tag is a quote behind optional blanks, or a + // letter, a digit or `_`, behind an optional `~` and, for a word, an optional + // backslash; the delimiters are no part of the text. Read: each byte once, up to the + // byte that decides. First row: the grammar's node `q!a\!` ends at the escaped + // delimiter; perl does not end the literal there, and all five bytes are read. + let literals: [(&str, &[u8], Reading, usize); 129] = [ + ("string_q_quoted", b"q!a\\!", (false, false), 5), + ("string_q_quoted", b"q!a\\!b!", (true, false), 7), + ("string_q_quoted", b"q{a\\}", (false, false), 5), + ("string_q_quoted", b"q{a\\\\}", (true, false), 6), + ("string_q_quoted", b"q{a\\\\\\}", (false, false), 7), + ("string_q_quoted", b"q{a{b}c}", (true, false), 8), + ("string_q_quoted", b"q{}", (true, false), 3), + ("string_q_quoted", b"q(a\\(b)", (true, false), 7), + ( + "string_q_quoted", + b"q(a\\(b); my $s = \"x)", + (false, false), + 8, + ), + ("string_q_quoted", b"q(a(b)", (false, false), 6), + ("string_q_quoted", b"q(a)b)", (false, false), 5), + ("string_q_quoted", b"q XaX", (true, false), 5), + ("string_q_quoted", b"q\n(a)", (true, false), 5), + ("string_q_quoted", b"q # c\n # d\n(a)", (true, false), 14), + ("string_q_quoted", b"q#a#", (true, false), 4), + ("string_q_quoted", b"q #a#", (false, false), 5), + ("string_q_quoted", b"q'a\\'b'", (true, false), 7), + ("string_q_quoted", b"q\\a\\", (true, false), 4), + ("string_q_quoted", b"q => 1, 2 =", (false, false), 4), + ("string_q_quoted", b"q\n=>=a=", (false, false), 4), + ("string_q_quoted", b"q # c\n=> 1, 2 =", (false, false), 8), + ("string_q_quoted", b"q=a=", (true, false), 4), + ("string_q_quoted", b"q===", (false, false), 4), + ("string_q_quoted", b"q}a}", (false, false), 2), + ("string_q_quoted", b"q)a)", (false, false), 2), + ("string_q_quoted", b"q ]a]", (false, false), 3), + ("string_q_quoted", b"q>a>", (false, false), 2), + ("string_q_quoted", b"q", (false, false), 1), + ("string_q_quoted", b"q ", (false, false), 2), + ("string_q_quoted", b"x(a)", (false, false), 2), + ("string_q_quoted", b"", (false, false), 0), + ("string_q_quoted", b"q(a)x", (false, false), 5), + ("string_q_quoted", b"q(<", (false, false), 6), + ("string_qq_quoted", b"qq{a}", (true, false), 5), + ("string_qq_quoted", b"qq{<<\"\"}", (true, true), 8), + ("string_qq_quoted", b"qq\"<<\"", (true, false), 6), + ("string_qq_quoted", b"qq{a{<<}E}", (true, false), 10), + ( + "string_double_quoted", + b"\"@{[ <>> 1 << 2\"", + (true, false), + 18, + ), + ("string_double_quoted", b"\"<< EOT\"", (true, false), 8), + ("string_double_quoted", b"\"<<\"", (true, false), 4), + ("string_double_quoted", b"\"<< \"", (true, false), 5), + ("string_double_quoted", b"\"<\"", (true, false), 3), + ("string_double_quoted", b"\"a < b\"", (true, false), 7), + ("string_double_quoted", b"\"<<-\"", (true, false), 5), + ("string_double_quoted", b"\"<<$x\"", (true, false), 6), + ("string_double_quoted", b"\"\"", (true, false), 2), + ("string_double_quoted", b"\"a\\\"b\"", (true, false), 6), + ("string_double_quoted", b"\"a\"b\"", (false, false), 4), + ("string_double_quoted", b"\"a", (false, false), 2), + ("string_double_quoted", b"\"<<\\\"E\"", (true, false), 7), + ("string_double_quoted", b"\"\\< 1, 2 => 3", + (false, false), + 4, + ), + ("substitution_pattern_s", b"s(a)(b)", (true, false), 7), + ("substitution_pattern_s", b"s", (true, false), 7), + ("substitution_pattern_s", b"s[a][b]e", (true, false), 8), + ("transliteration_tr_or_y", b"tr/a/b/", (true, false), 7), + ("transliteration_tr_or_y", b"y/a/b/", (true, false), 6), + ("transliteration_tr_or_y", b"tr{a\\{}{b}", (true, false), 10), + ("transliteration_tr_or_y", b"y(a\\()(b)", (true, false), 9), + ("transliteration_tr_or_y", b"tr{a}{b}", (true, false), 8), + ("transliteration_tr_or_y", b"tr [a] [b]", (true, false), 10), + ("transliteration_tr_or_y", b"y!a!b\\!", (false, false), 7), + ("transliteration_tr_or_y", b"tr/a/b/cdsr", (true, false), 11), + ("transliteration_tr_or_y", b"tr/a/< 1, s => 2, q =>", + (false, false), + 4, + ), + ( + "transliteration_tr_or_y", + b"y} = 1; $h{s} = 2; $h{q}", + (false, false), + 2, + ), + ("transliteration_tr_or_y", b"ty/a/b/", (false, false), 3), + ("transliteration_tr_or_y", b"t/a/b/", (false, false), 3), + ("transliteration_tr_or_y", b"y", (false, false), 1), + ("transliteration_tr_or_y", b"tr\x0b/a/b/", (true, false), 8), + ]; + for (kind, spelling, reads, bytes) in literals { + let quote = Quote::of(kind).unwrap(); + assert_eq!( + scan_charges(|budget| perl_reads(spelling, quote, budget)), + (reads, bytes), + "{kind} {}", + spelling.escape_ascii() + ); + } + // The bytes before a `/`, whether they start at the start of the input, and whether + // perl surely expects a term behind them, so that the `/` starts a pattern: at the + // start of the input; behind `(`, `,`, `=`, `~`, `!`, `&`, `|`, `?`, `:`, `;` or `{` + // that is not the name of a variable; and behind a keyword that takes a term and is + // not part of a longer name. White space may stand between. Anything else may be a + // division: a call without arguments, a variable, a closing bracket, a number. + let leads: [(&[u8], bool, bool); 70] = [ + (b"", true, true), + (b" \n", true, true), + (b" ", false, false), + (b"my $m = (", false, true), + (b"f(1,", false, true), + (b"$t =~ ", false, true), + (b"$t !~\n\t", false, true), + (b"my $m = ", false, true), + (b"$a && ", false, true), + (b"$a || ", false, true), + (b"$a ? ", false, true), + (b"$a ? 1 : ", false, true), + (b"1; ", false, true), + (b"if (1) { ", false, true), + (b"$m = ! ", false, true), + (b"{ ", false, false), + (b"! ", true, true), + (b"split ", false, false), + (b"split", false, false), + (b" grep ", false, true), + (b"1 if ", true, true), + (b"if", true, true), + (b"if", false, false), + (b" unless ", false, true), + (b" while ", false, true), + (b" until ", false, true), + (b" and ", false, true), + (b" or ", false, true), + (b" not ", false, true), + (b" xor ", false, true), + (b" return ", false, true), + (b" map ", false, true), + (b"time ", false, false), + (b"length $t ", false, false), + (b"$? ", false, false), + (b"$! ", false, false), + (b"$, ", false, false), + (b"$; ", false, false), + (b"${ ", false, false), + (b"@{ ", false, false), + (b"%! ", false, false), + (b"?", false, false), + (b"?", true, true), + (b"($t) ", false, false), + (b"$l[0] ", false, false), + (b"$h{a} ", false, false), + (b"4 ", false, false), + (b"'a' ", false, false), + (b"$o->split ", false, false), + (b"Foo::split ", false, false), + (b"Foo'if ", false, false), + (b"&grep ", false, false), + (b"$if ", false, false), + (b"@map ", false, false), + (b"%or ", false, false), + (b"*and ", false, false), + (b"xsplit ", false, false), + (b"split_ ", false, false), + (b"when ", false, false), + (b"print ", false, false), + (b" . ", false, false), + (b" + ", false, false), + (b"$i++ ", false, false), + (b"} ", false, false), + (b"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", false, false), + (b"xxxxxxxxxxxxxxxxxxxxxxxxxxxsplit", false, false), + (b"xxxxxxxxxxxxxxxxxxxxxxxxxx split", false, true), + (b" ", false, false), + (b" ", true, true), + (b"# c\n", false, false), + ]; + for (before, whole, term) in leads { + assert_eq!( + expects_term(before, whole), + term, + "{}", + before.escape_ascii() + ); + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_hidden_pod_search_charges_what_it_reads() { + // expected: per source and span, whether a line that starts with `=` and an ASCII + // letter starts in the span, and the bytes read: each byte of the span once, up to + // and including the letter. The byte before the span says whether its first byte + // starts a line. A span that is not empty costs one coverage search, which is one + // step with one included run. Every charge is passed on, so each can cancel. + let spans: [(&[u8], Range, bool, usize); 15] = [ + (b"1;\n=pod\n", 0..8, true, 5), + (b"1;\n=pod\n", 3..8, true, 2), + (b"1;\n=pod\n", 4..8, false, 4), + (b"1;\n=pod\n", 3..4, false, 1), + (b"1;\n=pod\n", 3..5, true, 2), + (b"=pod\n", 0..5, true, 2), + (b"=1\n==\n= a\n=_\n", 0..13, false, 13), + (b"a =b\n", 0..5, false, 5), + (b"1;\n\n=\n=Z", 0..8, true, 8), + (b"1;\n=pod\n", 8..8, false, 0), + (b"", 0..0, false, 0), + (b"x\n=a\n=b\n", 0..8, true, 4), + (b"x\r=a\n", 0..5, false, 5), + (b"a =b\n", 2..5, false, 3), + (b"1;\n=pod\n", 2..5, true, 3), + ]; + for (source, span, found, bytes) in spans { + let parser = parsed(source); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let budget = Counting::default(); + assert_eq!( + command_line(&context, span.clone(), &budget).unwrap(), + found, + "{span:?} {}", + source.escape_ascii() + ); + assert_eq!( + charged_totals(&budget), + (usize::from(!span.is_empty()), bytes), + "{span:?} {}", + source.escape_ascii() + ); + for fail_at in 1..=budget.charges.get() { + assert!(matches!( + command_line(&context, span.clone(), &failing_at(fail_at)), + Err(SourceError::Cancelled) + )); + } + } + // expected: a span with an excluded byte, or with one directly before it, is not + // read: the answer is the worst case, and no byte is charged. Two included runs: + // the coverage search probes twice. + let source: &[u8] = b"1; +2; +3; +"; + let tree = restricted(source, &[0..4, 5..9]); + let context = SourceContext::new(&tree, source); + for (span, found, charged) in [ + (5..9, true, (2, 0)), + (6..9, false, (2, 3)), + (0..5, true, (2, 0)), + ] { + let budget = Counting::default(); + assert_eq!(command_line(&context, span, &budget).unwrap(), found); + assert_eq!(charged_totals(&budget), charged); + } +} + +#[cfg(feature = "perl")] +#[test] +#[allow(clippy::too_many_lines)] +fn pod_doubt_walk_charges_its_searches_and_scans() { + // expected: per source, for each block the reason that withholds it, and the steps + // and bytes of the whole walk. One step per coverage search in one included run: for + // an identifier of six bytes or more; for the rest of the input behind one that + // spells `format`; for an identifier of one or two bytes and the six bytes before + // it; for a literal and the bytes before it that are read; for the byte before and + // the byte behind a `<<` operator that is no opener for the grammar, and for the + // rest of the input where a blank or a tab stands behind it; for the two bytes + // behind an end tag. The bytes are those of the scans, and for a literal the bytes + // before it: one before a single-quoted string, up to 32 before a pattern. After the + // first place that makes every later block doubtful, nothing is read. Second row: + // two searches; ` S`, `STDOUT `, ` =` and the line feed twice (13), then the eight + // lines of the body up to the dot line (21). The identifier `STDOUT` lies in the + // format and is not looked at. + let cases: [(&[u8], Doubts, Charged); 36] = [ + ( + b"%%%% (\n=pod\n\nx\n\n=cut\n", + vec![(7, Some(RECOVERY))], + (0, 0), + ), + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + vec![(19, Some(FORMAT))], + (2, 34), + ), + ( + b"format STDOUT =\n1\n.\n2;\n\n=pod\n\nreal\n\n=cut\n", + vec![(24, None)], + (2, 17), + ), + ( + b"format A =\nformat B =\n1\n.\n2;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + vec![(30, None)], + (3, 29), + ), + ( + b"my $o = bless {};\nsub format { 7 }\nmy $v = $o->format;\n\n=pod\n\nd\n\n=cu\ + t\nprint \"MARK\";\n", + vec![(56, None)], + (5, 13), + ), + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n\n=pod\n\nreal\n\n=cut\n", + vec![(19, Some(FORMAT)), (41, None)], + (2, 34), + ), + ( + b"format STDOUT =\n1;\n=pod\n\nd\n\n=cut\n2;\n", + vec![(19, Some(FORMAT))], + (2, 33), + ), + ( + b"my $s = \"@{[ <>> 1 << 2\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + vec![(29, None)], + (2, 24), + ), + ( + b"my $s = < 1, s => 2, q => 3);\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + vec![(35, Some(LITERAL))], + (1, 4), + ), + ( + b"my @m = split /,/, 'a,b'; my $n = 1 if $m[0] =~ /a/; my @o = grep /b/, @m;\n\ + \n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + vec![(76, None)], + (5, 99), + ), + ( + b"my $m = lc /A/;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + vec![(17, Some(LITERAL))], + (2, 14), + ), + ( + b"my $v = 1; sub go { 7 }\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + vec![(25, None)], + (2, 6), + ), + ]; + for (source, blocks, charged) in cases { + let parser = parsed(source); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let root = parser.ts_tree().root_node(); + let budget = Counting::default(); + assert_eq!( + doubt_walk(&context, root, &budget).unwrap(), + blocks, + "{}", + source.escape_ascii() + ); + assert_eq!( + charged_totals(&budget), + charged, + "{}", + source.escape_ascii() + ); + for fail_at in 1..=budget.charges.get() { + assert!(matches!( + doubt_walk(&context, root, &failing_at(fail_at)), + Err(SourceError::Cancelled) + )); + } + } + // expected: with two included runs a coverage search probes twice, and a span that + // holds an excluded byte is not read: no byte is charged for it. + let cut: [(&[u8], Included, Doubts, Charged); 12] = [ + ( + b"format STDOUT =\n1\n.\n2;\nmy $k = 3;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\ + \n", + &[0..25, 26..63], + vec![(35, Some(FORMAT))], + (4, 0), + ), + ( + b"format STDOUT =\n1\n.\n2;\nmy $k = 3;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\ + \n", + &[0..25, 25..63], + vec![(35, None)], + (3, 23), + ), + ( + b"forXmat STDOUT =\n1;\n=pod\n\nd\n\n=cut\n1\n.\n2;\n", + &[0..3, 4..41], + vec![(20, Some(FORMAT))], + (4, 34), + ), + ( + b"my $t = 2; my $s = $t <<$t;\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + &[0..21, 22..57], + vec![(29, Some(UNREAD_OPENER))], + (2, 0), + ), + ( + b"my $s = \"a b\";\n\n=pod\n\nd\n\n=cut\nprint \"MARK\";\n", + &[0..10, 11..44], + vec![(16, Some(LITERAL))], + (2, 0), + ), + ( + b"my $s = <x

\n\n=end html\n\n=cut", + b"=begin comments\n=end comments\n=cut", + b"=beginning", + b"=for comment\nInternal note.\n\n=head1 NAME\n\nFoo - bar\n\n=cut", + b"=begin comment\n\nold();\n\n=end comment\n\n=head1 X\n\nDoc.\n\n=cut", + b"", + ] { + counted(text); + } + let opens = |line: &[u8]| { + let budget = Counting::default(); + let answer = opens_pod_with_budget(line, &budget).unwrap(); + for fail_at in 1..=budget.charges.get() { + assert!(matches!( + opens_pod_with_budget(line, &failing_at(fail_at)), + Err(SourceError::Cancelled) + )); + } + (answer, charged_totals(&budget)) + }; + // expected: the command word and the byte that ends it; a line without `=` reads + // nothing. + assert_eq!(opens(b"=head1 NAME"), (true, (0, 6))); + assert_eq!(opens(b"=pod"), (true, (0, 3))); + assert_eq!(opens(b"=cut"), (false, (0, 3))); + assert_eq!(opens(b"=1"), (false, (0, 1))); + assert_eq!(opens(b"=head-x"), (false, (0, 5))); + assert_eq!(opens(b"=pod\x0bx"), (true, (0, 4))); + assert_eq!(opens(b"text"), (false, (0, 0))); +} + +#[cfg(feature = "perl")] +#[test] +fn pod_text_charges_its_lines_and_copies() { + let rendered = |source: &[u8]| { + let parser = parsed(source); + let [index, _] = indexes(&parser, Retain::Nothing); + let fragment = &index.facts.fragments[0]; + let budget = Counting::default(); + let content = render(Profile::Pod, &index.source, &[fragment], &budget).unwrap(); + for fail_at in 1..=budget.charges.get() { + assert!(matches!( + render( + Profile::Pod, + &index.source, + &[fragment], + &failing_at(fail_at) + ), + Err(TextError::Source(SourceError::Cancelled)) + )); + } + ( + matches!(content, Content::Complete { .. }), + budget.steps.get(), + budget.bytes.get(), + budget.checkpoints.get(), + ) + }; + // expected: steps: one for the fragment, one per line that is kept before the empty + // boundary lines go (4), three in the emitter (two empty-block tests and the block), + // one for the dropped empty line, and two per copied run (4 runs). Bytes: the 21 of + // the fragment for the line split, and twice the 15 of the text for validation and + // copy. Two checkpoints per copied run. + assert_eq!(rendered(PRIMARY), (true, 17, 51, 8)); + // One line, one run: 1 + 1 + 3 + 2 steps; 9 + 2 * 4 bytes. + assert_eq!(rendered(b"=pod\n=cut\n"), (true, 7, 17, 2)); + // A decoded CRLF costs one step and two bytes: 1 + 4 + 3 + 1 + 2 + 1 + 1 + 2 steps; + // 21 + 2 * 11 bytes. + assert_eq!( + rendered(b"=head1 A\r\n\r\na\r\n\r\n=cut\r\nsub f {}\r\n"), + (true, 15, 43, 8) + ); + // Pending text stops at the comment command: one step for the fragment and one for + // each of the five lines up to `=begin comment`; the 62 bytes of the line split and + // the space after `=begin` with the byte that ends it. Nothing is copied. + assert_eq!(rendered(MIXED_FIXTURE), (false, 6, 64, 0)); +} + +#[cfg(feature = "perl")] +#[test] +fn pod_text_of_a_fragment_with_a_gap_is_unavailable() { + // The collector withholds such a block, so this state is built by hand. The excluded + // byte is the `u` of `=cut`: no line of the text would be copied across it. + let source = b"=pod\n\nx\n\n=cut\n"; + let tree = restricted(source, &[0..11, 12..14]); + let context = SourceContext::new(&tree, source); + let block = nodes_of(tree.root_node(), &["pod_statement"]); + let [(_, range, _)] = &block[..] else { + panic!("one block, found {block:?}") + }; + let block = node_at(tree.root_node(), "pod_statement", range.clone()); + let fragment = Fragment { + source: context.pieces(0..13).unwrap(), + node: Some(context.node(block).unwrap()), + form: FragmentForm::Pod, + }; + assert!(fragment.source().has_excluded_gap()); + assert!(matches!( + render(Profile::Pod, &context, &[&fragment], &Counting::default()), + Err(TextError::Unavailable(UnavailableReason::ExcludedGap)) + )); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_block_classification_is_charged_to_the_collection() { + // A comment-only block of 4,000 rows: no document, so no text is built. + let source = tall(4_000, "=for comment x\n\n", "=cut\n"); + let parser = parsed(&source); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let (answer, (steps, bytes)) = block_charges(&source, 0, false); + assert_eq!(answer, PodBlock::CommentOnly(source.len() - 1)); + // expected: the command word (4), the spelling, and per row 15 + 1 + 2 for the + // command line and 1 for the empty line, then 4 + 1 for `=cut`. + assert_eq!((steps, bytes), (1, 4 + source.len() - 1 + 4_000 * 19 + 5)); + let before = observations(); + let index = parser.documentation(&context, &options).unwrap(); + let polls = observations().polls - before.polls; + assert_eq!(index.documents().len(), 0); + // expected: the seven checkpoints of a collection without a document (`EMPTY`), then + // one for each 16 KiB that the block's reading charges. The walk of the two nodes + // charges no byte and fewer steps than one interval. + assert_eq!(polls, EMPTY + bytes / BYTE_INTERVAL); + for checkpoint in 1..=polls { + assert!(matches!( + cancel_after(checkpoint, || parser.documentation(&context, &options)), + Err(CollectionError::Cancelled) + )); + } + assert!(cancel_after(polls + 1, || parser.documentation(&context, &options)).is_ok()); + assert!(matches!( + cancel_in_phase(WorkPhase::Classification, || parser + .documentation(&context, &options)), + Err(CollectionError::Cancelled) + )); + assert_eq!(view(&source), View::default()); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_fragment_pieces_are_charged_to_the_collection() { + // One comment-only block of 4,095 bytes and its line feed, read through 4,096 + // one-byte ranges that touch: no byte is excluded. + let source = format!("=for comment {}\n\n=cut\n", "x".repeat(4_076)).into_bytes(); + let ranges: Vec<_> = (0..source.len()).map(|at| at..at + 1).collect(); + assert_eq!(ranges.len(), 4_096); + let tree = restricted(&source, &ranges); + assert_eq!( + nodes_of(tree.root_node(), &["pod_statement"]), + [("pod_statement", 0..4_095, "source_file")] + ); + let collected = |retain| { + let before = observations(); + let index = collect( + LANG::Perl, + &tree, + &source, + &DocumentationContext::default(), + &options(retain), + ) + .unwrap(); + let pieces: Vec<_> = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + assert!(!fragment.get().source().has_excluded_gap()); + fragment.get().source().pieces().len() + }) + .collect(); + assert_eq!(index.documents().len(), 0); + (pieces, observations().polls - before.polls) + }; + // expected: the seven checkpoints of a collection without a document, and four in + // the range preparation, which steps once per range. The block's reading charges + // 8,198 bytes, less than one interval, and the walk of two nodes a few steps. + assert_eq!(collected(Retain::Nothing), (vec![], EMPTY + 4)); + // expected: cutting the fragment visits each of the 4,096 ranges, one step each, + // after 12 steps of search: four more checkpoints. One piece per range of the block. + assert_eq!(collected(Retain::Directives), (vec![4_095], EMPTY + 8)); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_block_text_is_charged_to_the_collection() { + // One documenting block of 4,000 paragraphs. + let source = tall(4_000, "=head1 A\n\n", "=cut\n"); + let parser = parsed(&source); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let (answer, (steps, bytes)) = block_charges(&source, 0, false); + assert_eq!(answer, PodBlock::Documents(source.len() - 1)); + assert_eq!(steps, 1); + let before = observations(); + let index = parser.documentation(&context, &options).unwrap(); + let polls = observations().polls - before.polls; + let document = index.documents().next().unwrap(); + let text = index.complete_text(document).unwrap().unwrap(); + // expected: 4,000 lines and the 3,999 line feeds between them and the empty lines, + // twice: `=head1 A`, LF, LF per paragraph, less the two line feeds after the last. + assert_eq!(text.mappings().len(), 3 * 4_000 - 2); + let budget = Counting::default(); + render( + Profile::Pod, + &index.source, + &[&index.facts.fragments[0]], + &budget, + ) + .unwrap(); + // expected: two checkpoints per copied run of the text. + assert_eq!(budget.checkpoints.get(), 2 * text.mappings().len()); + // expected: one document adds four checkpoints to the seven of `EMPTY`: a chunk and + // an end for the order of its fragments, and a chunk each for the document order and + // the association order. + let explicit = EMPTY + 4 + budget.checkpoints.get(); + // expected: at least the explicit checkpoints, and at most one more per interval of + // the bytes and steps that the block's reading and its text charge. The walk of the + // two nodes and the assembly of one document charge fewer than 100 steps, which can + // complete one more interval. + let intervals = (bytes + budget.bytes.get()) / BYTE_INTERVAL + + (steps + budget.steps.get()) / STEP_INTERVAL + + 1; + assert!(polls >= explicit, "{polls} < {explicit}"); + assert!( + polls <= explicit + intervals, + "{polls} > {explicit} + {intervals}" + ); + assert!(matches!( + cancel_in_phase(WorkPhase::Text, || parser.documentation(&context, &options)), + Err(CollectionError::Cancelled) + )); + // A cancelled collection leaves nothing behind: the next one succeeds. + assert_eq!( + parser + .documentation(&context, &options) + .unwrap() + .documents() + .len(), + 1 + ); +} + +#[cfg(feature = "perl")] +#[test] +fn perl_many_blocks_cost_linear_work() { + for blocks in [64, 512] { + let source = tall(blocks, "=head1 A\n\na\n\n=cut\n", ""); + let parser = parsed(&source); + // expected: the root and one leaf per block. + assert_eq!(parser.root_node().preorder().count(), blocks + 1); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + // expected: one visit and one child batch per node. + assert_eq!(after.visits - before.visits, blocks + 1); + assert_eq!(after.child_batches - before.child_batches, blocks + 1); + // expected: the file is the only owner. + assert_eq!(after.owner_projections - before.owner_projections, 1); + // expected: one text per document, built once. + assert_eq!(after.renders - before.renders, blocks); + // expected: no field name is requested or looked up for a Perl node. + assert_eq!(after.field_requests - before.field_requests, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + // expected: one fragment per block, cut with one search in one included range. + assert_eq!( + after.intersection_searches - before.intersection_searches, + blocks + ); + // expected: per block the command word `head1 ` (6), and the first line of the + // comment-region test: `=head1 A` with its line feed (9) and its first byte (1). + assert_eq!( + after.classifier_bytes - before.classifier_bytes, + 16 * blocks + ); + assert_eq!(index.documents().len(), blocks); + assert_eq!(index.associations().len(), blocks); + let last = index.documents().last().unwrap(); + let fragment = index.facts().document_fragment(last, 0).unwrap(); + assert_eq!( + span(fragment.get().source()), + 18 * (blocks - 1)..18 * blocks - 1 + ); + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_many_formats_cost_linear_work() { + let block = "\n=pod\n\nd\n\n=cut\n"; + let collected = |source: &[u8]| { + let parser = parsed(source); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + // expected: one visit per node. + assert_eq!( + after.visits - before.visits, + parser.root_node().preorder().count() + ); + let bytes = after.classifier_bytes - before.classifier_bytes; + // expected: within the bound of the rules for literal text: seven times the + // input, where no literal is read. The block's own reading is counted too and + // is far below the rest. + assert!(bytes <= 7 * source.len(), "{bytes}"); + (index.documents().len(), bytes) + }; + for formats in [64, 512] { + // Many formats, each read once from its own opener. + let source = tall(formats, "format F =\n1\n.\n2;\n", block); + // expected: per format the opener ` F`, `F `, ` =` and the line feed twice (8) + // and the two lines of the body (4). The block after the last format is a + // document: the command word `pod` with its line feed (4), and its first line + // with the line feed and its first byte (6). + assert_eq!(collected(&source), (1, 12 * formats + 10)); + // One format whose body holds many opener lines: they are picture text, and no + // scan starts from one of them. + let body = "format B =\n".repeat(formats); + let source = format!("format A =\n{body}1\n.\n2;\n{block}").into_bytes(); + // expected: the opener (8), every line of the body once (11 per opener line, 4 + // for the last two), and the block (10). + assert_eq!(collected(&source), (1, 8 + 11 * formats + 4 + 10)); + // The same, and a second format behind it: the state moves on to the next + // opener, 12 bytes, and the second block is a document too. + let source = format!("format A =\n{body}1\n.\n2;\n{block}format C =\n3\n.\n4;\n{block}"); + assert_eq!( + collected(source.as_bytes()), + (2, 8 + 11 * formats + 4 + 10 + 12 + 10) + ); + // A format without a last line: the body is read once to the end of the input, + // and the block in it is withheld without reading it. + let source = format!("format A =\n{body}1;\n{block}").into_bytes(); + // expected: the opener (8), the opener lines (11 each), `1;` (3), and the six + // lines of the rest: an empty line, `=pod`, an empty line, `d`, an empty line, + // `=cut` (15). The block passes the reader's own tests first: 4 and 6 bytes. + assert_eq!(collected(&source), (0, 8 + 11 * formats + 3 + 15 + 10)); + // Many formats with a picture line that holds a field and a value line that is + // a named variable. + let source = tall(formats, "format F =\n@x;\n$a\n.\n2;\n", block); + // expected: per format the opener (8), the picture line (4), the value line (3) + // and the dot line (2): each byte of a body once. + assert_eq!(collected(&source), (1, 17 * formats + 10)); + // The same with a string as the value: the end of the first format is not + // known. It runs to the end of the input, and no later opener is read. + let source = tall(formats, "format F =\n@x;\n\"a\"\n.\n2;\n", block); + // expected: the opener (8), the picture line (4) and the value line (4), once. + assert_eq!(collected(&source), (0, 16 + 10)); + } +} + +#[cfg(feature = "perl")] +#[test] +fn perl_many_literals_cost_linear_work() { + let block = "\n=pod\n\nd\n\n=cut\n"; + for literals in [64, 512] { + // A row, and what it holds: the bytes of its literal nodes, its patterns and its + // single-quoted strings. + let collected = |row: &str, (in_literals, patterns, quoted): (usize, usize, usize)| { + let source = tall(literals, row, block); + let parser = parsed(&source); + let before = observations(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = observations(); + assert_eq!( + after.visits - before.visits, + parser.root_node().preorder().count() + ); + let bytes = after.classifier_bytes - before.classifier_bytes; + // expected: within the bound: seven times the input; each byte of a literal + // node once; 32 bytes before each pattern and one before each + // single-quoted string. + let bound = 7 * source.len() + literals * (in_literals + 32 * patterns + quoted); + assert!(bytes <= bound, "{bytes} > {bound}"); + (index.documents().len(), bytes) + }; + // expected: each string is read once, from its first byte to its last (8). Its + // text holds `<<` and no tag. The block is a document: 10 bytes. + assert_eq!( + collected("my $s = \"a << b\";\n", (8, 0, 0)), + (1, 8 * literals + 10) + ); + // expected: each word list is read once (7). + assert_eq!( + collected("my @s = qw(a b);\n", (7, 0, 0)), + (1, 7 * literals + 10) + ); + // expected: each transliteration is read once, with both parts (7). + assert_eq!( + collected("my $n = tr/a/b/;\n", (7, 0, 0)), + (1, 7 * literals + 10) + ); + // expected: per row the byte before the string and the string (1 and 3), the 32 + // bytes before the pattern and the pattern (32 and 3). The first pattern has + // only 27 bytes before it. + assert_eq!( + collected("my $s = 'a'; my $m = $s =~ /a/;\n", (6, 1, 1)), + (1, 39 * literals - 5 + 10) + ); + // expected: the first string holds an opener. It is read once (7), and no later + // string is read. The block is withheld after its own tests. + assert_eq!(collected("my $s = \"a <