diff --git a/.bca-baseline.toml b/.bca-baseline.toml index ab0959a82..034e94e34 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -214,69 +214,1683 @@ 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 = 1354.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker.rs" +qualified = "Checker" +metric = "nom" +value = 32.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_block_text_with_budget" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_block_text_with_budget" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "abc" +value = 46.411205543489174 + +[[entry]] +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/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "cyclomatic" +value = 16.0 + +[[entry]] +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/checker/lua.rs" +qualified = "lua_first_block_with_budget" +metric = "nexits" +value = 13.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "abc" +value = 45.9782557302906 + +[[entry]] +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/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "halstead.effort" +value = 76517.53443423788 + +[[entry]] +path = "big-code-analysis-ast/src/checker/lua.rs" +qualified = "source_opener_with_budget" +metric = "nexits" +value = 16.0 + +[[entry]] +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/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "cognitive" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "halstead.effort" +value = 111370.05894260037 + +[[entry]] +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/checker/php.rs" +qualified = "php_file_docblock_with_budget" +metric = "nexits" +value = 14.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "ruby_core_answer" +metric = "halstead.effort" +value = 108974.41089443305 + +[[entry]] +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/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/checker/ruby.rs" +qualified = "source_opener_with_budget" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/checker/ruby.rs" +qualified = "yard_lookup" +metric = "nexits" +value = 7.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 = 1342.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "" metric = "loc.sloc" -value = 1288.0 +value = 1408.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>" +metric = "nom" +value = 38.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>" +metric = "wmc" +value = 193.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::finish" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::local_target" +metric = "abc" +value = 42.02380277890139 + +[[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 = 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 = 63.631753079732135 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "cognitive" +value = 55.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "cyclomatic" +value = 25.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "halstead.effort" +value = 302344.58600726264 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::marker_run" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::order_results" +metric = "abc" +value = 56.568542494923804 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::order_results" +metric = "halstead.effort" +value = 117920.734305176 + +[[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 = 128540.67461519902 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::recognize" +metric = "nexits" +value = 13.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::record_children" +metric = "halstead.effort" +value = 123120.1464196539 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +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 = 79.36623967405788 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "cognitive" +value = 30.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "cyclomatic" +value = 37.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "halstead.effort" +value = 224811.99731446727 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::register" +metric = "nexits" +value = 11.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::rust_attribute" +metric = "halstead.effort" +value = 87692.75627416509 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "abc" +value = 74.31016081263719 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "cognitive" +value = 49.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "cyclomatic" +value = 20.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "halstead.effort" +value = 360943.541018517 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "Builder<'s>::walk" +metric = "nexits" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "collect_typed" +metric = "abc" +value = 69.19537556802477 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "collect_typed" +metric = "halstead.effort" +value = 119247.95238292999 + +[[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 = 14.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "enum_comma_predecessor" +metric = "cognitive" +value = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "enum_comma_predecessor" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector.rs" +qualified = "ts_await_using" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>" +metric = "wmc" +value = 91.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 = 74436.41610815194 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "abc" +value = 58.532042506647585 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "cognitive" +value = 29.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "cyclomatic" +value = 27.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "halstead.effort" +value = 174125.18083177393 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::document" +metric = "nexits" +value = 10.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::named_document" +metric = "cognitive" +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 = 8.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 = 71810.47102733159 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/assembly.rs" +qualified = "Builder<'s>::render_draft" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules.rs" +qualified = "independent_row" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/body.rs" +qualified = "Builder<'_>::irules_body_row" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/body.rs" +qualified = "Builder<'_>::irules_body_row" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/body.rs" +qualified = "Builder<'_>::irules_initial_body_rows" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/body.rs" +qualified = "Builder<'_>::irules_next_body_row" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/command.rs" +qualified = "Builder<'_>::irules_collect_words" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/command.rs" +qualified = "Builder<'_>::irules_command" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/leading.rs" +qualified = "Builder<'_>::irules_publish_leading" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/registration.rs" +qualified = "Builder<'_>::irules_braces_match" +metric = "halstead.effort" +value = 51131.544688146765 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/registration.rs" +qualified = "Builder<'_>::irules_braces_match" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/irules/registration.rs" +qualified = "Builder<'_>::irules_owner_reason" +metric = "nexits" +value = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "" +metric = "loc.ploc" +value = 1060.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>" +metric = "wmc" +value = 178.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "abc" +value = 47.69696007084728 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "cognitive" +value = 23.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "halstead.effort" +value = 106093.78750709642 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::c_slots" +metric = "nexits" +value = 10.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::declaration_owners" +metric = "cognitive" +value = 21.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::declaration_owners" +metric = "cyclomatic" +value = 29.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "abc" +value = 60.73713855624086 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "cognitive" +value = 48.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "cyclomatic" +value = 43.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "halstead.effort" +value = 258546.63547781942 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::finalize_projection" +metric = "nexits" +value = 14.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::index_function_definition" +metric = "nexits" +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/projections.rs" +qualified = "Builder<'_>::ruby_call_owners" +metric = "abc" +value = 52.16320542297991 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::ruby_call_owners" +metric = "cognitive" +value = 34.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::ruby_call_owners" +metric = "cyclomatic" +value = 27.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::ruby_call_owners" +metric = "halstead.effort" +value = 126942.74323409495 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "Builder<'_>::ruby_call_owners" +metric = "nexits" +value = 14.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "csharp_declarator_names" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "php_single_name" +metric = "cognitive" +value = 19.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/projections.rs" +qualified = "php_single_name" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/tcl.rs" +qualified = "Builder<'_>::ruff_enter" +metric = "halstead.effort" +value = 51537.0401723912 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/collector/tcl.rs" +qualified = "Builder<'_>::ruff_procedure" +metric = "halstead.effort" +value = 55087.166889506625 + +[[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/forms.rs" +qualified = "assess" +metric = "cyclomatic" +value = 23.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/forms.rs" +qualified = "assess" +metric = "halstead.effort" +value = 67583.60316470347 + +[[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::insert_candidate" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::insert_candidate" +metric = "nexits" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "abc" +value = 38.301436004411116 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "cognitive" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "halstead.effort" +value = 89032.0985530095 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "Names::resolve_in" +metric = "nexits" +value = 10.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names.rs" +qualified = "insert_entry" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/grammar.rs" +qualified = "parameters" +metric = "nexits" +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 = 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 = 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" +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 = 96613.60694528196 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/names/tokens.rs" +qualified = "tokens" +metric = "nexits" +value = 9.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/recognition.rs" +qualified = "NativeRules::target" +metric = "halstead.effort" +value = 68507.84557116154 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/recognition.rs" +qualified = "NativeRules::target::" +metric = "cyclomatic" +value = 16.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 = "cognitive" +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "RunSelection<'t>::select" +metric = "halstead.effort" +value = 169280.51408505262 + +[[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 = 8.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/markers.rs" +qualified = "line_spelling_end" +metric = "halstead.effort" +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" +qualified = "check_suffix" +metric = "halstead.effort" +value = 57170.887340554174 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceDecision<'t, 'c>::new" +metric = "cyclomatic" +value = 15.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceDecision<'t, 'c>::new" +metric = "halstead.effort" +value = 80530.09145695144 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceDecision<'t, 'c>::new" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceDecision<'t, 'c>::new" +metric = "nexits" +value = 7.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "SourceMembers<'t, 'c>::collect" +metric = "halstead.effort" +value = 52209.39539893175 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/streaming/positional.rs" +qualified = "source_comment_with_budget" +metric = "halstead.effort" +value = 67592.15484428481 + +[[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" +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 = 40.755367744629666 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text.rs" +qualified = "TextBuilder<'s>::copied_pieces" +metric = "halstead.effort" +value = 49940.1623107612 + +[[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/cleanup.rs" +qualified = "Projection<'_, 's>::copy" +metric = "halstead.effort" +value = 77075.53720675639 + +[[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" +qualified = "python" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "abc" +value = 62.8410693734599 + +[[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 = 186003.77222354026 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/cleanup.rs" +qualified = "python_margin" +metric = "nexits" +value = 10.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 = 236385.53109906797 + +[[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 = 691.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "append_range" +metric = "nargs" +value = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "abc" +value = 67.21606950722423 + +[[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 = 28.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "halstead.effort" +value = 364741.035619172 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "beautify" +metric = "nexits" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "blank" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "abc" +value = 76.48529270389177 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "cognitive" +value = 50.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "cyclomatic" +value = 28.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "halstead.effort" +value = 346101.6552429602 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "delimiters" +metric = "nexits" +value = 14.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "abc" +value = 39.761790704142086 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "cognitive" +value = 29.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "cyclomatic" +value = 18.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "emit_blocks" +metric = "halstead.effort" +value = 98814.40708896417 + +[[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 = 8.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 = 65731.40015873815 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "abc" +value = 49.80963762164909 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "cognitive" +value = 40.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "cyclomatic" +value = 28.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "prepare" +metric = "halstead.effort" +value = 180324.49186795903 + +[[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" +qualified = "prepare" +metric = "nexits" +value = 9.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render_local" +metric = "cognitive" +value = 27.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/comments.rs" +qualified = "render_local" +metric = "halstead.effort" +value = 65890.30389303257 + +[[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_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" +metric = "abc" +value = 72.00694410957877 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "cognitive" +value = 19.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "cyclomatic" +value = 31.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "decode" +metric = "halstead.effort" +value = 258934.86151196677 + +[[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 = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/documentation/text/literals.rs" +qualified = "expand_tabs" +metric = "halstead.effort" +value = 48324.818357318996 + +[[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/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" +metric = "halstead.effort" +value = 48814.4893649235 + +[[entry]] +path = "big-code-analysis-ast/src/getter/bash.rs" +qualified = "BashCode::get_op_type" +metric = "halstead.effort" +value = 48396.006635040394 + +[[entry]] +path = "big-code-analysis-ast/src/getter/elixir.rs" +qualified = "ElixirCode::get_op_type" +metric = "halstead.effort" +value = 76343.62516430535 + +[[entry]] +path = "big-code-analysis-ast/src/getter/perl.rs" +qualified = "PerlCode::get_op_type" +metric = "halstead.effort" +value = 114615.11034682626 + +[[entry]] +path = "big-code-analysis-ast/src/getter/php.rs" +qualified = "PhpCode::get_op_type" +metric = "halstead.effort" +value = 77488.02857857732 + +[[entry]] +path = "big-code-analysis-ast/src/getter/ruby.rs" +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 = 918.0 + +[[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_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/getter.rs" -qualified = "Getter::is_braced_literal_slot" -metric = "halstead.effort" -value = 48814.4893649235 +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bind_nearest" +metric = "nargs" +value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/getter/bash.rs" -qualified = "BashCode::get_op_type" +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bound_doc_run" metric = "halstead.effort" -value = 48396.006635040394 +value = 57703.76052754793 [[entry]] -path = "big-code-analysis-ast/src/getter/elixir.rs" -qualified = "ElixirCode::get_op_type" -metric = "halstead.effort" -value = 76343.62516430535 +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "bound_doc_run" +metric = "nexits" +value = 5.0 [[entry]] -path = "big-code-analysis-ast/src/getter/perl.rs" -qualified = "PerlCode::get_op_type" -metric = "halstead.effort" -value = 114615.11034682626 +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/getter/php.rs" -qualified = "PhpCode::get_op_type" +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 = "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 = 77488.02857857732 +value = 79913.2034194401 [[entry]] -path = "big-code-analysis-ast/src/getter/ruby.rs" -qualified = "RubyCode::get_op_type" +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +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 + +[[entry]] +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 = 6.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "positional_run_with_budget" metric = "halstead.effort" -value = 101217.532578918 +value = 84354.94753520834 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "bind_leading" +qualified = "positional_run_with_budget" metric = "nargs" value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "bound_doc_run" +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" +qualified = "select_bound" +metric = "nargs" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "select_bound_with_budget" metric = "halstead.effort" -value = 74870.34845140431 +value = 74299.0960371325 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "bound_doc_run" +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" +qualified = "stretch_end" +metric = "nargs" value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" -qualified = "joined_run" +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 = 17.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/doc_comment.rs" +qualified = "stretch_end_with_budget" +metric = "halstead.effort" +value = 123841.80744856672 + +[[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" @@ -285,15 +1899,87 @@ value = 5.0 [[entry]] path = "big-code-analysis-ast/src/lang_helpers/python.rs" -qualified = "documentation_run" +qualified = "" +metric = "loc.ploc" +value = 728.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/lang_helpers/shdoc.rs" +qualified = "Reading<'s>::confirm" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs" +qualified = "" +metric = "loc.ploc" +value = 570.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs" +qualified = "Scan<'s>" +metric = "nom" +value = 30.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs" +qualified = "Scan<'s>" +metric = "wmc" +value = 186.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs" +qualified = "Scan<'s>::arithmetic" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs" +qualified = "Scan<'s>::resume" +metric = "nexits" +value = 5.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs" +qualified = "Scan<'s>::step" metric = "nexits" value = 5.0 +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan/forms.rs" +qualified = "Scan<'_>" +metric = "wmc" +value = 153.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan/forms.rs" +qualified = "Scan<'_>::form" +metric = "cyclomatic" +value = 16.0 + +[[entry]] +path = "big-code-analysis-ast/src/lang_helpers/shdoc/scan/forms.rs" +qualified = "Scan<'_>::pattern" +metric = "abc" +value = 39.824615503479755 + [[entry]] 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" @@ -301,9 +1987,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 @@ -331,6 +2041,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/.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..869abc5cb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,8 @@ 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 +tests/fixtures/documentation/irules-legacy/** -text +tests/fixtures/documentation/reference/** -text 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/.github/workflows/fuzz.yml b/.github/workflows/fuzz.yml index de0fe1d3b..72af201de 100644 --- a/.github/workflows/fuzz.yml +++ b/.github/workflows/fuzz.yml @@ -23,6 +23,8 @@ on: - 'src/**' - 'big-code-analysis-ast/**' - 'fuzz/**' + # The documentation seeds are byte copies of these fixtures. + - 'tests/fixtures/documentation/**' - 'Cargo.toml' - 'Cargo.lock' - 'tree-sitter-*/**' diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d0745346..e939e59bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,59 @@ for historical reference. ## [Unreleased] +### Added + +- **Source documentation extraction.** `Ast::documentation` returns a + `big_code_analysis::documentation::DocumentationIndex` that borrows the + `Ast`. It lists each documentation comment, docstring or attribute with + its raw source fragments, its cleaned text where that text is complete + (with exact origins back to the source bytes), and its association with + the declaration, field slot, clause group or file it documents, under one + named convention (`Profile`) per language. Forms an adapter recognizes but + cannot resolve yet stay visible as pending assessments, and superseded or + unattached candidates and directive comments are kept on request. It is a + Rust library API only: `bca`, `bca-web` and the Python bindings do not + expose it. `STABILITY.md` covers its shape; extracted values may change + with grammar and adapter fixes. Released metrics, DLOC included, are + unchanged. Coverage is partial in every language (#1654): + - Rust: outer and inner doc comments and `#[doc = "..."]` strings, + composed per target with rustdoc's cleanup. Metadata, computed and + `cfg_attr` carriers stay pending. + - Python: PEP 257 module, class and function docstrings, with + `inspect.cleandoc` text. Attribute docstrings and Sphinx `#:` comments + stay pending. + - Java, Kotlin and Groovy: Javadoc, KDoc and Groovydoc on declarations, + and on field and property slots. Java package documentation is eligible + for publication only in `package-info.java`, a name a path-backed `Ast` + supplies or `DocumentationContext::with_logical_filename` sets. + - C#: XML documentation, including field, constant and event-field slots. + - PHP: DocBlocks, including property and constant slots. The + `phpdocumentor` profile is recognized but has no adapter yet. + - JavaScript, Mozjs, TypeScript and TSX: JSDoc on declarations, exports, + namespaces and variable declarators. Parameters stay pending. + - C, C++, Mozcpp and Objective-C: Doxygen comments before and after + declarations, file comments, trailing enumerator comments, named + references such as `@fn`, and template and linkage wrappers. + - Go: doc comment groups, struct fields and interface elements. + - Ruby: YARD on methods, visibility-wrapped definitions and attribute + slots. As YARD reads it, a block may end up to two rows above its + statement, a lone comment trailing a statement's first row documents + it, a block ends where its column changes, and each row loses its + whole leading `#` run and one blank. A block whose last row is `#-` + documents nothing, nor do an empty one-row block and a magic + comment, which a statement looks past. Constants and aliases stay + pending; the `rdoc` profile is recognized but has no adapter yet. + - Lua: LDoc runs and long comments on functions, assignments, returned + tables and table fields, attached across blank rows as LDoc does; a + long comment's closing row is never text. + - Perl: POD blocks, as documentation of the file. + - Elixir: `@moduledoc` and `@doc` on modules and clause groups. + - Bash, Tcl and iRules: shdoc function comments, Ruff! procedure + documentation, and comments above iRules handlers and procedures. A + shdoc `##` row keeps its second `#`. Nested `#ruff` rows, TclOO method + bodies, namespace preambles and iRules body comments stay pending. + - `Ccomment` and `Preproc` report that they have no declaration model. + ### Changed - **(breaking), deferred to the next major (3.0):** the MI of a space @@ -34,6 +87,27 @@ for historical reference. (`big-code-analysis-py/src/sarif.rs`, `mi_is_empty`), which exists only because the wire cannot yet say "empty". (#1621) +### Security + +- **Kotlin source whose last line holds an annotation no longer hangs + the parser.** The pinned grammar, tree-sitter-kotlin-ng 1.1.0, has + two scanner loops that never stop at the end of input, and inside + an annotation's parentheses one stops only at a newline. + `class C\n@Ann` with no final newline never finished parsing, and + neither a `bca-web` deadline nor `ParseCancel` could stop it. + `/v1/ast` and `/v1/comment` pass source through unnormalised, so + each such request left a core spinning, and once `max(threads × 2, 4)` + were stuck every request got `503` until restart. The parser now + appends a `\n` to Kotlin source with no `\n` after its last `@`, and + `Ast::source()` and those two endpoints include that byte. The `bca` + CLI and the metric endpoints already end every file with one. + +- **A long C-family documentation comment line with many inline code + spans no longer takes quadratic time.** LOC scanned to the end of the + line for every opening backtick in a `/**` or `///` comment, so a + 480 KB line took about ten seconds, in `bca` and in `bca-web`'s metric + endpoints, whose walk cannot be cancelled. The scan is now linear. + ## [2.6.0] - 2026-11-17 ### Added 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 88536194f..1361570f5 100644 --- a/Makefile +++ b/Makefile @@ -88,7 +88,7 @@ find-by-ext = $(if $(FD),$(FD) --extension $(1) $(FD_EXCLUDE) $(2),find . -name NEXTEST := $(shell command -v cargo-nextest 2>/dev/null) TEST_CMD = $(if $(NEXTEST),$(NEXTEST) nextest run --workspace --all-features,cargo test --workspace --all-features --lib --bins --tests) -.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-coverage-claimed role-parity-corpus role-corpus-refresh role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-rumdl-lockstep check-rumdl-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test check-grammar-build-watch check-grammar-build-watch-test check-deny-manifests-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-check-deny-manifests-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest +.PHONY: role-census role-census-test role-coverage role-coverage-test role-coverage-observe role-coverage-claimed role-parity-corpus role-corpus-refresh role-bypass role-bypass-test mutation-report-test mutation-workflow-test drift-common-test drift-oracle-test drift-compare-test recovery-oracle-test perturb-test fuzz-seeds-check coverage-diff-test self-scan-bca-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test help check-tools worktree-setup worktree-setup-test build build-release check test test-doc chain-audit fmt fmt-check markdown-fmt markdown-lint shellcheck sh-fmt sh-fmt-check toml-fmt toml-fmt-check toml-lint makefile-check actionlint snapshot-anchors snapshot-anchors-test rustfmt-bail rustfmt-bail-test grammar-marker-sync grammar-marker-sync-test check-versions check-excluded-manifests check-excluded-manifests-test check-ruff-lockstep check-ruff-lockstep-test check-rumdl-lockstep check-rumdl-lockstep-test check-publish-metadata check-publish-metadata-test check-manpage-assets check-manpage-drift-test check-diagnostic-prefix check-diagnostic-prefix-test check-feature-gates check-feature-gates-test check-test-lang-gates check-test-lang-gates-compare check-test-lang-gates-test check-safety-doc-pin check-safety-doc-pin-test check-grammar-build-watch check-grammar-build-watch-test check-deny-manifests-test gate-status-test check-tools-test enums-check enums-codegen-drift enums-codegen-drift-test self-scan self-scan-headroom self-scan-write-baseline self-scan-write-baseline-headroom self-scan-baseline-fresh self-scan-profile-parity vcs lint clippy udeps insta-review insta-accept clean distclean install install-cli install-web doc doc-open doc-check doc-check-docsrs book book-serve book-pot book-po-update book-ja book-deploy all pre-commit ci release-check verify-changelog pkg-deb-local pkg-rpm-local dev-env-build dev-env-run dev-env-shell dev-env-rm py-bootstrap py-sync py-relock py-clean py-fmt py-fmt-check py-lint py-typecheck py-test py-stubtest smoke smoke-cli smoke-lib bench bench-scaling bench-walk fuzz-check fuzz-smoke fuzz-replay fuzz-run fuzz-tmin _check-find _pc-all _pc-fmt _pc-clippy _pc-test _pc-doc-check _pc-udeps _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-fuzz-seeds-check _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-check-deny-manifests-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test _pc-self-scan _pc-self-scan-headroom _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest _ci-all _ci-fmt-check _ci-clippy _ci-test _ci-doc-check _ci-build _ci-udeps _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-fuzz-seeds-check _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test _ci-enums-codegen-drift-test _ci-self-scan _ci-self-scan-headroom _ci-cargo-pipeline _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest .PHONY: plugin-test _pc-plugin-test _ci-plugin-test @@ -143,6 +143,7 @@ help: @echo " drift-compare-test Self-tests for the capture comparer (utils/drift-compare.py)" @echo " recovery-oracle-test Self-tests for the recovery-tree drift sweep (utils/recovery-oracle.py)" @echo " perturb-test Self-tests for the perturbation sweep driver (utils/perturb.py)" + @echo " fuzz-seeds-check Check the documentation fuzz corpus matches its generator" @echo " coverage-diff-test Self-tests for the two-report patch-coverage driver (utils/coverage-diff.py)" @echo " self-scan-bca-test Self-tests for the self-scan binary resolver (utils/self-scan-bca.py)" @echo " role-coverage Every runtime kind id claimed, excluded or baselined (#1692)" @@ -196,6 +197,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)" @@ -461,10 +464,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: + @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 # takes no file arguments here: invoked at the repo root it discovers @@ -557,6 +564,12 @@ perturb-test: @echo "Running perturb self-tests..." @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/perturb-test.py) +# The fuzz registry test pins these seeds to the documentation fixtures, but it +# runs only in the fuzz workflow; checking the generator here makes a fixture +# edit that was not regenerated fail in the same change. +fuzz-seeds-check: + @python3 -I "$(BASE_DIR)fuzz/generate_documentation_seeds.py" --check + coverage-diff-test: @echo "Running coverage-diff self-tests..." @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/coverage-diff-test.py) @@ -1402,13 +1415,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) # --------------------------------------------------------------------------- @@ -1465,6 +1485,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 @@ -1525,8 +1549,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 @@ -1542,6 +1566,14 @@ FUZZ_REQUIRE_SYMBOLIZER = if [ -z "$(FUZZ_SYMBOLIZER)" ]; then echo "no llvm-sym # Discoveries go here instead (gitignored); the seeds stay read-only. FUZZ_WORK = $(BASE_DIR)fuzz/corpus-work +# List the fuzz targets into `$targets`. An assignment takes the exit status of +# its command substitution under `-e`, where a `for t in $(…)` list does not, so +# a failing `cargo fuzz list` stops the recipe instead of running zero targets; +# a list without the documentation target is refused for the same reason. +FUZZ_TARGETS = targets=$$(cargo +nightly fuzz list); \ + printf '%s\n' "$$targets" | grep -qx documentation || \ + { echo "cargo fuzz list did not name the documentation target"; exit 1; } + fuzz-check: @if rustup toolchain list 2>/dev/null | grep -q '^nightly' && \ command -v cargo-fuzz >/dev/null 2>&1; then \ @@ -1578,13 +1610,14 @@ fuzz-smoke: @if rustup toolchain list 2>/dev/null | grep -q '^nightly' && \ command -v cargo-fuzz >/dev/null 2>&1; then \ $(FUZZ_REQUIRE_SYMBOLIZER); \ + $(FUZZ_TARGETS); \ failed=""; \ - for t in $$(cargo +nightly fuzz list); do \ + for t in $$targets; do \ echo "Fuzzing $$t for $(FUZZ_RUNS) runs..."; \ - 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=$(FUZZ_RUNS) -timeout=$(FUZZ_TIMEOUT) \ + "$(FUZZ_WORK)/$$t" "$(FUZZ_CORPUS)/$$t" \ + -- $(FUZZ_ARGS) -runs=$(FUZZ_RUNS) -timeout=$(FUZZ_TIMEOUT) \ || failed="$$failed $$t"; \ done; \ if [ -n "$$failed" ]; then \ @@ -1604,13 +1637,14 @@ fuzz-replay: @if rustup toolchain list 2>/dev/null | grep -q '^nightly' && \ command -v cargo-fuzz >/dev/null 2>&1; then \ $(FUZZ_REQUIRE_SYMBOLIZER); \ - for t in $$(cargo +nightly fuzz list); do \ + $(FUZZ_TARGETS); \ + for t in $$targets; 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"; \ @@ -1623,13 +1657,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"; \ @@ -1706,7 +1740,7 @@ lint: $(MAKE) -j --output-sync=target \ _ci-clippy _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-fuzz-seeds-check _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test # --------------------------------------------------------------------------- # Maintenance @@ -1893,7 +1927,7 @@ _pc-all: $(MAKE) -j --output-sync=target \ _pc-test _pc-plugin-test \ _pc-shellcheck _pc-markdown-lint _pc-toml-lint _pc-makefile-check \ - _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-check-deny-manifests-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ + _pc-actionlint _pc-snapshot-anchors _pc-snapshot-anchors-test _pc-rustfmt-bail _pc-rustfmt-bail-test _pc-role-census _pc-role-census-test _pc-role-coverage _pc-role-coverage-test _pc-role-bypass _pc-role-bypass-test _pc-mutation-report-test _pc-mutation-workflow-test _pc-drift-common-test _pc-drift-oracle-test _pc-drift-compare-test _pc-recovery-oracle-test _pc-perturb-test _pc-fuzz-seeds-check _pc-coverage-diff-test _pc-self-scan-bca-test _pc-grammar-marker-sync _pc-grammar-marker-sync-test _pc-check-versions _pc-check-versions-test _pc-check-grammar-crate-test _pc-check-excluded-manifests _pc-check-excluded-manifests-test _pc-check-ruff-lockstep _pc-check-ruff-lockstep-test _pc-check-rumdl-lockstep _pc-check-rumdl-lockstep-test _pc-check-publish-metadata _pc-check-publish-metadata-test _pc-check-manpage-assets _pc-check-manpage-drift-test _pc-check-diagnostic-prefix _pc-check-diagnostic-prefix-test _pc-check-feature-gates-test _pc-check-test-lang-gates _pc-check-test-lang-gates-test _pc-check-safety-doc-pin _pc-check-safety-doc-pin-test _pc-check-grammar-build-watch _pc-check-grammar-build-watch-test _pc-check-deny-manifests-test _pc-worktree-setup-test _pc-gate-status-test _pc-check-tools-test _pc-enums-check _pc-enums-codegen-drift _pc-enums-codegen-drift-test \ _pc-manpages \ _pc-self-scan _pc-self-scan-headroom \ _pc-py-fmt _pc-py-typecheck _pc-py-test _pc-py-stubtest @@ -1903,7 +1937,7 @@ _ci-all: $(MAKE) -j --output-sync=target \ _ci-cargo-pipeline _ci-plugin-test \ _ci-shellcheck _ci-markdown-lint _ci-toml-lint _ci-makefile-check \ - _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ + _ci-actionlint _ci-snapshot-anchors _ci-snapshot-anchors-test _ci-rustfmt-bail _ci-rustfmt-bail-test _ci-role-census _ci-role-census-test _ci-role-coverage _ci-role-coverage-test _ci-role-bypass _ci-role-bypass-test _ci-mutation-report-test _ci-mutation-workflow-test _ci-drift-common-test _ci-drift-oracle-test _ci-drift-compare-test _ci-recovery-oracle-test _ci-perturb-test _ci-fuzz-seeds-check _ci-coverage-diff-test _ci-self-scan-bca-test _ci-grammar-marker-sync _ci-grammar-marker-sync-test _ci-check-versions _ci-check-versions-test _ci-check-grammar-crate-test _ci-check-excluded-manifests _ci-check-excluded-manifests-test _ci-check-ruff-lockstep _ci-check-ruff-lockstep-test _ci-check-rumdl-lockstep _ci-check-rumdl-lockstep-test _ci-check-publish-metadata _ci-check-publish-metadata-test _ci-check-manpage-assets _ci-check-manpage-drift-test _ci-check-diagnostic-prefix _ci-check-diagnostic-prefix-test _ci-check-feature-gates-test _ci-check-test-lang-gates _ci-check-test-lang-gates-test _ci-check-safety-doc-pin _ci-check-safety-doc-pin-test _ci-check-grammar-build-watch _ci-check-grammar-build-watch-test _ci-check-deny-manifests-test _ci-worktree-setup-test _ci-gate-status-test _ci-check-tools-test _ci-enums-check _ci-enums-codegen-drift _ci-enums-codegen-drift-test \ _ci-py-fmt-check _ci-py-lint _ci-py-typecheck _ci-py-test _ci-py-stubtest # --------------------------------------------------------------------------- @@ -1944,6 +1978,7 @@ _ci-all: # ├── _pc-drift-compare-test # ├── _pc-recovery-oracle-test # ├── _pc-perturb-test +# ├── _pc-fuzz-seeds-check # ├── _pc-coverage-diff-test # ├── _pc-self-scan-bca-test # ├── _pc-role-coverage @@ -2082,6 +2117,9 @@ _pc-recovery-oracle-test: _pc-fmt _pc-perturb-test: _pc-fmt $(MAKE) perturb-test +_pc-fuzz-seeds-check: _pc-fmt + $(MAKE) fuzz-seeds-check + _pc-coverage-diff-test: _pc-fmt $(MAKE) coverage-diff-test @@ -2359,6 +2397,9 @@ _ci-recovery-oracle-test: _ci-perturb-test: $(MAKE) perturb-test +_ci-fuzz-seeds-check: + $(MAKE) fuzz-seeds-check + _ci-coverage-diff-test: $(MAKE) coverage-diff-test diff --git a/README.ja.md b/README.ja.md index 307e6c0ea..c7388a54d 100644 --- a/README.ja.md +++ b/README.ja.md @@ -120,6 +120,11 @@ big-code-analysis = "2" [ライブラリとして使う](https://dekobon.github.io/big-code-analysis/ja/library/index.html)の章を参照してください。 API リファレンスは [docs.rs](https://docs.rs/big-code-analysis) にあります。 +`Ast::documentation` は保持した構文木からソース文書、意味上の所有者、テキストからソースへの対応を抽出します。 +公開 API の `big_code_analysis::documentation` 型を使います。これは Rust ライブラリ専用の API で、`bca`、`bca-web`、 +Python バインディングからは利用できません。例は +[ソース文書の抽出](https://dekobon.github.io/big-code-analysis/ja/library/documentation.html)を参照してください。 + Python バインディング([PyO3](https://pyo3.rs/))は [`big-code-analysis-py/`](./big-code-analysis-py/README.md) にあり、 [PyPI の `big-code-analysis` パッケージ](https://pypi.org/project/big-code-analysis/)として同じメトリクスパイプラインを提供します。 diff --git a/README.md b/README.md index f10af117e..dfc0a4322 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,12 @@ chapter for task-oriented walkthroughs (quick start, in-memory analysis, walking `FuncSpace` results, error handling). The API reference is on [docs.rs](https://docs.rs/big-code-analysis). +`Ast::documentation` extracts source documentation, semantic owners and text-to-source +mappings from a held parse through the public `big_code_analysis::documentation` types. It +is a Rust library API only: `bca`, `bca-web` and the Python bindings do not expose it. See +[Extracting source documentation](https://dekobon.github.io/big-code-analysis/library/documentation.html) +for examples. + Python bindings ([PyO3](https://pyo3.rs/)) live in [`big-code-analysis-py/`](./big-code-analysis-py/README.md) and ship the same metric pipeline as the diff --git a/STABILITY.md b/STABILITY.md index 9b661f465..c9578bdd7 100644 --- a/STABILITY.md +++ b/STABILITY.md @@ -94,6 +94,41 @@ section. parser-generic `metrics` / `metrics_with_options` functions and the `MetricsCfg` builder were removed at `2.0` in favor of `analyze` / `Ast`. + - `Ast::documentation` and `big_code_analysis::documentation` expose a + borrowed source-documentation index and its explicitly re-exported result + and option types. `Ast::documentation` takes a `DocumentationContext` and + a `DocumentationOptions` by value, as `Ast::metrics` takes its options. + `DocumentationContext::default().with_logical_filename(name)` supplies + optional caller metadata; `DocumentationOptions::default()` can be refined + with `with_profile`, `with_unbound_evidence` and `with_directive_evidence`. + Both types are `#[non_exhaustive]` with private fields: build them through + `Default` and the builders, and read them through their accessors + (`logical_filename()`, `profile()`, `unbound_evidence()`, + `directive_evidence()`). `DocumentationOptions` is deliberately not + `Copy`, so a later option may own data. The index cannot outlive its `Ast` + and keeps no documentation cache in the `Ast`. The re-exported names, + method signatures, public fields and currently named enum variants are + protected by the `2.x` shape contract; `#[non_exhaustive]` permits + additive variants and fields. + Navigation between records (`document_fragment`, `associated_document`, + `associated_owner`, `slot_enclosing`, `document_order`) is on + `DocumentationIndex`; `Facts` iterates the raw records in collection + order, which is repeatable for the same source, profile and options but + otherwise unspecified. `FactRef` handles compare and hash by record + identity. `Convention`, `DocumentOrder`, `MappingPortions`, and `TextRange` + are re-exported as part of the result model; `DocumentOrder` is an opaque + `Ord` key whose parts have no accessors. `Profile::name()` values are + shape-stable identifiers: ASCII lowercase words joined by `-`. Node-based + queries accept the pinned `tree_sitter::Node`, obtainable from + `Ast::as_tree_sitter()`; this parameter and `NodeEvidence::node()` follow + the tree-sitter escape-hatch pin. + `CollectionError`, `OwnerError`, `FactError`, `SourceError` and + `TextRangeError` implement `Display + Error`; their display wording is not + shape-stable, nor is `Assessment::reason()`, nor any `Debug` output. + `CollectionError` is `Copy` by design: its variants carry only small + identifiers such as a `LANG` or a `Profile`. Internal collector functions + and test counters in the AST crate are not re-exported or promised by this + contract. - `Metric`, `MetricSet` in `src/metric_set.rs`: `Metric` carries `#[non_exhaustive]`, so adding variants is additive. `MetricSet` is the opaque bitfield consumed by @@ -547,7 +582,7 @@ The following are explicitly **not** part of the shape contract: crate *does* re-export from it (`LANG`, `ParseLangError`, `Node`, `MetricsError`, `SpaceKind`, `metrics::halstead::TokenRole`, the AST dump types, `Count` / `CountCollector`, the preprocessor types and - functions, and the file readers) are covered exactly as the sections + functions, the file readers, and the documentation result model) are covered exactly as the sections above describe, through this crate's paths. Depend on `big-code-analysis`; depend on `big-code-analysis-ast` directly only if you accept re-pinning on every release. @@ -581,6 +616,10 @@ versions, even within `2.x`.** Concretely: This is the one deliberate carve-out in the `2.x` contract. The *shape* of the data is stable; the *numbers in the cells* are not. +The same distinction applies to source documentation: its owners, byte +ranges, cleaned text, assessments and publication may change with pinned +grammar versions and fixes to source adapters. Exact-result reproducibility +requires an exact crate version, not only a stable API shape. If you need to compare metric runs across time, pin to an exact version (`big-code-analysis = "= 2.6.0"`) and store the version alongside the results. @@ -817,7 +856,8 @@ reach the raw tree-sitter surface. re-export. The rest of `Ast`'s API surface (`parse`, `from_tree_sitter`, `from_path`, `metrics`, `ops`, `strip_comments`, `functions`, `dump`, `dump_cursor`, `dump_indexed`, `count`, `find`, - `root_node`, `suppressions`, `language`, `source`, `name`) is + `root_node`, `suppressions`, `language`, `source`, `name`, + `documentation`) is shape-stable. `from_path` (#727) is the file-backed counterpart to `parse`; it returns the `#[non_exhaustive]` `FromPathError` (`Io`, `NonUtf8Path`, `Skipped(SkipReason)`, `UnknownLanguage`, 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/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/checker.rs b/big-code-analysis-ast/src/checker.rs index 90f2bc818..e83746e3d 100644 --- a/big-code-analysis-ast/src/checker.rs +++ b/big-code-analysis-ast/src/checker.rs @@ -409,6 +409,51 @@ 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 + } + /// Source-only direction test. Overrides must respect included-range barriers + /// 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, '_>, + ) -> 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; + /// 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 @@ -533,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). @@ -921,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/bash.rs b/big-code-analysis-ast/src/checker/bash.rs index 71591edaa..54bea5029 100644 --- a/big-code-analysis-ast/src/checker/bash.rs +++ b/big-code-analysis-ast/src/checker/bash.rs @@ -4,6 +4,10 @@ use super::*; impl Checker for BashCode { + // The source view reads shdoc runs by position; the rules are in + // `lang_helpers::shdoc`. No legacy answer below depends on it. + const SOURCE_POSITIONAL_DOCS: bool = true; + // The one `Comment` row of `roles/bash.rs`; no `DocComment` row (#1699). impl_comment_from_rows!(bash); 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/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/irules.rs b/big-code-analysis-ast/src/checker/irules.rs index a48f19463..7ae0d9c14 100644 --- a/big-code-analysis-ast/src/checker/irules.rs +++ b/big-code-analysis-ast/src/checker/irules.rs @@ -4,6 +4,10 @@ use super::*; impl Checker for IrulesCode { + fn is_source_doc_target<'a>(node: &Node<'a>, _: &[u8], _: Ancestors<'a, '_>) -> bool { + Self::source_target(node) + } + // The one `Comment` row of `roles/irules.rs`; no `DocComment` row (#1699). impl_comment_from_rows!(irules); @@ -63,3 +67,11 @@ impl Checker for IrulesCode { // the clause, and the row leaves it out (#1697). impl_else_if_from_row!(irules); } + +impl IrulesCode { + // Source-only, unlike the legacy DocTarget role table. + fn source_target(node: &Node<'_>) -> bool { + // role-bypass: allow(FuncOpener) — source-only handler and procedure targets must not change legacy DocTarget membership. + matches!(node.kind_id(), id if id == Irules::WhenEvent as u16 || id == Irules::Procedure as u16) + } +} 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/lua.rs b/big-code-analysis-ast/src/checker/lua.rs index b74966d95..3b8a86374 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. @@ -19,32 +19,124 @@ struct LdocText { tag: bool, } +impl LdocText { + fn read_with_budget( + &mut self, + bytes: &[u8], + budget: &B, + ) -> Result<(), B::Error> { + for line in scan::lines(bytes, 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, false, &NoBudget, + )) +} + +/// What the block that `first` opens holds. The source view reads each +/// member as LDoc does, without a long comment's closing row; the legacy +/// run reads every row, as its pinned LOC counts do. +fn lua_block_text_with_budget<'a, B: WorkBudget>( + first: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: bool, + 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 { - for line in node_bytes(&member, code).split(|&byte| byte == b'\n') { - let body = ldoc_line_body(line); - found.text |= body.iter().any(|&byte| { - !matches!(byte, b'-' | b'[' | b']' | b'=') && !byte.is_ascii_whitespace() - }); - found.tag |= - matches!(body.trim_ascii_start(), [b'@', tag, ..] if tag.is_ascii_alphanumeric()); - } - match after.next() { - Some(next) if run_continues_to::(&member, &next, code) => member = next, - _ => return found, + budget.step()?; + let spelling = node_bytes(&member, code); + let spelling = if source { + crate::lang_helpers::doc_text::ldoc_read_spelling(spelling, budget)? + } else { + spelling + }; + found.read_with_budget(spelling, 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..]) +} + +pub(crate) fn standalone_tag_with_budget( + raw: &[u8], + budget: &B, +) -> Result { + let mut found = false; + let body = crate::lang_helpers::doc_text::lua_long_comment_body(raw, budget)?.unwrap_or(raw); + for line in scan::lines(body, budget) { + budget.step()?; + found |= standalone_line_tag(line?, budget)?; + } + Ok(found) +} + +fn standalone_line_tag(line: &[u8], budget: &B) -> Result { + let body = scan::trim_start(ldoc_line_body(line, budget)?, budget)?; + let Some(tag) = body.strip_prefix(b"@") else { + return Ok(false); + }; + let end = + scan::position(tag, |byte| !byte.is_ascii_alphanumeric(), budget)?.unwrap_or(tag.len()); + standalone_tag_name(&tag[..end], budget) +} + +fn standalone_tag_name(name: &[u8], budget: &B) -> Result { + for structural in [ + b"module".as_slice(), + b"script", + b"example", + b"topic", + b"submodule", + b"classmod", + b"file", + b"function", + b"lfunction", + b"table", + b"section", + b"type", + b"annotation", + b"factory", + b"name", + b"field", + ] { + budget.bytes(name.len().max(structural.len()))?; + if name == structural { + return Ok(true); + } + } + Ok(false) } /// Whether the block `first` opens is the file's first LDoc block, which @@ -57,6 +149,20 @@ 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 { + infallible(lua_first_block_with_budget( + first, code, ancestors, None, &NoBudget, + )) + .expect("invariant: only a source context reports an excluded gap") +} + +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 // body's first statement after it, so the first-token test below would @@ -67,43 +173,166 @@ 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(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() { + 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 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, source.is_some(), budget)?.text { - return false; + return Ok(Ok(false)); } earliest = sibling; } + 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 - matches!(earliest.kind_id().into(), Lua::Comment | Lua::HashBangLine) + 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 { + return crate::documentation::budget::child(node, Node::is_named, budget); + } + 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()?; + let spelling = node_bytes(member, run.code); + text.read_with_budget( + crate::lang_helpers::doc_text::ldoc_read_spelling(spelling, budget)?, + 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 { + const SOURCE_POSITIONAL_DOCS: bool = true; + + fn is_source_doc_target<'a>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + ) -> bool { + let _ = (code, ancestors); + infallible(target_with_budget(node, &NoBudget)) + } + + fn source_doc_run_opener<'a>( + run: &crate::documentation::streaming::positional::RunContext<'_, 'a>, + ancestors: Ancestors<'a, '_>, + ) -> Result< + Option, + crate::documentation::UnresolvedReason, + > { + 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 39a0f20b3..25be74d85 100644 --- a/big-code-analysis-ast/src/checker/php.rs +++ b/big-code-analysis-ast/src/checker/php.rs @@ -2,6 +2,8 @@ #![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; /// A top-level node phpDocumentor's `createFileDocBlock` passes over @@ -21,22 +23,62 @@ 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. -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)) +/// 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, +) -> 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), }; - if !ancestors.parent_has_kind(comment, Php::Program as u16) - || !ancestors.siblings_before(comment).all(preamble_or_plain) - { - return false; + 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) { + return Ok(Some(false)); + } + 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 Ok(Some(false)); + } + } + if !view.covers_with_budget(0..boundary, budget)? { + return Ok(None); } let mut docs = 1_usize; - for node in ancestors.siblings_after(comment) { - if PhpCode::is_doc_comment(&node, code) { + let mut boundary = comment.end_byte(); + 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 docs == 2 + 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 // selection policy over the row, not membership @@ -48,10 +90,52 @@ fn php_file_docblock<'a>(comment: &Node<'a>, code: &[u8], ancestors: Ancestors<' | Php::ConstDeclaration2 | Php::InterfaceDeclaration | Php::TraitDeclaration - ); + ), + )); } } - 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 { + 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; + // 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 { @@ -60,6 +144,18 @@ impl Checker for PhpCode { impl_comment_from_rows!(php); impl_doc_comment_from_row!(php); + const SOURCE_LOCAL_DOCS: bool = true; + + fn source_doc_binds_forward<'a>( + node: &Node<'a>, + context: &crate::documentation::SourceContext<'a>, + ancestors: Ancestors<'a, '_>, + ) -> Option { + infallible(source_forward_with_budget( + node, context, ancestors, &NoBudget, + )) + } + // 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 @@ -72,34 +168,9 @@ 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) + .unwrap_or(false) }, ..DocBinding::new(KeptDocs::Leading { hidden: |node, code| !Self::is_doc_comment(node, code), diff --git a/big-code-analysis-ast/src/checker/ruby.rs b/big-code-analysis-ast/src/checker/ruby.rs index 459dd89bd..0e8ba74c0 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_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_yard_reads}; /// 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,12 +61,439 @@ 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>( + node: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + source: bool, +) -> bool { + 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); + let mut wrappers = Vec::new(); + let Some((core, core_chain)) = + ruby_documented_core(&statement, statement_chain, budget, |visited| { + if source && visited.id() != node.id() { + wrappers.push(visited); + } + })? + 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) + }; + 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)) +} + +/// Whether YARD refuses the block that `last` ends: `add_comment` returns +/// before it attaches a block whose last line is `#-`, so the block documents +/// nothing, not even through a directive. +pub(crate) fn source_detached_with_budget( + last: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + let bytes = crate::lang_helpers::doc_comment::node_bytes(last, code); + Ok(crate::documentation::byte_scan::trim_end(bytes, budget)? == b"#-") +} + +/// The block YARD still finds for a statement on `row` past a row of code, +/// given `block`, the sibling before that code. The code asked first and +/// took any block it found, except one `add_comment` refused; a block in +/// reach past code ends on the row before it. +fn refused_past_code<'a, B: WorkBudget>( + block: Option>, + row: usize, + code: &[u8], + budget: &B, +) -> Result>, B::Error> { + match block { + Some(block) if RubyCode::is_comment(&block) && yard_reaches(block.end_row(), row) => { + Ok(source_detached_with_budget(&block, code, budget)?.then_some(block)) + } + _ => Ok(None), + } +} + +/// Whether `on_comment` appends `next`'s row to the block `prev` ends: a +/// comment on the row above, at the same column. +fn yard_appends(prev: &Node<'_>, next: &Node<'_>) -> bool { + RubyCode::is_comment(prev) + && prev.end_row() + 1 == next.start_row() + && prev.as_tree_sitter().start_position().column + == next.as_tree_sitter().start_position().column +} + +/// Whether YARD gives the run from `first` to `last` to no statement: it +/// refuses the run, or `on_comment` leaves its one row empty, which +/// `insert_comments` passes over. +pub(crate) fn source_documents_nothing( + first: &Node<'_>, + last: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + Ok(source_detached_with_budget(last, code, budget)? + || (first.as_tree_sitter() == last.as_tree_sitter() && yard_empty_row(last, code, budget)?)) +} + +/// Whether `on_comment` reads `comment`'s row as empty: it strips one `#` +/// run and then at most one blank (`^(#+)\s{0,1}`), and `chomp` the line +/// end, so `#`, `#####` and `# ` leave nothing and `# x` leaves ` x`. +fn yard_empty_row( + comment: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + let bytes = crate::lang_helpers::doc_comment::node_bytes(comment, code); + let bytes = bytes.strip_suffix(b"\r").unwrap_or(bytes); + let hashes = crate::documentation::byte_scan::position(bytes, |byte| byte != b'#', budget)? + .unwrap_or(bytes.len()); + Ok(hashes > 0 + && matches!( + &bytes[hashes..], + [] | [b' ' | b'\t' | b'\r' | b'\n' | 0x0B | 0x0C] + )) +} + +/// The comment ending the block YARD's lookup finds for `statement` on the +/// two rows above it. `insert_comments` passes over a block `on_comment` +/// left empty or never stored, a magic comment, and asks the row above it. +/// Code on the row above asked first and took whatever block it found, +/// except one `add_comment` refused, which stays to be found. +fn yard_lookup<'a, B: WorkBudget>( + statement: &Node<'a>, + ancestors: Ancestors<'a, '_>, + code: &[u8], + budget: &B, +) -> Result>, B::Error> { + let row = statement.start_row(); + let mut before = ancestors + .siblings_before_with_budget(statement, budget)? + .peekable(); + while let Some(above) = before.next() { + budget.step()?; + if !yard_reaches(above.end_row(), row) { + return Ok(None); + } + if !RubyCode::is_comment(&above) { + return refused_past_code(before.next(), row, code, budget); + } + let bytes = crate::lang_helpers::doc_comment::node_bytes(&above, code); + let unstored = + crate::lang_helpers::doc_text::ruby_magic_comment_with_budget(bytes, budget)?; + // A block of two rows is never empty: `on_comment` joins them with a + // line end. + let alone = before.peek().is_none_or(|prev| !yard_appends(prev, &above)); + let passed_over = unstored || (alone && yard_empty_row(&above, code, budget)?); + if !passed_over { + return Ok(Some(above)); + } + } + Ok(None) +} + +/// The statement that takes `comment`, a lone comment trailing code on its +/// row, with the statement's own chain. YARD's `insert_comments` asks each +/// statement for a block ending on the row above it, then two rows above, +/// and only then on its own row, so the statement that starts on the +/// comment's row takes it unless it has a block above. A comment it leaves +/// may go to a later node, which YARD picks by its own tree; the source view +/// does not guess that node. +pub(crate) fn source_trailing_with_budget<'a, 'c, B: WorkBudget>( + comment: &Node<'a>, + ancestors: Ancestors<'a, 'c>, + code: &[u8], + budget: &B, +) -> Result, Ancestors<'a, 'c>)>, B::Error> { + let Some((statement, chain)) = trailing_holder(comment, ancestors, budget)? else { + return Ok(None); + }; + Ok((!yard_block_above(&statement, chain, code, budget)?).then_some((statement, chain))) +} + +/// Whether a YARD block that ends on `end_row` reaches a statement that starts +/// on `start_row`: `insert_comments` asks for a block ending on the row above +/// the statement, then on the row above that. +pub(crate) fn yard_reaches(end_row: usize, start_row: usize) -> bool { + (1..=2).contains(&start_row.saturating_sub(end_row)) +} + +/// The code a lone comment trails on its row, with its own chain. YARD walks +/// statements in pre-order, so the first one asked is the outermost that +/// starts on the row: an ancestor whose header holds the comment +/// (`def m # c`, `class C < B # c`), else the named sibling before the +/// comment, when that is no comment and starts on the row. +fn trailing_holder<'a, 'c, B: WorkBudget>( + comment: &Node<'a>, + ancestors: Ancestors<'a, 'c>, + budget: &B, +) -> Result, Ancestors<'a, 'c>)>, B::Error> { + let row = comment.start_row(); + let mut header = None; + for (ancestor, chain) in ancestors.iter(comment) { + budget.step()?; + if ancestor.start_row() != row { + break; + } + if !lists_statements(&ancestor) { + header = Some((ancestor, chain)); + } + } + if header.is_some() { + return Ok(header); + } + Ok(statement_before(comment, ancestors, budget)? + .filter(|holder| !RubyCode::is_comment(holder) && holder.start_row() == row) + .map(|holder| (holder, ancestors))) +} + +/// Whether `node` only lists statements, so YARD asks its children, never it. +fn lists_statements(node: &Node<'_>) -> bool { + // role-bypass: allow(Container) — which nodes YARD reads as a statement + // list, not whether one opens a space: a class opens one and is a statement + matches!( + node.kind_id().into(), + Ruby::Program + | Ruby::BodyStatement + | Ruby::BodyStatement2 + | Ruby::BlockBody + | Ruby::Then + | Ruby::Else + | Ruby::Do + | Ruby::Ensure + | Ruby::BeginBlock + | Ruby::EndBlock + | Ruby::ParenthesizedStatements + ) +} + +/// The named sibling before `node`, past the `;` tokens that separate +/// statements on one row. +fn statement_before<'a, B: WorkBudget>( + node: &Node<'a>, + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result>, B::Error> { + for sibling in ancestors.siblings_before_with_budget(node, budget)? { + budget.step()?; + if sibling.is_named() { + return Ok(Some(sibling)); + } + } + Ok(None) +} + +// Counts the statements `yard_block_above` reaches: a chain of trailing +// comments decides its answer once, which no published fact shows. +crate::observation::counter!(yard_block_steps); + +/// Whether YARD finds a block for `statement` on the two rows above it. A +/// comment that trails an earlier statement on its own row is there only +/// when that statement found a block above itself and left the comment, so +/// a chain of such statements has one answer. The walk records it for every +/// statement it passes, which makes a chain cost one walk in all. +fn yard_block_above<'a, B: WorkBudget>( + statement: &Node<'a>, + ancestors: Ancestors<'a, '_>, + code: &[u8], + budget: &B, +) -> Result { + // bca: suppress(cognitive, halstead) -- one backward walk decides a whole trailing-comment chain and records it. + let memo = ancestors.node_memo(crate::node::MemoQuestion::YardLeading); + let mut passed = Vec::new(); + let mut statement = *statement; + let mut ancestors = ancestors; + let found = loop { + budget.step()?; + yard_block_steps::record(); + if let Some(known) = memo.and_then(|memo| memo.get(&statement)) { + break known; + } + passed.push(statement); + let Some(above) = yard_lookup(&statement, ancestors, code, budget)? else { + break false; + }; + // A refused block stays where YARD found it, and blocks again. + if source_detached_with_budget(&above, code, budget)? { + break true; + } + // A holder that starts on the comment's row ends there too. + match trailing_holder(&above, ancestors, budget)? { + Some((holder, chain)) => (statement, ancestors) = (holder, chain), + None => break true, + } + }; + // Each passed statement was charged a step when the walk reached it. + if let Some(memo) = memo { + for statement in &passed { + memo.set(statement, found); + } + } + Ok(found) } 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(infallible(source_opener_with_budget( + run, ancestors, &NoBudget, + ))) + } // The `Comment` row of `roles/ruby.rs` (#1699); no `DocComment`. impl_comment_from_rows!(ruby); @@ -74,18 +509,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 { @@ -196,7 +620,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/checker/rust.rs b/big-code-analysis-ast/src/checker/rust.rs index dffa4e55e..276eb06d3 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,21 @@ 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) + .or_else(|| { + node.is_error() + .then_some(crate::documentation::UnresolvedReason::GrammarBoundary) + }) + } + // 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.rs b/big-code-analysis-ast/src/documentation.rs new file mode 100644 index 000000000..6ab09fa1e --- /dev/null +++ b/big-code-analysis-ast/src/documentation.rs @@ -0,0 +1,726 @@ +//! 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. +//! Collection retains immutable source facts, local text and prepared owner queries. +//! The root crate re-exports the public result model through its documentation facade; +//! collector plumbing remains an unstable direct-AST interface. +//! +//! 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. +//! 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. +//! 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; +mod canonical; +pub(crate) mod collector; +mod content; +mod forms; +mod index; +mod names; +mod options; +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; +mod text; + +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. +#[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, + /// 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, + /// 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 the shared byte-scan kernels, under any budget, including + /// the legacy metric path. An adapter's own per-byte scan is counted by + /// `byte_charges` instead. + pub classifier_bytes: usize, + /// Calls that charged the collection budget for source bytes, one per byte + /// of an adapter's own per-byte scan. + pub byte_charges: 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. + 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, + /// 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, + /// 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. +#[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(), + 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(), + byte_charges: budget::byte_charges::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(), + 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(), + 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(), + } +} + +/// 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] +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, PartialEq, Eq, Hash)] +pub(crate) struct FragmentId(pub(crate) usize); +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct DocumentId(pub(crate) usize); +#[derive(Clone, Copy)] +pub(crate) struct OwnerId(pub(crate) usize); +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct AssessmentId(pub(crate) usize); +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct AssociationId(pub(crate) usize); +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct QualificationId(pub(crate) usize); + +/// Give arena ids a `Debug` that names the kind but not the ordinal, so the +/// derived `Debug` of a public record that holds one exposes no ordinal. +macro_rules! opaque_id_debug { + ($($id:ty),+ $(,)?) => {$( + impl std::fmt::Debug for $id { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str(concat!(stringify!($id), "(..)")) + } + } + )+}; +} +pub(crate) use opaque_id_debug; + +opaque_id_debug!( + FragmentId, + DocumentId, + OwnerId, + AssessmentId, + AssociationId, + QualificationId, +); + +/// 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. Reserved: no adapter produces it yet. + AttributeBinding, + /// A Sphinx attribute comment. Reserved: no adapter produces it yet. + Sphinx, + /// Documentation preceding a declaration. + LeadingComment, + /// Documentation in a declaration's body. + BodyComment, + /// File or package documentation. + FilePackage, + /// Documentation declaring a virtual target. Reserved: no adapter produces it yet. + Virtual, + /// Documentation the collector inferred rather than read from a + /// convention. Reserved: no adapter produces it yet. No option enables 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)] +pub struct Facts<'s> { + scope: u8, + pub(crate) fragments: Vec>, + pub(crate) documents: Vec>, + pub(crate) owners: Vec>, + pub(crate) associations: Vec>, +} + +/// A document's place in source order: its first fragment's start and end, then +/// its role rank, then creation order. Keys compare; their parts are not exposed, +/// so no arena ordinal escapes the index. +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct DocumentOrder { + start: usize, + end: usize, + rank: u8, + creation: usize, +} + +impl DocumentOrder { + pub(crate) const fn new(start: usize, end: usize, rank: u8, creation: usize) -> Self { + Self { + start, + end, + rank, + creation, + } + } + + pub(crate) const fn creation(self) -> usize { + self.creation + } +} + +// Hand-written so the creation ordinal stays private, as `FactRef` promises. +impl std::fmt::Debug for DocumentOrder { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("DocumentOrder") + .field("start", &self.start) + .field("end", &self.end) + .field("rank", &self.rank) + .finish_non_exhaustive() + } +} + +/// 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. +pub struct FactRef<'i, T> { + scope: &'i u8, + ordinal: usize, + fact: &'i T, +} + +// Hand-written so neither the arena ordinal nor the scope is printed: a +// derived impl would expose the index-local id this type promises to hide. +impl std::fmt::Debug for FactRef<'_, T> { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.debug_tuple("FactRef").field(self.fact).finish() + } +} + +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> {} +/// Hashes what equality compares: the store's identity and the ordinal. +impl std::hash::Hash for FactRef<'_, T> { + fn hash(&self, state: &mut H) { + std::ptr::hash(self.scope, state); + self.ordinal.hash(state); + } +} +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> { + /// An empty store; only the collector fills one. + pub(crate) fn empty() -> Self { + Self { + scope: 0, + fragments: Vec::new(), + documents: Vec::new(), + owners: Vec::new(), + associations: Vec::new(), + } + } + + 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 collection order. + /// + /// Collection order is the order the collector created records in: the same + /// for the same source, profile and options, but otherwise unspecified. Use + /// [`DocumentationIndex::documents`] and + /// [`DocumentationIndex::associations`] for source order. + pub fn fragments(&self) -> impl ExactSizeIterator>> { + self.references(&self.fragments) + } + + /// Logical documents in collection order (see [`Facts::fragments`]). + pub fn documents(&self) -> impl ExactSizeIterator>> { + self.references(&self.documents) + } + + /// Semantic owners in collection order (see [`Facts::fragments`]), + /// independently of metric spaces. + pub fn owners(&self) -> impl ExactSizeIterator>> { + self.references(&self.owners) + } + + /// Profile-qualified attachment records in collection order (see + /// [`Facts::fragments`]). + 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn document_order( + &self, + document: FactRef<'_, Document<'s>>, + ) -> Result { + 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(DocumentOrder::new( + 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, +} + +impl std::fmt::Display for FactError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::ForeignIndex => "documentation handle belongs to another index", + Self::MissingRecord => "documentation record is missing", + }) + } +} + +impl std::error::Error for FactError {} + +#[cfg(test)] +mod facade_type_tests { + use super::*; + + #[test] + fn builders_are_chainable_and_preserve_independent_choices() { + let context = DocumentationContext::default().with_logical_filename("lib.rs"); + assert_eq!(context.logical_filename.as_deref(), Some("lib.rs")); + let options = DocumentationOptions::default() + .with_profile(Profile::Rust) + .with_unbound_evidence(true) + .with_directive_evidence(true); + assert_eq!(options.profile, Profile::Rust); + assert!(options.retain_unbound); + assert!(options.retain_directives); + let options = options.with_unbound_evidence(false); + assert!(!options.retain_unbound); + assert!(options.retain_directives); + } + + #[test] + fn error_displays_and_sources_are_available_without_debug_formatting() { + fn is_error() {} + is_error::(); + is_error::(); + is_error::(); + is_error::(); + is_error::(); + assert_eq!( + FactError::ForeignIndex.to_string(), + "documentation handle belongs to another index" + ); + assert_eq!( + TextRangeError::ScalarBoundary.to_string(), + "documentation text range splits a UTF-8 scalar" + ); + let error = CollectionError::Source(SourceError::ForeignTree); + assert_eq!( + error.to_string(), + "documentation source: documentation node belongs to another tree" + ); + assert_eq!( + std::error::Error::source(&error) + .map(ToString::to_string) + .as_deref(), + Some("documentation node belongs to another tree") + ); + let error = OwnerError::Fact(FactError::MissingRecord); + assert_eq!( + std::error::Error::source(&error) + .map(ToString::to_string) + .as_deref(), + Some("documentation record is missing") + ); + assert!(std::error::Error::source(&CollectionError::Cancelled).is_none()); + } +} + +#[cfg(test)] +mod tests; 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..28850c57d --- /dev/null +++ b/big-code-analysis-ast/src/documentation/budget.rs @@ -0,0 +1,282 @@ +//! Fallible work accounting shared by source kernels and their infallible callers. + +use std::cell::Cell; +use std::convert::Infallible; + +use super::SourceError; + +/// Steps of collection work between two cancellation polls. +pub(crate) const STEP_INTERVAL: usize = 1_024; +/// Source bytes charged between two cancellation polls; a bulk copy is split +/// into chunks of at most this size so a poll is never further away. +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>; + 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, + Projection, + TsAwait, + Ranges, + Batch, + Text, + Decoration, + 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; + +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, + phase: Cell, +} + +// These count actual checkpoints, not calls to a generic NoBudget wrapper. +crate::observation::counter!(polls, cfg(any(test, feature = "test-support"))); +crate::observation::counter!(byte_charges, cfg(any(test, feature = "test-support"))); + +#[cfg(all(test, feature = "irules"))] +thread_local! { + static CHARGES: Cell<(usize, usize)> = const { Cell::new((0, 0)) }; +} + +#[cfg(all(test, feature = "irules"))] +pub(super) fn charges() -> (usize, usize) { + CHARGES.with(Cell::get) +} + +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.phase.get()); + self.steps.set(0); + self.bytes.set(0); + if crate::cancel::requested() { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + + fn step(&self) -> Result<(), SourceError> { + #[cfg(all(test, feature = "irules"))] + CHARGES.with(|charges| charges.set((charges.get().0 + 1, charges.get().1))); + self.charge(&self.steps, 1, STEP_INTERVAL) + } + + fn bytes(&self, count: usize) -> Result<(), SourceError> { + #[cfg(all(test, feature = "irules"))] + CHARGES.with(|charges| charges.set((charges.get().0, charges.get().1 + count))); + byte_charges::record(); + 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(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)] +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 { + let Ok(value) = result; + value +} + +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 {} + } +} + +#[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/byte_scan.rs b/big-code-analysis-ast/src/documentation/byte_scan.rs new file mode 100644 index 000000000..b97ef68f5 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/byte_scan.rs @@ -0,0 +1,113 @@ +//! 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"))); + +/// 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, + 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 new file mode 100644 index 000000000..976a52d2c --- /dev/null +++ b/big-code-analysis-ast/src/documentation/canonical.rs @@ -0,0 +1,150 @@ +//! Canonical identities and flat child batches; no parent recovery on lookup. + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::ops::Range; + +use super::budget::WorkBudget; +use super::{AssessmentId, NodeEvidence, OwnerId, QualificationId, SourceContext, SourceError}; +use crate::Node; + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(super) struct NodeId(pub(super) usize); + +super::opaque_id_debug!(NodeId); + +#[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) 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, + pub(super) qualification: super::qualifications::QualificationSet, + pub(super) signature_complex: bool, +} + +#[derive(Debug)] +pub(super) struct CanonicalNodes<'s> { + root: NodeEvidence<'s>, + by_id: HashMap, + // Zero-width and recovered nodes can share a tree-sitter id; every + // later holder of an id waits here, in insertion order. + shared_ids: 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(), + shared_ids: 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()); + match self.by_id.entry(evidence.node().id()) { + Entry::Vacant(slot) => { + slot.insert(id); + } + Entry::Occupied(_) => { + self.shared_ids + .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(), + qualifications: Vec::new(), + pending_parent: None, + following: None, + following_gap: false, + owner_context: id, + name_scope: NodeId(0), + qualification: super::qualifications::QualificationSet::default(), + signature_complex: false, + }); + id + } + + pub(super) fn node(&self, id: NodeId) -> tree_sitter::Node<'s> { + self.nodes[id.0].evidence.node() + } + + pub(super) fn children_of(&self, id: NodeId) -> &[NodeId] { + &self.children[self.nodes[id.0].children.clone()] + } + + 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); + } + let first = self.by_id.get(&node.id()).copied(); + let shared = self + .shared_ids + .get(&node.id()) + .into_iter() + .flatten() + .copied(); + for id in first.into_iter().chain(shared) { + 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..de45a24b1 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector.rs @@ -0,0 +1,1462 @@ +//! Coordinated source-order traversal and immutable-index construction. + +use std::collections::{HashMap, HashSet}; + +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 elixir; +mod irules; +#[cfg(test)] +mod irules_documentation_grammar; +mod pod; +mod pod_doubt; +mod pod_format; +mod pod_literal; +mod projections; +mod python; +pub(super) mod qualifications; +mod rust; +mod tcl; +#[cfg(any(test, feature = "test-support"))] +pub(super) use rust::{attribute_children, carrier_children}; + +enum Visit { + Enter(NodeId, usize), + Exit(NodeId, usize), +} + +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::empty(), + canonical, + context: DocumentationContext { logical_filename }, + options: options.clone(), + 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(), + 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(), + rust_values: HashMap::new(), + names: super::names::Names::default(), + irules_scan: crate::lang_helpers::tcl_scan::CommandScan::default(), + irules_selected: HashSet::new(), + irules_body_initial: HashSet::new(), + pod_doubt: pod_doubt::Doubt::default(), + pod_hidden: pod::Hidden::default(), + tcl_scan: tcl::CommandScan::default(), + ruff_open: Vec::new(), + shdoc: crate::lang_helpers::shdoc::Reading::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)?; + if profile == Profile::Elixir { + builder.elixir_attributes(&budget)?; + } + if profile != Profile::Helper { + 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)>, + rust_values: HashMap, + names: super::names::Names, + irules_scan: crate::lang_helpers::tcl_scan::CommandScan<'s>, + irules_selected: HashSet, + irules_body_initial: HashSet, + pod_doubt: pod_doubt::Doubt, + pod_hidden: pod::Hidden, + tcl_scan: tcl::CommandScan<'s>, + ruff_open: Vec>, + shdoc: crate::lang_helpers::shdoc::Reading<'s>, +} + +trait OwnerCandidates: Checker { + 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, '_>, + budget: &CollectionBudget, + ) -> Result { + match T::lang() { + 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) + } + _ => NativeRules::::target(node, code, ancestors, budget), + } + } +} + +// 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>) -> OwnerId { + owner_projections::record(); + let owner_id = self.push_owner(id, owner); + self.index.canonical.nodes[id.0].projection = Projection::Ready(vec![owner_id]); + owner_id + } + + /// Appends an owner with its per-owner index rows, leaving `id`'s + /// projection to the caller. + fn push_owner(&mut self, id: NodeId, owner: Owner<'s>) -> OwnerId { + 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.qualifications_by_owner.push(Vec::new()); + self.index.owner_nodes.push(id); + owner_id + } + + /// Appends a document with its per-document index rows. + fn push_document( + &mut self, + document: Document<'s>, + source_cleaned: Option>, + ) -> DocumentId { + let id = DocumentId(self.index.facts.documents.len()); + self.index.facts.documents.push(document); + self.index.source_cleaned.push(source_cleaned); + self.index.qualifications_by_document.push(Vec::new()); + id + } + + fn assess(&mut self, assessment: Assessment<'s>) -> AssessmentId { + let id = AssessmentId(self.index.assessments.len()); + self.index.assessments.push(assessment); + id + } + + /// Records a node's document-free assessment as pending work on `scope`. + fn pend( + &mut self, + scope: NodeId, + axis: AssessmentAxis, + reason: &'static str, + node: NodeEvidence<'s>, + ) { + let assessment = self.assess(Assessment { + axis, + reason, + node: Some(node), + document: None, + }); + self.index.canonical.nodes[scope.0].pending.push(assessment); + } + + #[allow(clippy::too_many_lines)] // Enter/exit visitor: one arm per profile hook. + 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(); + let mut substitutions = 0usize; + while let Some(visit) = stack.pop() { + budget.step()?; + match visit { + Visit::Exit(id, depth) => { + chain.truncate(depth); + if self.index.profile == Profile::Shdoc { + let node = Node::from_tree_sitter(self.index.canonical.node(id)); + if matches!(node.kind(), "command_substitution" | "process_substitution") { + substitutions -= 1; + } + // A function that Bash does not end here, or + // that holds the place where the shdoc scan + // stopped: its end is not confirmed. + if let Some(reason) = self.shdoc.leave(&node, budget)? { + self.index.canonical.nodes[id.0] + .qualification + .insert(reason); + } + } + if self.index.profile != Profile::Helper { + if self.index.profile == Profile::Irules { + self.irules_register(id, budget)?; + self.irules_body_assessment(id, budget)?; + } + self.finalize_projection(id, budget)?; + } + if self.index.profile == Profile::Ruff { + self.ruff_procedure(id, budget)?; + self.ruff_pending_forms(id, budget)?; + } + if self.index.profile == Profile::Rust + && matches!( + self.index.canonical.node(id).kind(), + "attribute_item" | "inner_attribute_item" + ) + { + let node = Node::from_tree_sitter(self.index.canonical.node(id)); + self.rust_attribute(id, &node, 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(); + chain.truncate(depth); + let node = Node::from_tree_sitter(self.index.canonical.node(id)); + bounds(node.as_tree_sitter(), self.index.source.bytes().len())?; + self.inherit_context(id, &node); + if self.index.profile == Profile::Ruff { + self.ruff_enter(id, budget)?; + } + if self.index.profile == Profile::Shdoc { + if matches!(node.kind(), "command_substitution" | "process_substitution") { + substitutions += 1; + } + let comment = T::is_comment(&node); + self.shdoc + .enter(&self.index.source, &node, comment, budget)?; + } + 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 = + 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, + || { + if self.index.profile == Profile::Helper { + return Ok(()); + } + self.register::(id, &node, ancestors, substitutions > 0, 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 + [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 record_children( + &mut self, + id: NodeId, + cursor: &mut tree_sitter::TreeCursor<'s>, + children: &mut Vec>, + 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.node(id); + children.clear(); + fields.clear(); + cursor.reset(node); + let record_fields = fields_needed(self.index.profile, node.kind()); + 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 record_fields { + 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; + 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() + .zip(fields) + .rev() + { + 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 + .index + .source + .covers_with_budget(record.evidence.node().end_byte()..start, budget)?; + } + record.field = *field; + record.following = following; + record.following_gap = trivia && following_gap; + next_start = Some(child_node.start_byte()); + if !trivia { + following = Some(child); + following_gap = false; + } else if self.index.profile == Profile::Rust && !attribute { + following_gap |= !self + .index + .source + .covers_with_budget(child_node.start_byte()..child_node.end_byte(), budget)?; + } + } + Ok(()) + } + + #[allow(clippy::too_many_lines)] // Distinct language-specific owner and wrapper projections share the canonical registration path. + fn register( + &mut self, + id: NodeId, + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + in_substitution: bool, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + if id.0 == 0 || self.shdoc.text() { + return Ok(()); + } + 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 + ) && ancestors.parent(node).is_some_and(|parent| { + matches!(parent.kind(), "export_statement" | "ambient_declaration") + }); + let typescript_child = self.index.profile == Profile::BcaTypescriptSource + && match node.kind() { + "function_expression" | "generator_function" | "class" => { + ancestors + .parent(node) + .is_some_and(|parent| parent.kind() == "export_statement") + && self.index.canonical.nodes[id.0].field == Some("value") + && ts_async_export_value(node, self.index.source.bytes(), budget)? + } + "internal_module" => { + ancestors.parent(node).is_some_and(|parent| { + matches!( + parent.kind(), + "export_statement" | "ambient_declaration" | "expression_statement" + ) + }) && match (node.child(0), node.child_by_field_name("name")) { + (Some(keyword), Some(name)) => ts_line_continues( + self.index.source.bytes(), + keyword.end_byte(), + name.start_byte(), + budget, + )?, + _ => false, + } + } + "assignment_expression" => { + let parent = ancestors.parent(node); + let statement = parent + .is_some_and(|parent| parent.kind() == "expression_statement") + || (parent.is_some_and(|parent| parent.kind() == "await_expression") + && ancestors + .iter(node) + .nth(1) + .is_some_and(|outer| outer.0.kind() == "expression_statement")); + statement && ts_using_assignment(node, self.index.source.bytes(), budget)? + } + "await_expression" => { + super::budget::in_phase(budget, super::budget::WorkPhase::TsAwait, || { + ts_await_using(node, self.index.source.bytes(), ancestors, budget) + })? + } + _ => false, + }; + if self.index.profile == Profile::Irules && T::lang() == crate::LANG::Irules { + return Ok(()); + } + let qualifies = if typescript_child { + true + } else if wrapper_child { + T::owner_candidate(node, self.index.source.bytes(), ancestors, budget)? + } else { + NativeRules::::target(node, self.index.source.bytes(), ancestors, budget)? + }; + 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) + || (self.index.profile == Profile::Doxygen && node.kind() == "expression_statement") + || node.has_error() + || conditional_kind(node.kind()) + || node.is_missing() + || (self.index.profile == Profile::Shdoc && self.shdoc.waits()) + || (self.index.profile == Profile::Shdoc && in_substitution) + { + 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 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 + .insert(UnresolvedReason::GrammarBoundary); + } + if conditional_kind(node.kind()) { + record.qualification.insert(UnresolvedReason::Conditional); + } + } + + // A comment row behind the place where the shdoc scan stopped is not + // read: it is no document and no candidate. If the rules would select its + // run, the run is withheld: one assessment on its first row says so. + fn shdoc_withhold( + &mut self, + id: NodeId, + node: &Node<'s>, + ancestors: Ancestors<'s, '_>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let mut first = None; + positional::source_comment_with_budget::, CollectionBudget>( + node, + ancestors, + &mut positional::SourceRequest { + context: &self.index.source, + retain_unbound: false, + retain_directives: true, + sink: &mut |run| first = run.members.first().map(|member| member.node), + }, + budget, + )?; + if let Some(first) = first { + let parent = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); + let scope = self.index.canonical.nodes[parent.0].owner_context; + self.pend( + scope, + AssessmentAxis::Selection, + "Rows without a confirmed reading may be literal text", + first, + ); + } + Ok(()) + } + + fn recognize( + &mut self, + id: NodeId, + node: &Node<'s>, + ancestors: Ancestors<'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) { + if self.index.profile == Profile::Python { + self.python_string(node, ancestors, budget)?; + } + return Ok(()); + } + if self.shdoc.unread() { + return Ok(()); + } + if self.shdoc.withheld() { + return self.shdoc_withhold::(id, node, ancestors, budget); + } + let pending = match super::forms::assess( + self.index.profile, + node, + ancestors, + &self.index.source, + budget, + )? { + super::forms::CommentAssessment::Pending(reason) => { + Some((AssessmentAxis::Selection, reason)) + } + super::forms::CommentAssessment::PendingOwner(reason) => { + Some((AssessmentAxis::Owner, reason)) + } + _ => None, + }; + if let Some((axis, reason)) = pending { + let parent = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); + let scope = self.index.canonical.nodes[parent.0].owner_context; + let evidence = self.index.canonical.nodes[id.0].evidence; + self.pend(scope, axis, reason, evidence); + } + if self.index.profile == Profile::Irules { + return Ok(()); + } + let mut marker_runs = Vec::new(); + markers::source_comment_with_budget::, _>( + node, + ancestors, + &mut markers::SourceRequest { + context: &self.index.source, + 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_with_budget::, _>( + 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), + }, + budget, + )?; + for run in positional_runs { + let retain = self.index.options.retain_unbound; + if let Some(run) = self.shdoc.confirm(run, retain, budget)? { + self.positional_run(run, budget)?; + } + } + 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 + } + + #[allow(clippy::too_many_lines)] // A marker run's target and binding rules. + 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 structural_drafts: HashMap = 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 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: None, + role: DocumentRole::Primary, + unresolved: member.uncertainty, + pending: false, + gap: run.prefix_gap || run.suffix_gap, + }; + 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.node(target).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"; + } + } + 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"/*!<")) { + let mut trailing = code_before; + if let Some(comma) = code_before + && self.index.canonical.node(comma).kind() == "," + && self.index.canonical.nodes[comma.0] + .parent + .is_some_and(|parent| { + self.index.canonical.node(parent).kind() == "enumerator_list" + }) + { + match enum_comma_predecessor( + &self.index.canonical, + &self.index.source, + comma, + budget, + )? { + CommaPredecessor::Gap => { + draft.gap = true; + draft.unresolved = Some(UnresolvedReason::ExcludedGap); + trailing = None; + } + CommaPredecessor::Enumerator(sibling) => trailing = Some(sibling), + CommaPredecessor::Unreadable => {} + } + } + draft.target = trailing; + draft.binding = + trailing.map(|id| self.index.canonical.nodes[id.0].evidence); + draft.pending = trailing.is_none(); + } + } + if let Some(gatherer) = gatherer { + structural_drafts.insert(gatherer, self.drafts.len()); + } + 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, + }; + let mut structural_tag = false; + for member in run.members { + budget.step()?; + structural_tag |= ldoc_standalone_member( + self.index.profile, + self.index.source.bytes(), + &member, + budget, + )?; + 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() { + set_positional_target( + &mut draft, + self.index.profile, + run.selection, + structural_tag, + ); + 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_with_budget(raw, budget)? + { + 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_with_budget(raw, budget)? + } else { + crate::lang_helpers::doc_text::jsdoc_file_with_budget(raw, budget)? + }; + 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 carrier = self.rust_carrier(id, budget)?; + if matches!(carrier, rust::Carrier::Other) { + 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.node(outer).kind(), + "mod_item" | "function_item" + ) + }) + } + }; + 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) + ); + let pending_scope = target + .or(self.index.canonical.nodes[id.0].parent) + .unwrap_or(NodeId(0)); + let evidence = self.index.canonical.nodes[id.0].evidence; + if unassessed { + let 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" + }; + self.pend(pending_scope, AssessmentAxis::Occurrence, reason, evidence); + } + self.pend( + pending_scope, + AssessmentAxis::Publication, + "Rust documentation/publication metadata awaits interpretation", + evidence, + ); + let rust::Carrier::Doc(value) = carrier else { + return Ok(()); + }; + 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)); + self.rust_values.insert(fragment, value); + Ok(()) + } + + fn finish(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + if self.index.profile == Profile::Irules { + self.irules_unbound(budget)?; + } + self.pod_end(budget)?; + self.coalesce_rust(budget)?; + 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 + ) { + self.pend( + NodeId(id), + AssessmentAxis::Owner, + "Recognized declaration requires a semantic projection", + self.index.canonical.nodes[id].evidence, + ); + } + 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(DocumentOrder::new( + first.start, + last.end, + document.role.source_rank(), + ordinal, + )); + } + for key in super::ordering::ordered(keys, budget)? { + budget.step()?; + self.index + .documents_ordered + .push(DocumentId(key.creation())); + } + 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.0] = 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(AssociationId(ordinal)); + } + for &id in &self.index.associations_ordered { + budget.step()?; + for &owner in &self.index.facts.associations[id.0].owners { + budget.step()?; + self.index.associations_by_owner[owner.0].push(id); + } + } + self.order_qualifications(&ranks, budget)?; + Ok(()) + } +} + +fn ldoc_standalone_member( + profile: Profile, + source: &[u8], + member: &positional::RunMember<'_>, + budget: &CollectionBudget, +) -> Result { + if profile != Profile::Ldoc || !member.selected { + return Ok(false); + } + crate::checker::lua::standalone_tag_with_budget( + &source[member.node.node().byte_range()], + budget, + ) + .map_err(Into::into) +} + +fn set_positional_target( + draft: &mut Draft<'_>, + profile: Profile, + selection: positional::RunSelection, + structural_tag: bool, +) { + match selection { + positional::RunSelection::Opener(positional::OpenerReason::FirstFile) => { + draft.target = Some(NodeId(0)); + draft.role = DocumentRole::FilePackage; + draft.binding = None; + } + positional::RunSelection::Opener(positional::OpenerReason::Tagged) + if profile == Profile::Ldoc && draft.target.is_some() && !structural_tag => {} + positional::RunSelection::Opener( + positional::OpenerReason::Explicit | positional::OpenerReason::Tagged, + ) => { + draft.target = None; + draft.pending = true; + draft.binding = None; + } + _ => {} + } +} + +fn ts_line_continues( + code: &[u8], + start: usize, + end: usize, + budget: &B, +) -> Result { + let Some(gap) = code.get(start..end) else { + return Ok(false); + }; + for (at, &byte) in gap.iter().enumerate() { + budget.bytes(1)?; + if matches!(byte, b'\r' | b'\n') + || (byte == 0xe2 + && matches!(gap.get(at..at + 3), Some(b"\xe2\x80\xa8" | b"\xe2\x80\xa9"))) + { + return Ok(false); + } + } + Ok(true) +} + +fn ts_using_assignment( + assignment: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + let (Some(using), Some(left)) = (assignment.child(0), assignment.child_by_field_name("left")) + else { + return Ok(false); + }; + if using.kind() != "using" || left.kind() != "identifier" { + return Ok(false); + } + ts_line_continues(code, using.end_byte(), left.start_byte(), budget) +} + +fn ts_async_export_value( + value: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + let Some(async_token) = value.child(0).filter(|child| child.kind() == "async") else { + return Ok(true); + }; + let function = super::budget::child(value, |child| child.kind() == "function", budget)?; + let Some(function) = function else { + return Ok(false); + }; + ts_line_continues(code, async_token.end_byte(), function.start_byte(), budget) +} + +fn ts_await_using<'s, B: WorkBudget>( + node: &Node<'s>, + code: &[u8], + ancestors: Ancestors<'s, '_>, + budget: &B, +) -> Result { + if ancestors + .parent(node) + .is_none_or(|parent| parent.kind() != "expression_statement") + { + return Ok(false); + } + let await_token = super::budget::child(node, |child| child.kind() == "await", budget)?; + let Some(await_token) = await_token else { + return Ok(false); + }; + let child = super::budget::child( + node, + |child| child.is_named() && !matches!(child.kind(), "comment" | "html_comment"), + budget, + )?; + match child { + Some(assignment) if assignment.kind() == "assignment_expression" => { + if !ts_line_continues( + code, + await_token.end_byte(), + assignment.start_byte(), + budget, + )? { + return Ok(false); + } + ts_using_assignment(&assignment, code, budget) + } + _ => Ok(false), + } +} + +/// What precedes the comma before a trailing (`///<`) enumerator comment. +enum CommaPredecessor { + /// Excluded bytes separate the comma from the code before it. + Gap, + /// The enumerator the comment documents. + Enumerator(NodeId), + /// No error-free enumerator precedes the comma. + Unreadable, +} + +// Steps back through the comma's canonical child batch: tree-sitter's +// `prev_sibling` re-derives the parent from the root on every call, which is +// quadratic over a documented enumerator list. +fn enum_comma_predecessor( + canonical: &CanonicalNodes<'_>, + source: &SourceContext<'_>, + comma: NodeId, + budget: &B, +) -> Result { + let record = &canonical.nodes[comma.0]; + let parent = record + .parent + .expect("invariant: the caller matched the comma's enumerator_list parent"); + let before = &canonical.children_of(parent)[..record.ordinal]; + let comma_start = canonical.node(comma).start_byte(); + for (at, &sibling) in before.iter().enumerate().rev() { + budget.step()?; + let node = canonical.node(sibling); + if !source.covers_with_budget(node.end_byte()..comma_start, budget)? { + return Ok(CommaPredecessor::Gap); + } + if node.kind() == "comment" { + continue; + } + if node.kind() != "enumerator" || node.has_error() { + return Ok(CommaPredecessor::Unreadable); + } + for &previous in before[..at].iter().rev() { + budget.step()?; + let previous = canonical.node(previous); + if previous.kind() != "comment" { + if previous.is_error() { + return Ok(CommaPredecessor::Unreadable); + } + break; + } + } + return Ok(CommaPredecessor::Enumerator(sibling)); + } + Ok(CommaPredecessor::Unreadable) +} + +fn is_wrapper(profile: Profile, kind: &str) -> bool { + match profile { + Profile::Doxygen => matches!(kind, "template_declaration" | "linkage_specification"), + Profile::Jsdoc => matches!(kind, "export_statement" | "ambient_declaration"), + Profile::BcaTypescriptSource => matches!( + kind, + "export_statement" + | "ambient_declaration" + | "expression_statement" + | "await_expression" + ), + Profile::Yard => matches!( + kind, + "if_modifier" | "unless_modifier" | "body_statement" | "block_body" | "then" + ), + Profile::Ldoc => kind == "block", + _ => false, + } +} + +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"), + Profile::GoDoc => matches!(kind, "field_declaration" | "method_elem" | "type_elem"), + Profile::Jsdoc | Profile::BcaTypescriptSource => matches!( + kind, + "lexical_declaration" + | "variable_declaration" + | "using_declaration" + | "expression_statement" + | "required_parameter" + | "optional_parameter" + ), + _ => false, + } +} + +fn fields_needed(profile: Profile, kind: &str) -> bool { + (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")) +} + +fn transparent_doc_context(profile: Profile, kind: &str) -> bool { + if profile == Profile::Kdoc && matches!(kind, "primary_constructor" | "getter" | "setter") { + return true; + } + 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 c_family_tests; +#[cfg(test)] +mod cancellation_tests; +#[cfg(test)] +mod cost_tests; +#[cfg(test)] +mod csharp_tests; +#[cfg(test)] +mod elixir_tests; +#[cfg(test)] +mod form_tests; +#[cfg(test)] +mod go_tests; +#[cfg(test)] +mod groovy_tests; +#[cfg(test)] +mod irules_tests; +#[cfg(test)] +mod java_tests; +#[cfg(test)] +mod js_tests; +#[cfg(test)] +mod kotlin_tests; +#[cfg(test)] +mod lua_tests; +#[cfg(test)] +mod named_tests; +#[cfg(test)] +mod perl_tests; +#[cfg(test)] +mod php_tests; +#[cfg(test)] +mod projection_tests; +#[cfg(test)] +mod python_tests; +#[cfg(test)] +mod remediation_tests; +#[cfg(test)] +mod ruby_tests; +#[cfg(test)] +mod rust_tests; +#[cfg(test)] +mod shdoc_tests; +#[cfg(test)] +mod tcl_tests; +#[cfg(test)] +mod tests; +#[cfg(test)] +mod ts_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..78337c096 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/assembly.rs @@ -0,0 +1,438 @@ +//! Draft composition and once-per-document text materialization. + +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.node(target).kind() == "mod_item" { + DocumentRole::FilePackage + } else { + DocumentRole::Primary + } + } + 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.unresolved, None | Some(UnresolvedReason::ExcludedGap)) + && 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()?; + let pending = matches!(self.rust_values.get(&fragment), Some(rust::Value::Pending)); + let binding = target + .filter(|_| self.index.canonical.node(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)) { + 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 + .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, + role: target.map_or(DocumentRole::Primary, |id| self.rust_role(id)), + unresolved: None, + pending: pending || target.is_none(), + gap: false, + }); + } + } + Ok(()) + } + + #[allow(clippy::too_many_lines)] // One pass over one draft: content, composition, owners, assessments, association. + pub(super) fn document( + &mut self, + mut draft: Draft<'s>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let literal = self.literal_draft(&draft); + let (content, attribute) = if literal { + (self.python_content(&draft, budget)?, false) + } else { + 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 + }; + if prelex { + draft.unresolved = Some(UnresolvedReason::GrammarBoundary); + } + let composition = if attribute { + Composition::AttributeSequence + } else if draft.fragments.len() == 1 { + Composition::Single + } else if literal { + Composition::LiteralConcatenation + } else { + Composition::CommentRun + }; + let document = self.push_document( + Document { + fragments: std::mem::take(&mut draft.fragments), + composition, + role: draft.role, + content, + }, + spelling, + ); + self.pod_pending_text(document); + 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() + && !draft.gap + && let Some(result) = self.named_document(document, draft.scope, budget)? + { + for candidate in result.owners { + budget.step()?; + self.candidate_qualifications(document, candidate, budget)?; + owners.push(candidate.owner); + } + 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 + .headline()); + for &id in ids { + budget.step()?; + owners.push(id); + } + } + Projection::Pending | Projection::Unsupported => pending = true, + } + } + if named_resolution == Some(Resolution::Unresolved(UnresolvedReason::Ambiguous)) { + draft.unresolved = None; + } + if pending { + 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 literal + && matches!( + self.index.facts.documents[document.0].content, + Content::PendingAdapter + ) + { + self.python_pending_text(document, &owners, draft.target, budget)?; + } + 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, + resolution: draft + .unresolved + .map(Resolution::Unresolved) + .or(named_resolution) + .unwrap_or(Resolution::Resolved), + convention: Convention(self.index.profile), + binding: draft.binding, + lexical_scope: self.index.canonical.nodes[draft.scope.0].evidence, + publication: self.publication(draft.target, budget)?, + }); + } + Ok(()) + } + + fn publication( + &self, + target: Option, + budget: &CollectionBudget, + ) -> Result { + if self.index.profile == Profile::Javadoc + && target.is_some_and(|target| { + self.index.canonical.node(target).kind() == "package_declaration" + }) + { + java_package_publication(self.index.context.logical_filename.as_deref(), budget) + } else { + Ok(Publication::Unknown) + } + } + + fn pending_document( + &mut self, + draft: &Draft<'s>, + document: DocumentId, + owners: &[OwnerId], + pending_attribute_composition: bool, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let assessment = self.assess(Assessment { + axis: if pending_attribute_composition { + AssessmentAxis::Composition + } else { + AssessmentAxis::Owner + }, + 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" + } 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() { + 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(()) + } + + 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.node(target).kind()) + { + let assessment = self.assess(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( + &mut self, + document: DocumentId, + scope: NodeId, + budget: &CollectionBudget, + ) -> Result, 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 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 qualification = record.qualification; + let mut result = self.names.resolve_in(name, scope, budget)?; + 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)); + } + } + Ok(None) + } + + fn render_draft( + &self, + draft: &mut Draft<'s>, + budget: &CollectionBudget, + ) -> Result<(Content<'s>, bool), CollectionError> { + let mut keys = 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; + 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 result = if self.index.profile == Profile::Irules + && self.irules_continued_middle(draft, budget)? + { + Ok(Content::Unavailable(UnavailableReason::GrammarBoundary)) + } else 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, + &fragments, + budget, + ) + }; + 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)) + } + + 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), + } + } +} + +pub(super) fn java_package_publication( + filename: Option<&str>, + budget: &B, +) -> Result { + let Some(name) = filename else { + return Ok(Publication::Unknown); + }; + let expected = b"package-info.java"; + if name.len() != expected.len() { + return Ok(Publication::Ineligible); + } + for (&actual, &wanted) in name.as_bytes().iter().zip(expected) { + crate::documentation::byte_scan::one(budget).map_err(Into::into)?; + if actual != wanted { + return Ok(Publication::Ineligible); + } + } + Ok(Publication::Eligible) +} 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..506892780 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/assessment_tests.rs @@ -0,0 +1,397 @@ +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 + ); + }); +} + +#[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/c_family_tests.rs b/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs new file mode 100644 index 000000000..7c21cc1eb --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/c_family_tests.rs @@ -0,0 +1,2381 @@ +//! 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 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::*; +#[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, +} + +/// 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 { + 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(piece) => Run::Copied(piece.range()), + 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(); + let range = span(fragment.get().source()); + assert_eq!(fragment.get().form(), FragmentForm::Comment); + assert_eq!( + fragment.get().node().map(|carrier| site(carrier.node())), + Some(("comment", range.clone())) + ); + (candidate.get().disposition, range) + }) + .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), + })); + // 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, + 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); + view_from_parser(language, &parser) +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn view_from_parser(language: LANG, parser: &AnyParser) -> View { + 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; ///\n\"x\" @file".to_owned(), + map: vec![ + (0..7, Copied(4..11)), + (7..8, Synthetic), + (8..27, Copied(34..53)), + (27..28, Synthetic), + (28..37, Copied(76..85)), + ], + }, + Doc { + role: DocumentRole::Primary, + composition: Composition::CommentRun, + fragments: vec![104..116, 117..130], + text: "first\nsecond".to_owned(), + map: vec![ + (0..5, Copied(108..113)), + (5..6, Synthetic), + (6..12, Copied(121..127)), + ], + }, + ], + associations: vec![ + Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::File(0..157)], + binding: None, + }, + bound( + 1, + Resolution::Resolved, + vec![Holder::Node(("function_definition", 131..156))], + ), + ], + ..View::default() + }; + assert_eq!(view(language, source), expected); + // The sibling grammar must preserve the complete public view on the shared fixture. + if language == LANG::Mozcpp { + assert_eq!(view(LANG::Mozcpp, source), view(LANG::Cpp, source)); + } + assert_eq!( + view( + language, + &crate::test_support::documentation::source("doxygen-quote.h") + ), + View::default() + ); + assert_eq!( + view( + language, + &crate::test_support::documentation::source("doxygen-cdata.h") + ), + View::default() + ); + // expected: both quoted structural lookalikes are detached. Retention + // publishes their evidence in source order, not sorted by disposition. + let source = b"/** \"@file\" */\n\n/** */\n"; + let parser = clean(language, source); + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound: true, + ..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); + assert_eq!( + typed, + View { + evidence: vec![ + (CandidateDisposition::Unattached, 0..14), + (CandidateDisposition::Unattached, 16..42), + ], + ..View::default() + } + ); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn unit2_gather_tail(language: LANG) { + // expected: the first two comments gather as a file document; only the + // last comment is bound forward to the prototype after the gatherer. + assert_eq!( + view( + language, + b"/** head */\n/** @file */\n/** tail */\nint f(void);\n" + ), + View { + documents: vec![ + Doc { + role: DocumentRole::FilePackage, + composition: Composition::CommentRun, + fragments: vec![0..11, 12..24], + text: "head\n@file".to_owned(), + map: vec![ + (0..4, Copied(4..8)), + (4..5, Synthetic), + (5..10, Copied(16..21)) + ], + }, + comment(25..36, "tail", [(0..4, Copied(29..33))]), + ], + associations: vec![ + Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::File(0..50)], + binding: None + }, + bound( + 1, + Resolution::Resolved, + vec![Holder::Node(("declaration", 37..49))] + ), + ], + ..View::default() + } + ); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +#[allow(clippy::too_many_lines)] +fn unit2_comma(language: LANG) { + // expected: the comma is an unnamed child of enumerator_list, and A is its + // previous non-comment named sibling; the analogous variable remains pending. + let parser = clean(language, b"enum E { A, /**< ta */ B };\n"); + let comma = node_at(&parser, ",", 10..11); + assert!(!comma.is_named()); + assert_eq!(comma.parent().map(site), Some(("enumerator_list", 7..26))); + assert_eq!(comma.prev_sibling().map(site), Some(("enumerator", 9..10))); + assert_eq!( + view(language, b"enum E { A, /**< ta */ B };\n"), + owned( + comment(12..22, "ta", [(0..2, Copied(17..19))]), + vec![Holder::Node(("enumerator", 9..10))] + ) + ); + let spaced = clean(language, b"enum E { A /* gap */, /**< ta */ B };\n"); + let gap_comment = node_at(&spaced, "comment", 11..20); + assert_eq!(gap_comment.next_sibling().map(site), Some((",", 20..21))); + assert_eq!( + gap_comment.prev_sibling().map(site), + Some(("enumerator", 9..10)) + ); + assert_eq!( + view(language, b"enum E { A /* gap */, /**< ta */ B };\n"), + owned( + comment(22..32, "ta", [(0..2, Copied(27..29))]), + vec![Holder::Node(("enumerator", 9..10))] + ) + ); + // The excluded bytes hide the actual enumerator B between A and the comma. + let source = b"enum E { A, B, /**< ta */ C };\n"; + let point = |at: usize| tree_sitter::Point::new(0, at); + let ranges = [ + tree_sitter::Range { + start_byte: 0, + end_byte: 10, + start_point: point(0), + end_point: point(10), + }, + tree_sitter::Range { + start_byte: 13, + end_byte: source.len(), + start_point: point(13), + end_point: point(source.len()), + }, + ]; + let mut raw = tree_sitter::Parser::new(); + raw.set_language(&language.tree_sitter_language().unwrap()) + .unwrap(); + raw.set_included_ranges(&ranges).unwrap(); + let tree = raw.parse(source, None).unwrap(); + assert!(!tree.root_node().has_error()); + let index = collect( + language, + &tree, + source, + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let docs: Vec<_> = index.documents().collect(); + assert_eq!(docs.len(), 1); + assert_eq!(docs[0].get().role(), DocumentRole::Primary); + assert_eq!(docs[0].get().composition(), Composition::Single); + let fragment = index.facts().document_fragment(docs[0], 0).unwrap(); + assert_eq!(span(fragment.get().source()), 15..25); + assert_eq!(fragment.get().form(), FragmentForm::Comment); + assert_eq!( + fragment.get().node().map(|node| site(node.node())), + Some(("comment", 15..25)) + ); + assert_eq!( + index + .complete_text(docs[0]) + .unwrap() + .map(|text| text.text().to_owned()), + None + ); + assert!(matches!( + docs[0].get().content(), + Content::Unavailable(UnavailableReason::ExcludedGap) + )); + let associations: Vec<_> = index.associations().collect(); + assert_eq!(associations.len(), 1); + assert_eq!( + index.facts().associated_document(associations[0]), + Ok(docs[0]) + ); + assert_eq!( + associations[0].get().resolution, + Resolution::Unresolved(UnresolvedReason::ExcludedGap) + ); + assert_eq!(associations[0].get().owner_count(), 0); + assert!(associations[0].get().binding.is_none()); + assert_eq!(index.assessments().len(), 3); + assert_eq!(index.evidence().len(), 0); + if language == LANG::Mozcpp { + assert_eq!( + view(LANG::Mozcpp, b"enum E { A, /**< ta */ B };\n"), + view(LANG::Cpp, b"enum E { A, /**< ta */ B };\n") + ); + } + // expected: this comma belongs to the call's argument_list, not the + // enumerator_list. All initializer commas keep a pending document, not A. + for (source, comma_at, comment_at, text_at, text) in [ + ( + b"enum E { A = foo(1, /**< bad */ 2), B };\n".as_slice(), + 18..19, + 20..31, + 25..28, + "bad", + ), + ( + b"enum E { A = foo(1, /*!< bang */ 2), B };\n".as_slice(), + 18..19, + 20..32, + 25..29, + "bang", + ), + ( + b"enum E { A = foo(bar(1, /**< nested */ 2)), B };\n".as_slice(), + 22..23, + 24..38, + 29..35, + "nested", + ), + ] { + let parser = clean(language, source); + let comma = node_at(&parser, ",", comma_at.clone()); + assert_eq!( + comma.parent().map(|parent| parent.kind()), + Some("argument_list") + ); + let expected = View { + documents: vec![comment( + comment_at, + text, + [(0..text.len(), Copied(text_at))], + )], + assessments: unordered([pending(AWAITS_OWNER, Some((",", comma_at)), Some(0))]), + ..View::default() + }; + assert_eq!(view(language, source), expected); + let context = DocumentationContext::default(); + let options = DocumentationOptions { + retain_unbound: true, + ..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); + assert_eq!(typed, expected); + } + // Recovery puts `#ifdef` in an ERROR before X in C, and Objc keeps + // the comma within the preprocessor node. Neither may resolve X. + let source = b"enum E {\n A\n#ifdef X\n , /**< ta */ B\n#endif\n};\n"; + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 0); + let assessments: Vec<_> = index.assessments().collect(); + assert!(assessments.iter().any(|assessment| { + assessment.get().axis == AssessmentAxis::Owner + && assessment.get().reason == AWAITS_OWNER + && index.assessed_document(*assessment).unwrap().is_some() + })); + if language == LANG::C { + assert_eq!( + assessments[0].get().node.map(|node| site(node.node())), + Some((",", 24..25)) + ); + } + 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() + } + ); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn unit2_linkage(language: LANG) { + let one = b"/** e */\nextern \"C\" void f(void);\n"; + assert_eq!( + view(language, one), + View { + documents: vec![comment(0..8, "e", [(0..1, Copied(4..5))])], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::Node(("declaration", 20..33))], + binding: Some(("linkage_specification", 9..33)), + }], + ..View::default() + } + ); + if matches!(language, LANG::Cpp | LANG::Mozcpp) { + // expected: the inner variable declaration has one Field slot; + // the outer linkage specification remains the binding. + assert_eq!( + view(language, b"/** e */\nextern \"C++\" int x;\n"), + View { + documents: vec![comment(0..8, "e", [(0..1, Copied(4..5))])], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![field_slot(0, 26..27, &("declaration", 22..28))], + binding: Some(("linkage_specification", 9..28)), + }], + ..View::default() + } + ); + } + // A comment inside the header is skipped, not projected as an owner. + assert_eq!( + view( + language, + b"/** e */\nextern /* between */ \"C\" /* between */ void f(void);\n" + ), + View { + documents: vec![comment(0..8, "e", [(0..1, Copied(4..5))])], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::Node(("declaration", 48..61))], + binding: Some(("linkage_specification", 9..61)), + }], + ..View::default() + } + ); + // A declaration_list cannot project to one declaration, even when a tool picks first. + assert_eq!( + view( + language, + b"/** e */\nextern \"C\" { void f(void); void g(void); }\n" + ), + View { + documents: vec![comment(0..8, "e", [(0..1, Copied(4..5))])], + assessments: unordered([ + pending( + AWAITS_OWNER, + Some(("linkage_specification", 9..51)), + Some(0) + ), + pending( + NEEDS_PROJECTION, + Some(("linkage_specification", 9..51)), + None + ), + ]), + ..View::default() + } + ); +} + +#[cfg(any(feature = "cpp", feature = "mozcpp"))] +fn unit2_template(language: LANG) { + // expected: the outer template remains the binding for every projected inner owner. + for (source, owner, binding) in [ + ( + b"/** t */\ntemplate void f(T x);\n".as_slice(), + ("declaration", 31..43), + ("template_declaration", 9..43), + ), + ( + b"/** t */\ntemplate void f(T x) {}\n".as_slice(), + ("function_definition", 31..45), + ("template_declaration", 9..45), + ), + ( + b"/** t */\ntemplate class C {};\n".as_slice(), + ("class_specifier", 31..41), + ("template_declaration", 9..42), + ), + ( + b"/** t */\ntemplate template class C {};\n".as_slice(), + ("class_specifier", 53..63), + ("template_declaration", 9..64), + ), + ( + b"/** t */\ntemplate /* between */ void f(T x);\n".as_slice(), + ("declaration", 45..57), + ("template_declaration", 9..57), + ), + ( + b"/** b */\ntemplate requires true void g(T);\n".as_slice(), + ("declaration", 45..55), + ("template_declaration", 9..55), + ), + ( + b"/** p */\ntemplate struct S {};\n".as_slice(), + ("struct_specifier", 31..46), + ("template_declaration", 9..47), + ), + ] { + let text = match source.get(4).copied() { + Some(b'b') => "b", + Some(b'p') => "p", + _ => "t", + }; + assert_eq!( + view(language, source), + View { + documents: vec![comment(0..8, text, [(0..1, Copied(4..5))])], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::Node(owner)], + binding: Some(binding), + }], + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } + // Characterization: forward declarations and concepts have no supported + // inner owner yet. The wrapper keeps a pending assessment, not a resolved + // association and not an assertion of semantic absence. + for (source, wrapper) in [ + ( + b"/** f */\ntemplate struct S;\n".as_slice(), + 9..40, + ), + ( + b"/** f */\ntemplate class C;\n".as_slice(), + 9..39, + ), + ( + b"/** f */\ntemplate concept C = true;\n".as_slice(), + 9..48, + ), + ] { + assert_eq!( + view(language, source), + View { + documents: vec![comment(0..8, "f", [(0..1, Copied(4..5))])], + assessments: unordered([ + pending( + AWAITS_OWNER, + Some(("template_declaration", wrapper.clone())), + Some(0) + ), + pending( + NEEDS_PROJECTION, + Some(("template_declaration", wrapper)), + None + ), + ]), + ..View::default() + }, + "{}", + source.escape_ascii() + ); + } +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn unit2_recovered_enumerator(language: LANG) { + // expected: the error after A does not damage A itself or the preceding comma. + let source = b"enum E { A, /**< ta */ %% B };\n"; + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + assert_eq!( + view_from_parser(language, &parser), + View { + documents: vec![comment(12..22, "ta", [(0..2, Copied(17..19))])], + associations: vec![bound( + 0, + Resolution::Resolved, + vec![Holder::Node(("enumerator", 9..10))] + )], + assessments: unordered([pending( + NEEDS_PROJECTION, + Some(("enum_specifier", 0..29)), + None + ),]), + ..View::default() + } + ); +} + +#[cfg(any(feature = "cpp", feature = "mozcpp"))] +fn unit2_recovered_wrappers(language: LANG) { + for (source, wrapper, declaration, label) in [ + ( + b"/** t */\ntemplate void f(%%);\n".as_slice(), + "template_declaration", + 31..42, + "t", + ), + ( + b"/** e */\nextern \"C\" void f(%%);\n".as_slice(), + "linkage_specification", + 20..31, + "e", + ), + ] { + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + let wrapped = (wrapper, 9..declaration.end); + let declaration = ("declaration", declaration); + assert_eq!( + view_from_parser(language, &parser), + View { + documents: vec![comment(0..8, label, [(0..1, Copied(4..5))])], + assessments: unordered([ + pending( + "Complex signature awaits exact named matching", + Some(declaration.clone()), + None + ), + pending(AWAITS_OWNER, Some(wrapped.clone()), Some(0)), + pending(NEEDS_PROJECTION, Some(wrapped), None), + pending(NEEDS_PROJECTION, Some(declaration), None), + ]), + ..View::default() + } + ); + } +} + +// Characterization only: an unescaped physical LF inside an ordinary quoted +// string is invalid C/Objective-C. This pins today's grammar recovery, not +// conformant source documentation or an intended @file attachment. +#[cfg(any(feature = "c", feature = "objc"))] +fn unit2_invalid_multiline_quote(language: LANG) { + let (source, fragment, text_start, scope, declaration, root_len) = match language { + LANG::C => ( + b"const char *s = \"\n/** @file */\nint f(void);\n\";\n".as_slice(), + 18..30, + 22..27, + ("string_literal", 16..30), + ("declaration", 0..43), + 47, + ), + LANG::Objc => ( + b"id s = @\"\n/** @file */\nint f(void);\n\";\n".as_slice(), + 10..22, + 14..19, + ("string_literal", 7..22), + ("declaration", 0..35), + 39, + ), + other => panic!("not a characterization variant: {other:?}"), + }; + let parser = AnyParser::parse(language, source.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + assert_eq!( + node_at(&parser, "comment", fragment.clone()) + .parent() + .map(site), + Some(scope) + ); + assert_eq!( + view_from_parser(language, &parser), + View { + documents: vec![Doc { + role: DocumentRole::FilePackage, + ..comment(fragment, "@file", [(0..5, Copied(text_start))]) + }], + associations: vec![Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::File(0..root_len)], + binding: None + }], + assessments: unordered([pending(NEEDS_PROJECTION, Some(declaration), None)]), + ..View::default() + } + ); +} + +#[cfg(feature = "c")] +#[test] +fn c_unit2_invalid_multiline_quote() { + unit2_invalid_multiline_quote(LANG::C); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_invalid_multiline_quote() { + unit2_invalid_multiline_quote(LANG::Objc); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn unit2_literal_boundaries(language: LANG) { + let ordinary = b"const char *s = \"\\n/** @file */\\nint f(void);\\n\";\nint f(void);\n"; + let line = b"// /** @file */ int f(void);\nint f(void);\n"; + let block = b"/*\n/** @file * /\nint f(void);\n*/\nint f(void);\n"; + for source in [ordinary.as_slice(), line.as_slice(), block.as_slice()] { + let parser = clean(language, source); + assert_eq!(parser.root_node().end_byte(), source.len()); + assert_eq!(view(language, source), View::default()); + } +} + +#[cfg(any(feature = "cpp", feature = "mozcpp"))] +fn unit2_cpp_raw_literal(language: LANG) { + let source = b"const char *s = R\"(\n/** @file */\nint f(void);\n)\";\nint f(void);\n"; + assert_eq!(view(language, source), View::default()); +} + +#[cfg(feature = "objc")] +fn unit2_objc_literal() { + let source = b"id s = @\"\\n/** @file */\\nint f(void);\\n\";\nint f(void);\n"; + assert_eq!(view(LANG::Objc, source), View::default()); +} + +#[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] +fn unit2_line_gatherer_keeps_tail(language: LANG) { + // expected: Doxygen's adjacent /// row below @file belongs to the file, too; + // the block after those rows is a separate declaration document. + let source = b"/// head\n/// @file\n/// after\n/** tail */\nint f(void);\n"; + let expected = View { + documents: vec![ + Doc { + role: DocumentRole::FilePackage, + composition: Composition::CommentRun, + fragments: vec![0..8, 9..18, 19..28], + text: "head\n@file\nafter".to_owned(), + map: vec![ + (0..4, Copied(4..8)), + (4..5, Synthetic), + (5..10, Copied(13..18)), + (10..11, Synthetic), + (11..16, Copied(23..28)), + ], + }, + comment(29..40, "tail", [(0..4, Copied(33..37))]), + ], + associations: vec![ + Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::File(0..54)], + binding: None, + }, + bound( + 1, + Resolution::Resolved, + vec![Holder::Node(("declaration", 41..53))], + ), + ], + ..View::default() + }; + assert_eq!(view(language, source), expected); + // A retained candidate cannot mask a duplicate or a superseded tail. + let parser = clean(language, source); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + let index = parser + .documentation(&DocumentationContext::default(), &options) + .unwrap(); + assert_eq!(published(&index, parser.ts_tree().root_node()), expected); + assert_eq!(index.evidence().len(), 0); + + // A blank row ends the line gatherer's continuation, not the file document. + assert_eq!( + view( + language, + b"/// @file\n/// file second line\n\n/// func doc\nint f(void);\n" + ), + View { + documents: vec![ + Doc { + role: DocumentRole::FilePackage, + composition: Composition::CommentRun, + fragments: vec![0..9, 10..30], + text: "@file\nfile second line".to_owned(), + map: vec![ + (0..5, Copied(4..9)), + (5..6, Synthetic), + (6..22, Copied(14..30)) + ] + }, + comment(32..44, "func doc", [(0..8, Copied(36..44))]), + ], + associations: vec![ + Link { + document: 0, + resolution: Resolution::Resolved, + owners: vec![Holder::File(0..58)], + binding: None + }, + bound( + 1, + Resolution::Resolved, + vec![Holder::Node(("declaration", 45..57))] + ), + ], + ..View::default() + } + ); +} + +#[cfg(feature = "c")] +#[derive(Default)] +struct Unit2Counting { + steps: std::cell::Cell, + fail_at: Option, +} + +#[cfg(feature = "c")] +impl crate::documentation::budget::WorkBudget for Unit2Counting { + type Error = SourceError; + // test-lang-gates: hand-written(c) — method belongs to the c-gated budget implementation. + #[cfg(feature = "c")] + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + // test-lang-gates: hand-written(c) — method belongs to the c-gated budget implementation. + #[cfg(feature = "c")] + 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(()) + } + } + // test-lang-gates: hand-written(c) — method belongs to the c-gated budget implementation. + #[cfg(feature = "c")] + fn bytes(&self, _: usize) -> Result<(), SourceError> { + Ok(()) + } +} + +#[cfg(feature = "c")] +#[test] +fn c_unit2_comma_budget_has_two_sides_and_cancels_each_step() { + let source = b"enum E { A /* gap */, /**< ta */ B };\n"; + let parser = clean(LANG::C, source); + let index = collect( + LANG::C, + parser.ts_tree(), + parser.code(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let comma = index + .canonical + .lookup(node_at(&parser, ",", 20..21)) + .unwrap(); + let predecessor = |budget: &Unit2Counting| { + super::enum_comma_predecessor(&index.canonical, &index.source, comma, budget) + }; + let budget = Unit2Counting::default(); + let super::CommaPredecessor::Enumerator(owner) = predecessor(&budget).unwrap() else { + panic!("the enumerator before the comment's comma owns it"); + }; + assert_eq!(site(index.canonical.node(owner)), ("enumerator", 9..10)); + let steps = budget.steps.get(); + // expected: comment and enumerator, one gap lookup, one earlier-sibling check. + assert_eq!(steps, 4); + for fail_at in 1..=steps { + let budget = Unit2Counting { + fail_at: Some(fail_at), + ..Unit2Counting::default() + }; + assert!(matches!(predecessor(&budget), Err(SourceError::Cancelled))); + assert_eq!(budget.steps.get(), fail_at); + } +} + +#[cfg(feature = "c")] +#[test] +fn c_unit2_quoted_fixture() { + unit2_quoted_fixture(LANG::C); +} +#[cfg(feature = "c")] +#[test] +fn c_unit2_gather_tail() { + unit2_gather_tail(LANG::C); +} +#[cfg(feature = "c")] +#[test] +fn c_unit2_comma() { + unit2_comma(LANG::C); +} +#[cfg(feature = "c")] +#[test] +fn c_unit2_linkage() { + unit2_linkage(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_quoted_fixture() { + unit2_quoted_fixture(LANG::Cpp); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_gather_tail() { + unit2_gather_tail(LANG::Cpp); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_comma() { + unit2_comma(LANG::Cpp); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_linkage() { + unit2_linkage(LANG::Cpp); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_template() { + unit2_template(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_quoted_fixture() { + unit2_quoted_fixture(LANG::Mozcpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_gather_tail() { + unit2_gather_tail(LANG::Mozcpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_comma() { + unit2_comma(LANG::Mozcpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_linkage() { + unit2_linkage(LANG::Mozcpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_template() { + unit2_template(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_quoted_fixture() { + unit2_quoted_fixture(LANG::Objc); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_gather_tail() { + unit2_gather_tail(LANG::Objc); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_comma() { + unit2_comma(LANG::Objc); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_linkage() { + unit2_linkage(LANG::Objc); +} +#[cfg(feature = "c")] +#[test] +fn c_unit2_recovered_enumerator() { + unit2_recovered_enumerator(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_recovered_enumerator() { + unit2_recovered_enumerator(LANG::Cpp); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_recovered_wrappers() { + unit2_recovered_wrappers(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_recovered_enumerator() { + unit2_recovered_enumerator(LANG::Mozcpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_recovered_wrappers() { + unit2_recovered_wrappers(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_recovered_enumerator() { + unit2_recovered_enumerator(LANG::Objc); +} +#[cfg(feature = "c")] +#[test] +fn c_unit2_literal_boundaries() { + unit2_literal_boundaries(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_literal_boundaries() { + unit2_literal_boundaries(LANG::Cpp); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_cpp_raw_literal() { + unit2_cpp_raw_literal(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_literal_boundaries() { + unit2_literal_boundaries(LANG::Mozcpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_cpp_raw_literal() { + unit2_cpp_raw_literal(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_literal_boundaries() { + unit2_literal_boundaries(LANG::Objc); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_objc_literal() { + unit2_objc_literal(); +} +#[cfg(feature = "c")] +#[test] +fn c_unit2_line_gatherer_keeps_tail() { + unit2_line_gatherer_keeps_tail(LANG::C); +} +#[cfg(feature = "cpp")] +#[test] +fn cpp_unit2_line_gatherer_keeps_tail() { + unit2_line_gatherer_keeps_tail(LANG::Cpp); +} +#[cfg(feature = "mozcpp")] +#[test] +fn mozcpp_unit2_line_gatherer_keeps_tail() { + unit2_line_gatherer_keeps_tail(LANG::Mozcpp); +} +#[cfg(feature = "objc")] +#[test] +fn objc_unit2_line_gatherer_keeps_tail() { + unit2_line_gatherer_keeps_tail(LANG::Objc); +} + +// Count each new source-selection budget route apart from collection's other work. +#[cfg(feature = "c")] +#[derive(Default)] +struct Unit2SelectionCounting { + steps: std::cell::Cell, + byte_charges: std::cell::Cell, + fail_at: Option, +} + +#[cfg(feature = "c")] +impl crate::documentation::budget::WorkBudget for Unit2SelectionCounting { + type Error = SourceError; + // test-lang-gates: hand-written(c) — this method belongs to the c-only budget. + #[cfg(feature = "c")] + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + // test-lang-gates: hand-written(c) — this method belongs to the c-only budget. + #[cfg(feature = "c")] + 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(()) + } + } + // test-lang-gates: hand-written(c) — this method belongs to the c-only budget. + #[cfg(feature = "c")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.byte_charges.set(self.byte_charges.get() + count); + Ok(()) + } +} + +#[cfg(feature = "c")] +fn unit2_selection_with_budget<'s>( + parser: &'s AnyParser, + context: &SourceContext<'s>, + budget: &Unit2SelectionCounting, +) -> Result>, SourceError> { + let root = parser.root_node(); + let comment = root + .children() + .filter(|n| n.kind() == "comment") + .last() + .unwrap(); + let chain = [root]; + let ancestors = crate::Ancestors::known(&chain); + let mut output = Vec::new(); + crate::documentation::streaming::markers::source_comment_with_budget::< + crate::documentation::recognition::NativeRules, + _, + >( + &comment, + ancestors, + &mut crate::documentation::streaming::markers::SourceRequest { + context, + retain_unbound: false, + sink: &mut |run| output.push(run), + }, + budget, + )?; + Ok(output) +} + +#[cfg(feature = "c")] +#[test] +fn c_unit2_selection_budget_has_two_sides_and_cancels_each_step() { + for source in [ + b"/** head */\n/** @file */\n/** tail */\nint f(void);\n".as_slice(), + b"/// head\n/// @file\n/// after\n/** tail */\nint f(void);\n".as_slice(), + ] { + let parser = AnyParser::parse(LANG::C, source.to_vec(), None, None).unwrap(); + assert!(!parser.ts_tree().root_node().has_error()); + let context = SourceContext::new(parser.ts_tree(), parser.code()); + let budget = Unit2SelectionCounting::default(); + let result = unit2_selection_with_budget(&parser, &context, &budget).unwrap(); + assert_eq!(result.len(), 1); + assert_eq!(result[0].target.unwrap().node().kind(), "declaration"); + let steps = budget.steps.get(); + // expected: block form charges 41 steps, line continuation charges 70: + // The block's 41 = target check 2 + backward stretch 6 + reverse 1 + // + gather-call 1 + gather probes 2 + gathered 2 + offset search 2 + // + bound-selection 1 + member/coverage/classification 24; + // the contiguous line form's 70 adds 29 for one more gathered + // member, its line adjacency check and the longer source scan. + let expected = if source.starts_with(b"///") { 70 } else { 41 }; + assert!(steps >= expected, "{steps}"); + assert!(steps <= expected, "{steps}"); + assert!(budget.byte_charges.get() > 0); + for fail_at in 1..=steps { + let probe = Unit2SelectionCounting { + fail_at: Some(fail_at), + ..Unit2SelectionCounting::default() + }; + assert!( + matches!( + unit2_selection_with_budget(&parser, &context, &probe), + Err(SourceError::Cancelled) + ), + "{fail_at}" + ); + assert_eq!(probe.steps.get(), fail_at); + } + } +} 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..b74b7d618 --- /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(); + // 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, + &crate::documentation::budget::CollectionBudget::default(), + ) + }); + assert!(matches!(result, Err(SourceError::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..e75675326 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/cost_tests.rs @@ -0,0 +1,205 @@ +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); +} + +#[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); + } +} + +#[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/csharp_tests.rs b/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs new file mode 100644 index 000000000..2458b5992 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/csharp_tests.rs @@ -0,0 +1,1715 @@ +//! 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, except in the last test, which pins the parse-tree shapes +//! the other tests rely on. + +#![allow(clippy::single_range_in_vec_init, clippy::naive_bytecount)] + +#[cfg(feature = "csharp")] +use crate::documentation::budget::WorkBudget; +#[cfg(feature = "csharp")] +use crate::documentation::*; +#[cfg(feature = "csharp")] +use crate::test_support::for_each_node_with_chain; +#[cfg(feature = "csharp")] +use crate::{Ancestors, AnyParser, Checker, CsharpCode, LANG}; +#[cfg(feature = "csharp")] +use std::cell::Cell; +#[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(Clone, 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. +#[cfg(feature = "csharp")] +#[derive(Clone, Debug, PartialEq, Eq)] +struct Doc { + role: DocumentRole, + 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 = "csharp")] +#[derive(Debug, Default, PartialEq, Eq)] +struct View { + documents: Vec, + owners: Vec<(Resolution, &'static str, Range)>, + slots: Vec)>>, + evidence: Vec<(CandidateDisposition, Range)>, + assessments: usize, +} + +/// The expected document of one comment. +#[cfg(feature = "csharp")] +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 document of adjacent comments that join. +#[cfg(feature = "csharp")] +fn comment_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(), + } +} + +/// The expected view of one document that one resolved node owns, with no retained +/// 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)], + slots: vec![Vec::new()], + evidence: Vec::new(), + assessments: 0, + } +} + +#[cfg(feature = "csharp")] +fn field_document( + fragment: Range, + text: &str, + content: Range, + kind: &'static str, + declaration: Range, + names: &[Range], + resolution: Resolution, +) -> View { + // bca: suppress(nargs) -- each argument independently pins document bytes or one field-owner property. + View { + documents: vec![comment(fragment, text, [(0..text.len(), Copied(content))])], + owners: vec![(resolution, kind, declaration)], + slots: vec![ + names + .iter() + .enumerate() + .map(|(ordinal, name)| (SlotRole::Field, ordinal, name.clone())) + .collect(), + ], + evidence: Vec::new(), + assessments: 0, + } +} + +/// 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(piece) => Run::Copied(piece.range()), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +#[cfg(feature = "csharp")] +fn fragment_span(item: &Fragment<'_>) -> Range { + assert_eq!(item.form(), FragmentForm::Comment); + let range = span(item.source()); + let node = item.node().unwrap().node(); + assert_eq!(node.kind(), "comment"); + assert_eq!(node.byte_range(), range); + range +} + +#[cfg(feature = "csharp")] +fn published(index: &DocumentationIndex<'_>) -> View { + // bca: suppress(halstead) -- one reading of the published documents, associations, and retained evidence. + let facts = index.facts(); + let documents = index + .documents() + .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(); + fragment_span(fragment.get()) + }) + .collect(), + text: complete.text().to_owned(), + map: complete + .mappings() + .iter() + .map(|run| (run.output.range(), run_of(&run.origin))) + .collect(), + } + }) + .collect(); + let associations: Vec<_> = index + .associations() + .enumerate() + .map(|(position, association)| { + // bca: suppress(halstead) -- one association's node or ordered slots share binding and scope checks. + let attachment = association.get(); + let listed: Vec<_> = (0..attachment.owner_count()) + .map(|at| facts.associated_owner(association, at).unwrap()) + .collect(); + assert_ne!(attachment.owner_count(), 0); + let (declaration, slots) = match listed[0].get() { + Owner::Node(declared) => { + assert_eq!(listed.len(), 1); + (declared.node(), Vec::new()) + } + Owner::Slot(_) => { + let mut found = Vec::new(); + let mut enclosing = None; + for (ordinal, owner) in listed.iter().enumerate() { + let Owner::Slot(slot) = owner.get() else { + panic!("a field slot, found {:?}", owner.get()) + }; + let parent = facts.slot_enclosing(*owner).unwrap(); + let Owner::Node(node) = parent.get() else { + panic!("a declaration, found {:?}", parent.get()) + }; + assert!(enclosing.is_none_or(|previous| previous == node.node())); + enclosing = Some(node.node()); + assert_eq!(slot.ordinal, ordinal); + found.push((slot.role, slot.ordinal, span(&slot.source))); + } + (enclosing.unwrap(), found) + } + other => panic!("a declaration or field slot, found {other:?}"), + }; + // 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(); + assert_eq!(document, index.documents().nth(position).unwrap()); + assert_eq!(attachment.convention.name(), "csharp-xml"); + assert_eq!(attachment.publication, Publication::Unknown); + 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(), + ), + slots, + ) + }) + .collect(); + let (owners, slots) = associations.into_iter().unzip(); + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); + let evidence = index + .evidence() + .map(|candidate| { + let fragment = index.evidence_fragment(candidate).unwrap(); + (candidate.get().disposition, fragment_span(fragment.get())) + }) + .collect(); + View { + documents, + owners, + slots, + evidence, + assessments: index.assessments().len(), + } +} + +/// A parse whose tree holds no syntax error. +#[cfg(feature = "csharp")] +fn clean(source: &[u8]) -> AnyParser { + let parser = AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); + 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<'p>( + parser: &'p AnyParser, + options: &DocumentationOptions, +) -> [DocumentationIndex<'p>; 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}" + ); + // 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( + 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 mut expected = owned( + comment_run( + [16..20, 21..25], + "a\nb", + [ + (0..1, Copied(19..20)), + (1..2, Synthetic), + (2..3, Copied(24..25)), + ], + ), + "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() { + let rows: [(&[u8], Doc, Range); 4] = [ + ( + b"/// a\n// p\nclass C {}", + comment(0..5, "a", [(0..1, Copied(4..5))]), + 11..21, + ), + ( + b"///d\n#nullable enable\nclass C {}", + comment(0..4, "d", [(0..1, Copied(3..4))]), + 22..32, + ), + ( + 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\n", + comment(0..4, "r", [(0..1, Copied(3..4))]), + 15..25, + ), + ]; + for (source, document, owner) in rows { + assert_eq!( + view(source), + 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 { + 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) + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_excluded_placements_give_no_document() { + 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()); + assert_eq!( + retained(source), + View { + evidence: vec![(CandidateDisposition::Unattached, unattached)], + ..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 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")] +#[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)] + ); + assert!(top[0].is_extra()); + assert_eq!(&source[top[0].end_byte()..top[1].start_byte()], ending); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_two_declarations_keep_document_and_association_order() { + // Both independent comments precede different already-supported declarations. + let source = concat!( + "class C {\n///first\nint P { get; set; }\n", + "///second\nevent System.Action E { add {} remove {} }\n}" + ) + .as_bytes(); + let parser = clean(source); + let both = indexes(&parser, &DocumentationOptions::default()); + let seen = agreed(&both); + let first = owned( + comment(10..18, "first", [(0..5, Copied(13..18))]), + "property_declaration", + 19..38, + ); + let second = owned( + comment(39..48, "second", [(0..6, Copied(42..48))]), + "event_declaration", + 49..91, + ); + assert_eq!( + seen, + View { + documents: [first.documents[0].clone(), second.documents[0].clone()].into(), + owners: [first.owners[0].clone(), second.owners[0].clone()].into(), + slots: [first.slots[0].clone(), second.slots[0].clone()].into(), + ..View::default() + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_local_and_top_level_fields_do_not_publish_documents() { + let local = b"class C { void M() { ///local\nint x = 1; } }"; + let top = b"///top\nint x = 1;"; + for (source, range) in [(local.as_slice(), 21..29), (top, 0..6)] { + assert_eq!(view(source), View::default()); + assert_eq!( + retained(source), + View { + evidence: vec![(CandidateDisposition::Unattached, range)], + ..View::default() + } + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +#[allow(clippy::type_complexity, clippy::single_range_in_vec_init)] +fn csharp_field_const_and_event_names_each_own_one_field_slot() { + let cases: [(&[u8], Range, Range, &str, &[Range]); 3] = [ + ( + b"class C {\n///both\nint a, b;\n}", + 10..17, + 18..27, + "field_declaration", + &[22..23, 25..26], + ), + ( + b"class C {\n///one\nconst int K = 1;\n}", + 10..16, + 17..33, + "field_declaration", + &[27..28], + ), + ( + b"class C {\n///both\nevent System.Action E1, E2;\n}", + 10..17, + 18..45, + "event_field_declaration", + &[38..40, 42..44], + ), + ]; + for (source, fragment, declaration, kind, names) in cases { + let text = if kind == "field_declaration" && names.len() == 1 { + "one" + } else { + "both" + }; + let content = fragment.start + 3..fragment.end; + assert_eq!( + view(source), + field_document( + fragment, + text, + content, + kind, + declaration, + names, + Resolution::Resolved, + ), + "{}", + source.escape_ascii(), + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_field_modifiers_fixed_buffers_comments_and_unicode_keep_name_slots() { + for (source, fragment, text, owner, names) in [ + ( + b"class C {\n///both\n[System.Obsolete] private static readonly int a = 1, b;\n}" + .as_slice(), + 10..17, + "both", + 18..73, + vec![64..65, 71..72], + ), + ( + b"unsafe class C {\n///buf\nfixed int a[4];\n}".as_slice(), + 17..23, + "buf", + 24..39, + vec![34..35], + ), + ( + b"class C {\n///both\nint /* c */ a, /* c */ b;\n}".as_slice(), + 10..17, + "both", + 18..43, + vec![30..31, 41..42], + ), + ( + "class C {\n///unicode\nint Δ;\n}".as_bytes(), + 10..20, + "unicode", + 21..28, + vec![25..27], + ), + ( + b"class C {\n///unnamed\nint _;\n}".as_slice(), + 10..20, + "unnamed", + 21..27, + vec![25..26], + ), + ] { + assert_eq!( + view(source), + field_document( + fragment.clone(), + text, + fragment.start + 3..fragment.end, + "field_declaration", + owner, + &names, + Resolution::Resolved, + ), + "{}", + source.escape_ascii(), + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_later_documentation_inside_a_field_is_only_retained_evidence() { + let source = b"class C {\n///both\nint a, ///later\nb;\n}"; + let expected = field_document( + 10..17, + "both", + 13..17, + "field_declaration", + 18..36, + &[22..23, 34..35], + Resolution::Resolved, + ); + assert_eq!(view(source), expected); + let mut retained_view = expected; + retained_view + .evidence + .push((CandidateDisposition::Unattached, 25..33)); + assert_eq!(retained(source), retained_view); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_two_unattached_fragments_keep_their_source_order() { + let source = b"class C {\n///first\nint a, ///left\nb;\n// plain\n///right\n}"; + let mut expected = field_document( + 10..18, + "first", + 13..18, + "field_declaration", + 19..36, + &[23..24, 34..35], + Resolution::Resolved, + ); + assert_eq!(view(source), expected); + expected.evidence = vec![ + (CandidateDisposition::Unattached, 26..33), + (CandidateDisposition::Unattached, 46..54), + ]; + assert_eq!(retained(source), expected); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_field_and_event_documents_remain_distinct_in_one_class() { + let source = b"class C {\n///first\nint a;\n///second\nevent System.Action B;\n}"; + let parser = clean(source); + let both = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&both); + let first = field_document( + 10..18, + "first", + 13..18, + "field_declaration", + 19..25, + &[23..24], + Resolution::Resolved, + ); + let second = field_document( + 26..35, + "second", + 29..35, + "event_field_declaration", + 36..58, + &[56..57], + Resolution::Resolved, + ); + assert_eq!( + actual, + View { + documents: [first.documents[0].clone(), second.documents[0].clone()].into(), + owners: [first.owners[0].clone(), second.owners[0].clone()].into(), + slots: [first.slots[0].clone(), second.slots[0].clone()].into(), + evidence: Vec::new(), + assessments: 0, + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_error_field_constant_and_event_declarations_stay_pending() { + for (source, kind, range) in [ + ( + b"class C {\n///broken\nint a = ;\n}".as_slice(), + "field_declaration", + 20..29, + ), + ( + b"class C {\n///broken\nconst int K = ;\n}".as_slice(), + "field_declaration", + 20..35, + ), + ( + b"class C {\n///broken\nevent System.Action E = ;\n}".as_slice(), + "event_field_declaration", + 20..45, + ), + ] { + let parser = AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); + let field = node_at(&parser, kind, range); + assert!(field.has_error()); + let both = indexes(&parser, &DocumentationOptions::default()); + for index in &both { + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 0); + assert_eq!(index.assessments().len(), 3); + assert!(index.node_projection(field).unwrap().pending()); + assert!(index.node_associations(field).unwrap().projection_pending()); + } + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_broken_field_does_not_erase_the_next_documented_field() { + let source = b"class C {\n///a\nint x = ;\n///b\nint y;\n}"; + let parser = AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); + let both = indexes(&parser, &DocumentationOptions::default()); + for index in &both { + assert_eq!(index.documents().len(), 2); + assert_eq!(index.associations().len(), 1); + assert_eq!(index.assessments().len(), 3); + assert!( + index + .node_projection(node_at(&parser, "field_declaration", 15..24)) + .unwrap() + .pending() + ); + let good = node_at(&parser, "field_declaration", 30..36); + let projection = index.node_projection(good).unwrap(); + assert!(!projection.pending()); + assert_eq!(projection.owners().len(), 1); + let association = index.associations().next().unwrap(); + let second = index.documents().nth(1).unwrap(); + assert_eq!( + index.facts().associated_document(association).unwrap(), + second + ); + assert_eq!(index.complete_text(second).unwrap().unwrap().text(), "b"); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_field_inside_conditional_keeps_conditional_uncertainty() { + let source = b"class C {\n#if X\n///branch\nint a;\n#endif\n}"; + let mut expected = field_document( + 16..25, + "branch", + 19..25, + "field_declaration", + 26..32, + &[30..31], + Resolution::Unresolved(UnresolvedReason::Conditional), + ); + expected.assessments = 1; // The preproc_if itself is still pending. + assert_eq!(view(source), expected); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_document_before_a_conditional_wrapper_stays_pending_while_field_has_slots() { + let source = b"class C {\n///wrapper\n#if X\nint a;\n#endif\n}"; + let parser = clean(source); + let both = indexes(&parser, &DocumentationOptions::default()); + for index in &both { + assert_eq!(index.documents().len(), 1); + assert_eq!(index.associations().len(), 0); + assert_eq!(index.assessments().len(), 3); + let field = node_at(&parser, "field_declaration", 27..33); + let projection = index.node_projection(field).unwrap(); + assert!(!projection.pending()); + assert_eq!(projection.owners().len(), 1); + assert!(!index.node_associations(field).unwrap().projection_pending()); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_skipped_nested_class_field_keeps_the_existing_conditional_association() { + // Characterization, not conditional-compilation policy: a compiler skips this class. + let source = + b"#if false\nclass C {\n///LIT\nint Y;\n}\n#endif\nclass D {\n///REAL\nint Z;\n}\n"; + let parser = clean(source); + let first = field_document( + 20..26, + "LIT", + 23..26, + "field_declaration", + 27..33, + &[31..32], + Resolution::Unresolved(UnresolvedReason::Conditional), + ); + let second = field_document( + 53..60, + "REAL", + 56..60, + "field_declaration", + 61..67, + &[65..66], + Resolution::Resolved, + ); + assert_eq!( + agreed(&indexes(&parser, &DocumentationOptions::default())), + View { + documents: [first.documents[0].clone(), second.documents[0].clone()].into(), + owners: [first.owners[0].clone(), second.owners[0].clone()].into(), + slots: [first.slots[0].clone(), second.slots[0].clone()].into(), + assessments: 1, + ..View::default() + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_verbatim_backslash_does_not_swallow_the_following_field() { + // Characterization: C# verbatim strings do not escape a quote with backslash. + let source = concat!( + "class C {\n string s = @\"a\\\";\n", + " /// LIT\n public int Y;\n", + " string t = @\"\";\n /// REAL\n", + " public int Z;\n}\n" + ) + .as_bytes(); + let parser = clean(source); + let first = field_document( + 36..62, + "LIT", + 40..62, + "field_declaration", + 67..80, + &[78..79], + Resolution::Resolved, + ); + let second = field_document( + 105..132, + "REAL", + 109..132, + "field_declaration", + 137..150, + &[148..149], + Resolution::Resolved, + ); + assert_eq!( + agreed(&indexes(&parser, &DocumentationOptions::default())), + View { + documents: [first.documents[0].clone(), second.documents[0].clone()].into(), + owners: [first.owners[0].clone(), second.owners[0].clone()].into(), + slots: [first.slots[0].clone(), second.slots[0].clone()].into(), + ..View::default() + } + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_field_slot_and_declaration_queries_keep_distinct_owner_identities() { + let source = b"class C {\n///both\nint a, b;\n}"; + let parser = clean(source); + let declaration = node_at(&parser, "field_declaration", 18..27); + for index in indexes(&parser, &DocumentationOptions::default()) { + let association = index.associations().next().unwrap(); + let names: Vec<_> = (0..2) + .map(|at| index.facts().associated_owner(association, at).unwrap()) + .collect(); + assert_ne!(names[0], names[1]); + let projection = index.node_projection(declaration).unwrap(); + assert!(!projection.pending()); + assert!(projection.owners().eq(names.iter().copied())); + assert!( + index + .node_owners(declaration) + .unwrap() + .eq(names.iter().copied()) + ); + assert!(matches!( + index.node_associations(declaration), + Err(OwnerError::MultipleOwners) + )); + for slot in names { + assert!( + index + .owner_associations(slot) + .unwrap() + .associations() + .eq([association]) + ); + let enclosing = index.facts().slot_enclosing(slot).unwrap(); + assert!(matches!(enclosing.get(), Owner::Node(_))); + assert_eq!( + index + .owner_associations(enclosing) + .unwrap() + .associations() + .len(), + 0 + ); + } + for (kind, range) in [ + ("variable_declarator", 22..23), + ("identifier", 22..23), + ("variable_declarator", 25..26), + ] { + let node = node_at(&parser, kind, range); + assert!(matches!( + index.node_projection(node), + Err(OwnerError::UnsupportedOwner) + )); + } + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_undocumented_field_still_has_slots_without_a_document() { + let source = b"class C { int a, b; }"; + let parser = clean(source); + let field = node_at(&parser, "field_declaration", 10..19); + let both = indexes(&parser, &DocumentationOptions::default()); + assert_eq!(agreed(&both), View::default()); + for index in &both { + let projection = index.node_projection(field).unwrap(); + assert!(!projection.pending()); + assert_eq!(projection.owners().len(), 2); + assert_eq!(index.node_owners(field).unwrap().count(), 2); + assert_eq!(index.facts().owners().len(), 5); + assert!(matches!( + index.node_associations(field), + Err(OwnerError::MultipleOwners) + )); + for owner in projection.owners() { + let query = index.owner_associations(owner).unwrap(); + assert_eq!(query.associations().len(), 0); + assert_eq!(query.assessments().count(), 0); + } + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_slot_projection_requires_the_whole_declaration_included() { + let source = b"class C {\n///both\nint a, b;\n}"; + let included = [0..24, 25..source.len()]; // Space between comma and b is excluded. + let ranges: Vec<_> = included + .iter() + .map(|range| { + let point = |at: usize| { + let before = &source[..at]; + tree_sitter::Point::new( + before.iter().filter(|byte| **byte == b'\n').count(), + before + .iter() + .rev() + .take_while(|byte| **byte != b'\n') + .count(), + ) + }; + 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::Csharp.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + assert!(!tree.root_node().has_error()); + let options = DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }; + let index = collect( + LANG::Csharp, + &tree, + source, + &DocumentationContext::default(), + &options, + ) + .unwrap(); + assert_eq!(index.documents().len(), 0); + assert_eq!(index.associations().len(), 0); + assert_eq!(index.evidence().len(), 1); + let field = tree + .root_node() + .named_descendant_for_byte_range(18, 27) + .unwrap(); + assert_eq!(field.kind(), "field_declaration"); + assert!(index.node_projection(field).unwrap().pending()); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_error_beside_an_intact_field_does_not_erase_its_slot() { + let source = b"class C {\n///d\nint a;\n%\n}"; + let parser = AnyParser::parse(LANG::Csharp, source.to_vec(), None, None).unwrap(); + assert!(parser.root_node().has_error()); + let field = node_at(&parser, "field_declaration", 15..21); + assert!(!field.has_error()); + let mut expected = field_document( + 10..14, + "d", + 13..14, + "field_declaration", + 15..21, + &[19..20], + Resolution::Resolved, + ); + expected.assessments = 1; // Only the containing class remains pending. + assert_eq!( + agreed(&indexes(&parser, &DocumentationOptions::default())), + expected + ); +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_tuple_pattern_field_declarator_stays_pending_without_slots() { + let source = b"class C {\n/// doc\nint (a, b) = (1, 2);\n}\n"; + let parser = clean(source); + let declaration = node_at(&parser, "field_declaration", 18..38); + let variables = node_at(&parser, "variable_declarator", 22..37); + assert_eq!(variables.child(0).unwrap().kind(), "tuple_pattern"); + let both = indexes(&parser, &DocumentationOptions::default()); + assert_eq!( + agreed(&both), + View { + documents: vec![comment(10..17, "doc", [(0..3, Copied(14..17))])], + assessments: 2, + ..View::default() + } + ); + for index in &both { + assert!(index.node_projection(declaration).unwrap().pending()); + assert!( + index + .node_associations(declaration) + .unwrap() + .projection_pending() + ); + assert!( + !index + .facts() + .owners() + .any(|owner| matches!(owner.get(), Owner::Slot(_))) + ); + } +} + +#[cfg(feature = "csharp")] +#[derive(Default)] +struct Counting { + steps: Cell, + bytes: Cell, + fail_at: Option, +} + +#[cfg(feature = "csharp")] +impl WorkBudget for Counting { + type Error = SourceError; + + #[cfg(feature = "csharp")] + 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 = "csharp")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + Ok(()) + } +} + +#[cfg(feature = "csharp")] +fn wide_fields(width: usize) -> String { + let names: Vec<_> = (0..width).map(|at| format!("v{at}")).collect(); + format!("class C {{\n///audit\nint {};\n}}", names.join(", ")) +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_declarator_scan_charges_every_structural_child() { + for (source, declaration, steps, names) in [ + ( + b"class C {\n///both\nint a, b;\n}".as_slice(), + 18..27, + 5, + vec![22..23, 25..26], + ), + ( + b"class C {\n///both\nint /* c */ a, /* c */ b;\n}".as_slice(), + 18..43, + 7, + vec![30..31, 41..42], + ), + ( + b"class C {\n///both\n[System.Obsolete] private static readonly int a = 1, b;\n}" + .as_slice(), + 18..73, + 9, + vec![64..65, 71..72], + ), + ] { + let parser = clean(source); + let index = indexes(&parser, &DocumentationOptions::default()); + let id = index[0] + .canonical + .lookup(node_at(&parser, "field_declaration", declaration)) + .unwrap(); + let count = Counting::default(); + let found = super::projections::csharp_declarator_names(&index[0].canonical, id, &count) + .unwrap() + .unwrap(); + assert_eq!(count.steps.get(), steps); + assert_eq!(count.bytes.get(), 0); + assert_eq!( + found + .iter() + .map(|name| index[0].canonical.nodes[name.0] + .evidence + .node() + .byte_range()) + .collect::>(), + names, + ); + for fail_at in 1..=steps { + let budget = Counting { + fail_at: Some(fail_at), + ..Counting::default() + }; + assert!(matches!( + super::projections::csharp_declarator_names(&index[0].canonical, id, &budget), + Err(SourceError::Cancelled) + )); + assert_eq!(budget.steps.get(), fail_at); + } + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_field_width_has_linear_owner_and_name_work() { + for width in [8, 64, 256] { + let source = wide_fields(width); + let parser = clean(source.as_bytes()); + let before = observations(); + let indexes = indexes(&parser, &DocumentationOptions::default()); + let after = observations(); + let index = &indexes[0]; + let declaration = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap(); + let id = index + .canonical + .lookup(declaration.as_tree_sitter()) + .unwrap(); + let budget = Counting::default(); + let found = super::projections::csharp_declarator_names(&index.canonical, id, &budget) + .unwrap() + .unwrap(); + // expected: the first variable_declaration child, then its type, width + // declarators and width - 1 commas: 1 + (2 * width). + assert_eq!(budget.steps.get(), 2 * width + 1); + assert_eq!(found.len(), width); + // expected: file, class, declaration, and one field slot per name. + assert_eq!(index.facts().owners().len(), width + 3); + assert_eq!( + index.associations().next().unwrap().get().owner_count(), + width + ); + assert_eq!(after.field_requests - before.field_requests, 0); + assert_eq!(after.field_lookups - before.field_lookups, 0); + assert_eq!(after.renders - before.renders, 2); + assert_eq!( + after.visits - before.visits, + 2 * parser.root_node().preorder().count() + ); + } +} + +#[cfg(feature = "csharp")] +#[test] +fn csharp_wide_fields_cancel_in_both_the_name_scan_and_slot_loop() { + let width = 2048; + let source = wide_fields(width); + let parser = clean(source.as_bytes()); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = observations(); + parser.documentation(&context, &options).unwrap(); + let polls = observations().polls - before.polls; + let mut slots = 0; + let mut scan = 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))); + let owners = after.owner_projections - before.owner_projections; + let searches = after.intersection_searches - before.intersection_searches; + if owners == 3 && searches < width + 1 { + slots += 1; + } + if owners == 2 && after.visits - before.visits == parser.root_node().preorder().count() - 1 + { + scan += 1; + } + } + // expected: each of 2048 slots charges three steps, yielding 5 or 6 polls. + assert!((5..=6).contains(&slots), "slots={slots}"); + // expected: 4097 scanned children charge at least 4 and at most 5 polls. + assert!((4..=5).contains(&scan), "scan={scan}"); + assert_eq!( + crate::documentation::budget::cancel_after(polls + 1, || { + parser.documentation(&context, &options) + }) + .unwrap() + .associations() + .next() + .unwrap() + .get() + .owner_count(), + width, + ); +} diff --git a/big-code-analysis-ast/src/documentation/collector/elixir.rs b/big-code-analysis-ast/src/documentation/collector/elixir.rs new file mode 100644 index 000000000..c99b166c8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/elixir.rs @@ -0,0 +1,489 @@ +//! Elixir documentation attributes, read once the walk has recorded the tree. +//! +//! A `@moduledoc` documents its `defmodule … do … end` module. A `@doc` +//! documents the group of clauses that the next definition statement of the +//! same module body belongs to. The value must be one plain string. Every +//! other documentation attribute stays visible as a pending assessment. + +use super::*; +use crate::documentation::text::{TextBuilder, TextError}; + +mod body; +pub(super) mod syntax; + +use body::{Carrier, Group, Reading}; +use syntax::{Attribute, Gap, Kind, Word, at_operator, attribute, covers, kind, step}; + +const OUTSIDE: &str = "Elixir documentation attribute outside a module body awaits interpretation"; +const TEMPLATE: &str = + "Elixir documentation attribute in a quoted or unreadable call awaits interpretation"; +const RECOVERED: &str = "Recovered Elixir documentation attribute awaits interpretation"; +const UNOWNED: &str = "Elixir documentation attribute awaits an owner projection"; + +// The axis and the reason of the assessment that a document without a text carries. +type Pending = (AssessmentAxis, &'static str); + +const VALUE: Pending = ( + AssessmentAxis::Composition, + "Elixir documentation attribute value awaits decoding", +); +const SEVERAL: Pending = ( + AssessmentAxis::Selection, + "Several Elixir documentation attributes await selection", +); + +// Where the second pass stands when it reaches a node. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Place { + Code, + // Inside a `quote`, or a call whose first word is not fully included. + Template, + // Below a statement that nothing separates from the one before it. + Unreached, + // The children of a `defmodule` call with a body. + Module { call: NodeId, body: NodeId }, + // The body of that module. + Body(NodeId), + Statement, + // The children of an `@` operator: its operand is no call statement. + Attribute, +} + +impl Place { + fn of(self, child: NodeId) -> Self { + match self { + Self::Module { call, body } if child == body => Self::Body(call), + Self::Module { .. } => Self::Code, + place => place, + } + } + + // Whether anything below is read as a module or a definition. + fn reads(self) -> bool { + !matches!(self, Self::Template | Self::Unreached) + } + + // Why a documentation attribute that no body pass reads has no document. + fn reason(self, joined: bool) -> &'static str { + match self { + Self::Template => TEMPLATE, + Self::Unreached => RECOVERED, + _ if joined => RECOVERED, + _ => OUTSIDE, + } + } +} + +#[derive(Clone, Copy)] +struct Visit { + id: NodeId, + place: Place, + // How the node stands to the statement before it, if it is a statement + // or follows a recovery. + gap: Option, + // The grammar recovered in a statement that is, or holds, the node. + doubt: bool, +} + +struct Attachment { + role: DocumentRole, + binding: Option, + hidden: bool, + // The grammar recovered in a statement around the owner. + doubt: bool, + publication: Publication, +} + +// The text of one plain string, or why the attributes have none yet. +fn content<'s, B: WorkBudget>( + index: &DocumentationIndex<'s>, + carriers: &[Carrier], + budget: &B, +) -> Result<(Content<'s>, Option), SourceError> { + let [ + Carrier { + text: Some(text), .. + }, + ] = carriers + else { + let reason = if carriers.len() == 1 { VALUE } else { SEVERAL }; + return Ok((Content::PendingAdapter, Some(reason))); + }; + if syntax::rejected(&index.source.bytes()[text.clone()], budget).map_err(Into::into)? { + return Ok((Content::PendingAdapter, Some(VALUE))); + } + let mut builder = TextBuilder::default(); + match builder.source(&index.source, text.clone(), budget) { + Ok(()) => Ok((builder.finish(), None)), + Err(TextError::Source(error)) => Err(error), + Err(TextError::Unavailable(reason)) => Ok((Content::Unavailable(reason), None)), + } +} + +impl Builder<'_> { + // A second pass over the recorded tree, top down, so that a `quote` and + // a joined statement are known before what they hold. It reads nothing + // that it or `finish` writes. + pub(super) fn elixir_attributes( + &mut self, + budget: &B, + ) -> Result<(), SourceError> { + let tear = syntax::tear(&self.index.canonical, budget).map_err(Into::into)?; + let mut stack = vec![Visit { + id: NodeId(0), + place: Place::Code, + gap: None, + doubt: false, + }]; + while let Some(visit) = stack.pop() { + self.elixir_visit(visit, tear, &mut stack, budget)?; + } + Ok(()) + } + + // Reads one node and pushes its children, the first on top. + fn elixir_visit( + &mut self, + mut visit: Visit, + tear: Option, + stack: &mut Vec, + budget: &B, + ) -> Result<(), SourceError> { + step(budget)?; + let inner = self.elixir_node(&visit, budget)?; + let gaps = self.elixir_gaps(&mut visit, inner, tear, budget)?; + let children = self.index.canonical.children_of(visit.id); + for (at, &child) in children.iter().enumerate().rev() { + step(budget)?; + stack.push(Visit { + id: child, + place: inner.of(child), + gap: gaps.get(at).copied().flatten(), + doubt: visit.doubt, + }); + } + Ok(()) + } + + // Reads one node and answers where its children stand. + fn elixir_node( + &mut self, + visit: &Visit, + budget: &B, + ) -> Result { + let &Visit { id, place, gap, .. } = visit; + let joined = gap == Some(Gap::Joined); + let attribute = at_operator(&self.index.canonical, id, budget).map_err(Into::into)?; + // The body pass has read an attribute that is a statement. + if attribute && place != Place::Statement { + self.elixir_stray(id, place.reason(joined), budget)?; + } + if !place.reads() { + return Ok(place); + } + // The operand of `@` names an attribute and calls nothing. + if place != Place::Attribute && kind(&self.index.canonical, id) == "call" { + return self.elixir_call(id, place, joined, budget); + } + Ok(match place { + _ if joined => Place::Unreached, + _ if attribute => Place::Attribute, + Place::Body(_) => Place::Statement, + _ => Place::Code, + }) + } + + // What the pass knows before it descends from a node: whether the + // grammar recovered in the statement that the node is, and how the + // children stand to the statements before them. The body of a module is + // read with the same answers, so no pass reads a statement that another + // found joined. + fn elixir_gaps( + &mut self, + visit: &mut Visit, + inner: Place, + tear: Option, + budget: &B, + ) -> Result>, SourceError> { + if !inner.reads() { + return Ok(Vec::new()); + } + let canonical = &self.index.canonical; + // A statement below a broken one is in doubt already. + visit.doubt = visit.doubt + || visit.gap.is_some() + && syntax::broken(canonical, visit.id, budget).map_err(Into::into)?; + let gaps = syntax::gaps(&self.index, visit.id, tear, budget)?; + if let Place::Body(module) = visit.place { + self.elixir_module(module, visit, &gaps, budget)?; + } + Ok(gaps) + } + + // Reads a call by its first word. A joined call is a statement that the + // compiler does not reach: nothing below it is read, and a module or a + // definition stays visible as a pending owner. + fn elixir_call( + &mut self, + id: NodeId, + place: Place, + joined: bool, + budget: &B, + ) -> Result { + let word = syntax::word(&self.index, id, budget)?; + if !joined && word == Word::Quote { + return Ok(Place::Template); + } + if !joined && word == Word::Module { + let body = syntax::module_body(&self.index.canonical, id, budget); + // The body is read when the pass reaches it. + if let Some(body) = body.map_err(Into::into)? { + return Ok(Place::Module { call: id, body }); + } + } + // The body pass has read a definition that is a statement. + let read = place == Place::Statement && matches!(word, Word::Definition(_) | Word::Unread); + if word.declares() && !read { + self.index.canonical.nodes[id.0].projection = Projection::Pending; + } + Ok(if joined { + Place::Unreached + } else { + Place::Code + }) + } + + // A documentation attribute that no body pass reads. + fn elixir_stray( + &mut self, + id: NodeId, + reason: &'static str, + budget: &B, + ) -> Result<(), SourceError> { + let range = self.index.canonical.node(id).byte_range(); + if covers(&self.index, range, budget)? + && matches!( + attribute(&self.index, id, budget).map_err(Into::into)?, + Attribute::Doc | Attribute::Moduledoc | Attribute::Typedoc + ) + { + let carrier = &self.index.canonical.nodes[id.0]; + let (scope, evidence) = (carrier.parent.unwrap_or(NodeId(0)), carrier.evidence); + self.pend(scope, AssessmentAxis::Occurrence, reason, evidence); + } + Ok(()) + } + + // Reads the body of a module and files what its statements document. + fn elixir_module( + &mut self, + module: NodeId, + body: &Visit, + gaps: &[Option], + budget: &B, + ) -> Result<(), SourceError> { + let doubt = body.doubt; + let mut reading = body::read(&self.index, body.id, gaps, budget)?; + let owner = self.elixir_module_owner(module, &mut reading, budget)?; + self.elixir_marks(module, &reading, budget)?; + if !reading.moduledocs.is_empty() { + let attachment = Attachment { + role: DocumentRole::FilePackage, + binding: None, + hidden: false, + doubt, + publication: Publication::Unknown, + }; + self.elixir_document(&reading.moduledocs, owner, &attachment, budget)?; + } + self.elixir_groups(module, &reading.groups, doubt, budget) + } + + // The module owns its documentation unless it holds a syntax error or + // excluded bytes. Its statements are read either way. + fn elixir_module_owner( + &mut self, + module: NodeId, + reading: &mut Reading, + budget: &B, + ) -> Result { + let scope = self.index.canonical.nodes[module.0].evidence; + let owner = OwnerId(self.index.facts.owners.len()); + if scope.node().has_error() || !covers(&self.index, scope.node().byte_range(), budget)? { + reading.pending.push(module); + // `moduledocs` is emptied here, so the caller never uses `owner`. + reading.unowned.append(&mut reading.moduledocs); + } else { + self.add_owner(module, Owner::Node(scope)); + } + Ok(owner) + } + + fn elixir_groups( + &mut self, + module: NodeId, + groups: &[Group], + doubt: bool, + budget: &B, + ) -> Result<(), SourceError> { + for group in groups { + step(budget)?; + self.elixir_group(module, group, doubt, budget)?; + } + Ok(()) + } + + // What the body pass found and no owner takes. + fn elixir_marks( + &mut self, + module: NodeId, + reading: &Reading, + budget: &B, + ) -> Result<(), SourceError> { + for carrier in &reading.unowned { + step(budget)?; + let evidence = self.index.canonical.nodes[carrier.node.0].evidence; + self.pend(module, AssessmentAxis::Owner, UNOWNED, evidence); + } + for &carrier in &reading.recovered { + step(budget)?; + let evidence = self.index.canonical.nodes[carrier.0].evidence; + self.pend(module, AssessmentAxis::Occurrence, RECOVERED, evidence); + } + for &definition in &reading.pending { + step(budget)?; + self.index.canonical.nodes[definition.0].projection = Projection::Pending; + } + Ok(()) + } + + fn elixir_group( + &mut self, + module: NodeId, + group: &Group, + doubt: bool, + budget: &B, + ) -> Result<(), SourceError> { + let scope = self.index.canonical.nodes[module.0].evidence; + let owner = OwnerId(self.index.facts.owners.len()); + let mut pieces = Vec::new(); + for &clause in &group.clauses { + step(budget)?; + let evidence = self.index.canonical.nodes[clause.0].evidence; + let source = self + .index + .source + .pieces_with_budget(evidence.node().byte_range(), budget)?; + pieces.push(OwnerPiece { + source, + node: Some(evidence), + }); + self.index.canonical.nodes[clause.0].projection = Projection::Ready(vec![owner]); + } + // A query on any clause answers for the group; the first clause + // anchors it. + self.add_owner(group.clauses[0], Owner::Group(OwnerGroup { scope, pieces })); + if group.carriers.is_empty() { + return Ok(()); + } + let attachment = Attachment { + role: DocumentRole::Primary, + binding: group.binding, + hidden: group.hidden, + doubt, + // The compiler discards the documentation of a private definition. + publication: if matches!(group.kind, Kind::Defp | Kind::Defmacrop) { + Publication::Ineligible + } else { + Publication::Unknown + }, + }; + self.elixir_document(&group.carriers, owner, &attachment, budget) + } + + fn elixir_fragments( + &mut self, + carriers: &[Carrier], + budget: &B, + ) -> Result, SourceError> { + let mut fragments = Vec::new(); + for carrier in carriers { + step(budget)?; + let evidence = self.index.canonical.nodes[carrier.node.0].evidence; + let source = self + .index + .source + .pieces_with_budget(evidence.node().byte_range(), budget)?; + fragments.push(self.fragment(source, evidence, FragmentForm::Attribute)); + } + Ok(fragments) + } + + // One document for the attributes of one owner, with its association. + fn elixir_document( + &mut self, + carriers: &[Carrier], + owner: OwnerId, + attachment: &Attachment, + budget: &B, + ) -> Result<(), SourceError> { + let fragments = self.elixir_fragments(carriers, budget)?; + let (content, pending) = content(&self.index, carriers, budget)?; + let document = self.push_document( + Document { + fragments, + composition: if carriers.len() == 1 { + Composition::Single + } else { + Composition::AttributeSequence + }, + role: attachment.role, + content, + }, + None, + ); + let first = carriers[0].node; + if let Some((axis, reason)) = pending { + let assessment = self.assess(Assessment { + axis, + reason, + node: Some(self.index.canonical.nodes[first.0].evidence), + document: Some(document), + }); + self.index.assessments_by_owner[owner.0].push(assessment); + } + self.elixir_associate(document, owner, first, attachment); + Ok(()) + } + + fn elixir_associate( + &mut self, + document: DocumentId, + owner: OwnerId, + first: NodeId, + attachment: &Attachment, + ) { + // An `ERROR` above the owner is a recovery in a statement around it, + // so the doubt covers what the walk records for such a node. + let unresolved = attachment + .hidden + .then_some(UnresolvedReason::ExcludedGap) + .or(attachment + .doubt + .then_some(UnresolvedReason::GrammarBoundary)); + let scope = self.index.canonical.nodes[first.0] + .parent + .unwrap_or(NodeId(0)); + self.index.facts.associations.push(Association { + document, + owners: vec![owner], + resolution: unresolved.map_or(Resolution::Resolved, Resolution::Unresolved), + convention: Convention(self.index.profile), + binding: attachment + .binding + .map(|id| self.index.canonical.nodes[id.0].evidence), + lexical_scope: self.index.canonical.nodes[scope.0].evidence, + publication: attachment.publication, + }); + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/elixir/body.rs b/big-code-analysis-ast/src/documentation/collector/elixir/body.rs new file mode 100644 index 000000000..106c75c08 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/elixir/body.rs @@ -0,0 +1,219 @@ +//! One forward pass over the statements of a `defmodule … do … end` body. +//! It reads the tree and the source and writes nothing to the index. + +use std::collections::HashMap; +use std::collections::hash_map::RandomState; +use std::hash::{BuildHasher, Hasher}; +use std::ops::Range; + +use super::super::*; +use super::syntax::{ + Attribute, Gap, Kind, Word, at_operator, attribute, covers, definition, kind, plain, same, + step, word, +}; + +pub(super) struct Carrier { + pub(super) node: NodeId, + // The bytes between the quotes of a plain string value. + pub(super) text: Option>, +} + +// The clauses of one kind, name and source-written arity, in source order. +pub(super) struct Group { + pub(super) kind: Kind, + name: Range, + pub(super) clauses: Vec, + pub(super) carriers: Vec, + // The clause that took the first attribute. + pub(super) binding: Option, + // Excluded bytes lie between an attribute and the clause that took it. + pub(super) hidden: bool, +} + +#[derive(Default)] +pub(super) struct Reading { + pub(super) groups: Vec, + pub(super) moduledocs: Vec, + // Documentation attributes that no owner of this unit takes. + pub(super) unowned: Vec, + // Documentation attributes that hold a syntax error or are joined to the + // statement before them. + pub(super) recovered: Vec, + // Definitions that are not read. + pub(super) pending: Vec, +} + +enum Reads { + Sets(Attribute), + Defines(Kind), + Unread, + Other, +} + +struct Reader<'i, 's, B> { + index: &'i DocumentationIndex<'s>, + budget: &'i B, + by_key: HashMap<(Kind, usize, u64), Vec>, + hasher: RandomState, + // The `@doc` attributes that wait for a definition, and whether + // excluded bytes lie behind the first of them. + run: Vec, + barrier: bool, + found: Reading, +} + +// `gaps` says how each child of the body stands to the statement before it. +pub(super) fn read( + index: &DocumentationIndex<'_>, + body: NodeId, + gaps: &[Option], + budget: &B, +) -> Result { + let mut reader = Reader { + index, + budget, + by_key: HashMap::new(), + hasher: RandomState::new(), + run: Vec::new(), + barrier: false, + found: Reading::default(), + }; + for (at, &child) in index.canonical.children_of(body).iter().enumerate() { + step(budget)?; + reader.child(child, gaps.get(at).copied().flatten())?; + } + reader.release(); + Ok(reader.found) +} + +impl Reader<'_, '_, B> { + fn child(&mut self, child: NodeId, gap: Option) -> Result<(), SourceError> { + let statement = self.index.canonical.node(child); + let recovered = statement.is_error() || statement.is_missing(); + if (statement.kind() == "comment" || !statement.is_named()) && !recovered { + // A comment, `do`, `end` or `;`. + return Ok(()); + } + // Excluded bytes before the statement bar an attribute that waits. + self.barrier |= gap == Some(Gap::Hidden) && !self.run.is_empty(); + let included = !recovered && covers(self.index, statement.byte_range(), self.budget)?; + let reads = if included { + self.reads(child)? + } else { + Reads::Other + }; + self.apply( + child, + reads, + included && gap != Some(Gap::Joined) && !statement.has_error(), + ) + } + + fn reads(&self, child: NodeId) -> Result { + let canonical = &self.index.canonical; + if at_operator(canonical, child, self.budget).map_err(Into::into)? { + let sets = attribute(self.index, child, self.budget).map_err(Into::into)?; + return Ok(Reads::Sets(sets)); + } + let word = if kind(canonical, child) == "call" { + word(self.index, child, self.budget)? + } else { + Word::Other + }; + Ok(match word { + Word::Definition(kind) => Reads::Defines(kind), + Word::Unread => Reads::Unread, + _ => Reads::Other, + }) + } + + fn apply(&mut self, child: NodeId, reads: Reads, sound: bool) -> Result<(), SourceError> { + let carrier = |text| Carrier { node: child, text }; + match (reads, sound) { + (Reads::Sets(Attribute::Doc), true) => { + let text = self.plain(child)?; + self.run.push(carrier(text)); + } + (Reads::Sets(Attribute::Moduledoc), true) => { + let text = self.plain(child)?; + self.found.moduledocs.push(carrier(text)); + } + (Reads::Sets(Attribute::Typedoc), true) => self.found.unowned.push(carrier(None)), + // Any other attribute is read past. + (Reads::Sets(Attribute::Other), true) => {} + (Reads::Defines(kind), true) => return self.define(child, kind), + (Reads::Sets(Attribute::Doc | Attribute::Moduledoc | Attribute::Typedoc), false) => { + self.found.recovered.push(child); + self.release(); + } + (Reads::Defines(_), false) | (Reads::Unread, _) => { + self.found.pending.push(child); + self.release(); + } + // Any other statement ends the run without an owner. + _ => self.release(), + } + Ok(()) + } + + fn plain(&self, statement: NodeId) -> Result>, SourceError> { + plain(&self.index.canonical, statement, self.budget).map_err(Into::into) + } + + fn release(&mut self) { + self.found.unowned.append(&mut self.run); + self.barrier = false; + } + + fn define(&mut self, child: NodeId, kind: Kind) -> Result<(), SourceError> { + let key = definition(self.index, child, self.budget).map_err(Into::into)?; + let Some((name, arity)) = key else { + self.found.pending.push(child); + self.release(); + return Ok(()); + }; + let group = self.group(kind, name, arity)?; + let group = &mut self.found.groups[group]; + group.clauses.push(child); + if !self.run.is_empty() { + group.binding.get_or_insert(child); + group.hidden |= self.barrier; + group.carriers.append(&mut self.run); + self.barrier = false; + } + Ok(()) + } + + // The group of the same kind, name and arity, or a new one. + fn group( + &mut self, + kind: Kind, + name: Range, + arity: usize, + ) -> Result { + let source = self.index.source.bytes(); + let mut hash = self.hasher.build_hasher(); + for &byte in &source[name.clone()] { + self.budget.bytes(1).map_err(Into::into)?; + hash.write_u8(byte); + } + let bucket = self.by_key.entry((kind, arity, hash.finish())).or_default(); + for &group in bucket.iter() { + step(self.budget)?; + let known = self.found.groups[group].name.clone(); + if same(source, known, name.clone(), self.budget).map_err(Into::into)? { + return Ok(group); + } + } + bucket.push(self.found.groups.len()); + self.found.groups.push(Group { + kind, + name, + clauses: Vec::new(), + carriers: Vec::new(), + binding: None, + hidden: false, + }); + Ok(self.found.groups.len() - 1) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/elixir/syntax.rs b/big-code-analysis-ast/src/documentation/collector/elixir/syntax.rs new file mode 100644 index 000000000..6ee7fef18 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/elixir/syntax.rs @@ -0,0 +1,635 @@ +//! What the recorded tree and the source bytes say about one Elixir node. +//! Nothing here writes to the index. + +use std::ops::Range; + +use super::super::*; + +// The node kinds whose children are statements that a `;` or a line end +// separates: the file, the blocks of a call, the body of a `->` clause, a +// parenthesized block and the clauses of an anonymous function. +const SEQUENCES: [&str; 9] = [ + "source", + "do_block", + "after_block", + "rescue_block", + "catch_block", + "else_block", + "body", + "block", + "anonymous_function", +]; + +// The blocks of a `do` block that follow its statements with no separator. +const SECTIONS: [&str; 4] = ["after_block", "rescue_block", "catch_block", "else_block"]; + +// The quotes of a string, of a charlist and of their heredocs. +const QUOTES: [&str; 4] = ["\"", "'", "\"\"\"", "'''"]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(super) enum Kind { + Def, + Defp, + Defmacro, + Defmacrop, +} + +#[derive(Debug, PartialEq, Eq)] +pub(super) enum Word { + Quote, + Module, + // `defprotocol` and `defimpl`. + Protocol, + Definition(Kind), + // `defguard`, `defguardp` and `defdelegate`. + Unread, + Other, +} + +impl Word { + // Whether the word starts a module or a definition, read or not. + pub(super) fn declares(&self) -> bool { + !matches!(self, Self::Quote | Self::Other) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Attribute { + Doc, + Moduledoc, + Typedoc, + // `@callback` and `@macrocallback` take a pending `@doc`. + Callback, + Other, +} + +// How a child stands to the statement before it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Gap { + // No statement stands before it, or a `;` or a line end lies between. + Apart, + // Excluded bytes hide what lies between. + Hidden, + // Nothing separates the two: the compiler reads no statement here. + Joined, +} + +pub(super) fn kind(canonical: &CanonicalNodes<'_>, id: NodeId) -> &'static str { + canonical.node(id).kind() +} + +pub(super) fn step(budget: &B) -> Result<(), SourceError> { + budget.step().map_err(Into::into) +} + +// The children of a node that are no comment, in order. The compiler drops a +// comment, so no count and no position of a child may depend on one. An +// `ERROR` and a missing child stay. +pub(super) fn parts( + canonical: &CanonicalNodes<'_>, + id: NodeId, + budget: &B, +) -> Result, B::Error> { + let mut parts = Vec::new(); + for &child in canonical.children_of(id) { + budget.step()?; + if kind(canonical, child) != "comment" { + parts.push(child); + } + } + Ok(parts) +} + +pub(super) fn covers( + index: &DocumentationIndex<'_>, + range: Range, + budget: &B, +) -> Result { + index + .source + .covers_with_budget(range, budget) + .map_err(Into::into) +} + +fn spelled(index: &DocumentationIndex<'_>, id: NodeId, word: &[u8]) -> bool { + let name = index.canonical.node(id); + name.kind() == "identifier" && &index.source.bytes()[name.byte_range()] == word +} + +// The word a `call` starts with. A first word that is not fully included +// cannot be told from `quote`, so it is read as one. +pub(super) fn word( + index: &DocumentationIndex<'_>, + call: NodeId, + budget: &B, +) -> Result { + let canonical = &index.canonical; + let target = match parts(canonical, call, budget).map_err(Into::into)?.first() { + Some(&target) if kind(canonical, target) == "identifier" => canonical.node(target), + _ => return Ok(Word::Other), + }; + if !covers(index, target.byte_range(), budget)? { + return Ok(Word::Quote); + } + Ok(match &index.source.bytes()[target.byte_range()] { + b"quote" => Word::Quote, + b"defmodule" => Word::Module, + b"defprotocol" | b"defimpl" => Word::Protocol, + b"def" => Word::Definition(Kind::Def), + b"defp" => Word::Definition(Kind::Defp), + b"defmacro" => Word::Definition(Kind::Defmacro), + b"defmacrop" => Word::Definition(Kind::Defmacrop), + b"defguard" | b"defguardp" | b"defdelegate" => Word::Unread, + _ => Word::Other, + }) +} + +// The body of `defmodule NAME do … end`. The keyword form has none. +pub(super) fn module_body( + canonical: &CanonicalNodes<'_>, + module: NodeId, + budget: &B, +) -> Result, B::Error> { + Ok(match *parts(canonical, module, budget)? { + [_, _, body] if kind(canonical, body) == "do_block" => Some(body), + _ => None, + }) +} + +pub(super) fn at_operator( + canonical: &CanonicalNodes<'_>, + statement: NodeId, + budget: &B, +) -> Result { + if kind(canonical, statement) != "unary_operator" { + return Ok(false); + } + let operator = parts(canonical, statement, budget)?.first().copied(); + Ok(operator.is_some_and(|operator| kind(canonical, operator) == "@")) +} + +// The children of the operand of an `@` statement, and those of its +// argument list when the operand is `NAME ARGUMENTS`. The operand is the last +// child of the statement. Both lists are empty for another operand. +fn operand( + canonical: &CanonicalNodes<'_>, + statement: NodeId, + budget: &B, +) -> Result<(Vec, Vec), B::Error> { + let called = match parts(canonical, statement, budget)?.last() { + Some(&operand) if kind(canonical, operand) == "call" => parts(canonical, operand, budget)?, + _ => Vec::new(), + }; + let arguments = match *called { + [_, arguments] => parts(canonical, arguments, budget)?, + _ => Vec::new(), + }; + Ok((called, arguments)) +} + +// What a fully included `@` statement sets. `@doc`, `@doc()` and an +// argument list that holds only comments read the attribute and set nothing. +pub(super) fn attribute( + index: &DocumentationIndex<'_>, + statement: NodeId, + budget: &B, +) -> Result { + let canonical = &index.canonical; + let (called, arguments) = operand(canonical, statement, budget)?; + let name = match called.first() { + Some(&name) if kind(canonical, name) == "identifier" => name, + _ => return Ok(Attribute::Other), + }; + if let [open, close] = *arguments + && kind(canonical, open) == "(" + && kind(canonical, close) == ")" + { + return Ok(Attribute::Other); + } + Ok( + match &index.source.bytes()[canonical.node(name).byte_range()] { + b"doc" => Attribute::Doc, + b"moduledoc" => Attribute::Moduledoc, + b"typedoc" => Attribute::Typedoc, + b"callback" | b"macrocallback" => Attribute::Callback, + _ => Attribute::Other, + }, + ) +} + +// The one value of `NAME VALUE` or `NAME(VALUE)`, from the children of the +// argument list. +fn value(canonical: &CanonicalNodes<'_>, arguments: &[NodeId]) -> Option { + match *arguments { + [value] => Some(value), + [open, value, close] if kind(canonical, open) == "(" && kind(canonical, close) == ")" => { + Some(value) + } + _ => None, + } +} + +// The bytes between the quotes when the value of a documentation attribute +// is one plain string. The grammar gives an escape and an interpolation +// children of their own, and a heredoc other quotes. +pub(super) fn plain( + canonical: &CanonicalNodes<'_>, + statement: NodeId, + budget: &B, +) -> Result>, B::Error> { + let (_, arguments) = operand(canonical, statement, budget)?; + let string = value(canonical, &arguments).filter(|&value| kind(canonical, value) == "string"); + let Some(string) = string else { + return Ok(None); + }; + let quotes = match *parts(canonical, string, budget)? { + [open, close] => Some((open, close)), + [open, content, close] if kind(canonical, content) == "quoted_content" => { + Some((open, close)) + } + _ => None, + }; + Ok(quotes + .filter(|&(open, close)| kind(canonical, open) == "\"" && kind(canonical, close) == "\"") + .map(|(open, close)| canonical.node(open).end_byte()..canonical.node(close).start_byte())) +} + +// Whether the compiler rejects a character of a string: a line break other +// than LF or CR LF, or a bidirectional formatting character. +pub(in crate::documentation::collector) fn rejected( + text: &[u8], + budget: &B, +) -> Result { + for (at, &byte) in text.iter().enumerate() { + budget.bytes(1)?; + let next = |offset: usize| text.get(at + offset).copied(); + let found = match byte { + 0x0b | 0x0c => true, + b'\r' => next(1) != Some(b'\n'), + 0xc2 => next(1) == Some(0x85), + 0xe2 => matches!( + (next(1), next(2)), + (Some(0x80), Some(0xa8..=0xae)) | (Some(0x81), Some(0xa6..=0xa9)) + ), + _ => false, + }; + if found { + return Ok(true); + } + } + Ok(false) +} + +// Whether a line end or a `;` stands in the bytes between two statements. +// `escaped` starts true behind `?\` or `?`, which takes the line feed that +// starts the gap; `lines` is false behind `,`, where no line feed counts. A +// backslash before a line end continues the line, and a comment runs to its +// line end, which no backslash continues. +pub(in crate::documentation::collector) fn separated( + gap: &[u8], + mut escaped: bool, + lines: bool, + budget: &B, +) -> Result { + let mut comment = false; + for &byte in gap { + budget.bytes(1)?; + match byte { + b'\n' if lines && (comment || !escaped) => return Ok(true), + b';' if !comment => return Ok(true), + b'\n' if comment => comment = false, + b'#' => comment = true, + b'\\' => escaped = true, + b'\r' if escaped => {} + _ => escaped = false, + } + } + Ok(false) +} + +// How the child at `start` stands to `before`, the statement or recovery +// before it. The last leaf of `before` decides whether a line feed counts. +fn gap( + index: &DocumentationIndex<'_>, + mut before: NodeId, + start: usize, + budget: &B, +) -> Result { + let end = index.canonical.node(before).end_byte(); + while let Some(&last) = index.canonical.children_of(before).last() { + step(budget)?; + before = last; + } + let leaf = index.canonical.node(before); + if !covers(index, leaf.start_byte()..start, budget)? { + return Ok(Gap::Hidden); + } + let bytes = index.source.bytes(); + let (spelled, gap) = (&bytes[leaf.start_byte()..end], &bytes[end..start]); + let escaped = + (leaf.kind() == "char" && spelled == b"?\\") || (leaf.is_error() && spelled == b"?"); + let apart = separated(gap, escaped, spelled != b",", budget).map_err(Into::into)?; + Ok(if apart { Gap::Apart } else { Gap::Joined }) +} + +// Whether the grammar recovered at this node itself: an `ERROR`, a missing +// token, or a node with an error that none of its children holds, which is a +// missing token that the grammar shows no node for. +fn recovery( + canonical: &CanonicalNodes<'_>, + id: NodeId, + budget: &B, +) -> Result { + let written = canonical.node(id); + if written.is_error() || written.is_missing() { + return Ok(true); + } + if !written.has_error() { + return Ok(false); + } + for &child in canonical.children_of(id) { + budget.step()?; + if canonical.node(child).has_error() { + return Ok(false); + } + } + Ok(true) +} + +// Whether the grammar recovered in a statement outside the sequences below +// it. A `;` or a line end holds a recovery inside the statement it ends; in +// such a statement no part is known to be what the compiler reads. +pub(super) fn broken( + canonical: &CanonicalNodes<'_>, + statement: NodeId, + budget: &B, +) -> Result { + if !canonical.node(statement).has_error() { + return Ok(false); + } + // Every node of the stack holds an error. + let mut stack = vec![statement]; + while let Some(id) = stack.pop() { + budget.step()?; + let written = canonical.node(id); + // A sequence holds what its statements and its own tokens lack. + if SEQUENCES.contains(&written.kind()) { + continue; + } + let known = stack.len(); + for &child in canonical.children_of(id) { + budget.step()?; + if canonical.node(child).has_error() { + stack.push(child); + } + } + // An `ERROR`, or an error that no child holds: a missing token. + if written.is_error() || stack.len() == known { + return Ok(true); + } + } + Ok(false) +} + +// Whether a child that is no comment is a statement: a named child of a +// sequence that is no section. An `ERROR` child is named. +fn states(written: &tree_sitter::Node<'_>, sequence: bool) -> bool { + sequence && written.is_named() && !SECTIONS.contains(&written.kind()) +} + +// What stands before the next child of a node, comments left out: the last +// statement, a recovery that is the child directly before, and where the first +// torn literal of the file starts. +struct Before { + statement: Option, + recovery: Option, + tear: Option, +} + +impl Before { + // How a child stands. A child at or behind a torn literal counts as + // joined: the compiler reads no statement there either. An `ERROR` and a + // missing node are text that the grammar could not place, and are never + // joined by the node before them. + fn gap( + &self, + index: &DocumentationIndex<'_>, + written: &tree_sitter::Node<'_>, + states: bool, + budget: &B, + ) -> Result, SourceError> { + let start = written.start_byte(); + if self.tear.is_some_and(|tear| start >= tear) { + return Ok(Some(Gap::Joined)); + } + let unplaced = written.is_error() || written.is_missing(); + match self.recovery.or(self.statement.filter(|_| states)) { + Some(before) if !unplaced => gap(index, before, start, budget).map(Some), + _ => Ok(states.then_some(Gap::Apart)), + } + } + + fn pass(&mut self, child: NodeId, states: bool, recovers: bool) { + self.recovery = recovers.then_some(child); + if states { + self.statement = Some(child); + } + } +} + +// Where the grammar first dropped a quote: the start of the first quote that +// is a child of an `ERROR` node. The compiler pairs the quotes of a file from +// its start, so from there on the two read different bytes as text. +pub(super) fn tear( + canonical: &CanonicalNodes<'_>, + budget: &B, +) -> Result, B::Error> { + let mut first: Option = None; + let root = NodeId(0); + if !canonical.node(root).has_error() { + return Ok(first); + } + // Every node of the stack holds an error. + let mut stack = vec![root]; + while let Some(id) = stack.pop() { + budget.step()?; + let torn = canonical.node(id).is_error(); + for &child in canonical.children_of(id) { + budget.step()?; + let written = canonical.node(child); + if torn && QUOTES.contains(&written.kind()) { + let at = written.start_byte(); + first = Some(first.map_or(at, |first| first.min(at))); + } + if written.has_error() { + stack.push(child); + } + } + } + Ok(first) +} + +// How each child of a node stands to the statement before it: `None` for a +// child that is no statement and follows no recovery. The result is empty +// where no child can be joined. In a sequence every statement is compared +// with the statement before it. In every node the child after a recovery is +// compared with it: the grammar may have made a part of this node of the +// expression before a statement. +pub(super) fn gaps( + index: &DocumentationIndex<'_>, + parent: NodeId, + tear: Option, + budget: &B, +) -> Result>, SourceError> { + let canonical = &index.canonical; + let sequence = SEQUENCES.contains(&kind(canonical, parent)); + if !sequence && !canonical.node(parent).has_error() { + return Ok(Vec::new()); + } + let mut gaps = Vec::new(); + let mut before = Before { + statement: None, + recovery: None, + tear, + }; + for &child in canonical.children_of(parent) { + step(budget)?; + let written = canonical.node(child); + // A comment is no part of the program: it is compared with nothing, + // and nothing with it. + if written.kind() == "comment" { + gaps.push(None); + continue; + } + let states = states(&written, sequence); + gaps.push(before.gap(index, &written, states, budget)?); + let recovers = recovery(canonical, child, budget).map_err(Into::into)?; + before.pass(child, states, recovers); + } + Ok(gaps) +} + +// Whether two names are the same bytes. Their hash only finds the candidates. +pub(in crate::documentation::collector) fn same( + source: &[u8], + left: Range, + right: Range, + budget: &B, +) -> Result { + if left.len() != right.len() { + return Ok(false); + } + for (left, right) in source[left].iter().zip(&source[right]) { + budget.bytes(1)?; + if left != right { + return Ok(false); + } + } + Ok(true) +} + +// The head of a definition: the first child of its arguments, or what stands +// left of one `when` there. +fn guarded( + canonical: &CanonicalNodes<'_>, + arguments: NodeId, + budget: &B, +) -> Result, B::Error> { + let Some(&first) = parts(canonical, arguments, budget)?.first() else { + return Ok(None); + }; + if kind(canonical, first) != "binary_operator" { + return Ok(Some(first)); + } + Ok(Some(match *parts(canonical, first, budget)? { + [left, operator, _] if kind(canonical, operator) == "when" => left, + _ => first, + })) +} + +// The number of written arguments between `(` and `)`. A spliced argument +// stands for a number of them that only the running code knows. +fn arity( + index: &DocumentationIndex<'_>, + list: &[NodeId], + budget: &B, +) -> Result, B::Error> { + let canonical = &index.canonical; + let arguments = match list { + [open, arguments @ .., close] + if kind(canonical, *open) == "(" && kind(canonical, *close) == ")" => + { + arguments + } + _ => return Ok(None), + }; + let mut arity = 0; + for &argument in arguments { + budget.step()?; + if !canonical.node(argument).is_named() { + continue; + } + let target = parts(canonical, argument, budget)?.first().copied(); + if target.is_some_and(|target| spelled(index, target, b"unquote_splicing")) { + return Ok(None); + } + arity += 1; + } + Ok(Some(arity)) +} + +// The name and the source-written arity of `name(…)`. An `unquote` head +// names the definition only when the code runs. +fn named_call( + index: &DocumentationIndex<'_>, + head: NodeId, + budget: &B, +) -> Result, usize)>, B::Error> { + let canonical = &index.canonical; + let (name, list) = match *parts(canonical, head, budget)? { + [name, list] + if kind(canonical, head) == "call" + && kind(canonical, name) == "identifier" + && !spelled(index, name, b"unquote") => + { + (name, list) + } + _ => return Ok(None), + }; + let list = parts(canonical, list, budget)?; + let name = canonical.node(name).byte_range(); + Ok(arity(index, &list, budget)?.map(|arity| (name, arity))) +} + +// The name and the source-written arity of a simple head: `f`, `f(…)`, or +// either under one `when`. +fn head( + index: &DocumentationIndex<'_>, + arguments: NodeId, + budget: &B, +) -> Result, usize)>, B::Error> { + let canonical = &index.canonical; + let Some(head) = guarded(canonical, arguments, budget)? else { + return Ok(None); + }; + if kind(canonical, head) == "identifier" { + return Ok(Some((canonical.node(head).byte_range(), 0))); + } + named_call(index, head, budget) +} + +// The head of a definition statement: `def HEAD`, `def HEAD, do: …` or +// `def HEAD do … end`, with the head as the first child of the arguments. +pub(super) fn definition( + index: &DocumentationIndex<'_>, + statement: NodeId, + budget: &B, +) -> Result, usize)>, B::Error> { + let canonical = &index.canonical; + match *parts(canonical, statement, budget)? { + [_, arguments] | [_, arguments, _] if kind(canonical, arguments) == "arguments" => { + head(index, arguments, budget) + } + _ => Ok(None), + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/elixir_tests.rs b/big-code-analysis-ast/src/documentation/collector/elixir_tests.rs new file mode 100644 index 000000000..fe0da2311 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/elixir_tests.rs @@ -0,0 +1,6845 @@ +//! Elixir documentation attributes in the source view: the module or the group of clauses +//! that a `@moduledoc` or a `@doc` with one plain string documents, the text and the bytes +//! it is copied from, and the attributes that stay pending. A source is collected through +//! both entry points, except in the tests of restricted parses, of the queries and of cost. +//! The test of the byte scans calls three functions and collects nothing. One test collects +//! a Ruby source. The last test collects nothing and pins the parse shapes the reader +//! relies on. + +#[cfg(feature = "elixir")] +use super::Builder; +use super::elixir::syntax::{rejected, same, separated}; +use crate::documentation::SourceError; +use crate::documentation::budget::WorkBudget; +#[cfg(feature = "elixir")] +use crate::documentation::budget::cancel_after; +#[cfg(any(feature = "elixir", feature = "ruby"))] +use crate::documentation::*; +#[cfg(any(feature = "elixir", feature = "ruby"))] +use crate::{AnyParser, LANG}; +use std::cell::Cell; +#[cfg(feature = "elixir")] +use std::fmt::Write; +#[cfg(feature = "elixir")] +use std::ops::Range; + +// The short names the views use for the reasons of pending assessments. +#[cfg(feature = "elixir")] +const REASONS: [(&str, &str); 7] = [ + ( + "OUTSIDE", + "Elixir documentation attribute outside a module body awaits interpretation", + ), + ( + "TEMPLATE", + "Elixir documentation attribute in a quoted or unreadable call awaits interpretation", + ), + ( + "RECOVERED", + "Recovered Elixir documentation attribute awaits interpretation", + ), + ( + "UNOWNED", + "Elixir documentation attribute awaits an owner projection", + ), + ( + "VALUE", + "Elixir documentation attribute value awaits decoding", + ), + ( + "SEVERAL", + "Several Elixir documentation attributes await selection", + ), + ( + "PROJECTION", + "Recognized declaration requires a semantic projection", + ), +]; + +// What one collection publishes, each record as one line: +// - `owners`: every owner after the file, in owner order, as `module A..B` or +// `group A..B: C..D, …` (the module of the group, then its clauses); +// - `documents`: `ROLE COMPOSITION [FRAGMENT, …] CONTENT`, with the content `"text"` and +// one `OUTPUT<-SOURCE` per mapping, `pending`, or `unavailable REASON`; +// - `associations`: `DOCUMENT RESOLUTION OWNER by BINDING PUBLICATION`; +// - `assessments`: `AXIS REASON KIND RANGE DOCUMENT`, sorted, because the contract gives +// assessments no order. +#[cfg(feature = "elixir")] +#[derive(Debug, PartialEq, Eq)] +struct View { + owners: Vec, + documents: Vec, + associations: Vec, + assessments: Vec, +} + +#[cfg(feature = "elixir")] +type Rows = [&'static [&'static str]; 4]; + +#[cfg(feature = "elixir")] +fn expected(rows: Rows) -> View { + let [owners, documents, associations, assessments] = + rows.map(|row| row.iter().map(ToString::to_string).collect()); + View { + owners, + documents, + associations, + assessments, + } +} + +#[cfg(feature = "elixir")] +fn span(range: &Range) -> String { + format!("{}..{}", range.start, range.end) +} + +// The pieces of a spelling, which together are the bytes of its node. +#[cfg(feature = "elixir")] +fn spelled(source: &SourcePieces<'_>, node: tree_sitter::Node<'_>) -> String { + let pieces = source.pieces(); + assert!(!source.has_excluded_gap()); + assert_eq!( + pieces[0].range().start..pieces[pieces.len() - 1].range().end, + node.byte_range() + ); + let ranges: Vec<_> = pieces.iter().map(|piece| span(&piece.range())).collect(); + ranges.join("+") +} + +#[cfg(feature = "elixir")] +fn owner_text(owner: &Owner<'_>) -> String { + match owner { + Owner::Node(module) => { + assert_eq!(module.node().kind(), "call"); + format!("module {}", span(&module.node().byte_range())) + } + Owner::Group(group) => { + assert_eq!(group.scope.node().kind(), "call"); + let clauses: Vec<_> = group + .pieces + .iter() + .map(|piece| { + let clause = piece.node.unwrap().node(); + assert_eq!(clause.kind(), "call"); + // expected: a clause is fully included, so its pieces touch. + spelled(&piece.source, clause); + span(&clause.byte_range()) + }) + .collect(); + format!( + "group {}: {}", + span(&group.scope.node().byte_range()), + clauses.join(", ") + ) + } + _ => panic!("unexpected owner variant"), + } +} + +#[cfg(feature = "elixir")] +fn document_text<'s>( + index: &DocumentationIndex<'s>, + document: FactRef<'_, Document<'s>>, +) -> String { + let fact = document.get(); + let mut fragments = Vec::new(); + for position in 0..fact.fragment_count() { + let fragment = index.facts().document_fragment(document, position).unwrap(); + assert_eq!(fragment.get().form(), FragmentForm::Attribute); + let attribute = fragment.get().node().unwrap().node(); + assert_eq!(attribute.kind(), "unary_operator"); + fragments.push(spelled(fragment.get().source(), attribute)); + } + // expected: the profile has no prelexing and no documentation command. + assert!(index.source_cleaned_text(document).unwrap().is_none()); + assert_eq!(index.document_qualifications(document).unwrap().len(), 0); + let complete = index.complete_text(document).unwrap(); + let content = match fact.content() { + Content::Complete { .. } => { + let complete = complete.unwrap(); + let mut text = format!("{:?}", complete.text()); + for mapping in complete.mappings() { + let Origin::Copied(piece) = &mapping.origin else { + panic!("the text of a plain string is copied"); + }; + let output = span(&mapping.output.range()); + write!(text, " {output}<-{}", span(&piece.range())).unwrap(); + } + text + } + Content::PendingAdapter => { + assert!(complete.is_none()); + "pending".to_owned() + } + Content::Unavailable(reason) => format!("unavailable {reason:?}"), + other => panic!("unexpected content {other:?}"), + }; + format!( + "{:?} {:?} [{}] {content}", + fact.role(), + fact.composition(), + fragments.join(", ") + ) +} + +// Builds the view and asserts what is the same for every source of the unit. +#[cfg(feature = "elixir")] +fn published(index: &DocumentationIndex<'_>) -> View { + // bca: suppress(abc, halstead) -- one reading of every record kind of the index. + assert_eq!(index.profile(), Profile::Elixir); + assert_eq!(index.capability(), Capability::Partial); + // expected: no documentation command names its declaration. + assert_eq!(index.qualifications().len(), 0); + // expected: the unit retains no candidate, whatever the options are. + assert_eq!(index.evidence().len(), 0); + let mut owners = index.facts().owners(); + assert!(matches!(owners.next().unwrap().get(), Owner::File(_))); + let documents: Vec<_> = index.documents().collect(); + let position = |document| { + documents + .iter() + .position(|known| *known == document) + .unwrap() + }; + let mut associations = Vec::new(); + for association in index.associations() { + let fact = association.get(); + assert_eq!(fact.convention.name(), "elixir"); + assert_eq!(fact.owner_count(), 1); + let document = index.facts().associated_document(association).unwrap(); + let first = index.facts().document_fragment(document, 0).unwrap(); + // expected: the lexical scope is the body that holds the first attribute. + let body = first.get().node().unwrap().node().parent().unwrap(); + assert_eq!(body.kind(), "do_block"); + assert_eq!(fact.lexical_scope.node(), body); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let binding = fact.binding.map_or("-".to_owned(), |clause| { + assert_eq!(clause.node().kind(), "call"); + span(&clause.node().byte_range()) + }); + associations.push(format!( + "{} {:?} {} by {binding} {:?}", + position(document), + fact.resolution, + owner_text(owner.get()), + fact.publication + )); + } + let mut assessments = Vec::new(); + for assessment in index.assessments() { + let fact = assessment.get(); + let reason = REASONS + .iter() + .find(|(_, reason)| *reason == fact.reason) + .map_or(fact.reason, |(label, _)| label); + let node = fact.node.unwrap().node(); + let document = index + .assessed_document(assessment) + .unwrap() + .map_or("-".to_owned(), |document| position(document).to_string()); + assessments.push(format!( + "{:?} {reason} {} {} {document}", + fact.axis, + node.kind(), + span(&node.byte_range()) + )); + } + assessments.sort(); + View { + owners: owners.map(|owner| owner_text(owner.get())).collect(), + documents: documents + .iter() + .map(|document| document_text(index, *document)) + .collect(), + associations, + assessments, + } +} + +#[cfg(feature = "elixir")] +fn parsed(source: &[u8]) -> AnyParser { + AnyParser::parse(LANG::Elixir, source.to_vec(), None, None).unwrap() +} + +// One view through both entry points. +#[cfg(feature = "elixir")] +fn collected(source: &[u8], options: &DocumentationOptions) -> View { + let parser = parsed(source); + let context = DocumentationContext::default(); + let typed = published(&parser.documentation(&context, options).unwrap()); + let raw = collect( + LANG::Elixir, + parser.ts_tree(), + parser.code(), + &context, + options, + ) + .unwrap(); + assert_eq!(typed, published(&raw)); + typed +} + +#[cfg(feature = "elixir")] +fn view(source: &str) -> View { + collected(source.as_bytes(), &DocumentationOptions::default()) +} + +#[cfg(feature = "elixir")] +fn assert_views(rows: &[(&str, Rows)]) { + for (source, rows) in rows { + assert_eq!(view(source), expected(*rows), "{source}"); + } +} + +// The one node of that kind and byte range. +#[cfg(feature = "elixir")] +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(node) = stack.pop() { + if node.kind() == kind && node.byte_range() == *range { + found.push(node); + } + stack.extend(node.children(&mut node.walk())); + } + assert_eq!(found.len(), 1, "{kind} {range:?}"); + found[0] +} + +#[cfg(feature = "elixir")] +fn restricted(source: &str, included: &[Range]) -> tree_sitter::Tree { + let point = |offset: usize| { + let mut lines = source.as_bytes()[..offset].split(|byte| *byte == b'\n'); + let column = lines.next_back().map_or(0, <[u8]>::len); + tree_sitter::Point::new(lines.count(), 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::Elixir.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + parser.parse(source, None).unwrap() +} + +// A budget that counts what it is charged and never cancels. +#[derive(Default)] +struct Counting { + steps: Cell, + scanned: Cell, + checkpoints: Cell, +} + +impl WorkBudget for Counting { + 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(()) + } + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.scanned.set(self.scanned.get() + count); + Ok(()) + } +} + +// What the second pass charges for one source: steps, bytes and checkpoints. The pass +// reads nothing that it or the end of the collection writes, so a second run over the +// finished index does the same work. +#[cfg(feature = "elixir")] +fn charged(source: &[u8]) -> [usize; 3] { + let parser = parsed(source); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let mut builder = Builder { + index, + drafts: Vec::new(), + pending_attributes: Vec::new(), + rust_values: std::collections::HashMap::new(), + names: crate::documentation::names::Names::default(), + pod_doubt: super::pod_doubt::Doubt::default(), + pod_hidden: super::pod::Hidden::default(), + tcl_scan: crate::lang_helpers::tcl_scan::CommandScan::default(), + ruff_open: Vec::new(), + irules_scan: crate::lang_helpers::tcl_scan::CommandScan::default(), + irules_selected: std::collections::HashSet::default(), + irules_body_initial: std::collections::HashSet::default(), + shdoc: crate::lang_helpers::shdoc::Reading::default(), + }; + let budget = Counting::default(); + builder.elixir_attributes(&budget).unwrap(); + [ + budget.steps.get(), + budget.scanned.get(), + budget.checkpoints.get(), + ] +} + +#[cfg(feature = "elixir")] +#[test] +fn elixir_primary_fixture_documents_its_definition_group() { + let source = crate::test_support::documentation::source("primary.ex"); + assert_eq!( + source, + b"defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend" + ); + let rows: Rows = [ + &["module 0..52", "group 0..52: 32..48"], + &["Primary Single [17..29] \"audit\" 0..5<-23..28"], + &["0 Resolved group 0..52: 32..48 by 32..48 Unknown"], + &[], + ]; + let options = DocumentationOptions::default(); + assert_eq!(collected(&source, &options), expected(rows)); + // expected: the unit retains no candidate, so no retention option changes the view. + for (retain_unbound, retain_directives) in [(true, false), (false, true), (true, true)] { + let options = DocumentationOptions { + retain_unbound, + retain_directives, + ..options + }; + assert_eq!(collected(&source, &options), expected(rows)); + } + // The independent primary requirement: the fragment, the owner's range and kind, the + // text. The owner of a definition is a group, also with one clause. + let parser = parsed(&source); + let index = parser + .documentation(&DocumentationContext::default(), &options) + .unwrap(); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + let Owner::Group(group) = owner.get() else { + panic!("a definition is a group of its clauses"); + }; + let clause = group.pieces[0].node.unwrap().node(); + let document = index.documents().next().unwrap(); + let fragment = index.facts().document_fragment(document, 0).unwrap(); + let fragment = fragment.get().source().pieces()[0].range(); + crate::test_support::documentation::assert_primary_extraction( + LANG::Elixir, + Ok(serde_json::json!([{ + "fragments": [[fragment.start, fragment.end]], + "owner": [clause.start_byte(), clause.end_byte()], + "owner_kind": clause.kind(), + "text": index.complete_text(document).unwrap().unwrap().text(), + }])), + ); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_moduledoc_documents_its_module() { + assert_views(&[ + // b01_moduledoc + ( + "defmodule M do\n@moduledoc \"audit\"\nend", + [ + &["module 0..37"], + &["FilePackage Single [15..33] \"audit\" 0..5<-27..32"], + &["0 Resolved module 0..37 by - Unknown"], + &[], + ], + ), + // b02_moduledoc_after_definition + ( + "defmodule M do\ndef f(), do: :ok\n@moduledoc \"audit\"\nend", + [ + &["module 0..54", "group 0..54: 15..31"], + &["FilePackage Single [32..50] \"audit\" 0..5<-44..49"], + &["0 Resolved module 0..54 by - Unknown"], + &[], + ], + ), + // b03_moduledoc_then_doc + ( + concat!( + "defmodule M do\n@moduledoc \"m\"\n@doc \"d\"\ndef f(), do: :ok\n", + "end" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &[ + "FilePackage Single [15..29] \"m\" 0..1<-27..28", + "Primary Single [30..38] \"d\" 0..1<-36..37", + ], + &[ + "0 Resolved module 0..59 by - Unknown", + "1 Resolved group 0..59: 39..55 by 39..55 Unknown", + ], + &[], + ], + ), + // b04_doc_then_moduledoc + ( + concat!( + "defmodule M do\n@doc \"d\"\n@moduledoc \"m\"\ndef f(), do: :ok\n", + "end" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &[ + "Primary Single [15..23] \"d\" 0..1<-21..22", + "FilePackage Single [24..38] \"m\" 0..1<-36..37", + ], + &[ + "0 Resolved group 0..59: 39..55 by 39..55 Unknown", + "1 Resolved module 0..59 by - Unknown", + ], + &[], + ], + ), + // b05_nested_modules + ( + concat!( + "defmodule A do\n@moduledoc \"a\"\ndefmodule B do\n@moduledoc \"b", + "\"\n@doc \"g\"\ndef g(), do: 1\nend\n@doc \"f\"\ndef f(), do: 2", + "\nend" + ), + [ + &[ + "module 0..115", + "group 0..115: 97..111", + "module 30..87", + "group 30..87: 69..83", + ], + &[ + "FilePackage Single [15..29] \"a\" 0..1<-27..28", + "FilePackage Single [45..59] \"b\" 0..1<-57..58", + "Primary Single [60..68] \"g\" 0..1<-66..67", + "Primary Single [88..96] \"f\" 0..1<-94..95", + ], + &[ + "0 Resolved module 0..115 by - Unknown", + "1 Resolved module 30..87 by - Unknown", + "2 Resolved group 30..87: 69..83 by 69..83 Unknown", + "3 Resolved group 0..115: 97..111 by 97..111 Unknown", + ], + &[], + ], + ), + // b06_undocumented + ( + "defmodule M do\ndef f(), do: :ok\nend", + [&["module 0..35", "group 0..35: 15..31"], &[], &[], &[]], + ), + // b07_empty_module + ("defmodule M do\nend", [&["module 0..18"], &[], &[], &[]]), + // b08_two_modules + ( + concat!( + "defmodule A do\n@doc \"one\"\ndef f(), do: 1\nend\ndefmodule B d", + "o\n@doc \"two\"\ndef f(), do: 2\nend\n" + ), + [ + &[ + "module 0..44", + "group 0..44: 26..40", + "module 45..89", + "group 45..89: 71..85", + ], + &[ + "Primary Single [15..25] \"one\" 0..3<-21..24", + "Primary Single [60..70] \"two\" 0..3<-66..69", + ], + &[ + "0 Resolved group 0..44: 26..40 by 26..40 Unknown", + "1 Resolved group 45..89: 71..85 by 71..85 Unknown", + ], + &[], + ], + ), + // b09_module_name_in_parentheses + ( + "defmodule(M) do\n@moduledoc \"audit\"\nend", + [ + &["module 0..38"], + &["FilePackage Single [16..34] \"audit\" 0..5<-28..33"], + &["0 Resolved module 0..38 by - Unknown"], + &[], + ], + ), + // b10_module_in_a_function_body + ( + concat!( + "defmodule M do\ndef g() do\ndefmodule N do\n@moduledoc \"n\"\nen", + "d\nend\nend" + ), + [ + &["module 0..67", "group 0..67: 15..63", "module 26..59"], + &["FilePackage Single [41..55] \"n\" 0..1<-53..54"], + &["0 Resolved module 26..59 by - Unknown"], + &[], + ], + ), + // b11_moduledoc_with_a_pending_value + ( + "defmodule M do\n@moduledoc false\nend", + [ + &["module 0..35"], + &["FilePackage Single [15..31] pending"], + &["0 Resolved module 0..35 by - Unknown"], + &["Composition VALUE unary_operator 15..31 0"], + ], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_clauses_join_one_group_by_kind_name_and_arity() { + assert_views(&[ + // c01_head_and_clauses + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x)\ndef f(0), do: 0\ndef f", + "(x), do: x\nend" + ), + [ + &["module 0..72", "group 0..72: 28..36, 37..52, 53..68"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..72: 28..36, 37..52, 53..68 by 28..36 Unknown"], + &[], + ], + ), + // c02_arity + ( + concat!( + "defmodule M do\n@doc \"one\"\ndef f(x), do: x\n@doc \"two\"\ndef", + " f(x,y), do: x+y\nend" + ), + [ + &["module 0..76", "group 0..76: 26..41", "group 0..76: 53..72"], + &[ + "Primary Single [15..25] \"one\" 0..3<-21..24", + "Primary Single [42..52] \"two\" 0..3<-48..51", + ], + &[ + "0 Resolved group 0..76: 26..41 by 26..41 Unknown", + "1 Resolved group 0..76: 53..72 by 53..72 Unknown", + ], + &[], + ], + ), + // c03_default_argument + ( + "defmodule M do\n@doc \"audit\"\ndef f(x \\\\ 0), do: x\nend", + [ + &["module 0..52", "group 0..52: 28..48"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..52: 28..48 by 28..48 Unknown"], + &[], + ], + ), + // c04_clause_that_is_not_adjacent + ( + concat!( + "defmodule M do\ndef h(x), do: x\n@doc \"audit\"\ndef i(x), do: x", + "\ndef h(y), do: y\nend" + ), + [ + &[ + "module 0..79", + "group 0..79: 15..30, 60..75", + "group 0..79: 44..59", + ], + &["Primary Single [31..43] \"audit\" 0..5<-37..42"], + &["0 Resolved group 0..79: 44..59 by 44..59 Unknown"], + &[], + ], + ), + // c05_guarded_and_plain_clause + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when x > 0, do: x\ndef ", + "f(x), do: x\nend" + ), + [ + &["module 0..74", "group 0..74: 28..54, 55..70"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..74: 28..54, 55..70 by 28..54 Unknown"], + &[], + ], + ), + // c06_bare_head_and_empty_parentheses + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f\ndef f(), do: :ok\ndef f w", + "hen true, do: :no\nend" + ), + [ + &["module 0..79", "group 0..79: 28..33, 34..50, 51..75"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..79: 28..33, 34..50, 51..75 by 28..33 Unknown"], + &[], + ], + ), + // c07_kinds_stay_apart + ( + concat!( + "defmodule M do\n@doc \"one\"\ndef f(x), do: x\n@doc \"two\"\ndef", + "macro f(x), do: x\ndefp f(x), do: x\ndefmacrop f(x), do: x\nend" + ), + [ + &[ + "module 0..116", + "group 0..116: 26..41", + "group 0..116: 53..73", + "group 0..116: 74..90", + "group 0..116: 91..112", + ], + &[ + "Primary Single [15..25] \"one\" 0..3<-21..24", + "Primary Single [42..52] \"two\" 0..3<-48..51", + ], + &[ + "0 Resolved group 0..116: 26..41 by 26..41 Unknown", + "1 Resolved group 0..116: 53..73 by 53..73 Unknown", + ], + &[], + ], + ), + // c08_written_arguments_are_counted + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(a, # c\n b), do: a\ndef f(", + "a, b), do: b\ndef g(a, b: 1), do: a\ndef g(a, b), do: b\ndef f(a", + "), do: a\nend" + ), + [ + &[ + "module 0..131", + "group 0..131: 28..51, 52..70", + "group 0..131: 71..92, 93..111", + "group 0..131: 112..127", + ], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..131: 28..51, 52..70 by 28..51 Unknown"], + &[], + ], + ), + // c09_names_of_one_length + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef ab(x), do: x\ndef ac(x), do:", + " x\ndef ab(y), do: y\nend" + ), + [ + &[ + "module 0..82", + "group 0..82: 28..44, 62..78", + "group 0..82: 45..61", + ], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..82: 28..44, 62..78 by 28..44 Unknown"], + &[], + ], + ), + // c10_do_on_the_next_row + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x)\ndo\nx\nend\ndef f(y) d", + "o\ny\nend\nend" + ), + [ + &["module 0..67", "group 0..67: 28..45, 46..63"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..67: 28..45, 46..63 by 28..45 Unknown"], + &[], + ], + ), + // c11_unquoted_argument + ( + "defmodule M do\n@doc \"audit\"\ndef f(unquote(x)), do: x\nend", + [ + &["module 0..56", "group 0..56: 28..52"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..56: 28..52 by 28..52 Unknown"], + &[], + ], + ), + // c12_names_that_the_compiler_normalizes + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef \u{b5}(x), do: x\ndef ", + "\u{3bc}(x), do: x\nend" + ), + [ + &["module 0..65", "group 0..65: 28..44", "group 0..65: 45..61"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..65: 28..44 by 28..44 Unknown"], + &[], + ], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +fn elixir_private_definitions_keep_their_document_as_ineligible() { + assert_views(&[ + // d01_defp + ( + "defmodule M do\n@doc \"audit\"\ndefp f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 28..45"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..49: 28..45 by 28..45 Ineligible"], + &[], + ], + ), + // d02_defmacrop + ( + "defmodule M do\n@doc \"audit\"\ndefmacrop f(), do: :ok\nend", + [ + &["module 0..54", "group 0..54: 28..50"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..54: 28..50 by 28..50 Ineligible"], + &[], + ], + ), + // d03_defp_with_a_pending_value + ( + "defmodule M do\n@doc false\ndefp f(), do: :ok\nend", + [ + &["module 0..47", "group 0..47: 26..43"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..47: 26..43 by 26..43 Ineligible"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_attribute_is_read_past_comments_and_other_attributes() { + assert_views(&[ + // e01_semicolon_comment_blank_row_and_spec + ( + concat!( + "defmodule M do\n@doc \"audit\"; # note\n\n@spec f() :: atom()\nd", + "ef f(), do: :ok\nend" + ), + [ + &["module 0..77", "group 0..77: 57..73"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..77: 57..73 by 57..73 Unknown"], + &[], + ], + ), + // e02_other_attributes_and_reads + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@impl true\n@deprecated \"x\"\n@", + "foo 1\n@doc\n@doc()\ndef f(), do: :ok\nend" + ), + [ + &["module 0..94", "group 0..94: 74..90"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..94: 74..90 by 74..90 Unknown"], + &[], + ], + ), + // e03_crlf + ( + "defmodule M do\r\n@doc \"audit\"\r\ndef f(), do: :ok\r\nend", + [ + &["module 0..51", "group 0..51: 30..46"], + &["Primary Single [16..28] \"audit\" 0..5<-22..27"], + &["0 Resolved group 0..51: 30..46 by 30..46 Unknown"], + &[], + ], + ), + // e04_row_with_a_lone_backslash + ( + "defmodule M do\n@doc \"audit\"\n\\\ndef f(), do: :ok\nend", + [ + &["module 0..50", "group 0..50: 30..46"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..50: 30..46 by 30..46 Unknown"], + &[], + ], + ), + // e05_semicolon_on_one_row + ( + "defmodule M do\n@doc \"audit\"; def f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 29..45"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..49: 29..45 by 29..45 Unknown"], + &[], + ], + ), + // e06_comment_that_ends_with_a_backslash + ( + "defmodule M do\n@doc \"audit\" # c \\\ndef f(), do: :ok\nend", + [ + &["module 0..54", "group 0..54: 34..50"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..54: 34..50 by 34..50 Unknown"], + &[], + ], + ), + // e07_continued_row_then_comment + ( + "defmodule M do\n@doc \"audit\" \\\n# c\ndef f(), do: :ok\nend", + [ + &["module 0..54", "group 0..54: 34..50"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..54: 34..50 by 34..50 Unknown"], + &[], + ], + ), + // e08_space_after_the_operator + ( + "defmodule M do\n@ doc \"audit\"\ndef f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 29..45"], + &["Primary Single [15..28] \"audit\" 0..5<-22..27"], + &["0 Resolved group 0..49: 29..45 by 29..45 Unknown"], + &[], + ], + ), + // e09_line_end_after_the_operator + ( + "defmodule M do\n@\ndoc \"audit\"\ndef f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 29..45"], + &["Primary Single [15..28] \"audit\" 0..5<-22..27"], + &["0 Resolved group 0..49: 29..45 by 29..45 Unknown"], + &[], + ], + ), + // e10_comment_after_the_operator + ( + "defmodule M do\n@ # c\ndoc \"audit\"\ndef f(), do: :ok\nend", + [ + &["module 0..53", "group 0..53: 33..49"], + &["Primary Single [15..32] \"audit\" 0..5<-26..31"], + &["0 Resolved group 0..53: 33..49 by 33..49 Unknown"], + &[], + ], + ), + // e11_value_in_parentheses + ( + "defmodule M do\n@doc(\"audit\")\ndef f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 29..45"], + &["Primary Single [15..28] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..49: 29..45 by 29..45 Unknown"], + &[], + ], + ), + // e13_moduledoc_and_reads_between + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@behaviour B\n@type t :: atom()", + "\n@opaque o :: atom()\n@before_compile B\ndef f(), do: :ok\nend" + ), + [ + &["module 0..117", "group 0..117: 97..113"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..117: 97..113 by 97..113 Unknown"], + &[], + ], + ), + // e12_typedoc_between + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@typedoc \"t\"\n@type t :: atom(", + ")\ndef f(), do: :ok\nend" + ), + [ + &["module 0..79", "group 0..79: 59..75"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..79: 59..75 by 59..75 Unknown"], + &["Owner UNOWNED unary_operator 28..40 -"], + ], + ), + ]); +} + +// Decision E5 leaves this undecided: by the reading of the compiler the next definition +// takes the attribute whatever stands between. The unit publishes no owner and one +// assessment; a later unit decides. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_statement_between_leaves_the_attribute_without_an_owner() { + assert_views(&[ + // f01_match_between + ( + "defmodule M do\n@doc \"audit\"\nx = 1\ndef f(), do: :ok\nend", + [ + &["module 0..54", "group 0..54: 34..50"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f02_alias_between + ( + "defmodule M do\n@doc \"audit\"\nalias A.B\ndef f(), do: :ok\nend", + [ + &["module 0..58", "group 0..58: 38..54"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f03_nested_module_between + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefmodule N do\ndef g(), do: 1\n", + "end\ndef f(), do: :ok\nend" + ), + [ + &[ + "module 0..82", + "group 0..82: 62..78", + "module 28..61", + "group 28..61: 43..57", + ], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f04_end_of_the_body + ( + "defmodule M do\n@doc \"audit\"\nend", + [ + &["module 0..31"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f05_unary_statement_between + ( + "defmodule M do\n@doc \"audit\"\n- 1\ndef f(), do: :ok\nend", + [ + &["module 0..52", "group 0..52: 32..48"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f06_callback_takes_the_attribute + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@callback g() :: atom()\ndef f()", + ", do: :ok\nend" + ), + [ + &["module 0..72", "group 0..72: 52..68"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f07_macrocallback_takes_the_attribute + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@macrocallback g() :: atom()\nde", + "f f(), do: :ok\nend" + ), + [ + &["module 0..77", "group 0..77: 57..73"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f08_two_attributes_released + ( + concat!( + "defmodule M do\n@doc \"a\"\n@doc \"b\"\nx = 1\ndef f(), do: :ok", + "\nend" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &[], + &[], + &[ + "Owner UNOWNED unary_operator 15..23 -", + "Owner UNOWNED unary_operator 24..32 -", + ], + ], + ), + // f09_list_on_the_next_row + ( + "defmodule M do\n@doc \"audit\"\n[0]\ndef f(), do: :ok\nend", + [ + &["module 0..52", "group 0..52: 32..48"], + &[], + &[], + &["Owner UNOWNED unary_operator 15..27 -"], + ], + ), + // f10_next_run_after_a_release + ( + concat!( + "defmodule M do\n@doc \"a\"\nx = 1\n@doc \"b\"\ndef f(), do: :ok", + "\nend" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &["Primary Single [30..38] \"b\" 0..1<-36..37"], + &["0 Resolved group 0..59: 39..55 by 39..55 Unknown"], + &["Owner UNOWNED unary_operator 15..23 -"], + ], + ), + ]); +} + +// A pending outcome: these definitions are not read yet. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_definitions_that_are_not_read_stay_pending() { + assert_views(&[ + // g01_defguard + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefguard is_ok(x) when x == :ok", + "\ndef f(), do: :ok\nend" + ), + [ + &["module 0..80", "group 0..80: 60..76"], + &[], + &[], + &[ + "Owner PROJECTION call 28..59 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g02_defguardp + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefguardp is_ok(x) when x == :ok", + "\ndef f(), do: :ok\nend" + ), + [ + &["module 0..81", "group 0..81: 61..77"], + &[], + &[], + &[ + "Owner PROJECTION call 28..60 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g03_defdelegate + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefdelegate g(x), to: N\ndef f()", + ", do: :ok\nend" + ), + [ + &["module 0..72", "group 0..72: 52..68"], + &[], + &[], + &[ + "Owner PROJECTION call 28..51 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g04_operator_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef a + b, do: a\ndef f(), do: :", + "ok\nend" + ), + [ + &["module 0..65", "group 0..65: 45..61"], + &[], + &[], + &[ + "Owner PROJECTION call 28..44 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g05_unquote_head_with_arguments + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef unquote(name)(x), do: x\ndef", + " f(), do: :ok\nend" + ), + [ + &["module 0..76", "group 0..76: 56..72"], + &[], + &[], + &[ + "Owner PROJECTION call 28..55 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g06_unquote_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef unquote(name), do: 1\ndef f(", + "), do: :ok\nend" + ), + [ + &["module 0..73", "group 0..73: 53..69"], + &[], + &[], + &[ + "Owner PROJECTION call 28..52 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g07_spliced_arguments + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef g(unquote_splicing(args)), d", + "o: 1\ndef f(), do: :ok\nend" + ), + [ + &["module 0..85", "group 0..85: 65..81"], + &[], + &[], + &[ + "Owner PROJECTION call 28..64 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g08_definition_call_in_parentheses + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef(g(x), do: x)\ndef f(), do: :", + "ok\nend" + ), + [ + &["module 0..65", "group 0..65: 45..61"], + &[], + &[], + &[ + "Owner PROJECTION call 28..44 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g09_head_without_parentheses + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef g x, y do\nx\nend\ndef f(), ", + "do: :ok\nend" + ), + [ + &["module 0..68", "group 0..68: 48..64"], + &[], + &[], + &[ + "Owner PROJECTION call 28..47 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g10_qualified_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef N.g(y), do: y\ndef f(), do: ", + ":ok\nend" + ), + [ + &["module 0..66", "group 0..66: 46..62"], + &[], + &[], + &[ + "Owner PROJECTION call 28..45 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g11_guarded_operator_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef a + b when a > 0, do: a\ndef", + " f(), do: :ok\nend" + ), + [ + &["module 0..76", "group 0..76: 56..72"], + &[], + &[], + &[ + "Owner PROJECTION call 28..55 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g12_private_operator_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefp a + b, do: a\ndef f(), do: ", + ":ok\nend" + ), + [ + &["module 0..66", "group 0..66: 46..62"], + &[], + &[], + &[ + "Owner PROJECTION call 28..45 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g13_macro_with_an_unquote_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefmacro unquote(name)(x), do: x", + "\ndef f(), do: :ok\nend" + ), + [ + &["module 0..81", "group 0..81: 61..77"], + &[], + &[], + &[ + "Owner PROJECTION call 28..60 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // g14_private_macro_with_a_qualified_head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefmacrop N.g(y), do: y\ndef f()", + ", do: :ok\nend" + ), + [ + &["module 0..72", "group 0..72: 52..68"], + &[], + &[], + &[ + "Owner PROJECTION call 28..51 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + ]); +} + +// Every value but one plain string is a pending outcome of this unit. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_plain_string_is_the_only_value_with_text() { + assert_views(&[ + // h01_empty_string + ( + "defmodule M do\n@doc \"\"\ndef f(), do: :ok\nend", + [ + &["module 0..43", "group 0..43: 23..39"], + &["Primary Single [15..22] \"\""], + &["0 Resolved group 0..43: 23..39 by 23..39 Unknown"], + &[], + ], + ), + // h02_hash_without_brace + ( + "defmodule M do\n@doc \"a#b\"\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] \"a#b\" 0..3<-21..24"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &[], + ], + ), + // h03_line_end_inside + ( + "defmodule M do\n@doc \"au\ndit\"\ndef f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 29..45"], + &["Primary Single [15..28] \"au\\ndit\" 0..6<-21..27"], + &["0 Resolved group 0..49: 29..45 by 29..45 Unknown"], + &[], + ], + ), + // h04_crlf_inside + ( + "defmodule M do\n@doc \"au\r\ndit\"\ndef f(), do: :ok\nend", + [ + &["module 0..50", "group 0..50: 30..46"], + &["Primary Single [15..29] \"au\\r\\ndit\" 0..7<-21..28"], + &["0 Resolved group 0..50: 30..46 by 30..46 Unknown"], + &[], + ], + ), + // h05_two_byte_character + ( + "defmodule M do\n@doc \"\u{e9}t\u{e9}\"\ndef f(), do: :ok\nend", + [ + &["module 0..48", "group 0..48: 28..44"], + &["Primary Single [15..27] \"\u{e9}t\u{e9}\" 0..5<-21..26"], + &["0 Resolved group 0..48: 28..44 by 28..44 Unknown"], + &[], + ], + ), + // h06_tab_inside + ( + "defmodule M do\n@doc \"a\tb\"\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] \"a\\tb\" 0..3<-21..24"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &[], + ], + ), + // h10_heredoc + ( + concat!( + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\"\ndef f(), do: :ok\nen", + "d" + ), + [ + &["module 0..54", "group 0..54: 34..50"], + &["Primary Single [15..33] pending"], + &["0 Resolved group 0..54: 34..50 by 34..50 Unknown"], + &["Composition VALUE unary_operator 15..33 0"], + ], + ), + // h11_escape + ( + "defmodule M do\n@doc \"a\\nb\"\ndef f(), do: :ok\nend", + [ + &["module 0..47", "group 0..47: 27..43"], + &["Primary Single [15..26] pending"], + &["0 Resolved group 0..47: 27..43 by 27..43 Unknown"], + &["Composition VALUE unary_operator 15..26 0"], + ], + ), + // h12_interpolation + ( + "defmodule M do\n@doc \"a#{x}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..49", "group 0..49: 29..45"], + &["Primary Single [15..28] pending"], + &["0 Resolved group 0..49: 29..45 by 29..45 Unknown"], + &["Composition VALUE unary_operator 15..28 0"], + ], + ), + // h13_raw_sigil + ( + "defmodule M do\n@doc ~S(a)\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + // h14_cooked_sigil + ( + "defmodule M do\n@doc ~s(a)\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + // h15_charlist + ( + "defmodule M do\n@doc 'audit'\ndef f(), do: :ok\nend", + [ + &["module 0..48", "group 0..48: 28..44"], + &["Primary Single [15..27] pending"], + &["0 Resolved group 0..48: 28..44 by 28..44 Unknown"], + &["Composition VALUE unary_operator 15..27 0"], + ], + ), + // h16_false + ( + "defmodule M do\n@doc false\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + // h17_nil + ( + "defmodule M do\n@doc nil\ndef f(), do: :ok\nend", + [ + &["module 0..44", "group 0..44: 24..40"], + &["Primary Single [15..23] pending"], + &["0 Resolved group 0..44: 24..40 by 24..40 Unknown"], + &["Composition VALUE unary_operator 15..23 0"], + ], + ), + // h18_keyword_metadata + ( + "defmodule M do\n@doc since: \"1\"\ndef f(), do: :ok\nend", + [ + &["module 0..51", "group 0..51: 31..47"], + &["Primary Single [15..30] pending"], + &["0 Resolved group 0..51: 31..47 by 31..47 Unknown"], + &["Composition VALUE unary_operator 15..30 0"], + ], + ), + // h19_concatenation + ( + "defmodule M do\n@doc \"a\" <> \"b\"\ndef f(), do: :ok\nend", + [ + &["module 0..51", "group 0..51: 31..47"], + &["Primary Single [15..30] pending"], + &["0 Resolved group 0..51: 31..47 by 31..47 Unknown"], + &["Composition VALUE unary_operator 15..30 0"], + ], + ), + // h20_text_and_metadata + ( + concat!( + "defmodule M do\n@doc \"audit\", since: \"1\"\ndef f(), do: :ok\n", + "end" + ), + [ + &["module 0..60", "group 0..60: 40..56"], + &["Primary Single [15..39] pending"], + &["0 Resolved group 0..60: 40..56 by 40..56 Unknown"], + &["Composition VALUE unary_operator 15..39 0"], + ], + ), + // h21_block_after_a_space + ( + "defmodule M do\n@doc (\"audit\")\ndef f(), do: :ok\nend", + [ + &["module 0..50", "group 0..50: 30..46"], + &["Primary Single [15..29] pending"], + &["0 Resolved group 0..50: 30..46 by 30..46 Unknown"], + &["Composition VALUE unary_operator 15..29 0"], + ], + ), + // h22_do_block + ( + "defmodule M do\n@doc \"audit\" do\nend\ndef f(), do: :ok\nend", + [ + &["module 0..55", "group 0..55: 35..51"], + &["Primary Single [15..34] pending"], + &["0 Resolved group 0..55: 35..51 by 35..51 Unknown"], + &["Composition VALUE unary_operator 15..34 0"], + ], + ), + // h23_lone_cr_inside + ( + "defmodule M do\n@doc \"a\rb\"\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + // h24_vertical_tab_inside + ( + "defmodule M do\n@doc \"a\u{b}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + // h25_form_feed_inside + ( + "defmodule M do\n@doc \"a\u{c}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] pending"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &["Composition VALUE unary_operator 15..25 0"], + ], + ), + // h26_next_line_character + ( + "defmodule M do\n@doc \"a\u{85}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..47", "group 0..47: 27..43"], + &["Primary Single [15..26] pending"], + &["0 Resolved group 0..47: 27..43 by 27..43 Unknown"], + &["Composition VALUE unary_operator 15..26 0"], + ], + ), + // h27_line_separator + ( + "defmodule M do\n@doc \"a\u{2028}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..48", "group 0..48: 28..44"], + &["Primary Single [15..27] pending"], + &["0 Resolved group 0..48: 28..44 by 28..44 Unknown"], + &["Composition VALUE unary_operator 15..27 0"], + ], + ), + // h28_right_to_left_override + ( + "defmodule M do\n@doc \"a\u{202e}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..48", "group 0..48: 28..44"], + &["Primary Single [15..27] pending"], + &["0 Resolved group 0..48: 28..44 by 28..44 Unknown"], + &["Composition VALUE unary_operator 15..27 0"], + ], + ), + // h29_pop_directional_isolate + ( + "defmodule M do\n@doc \"a\u{2069}b\"\ndef f(), do: :ok\nend", + [ + &["module 0..48", "group 0..48: 28..44"], + &["Primary Single [15..27] pending"], + &["0 Resolved group 0..48: 28..44 by 28..44 Unknown"], + &["Composition VALUE unary_operator 15..27 0"], + ], + ), + // h30_comment_in_parentheses + ( + "defmodule M do\n@doc(# c\n\"audit\")\ndef f(), do: :ok\nend", + [ + &["module 0..53", "group 0..53: 33..49"], + &["Primary Single [15..32] \"audit\" 0..5<-25..30"], + &["0 Resolved group 0..53: 33..49 by 33..49 Unknown"], + &[], + ], + ), + // h31_atom + ( + "defmodule M do\n@doc :audit\ndef f(), do: :ok\nend", + [ + &["module 0..47", "group 0..47: 27..43"], + &["Primary Single [15..26] pending"], + &["0 Resolved group 0..47: 27..43 by 27..43 Unknown"], + &["Composition VALUE unary_operator 15..26 0"], + ], + ), + // h32_number + ( + "defmodule M do\n@doc 1\ndef f(), do: :ok\nend", + [ + &["module 0..42", "group 0..42: 22..38"], + &["Primary Single [15..21] pending"], + &["0 Resolved group 0..42: 22..38 by 22..38 Unknown"], + &["Composition VALUE unary_operator 15..21 0"], + ], + ), + // h33_neighbours_of_the_rejected + ( + concat!( + "defmodule M do\n@doc \"a\u{84}\u{2027}\u{202f}\u{2065}\u{206a}b", + "\"\ndef f(), do: :ok\nend" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &[concat!( + "Primary Single [15..38] \"a\\u{84}\u{2027}\\u{202f}\\u{2065}\\u{", + "206a}b\" 0..16<-21..37" + )], + &["0 Resolved group 0..59: 39..55 by 39..55 Unknown"], + &[], + ], + ), + // h35_backslash_before_a_line_end_inside + ( + "defmodule M do\n@doc \"a\\\nb\"\ndef f(), do: :ok\nend", + [ + &["module 0..47", "group 0..47: 27..43"], + &["Primary Single [15..26] pending"], + &["0 Resolved group 0..47: 27..43 by 27..43 Unknown"], + &["Composition VALUE unary_operator 15..26 0"], + ], + ), + ]); + // A byte that is no UTF-8 is in no `&str`. + let source = b"defmodule M do\n@doc \"a\xffb\"\ndef f(), do: :ok\nend"; + let rows: Rows = [ + &["module 0..46", "group 0..46: 26..42"], + &["Primary Single [15..25] unavailable InvalidEncoding"], + &["0 Resolved group 0..46: 26..42 by 26..42 Unknown"], + &[], + ]; + assert_eq!( + collected(source, &DocumentationOptions::default()), + expected(rows) + ); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_rows_the_language_continues_belong_to_the_value() { + assert_views(&[ + // n01_pipe_on_the_next_row + ( + "defmodule M do\n@doc \"audit\"\n|> g()\ndef f(), do: :ok\nend", + [ + &["module 0..55", "group 0..55: 35..51"], + &["Primary Single [15..34] pending"], + &["0 Resolved group 0..55: 35..51 by 35..51 Unknown"], + &["Composition VALUE unary_operator 15..34 0"], + ], + ), + // n02_concatenation_on_the_next_row + ( + concat!( + "defmodule M do\n@doc \"audit\"\n<> \"more\"\ndef f(), do: :ok\ne", + "nd" + ), + [ + &["module 0..58", "group 0..58: 38..54"], + &["Primary Single [15..37] pending"], + &["0 Resolved group 0..58: 38..54 by 38..54 Unknown"], + &["Composition VALUE unary_operator 15..37 0"], + ], + ), + // n03_when_on_the_next_row + ( + "defmodule M do\n@doc \"audit\"\nwhen x\ndef f(), do: :ok\nend", + [ + &["module 0..55", "group 0..55: 35..51"], + &["Primary Single [15..34] pending"], + &["0 Resolved group 0..55: 35..51 by 35..51 Unknown"], + &["Composition VALUE unary_operator 15..34 0"], + ], + ), + // n04_do_on_the_next_row + ( + "defmodule M do\n@doc \"audit\"\ndo\nend\ndef f(), do: :ok\nend", + [ + &["module 0..55", "group 0..55: 35..51"], + &["Primary Single [15..34] pending"], + &["0 Resolved group 0..55: 35..51 by 35..51 Unknown"], + &["Composition VALUE unary_operator 15..34 0"], + ], + ), + // n05_comment_row_then_pipe + ( + concat!( + "defmodule M do\n@doc \"audit\"\n# c\n|> g()\ndef f(), do: :ok\ne", + "nd" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &["Primary Single [15..38] pending"], + &["0 Resolved group 0..59: 39..55 by 39..55 Unknown"], + &["Composition VALUE unary_operator 15..38 0"], + ], + ), + // n06_blank_rows_then_pipe + ( + concat!( + "defmodule M do\n@doc \"audit\"\n\n\n|> g()\ndef f(), do: :ok\nen", + "d" + ), + [ + &["module 0..57", "group 0..57: 37..53"], + &["Primary Single [15..36] pending"], + &["0 Resolved group 0..57: 37..53 by 37..53 Unknown"], + &["Composition VALUE unary_operator 15..36 0"], + ], + ), + // n07_not_in_on_the_next_row + ( + "defmodule M do\n@doc \"audit\"\nnot in x\ndef f(), do: :ok\nend", + [ + &["module 0..57", "group 0..57: 37..53"], + &["Primary Single [15..36] pending"], + &["0 Resolved group 0..57: 37..53 by 37..53 Unknown"], + &["Composition VALUE unary_operator 15..36 0"], + ], + ), + // n08_dot_on_the_next_row + ( + "defmodule M do\n@doc \"audit\"\n.g()\ndef f(), do: :ok\nend", + [ + &["module 0..53", "group 0..53: 33..49"], + &["Primary Single [15..32] pending"], + &["0 Resolved group 0..53: 33..49 by 33..49 Unknown"], + &["Composition VALUE unary_operator 15..32 0"], + ], + ), + ]); +} + +// A pending outcome: the selection among several attributes is a later unit. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_several_attributes_for_one_owner_form_one_pending_document() { + assert_views(&[ + // i01_attribute_before_a_later_clause + ( + concat!( + "defmodule M do\n@doc \"old\"\ndef g(0), do: 0\n@doc \"new\"\ndef", + " g(x), do: x\nend" + ), + [ + &["module 0..72", "group 0..72: 26..41, 53..68"], + &["Primary AttributeSequence [15..25, 42..52] pending"], + &["0 Resolved group 0..72: 26..41, 53..68 by 26..41 Unknown"], + &["Selection SEVERAL unary_operator 15..25 0"], + ], + ), + // i02_two_in_one_run + ( + concat!( + "defmodule M do\n@doc \"old\"\n@doc \"new\"\ndef f(), do: :ok\nen", + "d" + ), + [ + &["module 0..57", "group 0..57: 37..53"], + &["Primary AttributeSequence [15..25, 26..36] pending"], + &["0 Resolved group 0..57: 37..53 by 37..53 Unknown"], + &["Selection SEVERAL unary_operator 15..25 0"], + ], + ), + // i03_metadata_then_text + ( + concat!( + "defmodule M do\n@doc since: \"1\"\n@doc \"audit\"\ndef f(), do: ", + ":ok\nend" + ), + [ + &["module 0..64", "group 0..64: 44..60"], + &["Primary AttributeSequence [15..30, 31..43] pending"], + &["0 Resolved group 0..64: 44..60 by 44..60 Unknown"], + &["Selection SEVERAL unary_operator 15..30 0"], + ], + ), + // i04_false_then_text + ( + concat!( + "defmodule M do\n@doc false\n@doc \"audit\"\ndef f(), do: :ok\nen", + "d" + ), + [ + &["module 0..59", "group 0..59: 39..55"], + &["Primary AttributeSequence [15..25, 26..38] pending"], + &["0 Resolved group 0..59: 39..55 by 39..55 Unknown"], + &["Selection SEVERAL unary_operator 15..25 0"], + ], + ), + // i05_two_moduledocs + ( + concat!( + "defmodule M do\n@moduledoc \"a\"\ndef f(), do: :ok\n@moduledoc ", + "\"b\"\nend" + ), + [ + &["module 0..65", "group 0..65: 30..46"], + &["FilePackage AttributeSequence [15..29, 47..61] pending"], + &["0 Resolved module 0..65 by - Unknown"], + &["Selection SEVERAL unary_operator 15..29 0"], + ], + ), + // i06_binding_is_the_first_taker + ( + concat!( + "defmodule M do\ndef g(0), do: 0\n@doc \"old\"\ndef g(1), do: 1\n", + "@doc \"new\"\ndef g(x), do: x\nend" + ), + [ + &["module 0..88", "group 0..88: 15..30, 42..57, 69..84"], + &["Primary AttributeSequence [31..41, 58..68] pending"], + &["0 Resolved group 0..88: 15..30, 42..57, 69..84 by 42..57 Unknown"], + &["Selection SEVERAL unary_operator 31..41 0"], + ], + ), + ]); +} + +// A pending outcome: these attributes are assessed and have no document yet. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_attributes_outside_a_module_body_are_assessed() { + assert_views(&[ + // j01_file_level + ( + "@doc \"audit\"\ndef f(), do: :ok", + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 0..12 -", + "Owner PROJECTION call 13..29 -", + ], + ], + ), + // j02_function_body + ( + "defmodule M do\ndef g() do\n@doc \"audit\"\n:ok\nend\nend", + [ + &["module 0..50", "group 0..50: 15..46"], + &[], + &[], + &["Occurrence OUTSIDE unary_operator 26..38 -"], + ], + ), + // j03_block_in_a_module_body + ( + concat!( + "defmodule M do\nif true do\n@doc \"audit\"\ndef f(), do: :ok\nen", + "d\nend" + ), + [ + &["module 0..63"], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 26..38 -", + "Owner PROJECTION call 39..55 -", + ], + ], + ), + // j04_keyword_form_of_defmodule + ( + "defmodule M, do: (@doc \"audit\"; def f(), do: :ok)", + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 18..30 -", + "Owner PROJECTION call 0..49 -", + "Owner PROJECTION call 32..48 -", + ], + ], + ), + // j05_defprotocol + ( + "defprotocol P do\n@doc \"audit\"\ndef f(x)\nend", + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 17..29 -", + "Owner PROJECTION call 0..42 -", + "Owner PROJECTION call 30..38 -", + ], + ], + ), + // j06_defimpl + ( + "defimpl P, for: M do\n@doc \"audit\"\ndef f(), do: :ok\nend", + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 21..33 -", + "Owner PROJECTION call 0..54 -", + "Owner PROJECTION call 34..50 -", + ], + ], + ), + // j07_moduledoc_and_typedoc_at_file_level + ( + "@moduledoc \"m\"\n@typedoc \"t\"\n", + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 0..14 -", + "Occurrence OUTSIDE unary_operator 15..27 -", + ], + ], + ), + // j08_attribute_as_an_operand + ( + "defmodule M do\nx = @doc \"audit\"\ndef f(), do: :ok\nend", + [ + &["module 0..52", "group 0..52: 32..48"], + &[], + &[], + &["Occurrence OUTSIDE unary_operator 19..31 -"], + ], + ), + // j09_section_of_a_module_block + ( + concat!( + "defmodule M do\ndef f(), do: :ok\nelse\n@doc \"audit\"\ndef g(),", + " do: 1\nend" + ), + [ + &["module 0..68", "group 0..68: 15..31"], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 37..49 -", + "Owner PROJECTION call 50..64 -", + ], + ], + ), + ]); +} + +// A pending outcome: what a quoted attribute becomes is undecided. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_quoted_code_is_a_template() { + assert_views(&[ + // k01_quote_in_a_module + ( + concat!( + "defmodule M do\nquote do\n@doc \"audit\"\ndef f(), do: :ok\nend", + "\nend" + ), + [ + &["module 0..61"], + &[], + &[], + &["Occurrence TEMPLATE unary_operator 24..36 -"], + ], + ), + // k02_module_in_a_quote + ( + concat!( + "quote do\ndefmodule M do\n@moduledoc \"audit\"\n@doc \"x\"\ndef ", + "f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence TEMPLATE unary_operator 24..42 -", + "Occurrence TEMPLATE unary_operator 43..51 -", + ], + ], + ), + // k03_keyword_form_of_quote + ( + "quote do: (@doc \"audit\"; def f(), do: :ok)", + [ + &[], + &[], + &[], + &["Occurrence TEMPLATE unary_operator 11..23 -"], + ], + ), + // k04_definition_after_a_quote + ( + concat!( + "defmodule M do\nquote do\n@doc \"t\"\ndef g(), do: 1\nend\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend" + ), + [ + &["module 0..85", "group 0..85: 65..81"], + &["Primary Single [52..64] \"audit\" 0..5<-58..63"], + &["0 Resolved group 0..85: 65..81 by 65..81 Unknown"], + &["Occurrence TEMPLATE unary_operator 24..32 -"], + ], + ), + // k05_module_after_a_quote + ( + concat!( + "quote do\nquote do\n@doc \"a\"\nend\nend\ndefmodule M do\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend" + ), + [ + &["module 35..83", "group 35..83: 63..79"], + &["Primary Single [50..62] \"audit\" 0..5<-56..61"], + &["0 Resolved group 35..83: 63..79 by 63..79 Unknown"], + &["Occurrence TEMPLATE unary_operator 18..26 -"], + ], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_statement_with_a_syntax_error_is_not_read() { + assert_views(&[ + // l01_definition_with_an_error + ( + concat!( + "defmodule M do\n @doc \"audit\"\n def f(, do: :ok\n @doc \"ne", + "xt\"\n def g(), do: :ok\nend\n" + ), + [ + &["group 0..84: 64..80"], + &["Primary Single [50..61] \"next\" 0..4<-56..60"], + &["0 Resolved group 0..84: 64..80 by 64..80 Unknown"], + &[ + "Owner PROJECTION call 0..84 -", + "Owner PROJECTION call 32..47 -", + "Owner UNOWNED unary_operator 17..29 -", + ], + ], + ), + // l07_defp_with_an_error + ( + concat!( + "defmodule M do\n @doc \"audit\"\n defp f(, do: :ok\n @doc \"n", + "ext\"\n def g(), do: :ok\nend\n" + ), + [ + &["group 0..85: 65..81"], + &["Primary Single [51..62] \"next\" 0..4<-57..61"], + &["0 Resolved group 0..85: 65..81 by 65..81 Unknown"], + &[ + "Owner PROJECTION call 0..85 -", + "Owner PROJECTION call 32..48 -", + "Owner UNOWNED unary_operator 17..29 -", + ], + ], + ), + // l08_defmacro_with_an_error + ( + concat!( + "defmodule M do\n @doc \"audit\"\n defmacro f(, do: :ok\n @doc", + " \"next\"\n def g(), do: :ok\nend\n" + ), + [ + &["group 0..89: 69..85"], + &["Primary Single [55..66] \"next\" 0..4<-61..65"], + &["0 Resolved group 0..89: 69..85 by 69..85 Unknown"], + &[ + "Owner PROJECTION call 0..89 -", + "Owner PROJECTION call 32..52 -", + "Owner UNOWNED unary_operator 17..29 -", + ], + ], + ), + // l09_defmacrop_with_an_error + ( + concat!( + "defmodule M do\n @doc \"audit\"\n defmacrop f(, do: :ok\n @do", + "c \"next\"\n def g(), do: :ok\nend\n" + ), + [ + &["group 0..90: 70..86"], + &["Primary Single [56..67] \"next\" 0..4<-62..66"], + &["0 Resolved group 0..90: 70..86 by 70..86 Unknown"], + &[ + "Owner PROJECTION call 0..90 -", + "Owner PROJECTION call 32..53 -", + "Owner UNOWNED unary_operator 17..29 -", + ], + ], + ), + // l02_attribute_with_an_error + ( + "defmodule M do\n@doc \"a\" \"b\"\ndef f(), do: :ok\nend", + [ + &["group 0..48: 28..44"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 15..27 -", + "Owner PROJECTION call 0..48 -", + ], + ], + ), + // l03_moduledoc_with_an_error_ends_the_run + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@moduledoc \"a\" \"b\"\ndef f(),", + " do: :ok\nend" + ), + [ + &["group 0..67: 47..63"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 28..46 -", + "Owner PROJECTION call 0..67 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // l04_module_without_its_end + ( + concat!( + "defmodule M do\n@moduledoc \"m\"\n@doc \"audit\"\ndef f(), do: :", + "ok\n" + ), + [ + &["group 0..60: 43..59"], + &["Primary Single [30..42] \"audit\" 0..5<-36..41"], + &["0 Resolved group 0..60: 43..59 by 43..59 Unknown"], + &[ + "Owner PROJECTION call 0..60 -", + "Owner UNOWNED unary_operator 15..29 -", + ], + ], + ), + // l05_error_node_between + ( + "defmodule M do\n@doc \"audit\"\n1 def f(), do: :ok\nend", + [ + &[], + &[], + &[], + &[ + "Owner PROJECTION call 0..50 -", + "Owner PROJECTION call 30..46 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // l06_other_attribute_with_an_error + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@spec f( :: atom()\ndef f(), do:", + " :ok\nend" + ), + [ + &["group 0..67: 47..63"], + &[], + &[], + &[ + "Owner PROJECTION call 0..67 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // l11_error_row_between + ( + "defmodule M do\n@doc \"audit\"\n)\ndef f(), do: :ok\nend", + [ + &["group 0..50: 30..46"], + &[], + &[], + &[ + "Owner PROJECTION call 0..50 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // l12_nul_byte_in_a_comment + ( + "defmodule M do\n@doc \"audit\" # c\u{0} d\ndef f(), do: :ok\nend", + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 15..51 -", + "Owner PROJECTION call 0..55 -", + ], + ], + ), + // l10_nul_byte_in_a_string + ( + "defmodule M do\n@doc \"a\u{0}b\"\ndef f(), do: :ok\nend", + [ + &["group 0..46: 26..42"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 15..25 -", + "Owner PROJECTION call 0..46 -", + ], + ], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_statement_needs_a_line_end_or_semicolon_before_it() { + assert_views(&[ + // m01_definition_after_end_on_one_row + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f() do\n:ok\nend def g(), do", + ": :ok\nend" + ), + [ + &["group 0..67: 28..46"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..67: 28..46 by 28..46 Unknown"], + &[ + "Owner PROJECTION call 0..67 -", + "Owner PROJECTION call 47..63 -", + ], + ], + ), + // m02_attribute_after_end_on_one_row + ( + concat!( + "defmodule M do\ndef g() do\n:ok\nend @doc \"audit\"\ndef f(), do", + ": :ok\nend" + ), + [ + &["group 0..67: 15..33", "group 0..67: 47..63"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 34..46 -", + "Owner PROJECTION call 0..67 -", + ], + ], + ), + // m03_definition_after_a_heredoc_on_one_row + ( + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\" def f(), do: :ok\nend", + [ + &[], + &[], + &[], + &[ + "Owner PROJECTION call 0..54 -", + "Owner PROJECTION call 34..50 -", + "Owner UNOWNED unary_operator 15..33 -", + ], + ], + ), + // m04_attribute_after_a_continued_row + ( + concat!( + "defmodule M do\ndef g() do\n:ok\nend \\\n@doc \"audit\"\ndef f()", + ", do: :ok\nend" + ), + [ + &["group 0..69: 15..33", "group 0..69: 49..65"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 36..48 -", + "Owner PROJECTION call 0..69 -", + ], + ], + ), + // m05_definition_after_a_continued_crlf_row + ( + concat!( + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\" \\\r\ndef f(), do: :o", + "k\nend" + ), + [ + &[], + &[], + &[], + &[ + "Owner PROJECTION call 0..57 -", + "Owner PROJECTION call 37..53 -", + "Owner UNOWNED unary_operator 15..33 -", + ], + ], + ), + // m06_definition_after_a_moduledoc_on_one_row + ( + concat!( + "defmodule M do\n@moduledoc \"\"\"\naudit\n\"\"\" def f(), do: :o", + "k\nend" + ), + [ + &[], + &[], + &[], + &[ + "Owner PROJECTION call 0..60 -", + "Owner PROJECTION call 40..56 -", + "Owner UNOWNED unary_operator 15..39 -", + ], + ], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +fn elixir_error_node_above_a_module_leaves_its_associations_unresolved() { + assert_views(&[ + // p01_module_under_an_error_node + ( + concat!( + "defmodule A do\n) ) (\ndefmodule M do\n@moduledoc \"m\"\n@doc \"", + "audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 21..84", "group 21..84: 64..80"], + &[ + "FilePackage Single [36..50] \"m\" 0..1<-48..49", + "Primary Single [51..63] \"audit\" 0..5<-57..62", + ], + &[ + "0 Unresolved(GrammarBoundary) module 21..84 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 21..84: 64..80 by 64..80 Unk", + "nown" + ), + ], + &["Owner PROJECTION call 0..11 -"], + ], + ), + ]); +} + +// These spellings set or define the same things for the compiler. The unit does not see +// them; the rows pin that nothing is claimed for them. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_spellings_the_unit_does_not_see_publish_nothing() { + assert_views(&[ + // q01_qualified_attribute_and_definition + ( + concat!( + "defmodule M do\nKernel.@(doc \"audit\")\nKernel.def f(), do: :ok", + "\nend" + ), + [&["module 0..64"], &[], &[], &[]], + ), + // q02_qualified_defmodule + ( + "Kernel.defmodule M do\n@doc \"audit\"\ndef f(), do: :ok\nend", + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 22..34 -", + "Owner PROJECTION call 35..51 -", + ], + ], + ), + // q03_attribute_set_by_a_call + ( + concat!( + "defmodule M do\nModule.put_attribute(__MODULE__, :doc, {1, \"aud", + "it\"})\ndef f(), do: :ok\nend" + ), + [&["module 0..88", "group 0..88: 68..84"], &[], &[], &[]], + ), + // q04_macros_that_document + ( + concat!( + "defmodule M do\ndocs \"audit\"\nuse Documented, doc: \"audit\"\n", + "def f(), do: :ok\nend" + ), + [&["module 0..77", "group 0..77: 57..73"], &[], &[], &[]], + ), + // q05_other_attribute_names + ( + concat!( + "defmodule M do\n@docs \"audit\"\n@moduledocs \"audit\"\n@typedoc", + "s \"audit\"\ndef f(), do: :ok\nend" + ), + [&["module 0..87", "group 0..87: 67..83"], &[], &[], &[]], + ), + // q06_definitions_in_a_quote_and_under_an_operator + ( + concat!( + "quote do\ndef f(), do: :ok\ndefmodule M do\nend\nend\n@\ndef g()", + ", do: 1\n" + ), + [&[], &[], &[], &[]], + ), + ]); +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_excluded_ranges_bar_attachment_and_hide_words() { + let rows: [(&str, &[Range], Rows); 12] = [ + // o01_gap_between_attribute_and_definition + ( + "defmodule M do\n@doc \"audit\"\n# x\ndef f(), do: :ok\nend", + &[0..28, 32..52], + [ + &["group 0..52: 32..48"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Unresolved(ExcludedGap) group 0..52: 32..48 by 32..48 Unknown"], + &[ + "Owner PROJECTION call 0..52 -", + "Owner PROJECTION do_block 12..52 -", + ], + ], + ), + // o02_later_whole_pair + ( + concat!( + "defmodule M do\n@doc \"audit\"\n# x\ndef f(), do: :ok\n@doc \"la", + "ter\"\ndef g(), do: 1\nend" + ), + &[0..28, 32..80], + [ + &["group 0..80: 32..48", "group 0..80: 62..76"], + &[ + "Primary Single [15..27] \"audit\" 0..5<-21..26", + "Primary Single [49..61] \"later\" 0..5<-55..60", + ], + &[ + "0 Unresolved(ExcludedGap) group 0..80: 32..48 by 32..48 Unknown", + "1 Resolved group 0..80: 62..76 by 62..76 Unknown", + ], + &[ + "Owner PROJECTION call 0..80 -", + "Owner PROJECTION do_block 12..80 -", + ], + ], + ), + // o03_gap_between_two_clauses + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(0), do: 0\n# x\ndef f(x), ", + "do: x\nend" + ), + &[0..44, 48..67], + [ + &["group 0..67: 28..43, 48..63"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..67: 28..43, 48..63 by 28..43 Unknown"], + &[ + "Owner PROJECTION call 0..67 -", + "Owner PROJECTION do_block 12..67 -", + ], + ], + ), + // o04_gap_inside_a_definition + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(0), do: (\n# x\n0)\ndef f(", + "x), do: x\nend" + ), + &[0..44, 48..70], + [ + &["group 0..70: 51..66"], + &[], + &[], + &[ + "Owner PROJECTION arguments 32..50 -", + "Owner PROJECTION block 42..50 -", + "Owner PROJECTION call 0..70 -", + "Owner PROJECTION call 28..50 -", + "Owner PROJECTION do_block 12..70 -", + "Owner PROJECTION keywords 38..50 -", + "Owner PROJECTION pair 38..50 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // o08_statement_after_the_gap_releases_the_attribute + ( + concat!( + "defmodule M do\n@doc \"audit\"\n# x\nx = 1\n@doc \"later\"\ndef ", + "g(), do: 1\nend" + ), + &[0..28, 32..69], + [ + &["group 0..69: 51..65"], + &["Primary Single [38..50] \"later\" 0..5<-44..49"], + &["0 Resolved group 0..69: 51..65 by 51..65 Unknown"], + &[ + "Owner PROJECTION call 0..69 -", + "Owner PROJECTION do_block 12..69 -", + "Owner UNOWNED unary_operator 15..27 -", + ], + ], + ), + // o09_gap_with_no_attribute_waiting + ( + concat!( + "defmodule M do\ndef f(0), do: 0\n# x\n@doc \"later\"\ndef g(), d", + "o: 1\nend" + ), + &[0..31, 35..66], + [ + &["group 0..66: 15..30", "group 0..66: 48..62"], + &["Primary Single [35..47] \"later\" 0..5<-41..46"], + &["0 Resolved group 0..66: 48..62 by 48..62 Unknown"], + &[ + "Owner PROJECTION call 0..66 -", + "Owner PROJECTION do_block 12..66 -", + ], + ], + ), + // o05_gap_inside_the_attribute + ( + "defmodule M do\n@doc \"audit\"\ndef f(), do: :ok\nend", + &[0..23, 25..48], + [ + &["group 0..48: 28..44"], + &[], + &[], + &[ + "Owner PROJECTION arguments 20..27 -", + "Owner PROJECTION call 0..48 -", + "Owner PROJECTION call 16..27 -", + "Owner PROJECTION do_block 12..48 -", + "Owner PROJECTION quoted_content 21..26 -", + "Owner PROJECTION string 20..27 -", + "Owner PROJECTION unary_operator 15..27 -", + ], + ], + ), + // o06_gap_inside_the_module_word + ( + "defmoXXdule M do\n@doc \"audit\"\ndef f(), do: :ok\nend", + &[0..5, 7..50], + [ + &[], + &[], + &[], + &[ + "Occurrence TEMPLATE unary_operator 17..29 -", + "Owner PROJECTION call 0..50 -", + "Owner PROJECTION identifier 0..11 -", + ], + ], + ), + // o10_gap_inside_an_attribute_at_file_level + ( + "@doc \"audit\"\ndef f(), do: :ok", + &[0..8, 10..29], + [ + &[], + &[], + &[], + &[ + "Owner PROJECTION arguments 5..12 -", + "Owner PROJECTION call 1..12 -", + "Owner PROJECTION call 13..29 -", + "Owner PROJECTION quoted_content 6..11 -", + "Owner PROJECTION string 5..12 -", + "Owner PROJECTION unary_operator 0..12 -", + ], + ], + ), + // o07_adjacent_ranges + ( + "defmodule M do\n@doc \"audit\"\ndef f(), do: :ok\nend", + &[0..23, 23..48], + [ + &["module 0..48", "group 0..48: 28..44"], + &[concat!( + "Primary Single [15..23+23..27] \"audit\" 0..2<-21..23 2..5<-23..", + "26" + )], + &["0 Resolved group 0..48: 28..44 by 28..44 Unknown"], + &[], + ], + ), + // o11_gap_before_a_module_at_file_level + ( + concat!( + ":ok\n# x\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef ", + "f(), do: :ok\nend" + ), + &[0..4, 8..71], + [ + &["module 8..71", "group 8..71: 51..67"], + &[ + "FilePackage Single [23..37] \"x\" 0..1<-35..36", + "Primary Single [38..50] \"audit\" 0..5<-44..49", + ], + &[ + "0 Resolved module 8..71 by - Unknown", + "1 Resolved group 8..71: 51..67 by 51..67 Unknown", + ], + &[], + ], + ), + // o12_excluded_gap_after_an_escaped_line_feed + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@foo ?\\\n# x\ndef f(), do: :ok", + "\nend" + ), + &[0..36, 40..60], + [ + &["group 0..60: 40..56"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Unresolved(ExcludedGap) group 0..60: 40..56 by 40..56 Unknown"], + &[ + "Owner PROJECTION call 0..60 -", + "Owner PROJECTION do_block 12..60 -", + ], + ], + ), + ]; + for (source, included, rows) in rows { + let tree = restricted(source, included); + let index = collect( + LANG::Elixir, + &tree, + source.as_bytes(), + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(published(&index), expected(rows), "{source} {included:?}"); + } +} + +// The labels of the assessments that a query surfaces, sorted. +#[cfg(feature = "elixir")] +fn surfaced<'i, 's: 'i>( + assessments: impl Iterator>>, +) -> Vec<&'static str> { + let mut labels: Vec<_> = assessments + .map(|assessment| { + let reason = assessment.get().reason; + REASONS + .iter() + .find(|(_, known)| *known == reason) + .map_or(reason, |(label, _)| label) + }) + .collect(); + labels.sort_unstable(); + labels +} + +// The node of a written statement: the first `kind` node that spells `spelling`. +#[cfg(feature = "elixir")] +fn written<'t>( + tree: &'t tree_sitter::Tree, + source: &str, + kind: &str, + spelling: &str, +) -> tree_sitter::Node<'t> { + let start = source.find(spelling).unwrap(); + node_at(tree, kind, &(start..start + spelling.len())) +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_node_and_owner_queries_answer_for_the_group_and_the_module() { + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + // Every clause answers for its group, and the module for itself. + let source = "defmodule M do\n@doc \"audit\"\ndef f(x)\ndef f(0), do: 0\ndef f(x), do: x\nend"; + let parser = parsed(source.as_bytes()); + let index = parser.documentation(&context, &options).unwrap(); + let tree = parser.ts_tree(); + let association = index.associations().next().unwrap(); + let group = index.facts().associated_owner(association, 0).unwrap(); + for clause in ["def f(x)", "def f(0), do: 0", "def f(x), do: x"] { + let clause = written(tree, source, "call", clause); + let projection = index.node_projection(clause).unwrap(); + assert!(!projection.pending()); + assert!(projection.owners().eq([group])); + assert!(index.node_owners(clause).unwrap().eq([group])); + let query = index.node_associations(clause).unwrap(); + assert!(!query.projection_pending()); + assert!(query.associations().eq([association])); + assert_eq!(query.assessments().count(), 0); + } + let owned = index.owner_associations(group).unwrap(); + assert!(owned.associations().eq([association])); + assert_eq!(owned.qualifications().len(), 0); + let module = index.node_associations(tree.root_node().child(0).unwrap()); + let module = module.unwrap(); + assert!(!module.projection_pending()); + assert_eq!(module.associations().len(), 0); + assert_eq!(module.assessments().count(), 0); + // An attribute, a body, a head and a token are no owners. + for (kind, spelling) in [ + ("unary_operator", "@doc \"audit\""), + ("do_block", &source[12..]), + ("call", "f(0)"), + ("identifier", "defmodule"), + ("end", "end"), + ] { + let node = written(tree, source, kind, spelling); + assert!(matches!( + index.node_associations(node), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_projection(node), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_owners(node), + Err(OwnerError::UnsupportedOwner) + )); + } + // An attribute without an owner is surfaced by its module and by every group in it. + let source = "defmodule M do\n@doc \"audit\"\nx = 1\ndef f(), do: :ok\nend"; + let parser = parsed(source.as_bytes()); + let index = parser.documentation(&context, &options).unwrap(); + let tree = parser.ts_tree(); + for node in [ + tree.root_node().child(0).unwrap(), + written(tree, source, "call", "def f(), do: :ok"), + ] { + let query = index.node_associations(node).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 0); + assert_eq!(surfaced(query.assessments()), ["UNOWNED"]); + } + // A definition that is not read is a pending owner. + let source = "defmodule M do\n@doc \"audit\"\ndef a + b, do: a\nend"; + let parser = parsed(source.as_bytes()); + let index = parser.documentation(&context, &options).unwrap(); + let definition = written(parser.ts_tree(), source, "call", "def a + b, do: a"); + assert!(index.node_projection(definition).unwrap().pending()); + assert!(matches!( + index.node_owners(definition), + Err(OwnerError::PendingOwner) + )); + let query = index.node_associations(definition).unwrap(); + assert!(query.projection_pending()); + assert_eq!(surfaced(query.assessments()), ["PROJECTION", "UNOWNED"]); + // A pending value is surfaced by the owner of its document. + let source = "defmodule M do\n@doc false\ndefp f(), do: :ok\nend"; + let parser = parsed(source.as_bytes()); + let index = parser.documentation(&context, &options).unwrap(); + let clause = written(parser.ts_tree(), source, "call", "defp f(), do: :ok"); + let query = index.node_associations(clause).unwrap(); + assert_eq!(query.associations().len(), 1); + assert_eq!(surfaced(query.assessments()), ["VALUE"]); + // A module with a syntax error is a pending owner, and a quoted module is none. + let source = "defmodule M do\n@moduledoc \"m\"\n@doc \"audit\"\ndef f(), do: :ok\n"; + let parser = parsed(source.as_bytes()); + let index = parser.documentation(&context, &options).unwrap(); + let module = parser.ts_tree().root_node().child(0).unwrap(); + assert!(module.has_error()); + assert!(index.node_projection(module).unwrap().pending()); + let source = "quote do\ndefmodule M do\n@moduledoc \"audit\"\nend\nend"; + let parser = parsed(source.as_bytes()); + let index = parser.documentation(&context, &options).unwrap(); + let module = written( + parser.ts_tree(), + source, + "call", + "defmodule M do\n@moduledoc \"audit\"\nend", + ); + assert!(matches!( + index.node_projection(module), + Err(OwnerError::UnsupportedOwner) + )); +} + +#[test] +fn elixir_gap_string_and_name_scans_read_each_byte_once() { + // (the bytes between two statements, whether `?\` or `?` takes the first line + // feed, whether a line feed counts, whether they separate them, the bytes read) + let gaps: [(&[u8], bool, bool, bool, usize); 21] = [ + // expected: a line end; the scan stops there. + (b"\n", false, true, true, 1), + (b" \n ", false, true, true, 3), + (b"\r\n", false, true, true, 2), + // expected: no line end and no `;`. + (b"", false, true, false, 0), + (b" ", false, true, false, 2), + // expected: a backslash continues the line over LF and over CR LF. + (b" \\\n", false, true, false, 3), + (b" \\\r\n", false, true, false, 4), + // expected: the line end after a continued one is real. + (b" \\\n\n", false, true, true, 4), + // expected: a backslash that is not before the line end continues nothing. + (b"\\ \n", false, true, true, 3), + (b";", false, true, true, 1), + (b" ; \n", false, true, true, 2), + // expected: a comment runs to its line end, which no backslash continues, and + // a `;` inside it separates nothing. + (b" # c; \\\n", false, true, true, 8), + (b" # c;", false, true, false, 5), + (b" \\\n# c\n", false, true, true, 7), + // expected: `?\` or `?` takes the first line feed; a second line feed, a `;` or + // a comment after it separates. + (b"\n ", true, true, false, 3), + (b"\n\n", true, true, true, 2), + (b"\n;", true, true, true, 2), + (b"\n# c\n", true, true, true, 5), + // expected: behind a `,` token no line feed counts; a `;` outside a comment + // does, and a line feed still ends a comment before `;`. + (b"\n\n", false, false, false, 2), + (b" # c;\n", false, false, false, 6), + (b" # c\n;", false, false, true, 6), + ]; + for (gap, escaped, lines, apart, read) in gaps { + let budget = Counting::default(); + assert_eq!( + separated(gap, escaped, lines, &budget), + Ok(apart), + "{gap:?}" + ); + assert_eq!(budget.scanned.get(), read, "{gap:?}"); + assert_eq!(budget.steps.get() + budget.checkpoints.get(), 0, "{gap:?}"); + } + // (the bytes between two quotes, whether the compiler rejects one, the bytes read) + let texts: [(&str, bool, usize); 20] = [ + ("", false, 0), + ("audit", false, 5), + // expected: LF and CR LF are kept; a CR without LF is rejected. + ("a\nb", false, 3), + ("a\r\nb", false, 4), + ("a\rb", true, 2), + ("a\r", true, 2), + ("\u{b}", true, 1), + ("\u{c}", true, 1), + // expected: U+0085, U+2028 and U+2029 are line breaks; their neighbours are text. + ("\u{84}", false, 2), + ("\u{85}", true, 1), + ("\u{86}", false, 2), + ("\u{2027}", false, 3), + ("\u{2028}", true, 1), + ("\u{2029}", true, 1), + // expected: U+202A to U+202E and U+2066 to U+2069 are bidirectional controls. + ("\u{202a}", true, 1), + ("\u{202e}", true, 1), + ("\u{202f}", false, 3), + ("\u{2065}", false, 3), + ("\u{2066}x\u{2069}", true, 1), + ("\u{206a}", false, 3), + ]; + for (text, found, read) in texts { + let budget = Counting::default(); + assert_eq!(rejected(text.as_bytes(), &budget), Ok(found), "{text:?}"); + assert_eq!(budget.scanned.get(), read, "{text:?}"); + assert_eq!(budget.steps.get() + budget.checkpoints.get(), 0, "{text:?}"); + } + // (two names, whether they are the same bytes, the bytes read) + let names: [(&str, &str, bool, usize); 6] = [ + ("ab", "ab", true, 2), + // expected: the comparison stops at the first byte that differs. + ("ab", "ac", false, 2), + ("xb", "ab", false, 1), + // expected: names of two lengths differ, and no byte is read. + ("ab", "abc", false, 0), + ("abc", "ab", false, 0), + ("", "", true, 0), + ]; + for (left, right, equal, read) in names { + let source = format!("{left}{right}"); + let budget = Counting::default(); + let found = same( + source.as_bytes(), + 0..left.len(), + left.len()..source.len(), + &budget, + ); + assert_eq!(found, Ok(equal), "{left} {right}"); + assert_eq!(budget.scanned.get(), read, "{left} {right}"); + assert_eq!( + budget.steps.get() + budget.checkpoints.get(), + 0, + "{left} {right}" + ); + } +} + +// `count` clauses of one function. +#[cfg(feature = "elixir")] +fn clauses(count: usize) -> String { + format!("defmodule M do\n{}end", "def f(x), do: x\n".repeat(count)) +} + +// `count` documented functions of one clause each. +#[cfg(feature = "elixir")] +fn functions(count: usize) -> String { + let mut source = "defmodule M do\n".to_owned(); + for at in 0..count { + writeln!(source, "@doc \"d\"\ndef f{at}(x), do: x").unwrap(); + } + source + "end" +} + +// `count` attributes before one definition. +#[cfg(feature = "elixir")] +fn attributes(count: usize) -> String { + format!( + "defmodule M do\n{}def f(), do: :ok\nend", + "@doc \"d\"\n".repeat(count) + ) +} + +// `count` attributes at file level. +#[cfg(feature = "elixir")] +fn strays(count: usize) -> String { + "@doc \"d\"\n".repeat(count) +} + +// Two clauses of a function with `count` arguments and a name of `count` letters. +#[cfg(feature = "elixir")] +fn wide(count: usize) -> String { + let head = format!("{}({})", "n".repeat(count), vec!["x"; count].join(", ")); + format!("defmodule M do\ndef {head}, do: 0\ndef {head}, do: 1\nend") +} + +// One documented function with `count` comment rows in the parentheses of its attribute +// and as many in its argument list. +#[cfg(feature = "elixir")] +fn commented(count: usize) -> String { + let rows = "# c\n".repeat(count); + format!("defmodule M do\n@doc({rows}\"audit\")\ndef f({rows}x), do: x\nend") +} + +// `count` statements at file level. +#[cfg(feature = "elixir")] +fn statements(count: usize) -> String { + "x = 1\n".repeat(count) +} + +// `count` rows, each a module that is joined to the expression before it. +#[cfg(feature = "elixir")] +fn joined(count: usize) -> String { + "x = 1 defmodule X do\n@doc \"d\"\nend\n".repeat(count) +} + +// One statement: `count` operators deep, with a syntax error in the block at its end. +#[cfg(feature = "elixir")] +fn chain(count: usize) -> String { + format!("{}(1 1)", "a ++ ".repeat(count)) +} + +// `count` blocks, each in the one before, with a syntax error in the last. +#[cfg(feature = "elixir")] +fn blocks(count: usize) -> String { + format!("{}1 1{}", "(".repeat(count), ")".repeat(count)) +} + +// One documented function with `count` spaces after its attribute. +#[cfg(feature = "elixir")] +fn gapped(count: usize) -> String { + format!( + "defmodule M do\n@doc \"audit\"{}\ndef f(), do: :ok\nend", + " ".repeat(count) + ) +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_pass_charges_every_loop_and_byte_scan() { + // Each row is the steps, bytes and checkpoints of the second pass, as the charge + // table of the pass gives them for the parse of the source: a step for every node + // and for every child pushed, for every child that a count or a place of children + // passes, for every child that is compared with the statement before it, for every + // node searched for a recovery, for every statement of a body, for every coverage + // check and for every record filed; a byte for every byte of a gap, of a name + // hashed or compared and of a text scanned, and two for every byte of text copied. + let fixed: [(&str, [usize; 3]); 47] = [ + // a01_primary + // expected: steps: walk 59 + children 38 + gaps 5 + tail 4 + statements 4 + coverage 8 + + // filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text 10. + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + [128, 17, 2], + ), + // b03_moduledoc_then_doc + // expected: steps: walk 77 + children 55 + gaps 6 + tail 8 + statements 5 + coverage 10 + // + filed 4 + pieces 10 + copy 2; bytes: gap 2 + name 1 + scan 2 + text 4. + ( + concat!( + "defmodule M do\n@moduledoc \"m\"\n@doc \"d\"\ndef f(), do: :ok\n", + "end" + ), + [177, 9, 4], + ), + // c01_head_and_clauses + // expected: steps: walk 107 + children 69 + gaps 7 + tail 12 + statements 6 + coverage + // 18 + arguments 3 + candidates 2 + filed 5 + pieces 10 + copy 1; bytes: gap 3 + + // name 5 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x)\ndef f(0), do: 0\ndef f", + "(x), do: x\nend" + ), + [240, 23, 2], + ), + // c08_written_arguments_are_counted + // expected: steps: walk 197 + children 113 + gaps 9 + tail 20 + statements 8 + coverage + // 28 + arguments 13 + candidates 2 + filed 9 + pieces 14 + copy 1; bytes: gap 5 + + // name 7 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(a, # c\n b), do: a\ndef f(", + "a, b), do: b\ndef g(a, b: 1), do: a\ndef g(a, b), do: b\ndef f(a", + "), do: a\nend" + ), + [414, 27, 2], + ), + // c09_names_of_one_length + // expected: steps: walk 117 + children 71 + gaps 7 + tail 12 + statements 6 + coverage + // 18 + arguments 3 + candidates 1 + filed 6 + pieces 10 + copy 1; bytes: gap 3 + + // name 8 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef ab(x), do: x\ndef ac(x), do:", + " x\ndef ab(y), do: y\nend" + ), + [252, 26, 2], + ), + // e01_semicolon_comment_blank_row_and_spec + // expected: steps: walk 97 + children 51 + gaps 8 + tail 10 + statements 7 + coverage 12 + // + filed 3 + pieces 6 + copy 1; bytes: gap 2 + name 1 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"; # note\n\n@spec f() :: atom()\nd", + "ef f(), do: :ok\nend" + ), + [195, 18, 2], + ), + // e10_comment_after_the_operator + // expected: steps: walk 61 + children 42 + gaps 5 + tail 4 + statements 4 + coverage 8 + + // filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text 10. + ( + "defmodule M do\n@ # c\ndoc \"audit\"\ndef f(), do: :ok\nend", + [134, 17, 2], + ), + // f08_two_attributes_released + // expected: steps: walk 85 + children 55 + gaps 7 + tail 9 + statements 6 + coverage 12 + // + marks 2 + filed 2 + pieces 2; bytes: gap 3 + name 1. + ( + concat!( + "defmodule M do\n@doc \"a\"\n@doc \"b\"\nx = 1\ndef f(), do: :ok", + "\nend" + ), + [180, 4, 0], + ), + // g04_operator_head + // expected: steps: walk 83 + children 53 + gaps 6 + tail 8 + statements 5 + coverage 12 + // + marks 2 + filed 2 + pieces 2; bytes: gap 2 + name 1. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef a + b, do: a\ndef f(), do: :", + "ok\nend" + ), + [173, 3, 0], + ), + // h01_empty_string + // expected: steps: walk 57 + children 37 + gaps 5 + tail 4 + statements 4 + coverage 8 + + // filed 3 + pieces 4; bytes: gap 1 + name 1. + ( + "defmodule M do\n@doc \"\"\ndef f(), do: :ok\nend", + [122, 2, 0], + ), + // h10_heredoc + // expected: steps: walk 59 + children 38 + gaps 5 + tail 4 + statements 4 + coverage 8 + + // filed 3 + pieces 4; bytes: gap 1 + name 1. + ( + concat!( + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\"\ndef f(), do: :ok\nen", + "d" + ), + [125, 2, 0], + ), + // h23_lone_cr_inside + // expected: steps: walk 59 + children 38 + gaps 5 + tail 4 + statements 4 + coverage 8 + + // filed 3 + pieces 4; bytes: gap 1 + name 1 + scan 2. + ( + "defmodule M do\n@doc \"a\rb\"\ndef f(), do: :ok\nend", + [125, 4, 0], + ), + // i02_two_in_one_run + // expected: steps: walk 77 + children 55 + gaps 6 + tail 8 + statements 5 + coverage 10 + // + filed 4 + pieces 6; bytes: gap 2 + name 1. + ( + concat!( + "defmodule M do\n@doc \"old\"\n@doc \"new\"\ndef f(), do: :ok\nen", + "d" + ), + [171, 3, 0], + ), + // j01_file_level + // expected: steps: walk 45 + children 11 + gaps 2 + tail 4 + coverage 4; bytes: gap 1. + ("@doc \"audit\"\ndef f(), do: :ok", [66, 1, 0]), + // k02_module_in_a_quote + // expected: steps: walk 87 + children 16 + gaps 1 + coverage 3. + ( + concat!( + "quote do\ndefmodule M do\n@moduledoc \"audit\"\n@doc \"x\"\ndef ", + "f(), do: :ok\nend\nend" + ), + [107, 0, 0], + ), + // l02_attribute_with_an_error + // expected: steps: tear 28 + walk 71 + children 30 + gaps 19 + tail 7 + recovery 37 + + // statements 4 + coverage 8 + marks 2 + filed 2 + pieces 2; bytes: gap 2 + name 1. + ( + "defmodule M do\n@doc \"a\" \"b\"\ndef f(), do: :ok\nend", + [210, 3, 0], + ), + // l04_module_without_its_end + // expected: steps: tear 13 + walk 77 + children 55 + gaps 9 + tail 8 + recovery 13 + + // statements 5 + coverage 9 + marks 2 + filed 3 + pieces 6 + copy 1; bytes: gap 2 + + // name 1 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@moduledoc \"m\"\n@doc \"audit\"\ndef f(), do: :", + "ok\n" + ), + [201, 18, 2], + ), + // m01_definition_after_end_on_one_row + // expected: steps: tear 12 + walk 83 + children 43 + gaps 12 + tail 6 + recovery 13 + + // statements 5 + coverage 11 + marks 2 + filed 3 + pieces 6 + copy 1; bytes: gap 2 + + // name 1 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f() do\n:ok\nend def g(), do", + ": :ok\nend" + ), + [197, 18, 2], + ), + // h30_comment_in_parentheses + // expected: steps: walk 65 + children 44 + gaps 5 + tail 3 + statements 4 + coverage 8 + + // filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text 10. + ( + "defmodule M do\n@doc(# c\n\"audit\")\ndef f(), do: :ok\nend", + [139, 17, 2], + ), + // p01_module_under_an_error_node + // expected: steps: tear 12 + walk 99 + children 59 + gaps 14 + tail 9 + recovery 6 + + // statements 5 + coverage 12 + filed 4 + pieces 10 + copy 2; bytes: gap 3 + name 1 + + // scan 6 + text 12. + ( + concat!( + "defmodule A do\n) ) (\ndefmodule M do\n@moduledoc \"m\"\n@doc \"", + "audit\"\ndef f(), do: :ok\nend\nend" + ), + [232, 22, 4], + ), + // r01_doc_read_with_a_comment + // expected: steps: walk 57 + children 32 + gaps 5 + tail 3 + statements 4 + coverage 8 + + // filed 2 + pieces 2; bytes: gap 1 + name 1. + ( + "defmodule M do\n@doc( # c\n)\ndef f(), do: :ok\nend", + [113, 2, 0], + ), + // r05_read_before_a_real_attribute + // expected: steps: walk 75 + children 49 + gaps 6 + tail 7 + statements 5 + coverage 10 + // + filed 3 + pieces 6 + copy 1; bytes: gap 2 + name 1 + scan 5 + text 10. + ( + concat!( + "defmodule M do\n@doc( # c\n)\n@doc \"audit\"\ndef f(), do: :ok\n", + "end" + ), + [162, 18, 2], + ), + // t01_comment_before_the_do_of_a_module + // expected: steps: walk 61 + children 40 + gaps 5 + tail 4 + statements 4 + coverage 8 + + // filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text 10. + ( + "defmodule M # c\ndo\n@doc \"audit\"\ndef f(), do: :ok\nend", + [132, 17, 2], + ), + // t03_comment_after_when + // expected: steps: walk 79 + children 45 + gaps 5 + tail 4 + statements 4 + coverage 9 + + // arguments 1 + filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text + // 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when # c\n is_atom(x), ", + "do: x\nend" + ), + [157, 17, 2], + ), + // t10_two_comments_in_a_guarded_macro + // expected: steps: walk 79 + children 49 + gaps 8 + tail 4 + statements 4 + coverage 9 + + // arguments 1 + filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text + // 10. + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefmacro m(x) # c\n when is_atom", + "(x) # d\n do\nx\nend\nend" + ), + [164, 17, 2], + ), + // s01_module_after_a_module_at_file_level + // expected: steps: tear 3 + walk 109 + children 40 + gaps 5 + tail 2 + statements 3 + + // coverage 7 + filed 1 + pieces 4 + copy 1; bytes: gap 1 + scan 1 + text 2. + ( + concat!( + "defmodule A do\n@moduledoc \"a\"\nend defmodule X do\n@moduledoc", + " \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend" + ), + [175, 4, 2], + ), + // s02_module_after_a_definition_in_a_body + // expected: steps: tear 11 + walk 115 + children 42 + gaps 11 + tail 2 + recovery 12 + + // statements 4 + coverage 11 + marks 1 + filed 2 + pieces 2; bytes: gap 1 + name 1. + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend defmodule X do\n@moduledoc ", + "\"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [213, 2, 0], + ), + // s13_module_after_an_expression_at_file_level + // expected: steps: tear 9 + walk 87 + children 17 + gaps 6 + tail 1 + recovery 10 + + // coverage 4; bytes: gap 1. + ( + concat!( + "x = 1 defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(),", + " do: :ok\nend" + ), + [134, 1, 0], + ), + // s14_module_after_a_string + // expected: steps: tear 25 + walk 109 + children 23 + gaps 16 + tail 1 + recovery 21 + + // statements 3 + coverage 6 + marks 1; bytes: gap 1. + ( + concat!( + "defmodule M do\n\"s\" defmodule X do\n@moduledoc \"x\"\n@doc \"a", + "udit\"\ndef f(), do: :ok\nend\nend" + ), + [205, 1, 0], + ), + // u05_module_as_an_argument_of_a_call + // expected: steps: walk 93 + children 57 + gaps 6 + tail 8 + statements 5 + coverage 10 + // + filed 4 + pieces 10 + copy 2; bytes: gap 2 + name 1 + scan 6 + text 12. + ( + concat!( + "IO.inspect(defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef", + " f(), do: :ok\nend)" + ), + [195, 21, 4], + ), + // v01_expression_read_into_a_match + // expected: steps: tear 8 + walk 85 + children 55 + gaps 10 + tail 8 + recovery 8 + + // statements 5 + coverage 11 + filed 4 + pieces 10 + copy 2; bytes: gap 3 + name 1 + + // scan 6 + text 12. + ( + concat!( + "1 y = defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(),", + " do: :ok\nend" + ), + [206, 22, 4], + ), + // v05_error_in_a_head_and_a_sound_statement_after_it + // expected: steps: tear 23 + walk 179 + children 114 + gaps 25 + tail 22 + recovery 25 + + // statements 11 + coverage 24 + marks 3 + filed 7 + pieces 16 + copy 3; bytes: gap 5 + // + name 2 + scan 9 + text 18. + ( + concat!( + "defmodule M do\n@doc \"one\"\ndef a(, do: (\ndefmodule X do\n@mo", + "duledoc \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\n)\n@doc \"", + "two\"\ndef b(), do: :ok\nend" + ), + [452, 34, 6], + ), + // v06_recovery_among_the_clauses_of_a_function + // expected: steps: tear 14 + walk 115 + children 55 + gaps 16 + tail 11 + recovery 12 + + // statements 5 + coverage 12 + filed 4 + pieces 10 + copy 2; bytes: gap 4 + name 1 + + // scan 6 + text 12. + ( + concat!( + "f = fn\n1 1 -> :ok\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + [256, 23, 4], + ), + // v07_attribute_read_into_the_next_definition + // expected: steps: tear 20 + walk 121 + children 64 + gaps 21 + tail 9 + recovery 28 + + // statements 5 + coverage 13 + filed 4 + pieces 10 + copy 2; bytes: gap 3 + name 1 + + // scan 6 + text 12. + ( + concat!( + "@doc \"before\" def g() do\ndefmodule X do\n@moduledoc \"x\"\n@d", + "oc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [297, 22, 4], + ), + // w01_string_without_its_end + // expected: steps: tear 21 + walk 89 + children 21 + gaps 16 + recovery 22 + statements + // 5 + coverage 7 + marks 3. + ( + concat!( + "defmodule M do\nx = \"a\n@doc \"LIT\"\ndef lit, do: :ok\n@doc \"", + "REAL\"\ndef real, do: :ok\nend" + ), + [184, 0, 0], + ), + // w03_statements_before_the_tear_are_read + // expected: steps: tear 22 + walk 147 + children 53 + gaps 17 + tail 8 + recovery 23 + + // statements 7 + coverage 14 + marks 3 + filed 3 + pieces 6 + copy 1; bytes: gap 2 + + // name 1 + scan 3 + text 6. + ( + concat!( + "defmodule M do\n@doc \"one\"\ndef a(), do: :ok\nx = \"s\n@doc \"", + "two\"\ndef b(), do: :ok\n@doc \"three\"\ndef c(), do: :ok\nend" + ), + [304, 12, 2], + ), + // x01_escaped_line_feed_at_file_level + // expected: steps: walk 79 + children 17 + gaps 2 + coverage 4; bytes: gap 1. + ( + concat!( + "?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [102, 1, 0], + ), + // x11_escaped_line_feed_between_clauses_of_a_function + // expected: steps: walk 105 + children 14 + gaps 6 + tail 2 + coverage 3; bytes: gap 1. + ( + concat!( + "fn\n1 -> ?\\\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audi", + "t\"\ndef f(), do: :ok\nend\nend" + ), + [130, 1, 0], + ), + // x17_assigned_escaped_line_feed_at_file_level + // expected: steps: walk 85 + children 17 + gaps 2 + tail 1 + coverage 4; bytes: gap 1. + ( + concat!( + "x = ?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"funct", + "ion\"\n def f(), do: :ok\nend\n" + ), + [109, 1, 0], + ), + // x19_bare_question_mark_and_line_feed_at_file_level + // expected: steps: tear 5 + walk 81 + children 17 + gaps 3 + tail 1 + recovery 2 + + // coverage 4; bytes: gap 1. + ( + concat!( + "?\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [113, 1, 0], + ), + // x21_bare_question_mark_after_a_character_token + // expected: steps: tear 6 + walk 83 + children 17 + gaps 4 + tail 1 + recovery 3 + + // coverage 4; bytes: gap 1. + ( + concat!( + "???\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [118, 1, 0], + ), + // x23_line_feed_after_a_comma + // expected: steps: tear 6 + walk 83 + children 17 + gaps 4 + tail 1 + recovery 3 + + // coverage 4; bytes: gap 1. + ( + concat!( + "foo,\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [118, 1, 0], + ), + // y01_second_line_feed_after_an_escaped_line_feed + // expected: steps: walk 79 + children 55 + gaps 7 + tail 8 + statements 5 + coverage 11 + // + filed 4 + pieces 10 + copy 2; bytes: gap 4 + name 1 + scan 14 + text 28. + ( + concat!( + "?\\\n\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [181, 47, 4], + ), + // y28_semicolon_after_a_comment_after_a_comma + // expected: steps: tear 8 + walk 87 + children 55 + gaps 11 + tail 10 + recovery 2 + + // statements 5 + coverage 12 + filed 4 + pieces 10 + copy 2; bytes: gap 13 + name 1 + // + scan 14 + text 28. + ( + concat!( + "foo, # c\n;defmodule M do\n @moduledoc \"module\"\n @doc \"fun", + "ction\"\n def f(), do: :ok\nend\n" + ), + [206, 56, 4], + ), + // z01_comment_with_a_rejected_character + // expected: steps: walk 61 + children 38 + gaps 6 + tail 4 + statements 5 + coverage 8 + + // filed 3 + pieces 6 + copy 1; bytes: gap 8 + name 1 + scan 5 + text 10. + ( + "defmodule M do\n@doc \"audit\" # c\u{c} d\ndef f(), do: :ok\nend", + [132, 24, 2], + ), + // z04_empty_clause_body + // expected: steps: tear 23 + walk 113 + children 25 + gaps 21 + tail 10 + recovery 28 + + // coverage 9; bytes: gap 3. + ( + concat!( + "case x do\n a ->\n b -> defmodule X do\n @moduledoc \"m\"\n", + " @doc \"d\"\n def f(), do: :ok\n end\nend\n" + ), + [229, 3, 0], + ), + // z05_operator_row_behind_an_escaped_line_feed + // expected: steps: walk 83 + children 16 + gaps 2 + coverage 3; bytes: gap 1. + ( + concat!( + "?\\\n- defmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [104, 1, 0], + ), + ]; + for (source, charges) in fixed { + assert_eq!(charged(source.as_bytes()), charges, "{source}"); + } + // Twice the size costs in proportion: no loop of the pass is worse than linear. + let grown: [(String, [usize; 3]); 20] = [ + // expected: steps: walk 239 + children 134 + gaps 11 + tail 28 + statements 10 + + // coverage 41 + arguments 8 + candidates 7 + filed 9 + pieces 16; bytes: gap 7 + + // name 15. + (clauses(8), [503, 22, 0]), + // expected: steps: walk 1807 + children 1030 + gaps 67 + tail 252 + statements 66 + + // coverage 321 + arguments 64 + candidates 63 + filed 65 + pieces 128; bytes: gap 63 + // + name 127. + (clauses(64), [3863, 190, 0]), + // expected: steps: walk 383 + children 270 + gaps 19 + tail 60 + statements 18 + + // coverage 57 + arguments 8 + filed 24 + pieces 48 + copy 8; bytes: gap 15 + name 16 + // + scan 8 + text 16. + (functions(8), [895, 55, 16]), + // expected: steps: walk 2959 + children 2118 + gaps 131 + tail 508 + statements 130 + + // coverage 449 + arguments 64 + filed 192 + pieces 384 + copy 64; bytes: gap 127 + + // name 182 + scan 64 + text 128. + (functions(64), [6999, 501, 128]), + // expected: steps: walk 185 + children 157 + gaps 12 + tail 32 + statements 11 + + // coverage 22 + filed 10 + pieces 18; bytes: gap 8 + name 1. + (attributes(8), [447, 9, 0]), + // expected: steps: walk 1193 + children 1109 + gaps 68 + tail 256 + statements 67 + + // coverage 134 + filed 66 + pieces 130; bytes: gap 64 + name 1. + (attributes(64), [3023, 65, 0]), + // expected: steps: walk 145 + children 56 + gaps 8 + tail 28 + coverage 15; bytes: gap + // 7. + (strays(8), [252, 7, 0]), + // expected: steps: walk 1153 + children 448 + gaps 64 + tail 252 + coverage 127; bytes: + // gap 63. + (strays(64), [2044, 63, 0]), + // expected: steps: walk 127 + children 66 + gaps 5 + tail 4 + statements 4 + coverage 11 + // + arguments 30 + candidates 1 + filed 3 + pieces 4; bytes: gap 1 + name 24. + (wide(8), [255, 25, 0]), + // expected: steps: walk 575 + children 290 + gaps 5 + tail 4 + statements 4 + coverage + // 11 + arguments 254 + candidates 1 + filed 3 + pieces 4; bytes: gap 1 + name 192. + (wide(64), [1151, 193, 0]), + // expected: steps: walk 97 + children 67 + gaps 5 + tail 3 + statements 4 + coverage 8 + + // arguments 1 + filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text + // 10. + (commented(8), [195, 17, 2]), + // expected: steps: walk 321 + children 235 + gaps 5 + tail 3 + statements 4 + coverage 8 + // + arguments 1 + filed 3 + pieces 6 + copy 1; bytes: gap 1 + name 1 + scan 5 + text + // 10. + (commented(64), [587, 17, 2]), + // expected: steps: walk 65 + gaps 8 + tail 7 + coverage 7; bytes: gap 7. + (statements(8), [87, 7, 0]), + // expected: steps: walk 513 + gaps 64 + tail 63 + coverage 63; bytes: gap 63. + (statements(64), [703, 63, 0]), + // expected: steps: tear 65 + walk 337 + children 80 + gaps 48 + tail 29 + recovery 80 + + // coverage 31; bytes: gap 15. + (joined(8), [670, 15, 0]), + // expected: steps: tear 513 + walk 2689 + children 640 + gaps 384 + tail 253 + recovery + // 640 + coverage 255; bytes: gap 127. + (joined(64), [5374, 127, 0]), + // expected: steps: tear 41 + walk 61 + gaps 30 + tail 1 + recovery 62 + coverage 1. + (chain(8), [196, 0, 0]), + // expected: steps: tear 265 + walk 397 + gaps 198 + tail 1 + recovery 454 + coverage 1. + (chain(64), [1316, 0, 0]), + // expected: steps: tear 37 + walk 55 + gaps 27 + tail 1 + recovery 27 + coverage 1. + (blocks(8), [148, 0, 0]), + // expected: steps: tear 261 + walk 391 + gaps 195 + tail 1 + recovery 195 + coverage 1. + (blocks(64), [1044, 0, 0]), + ]; + for (source, charges) in grown { + let lead = &source[..source.len().min(48)]; + assert_eq!(charged(source.as_bytes()), charges, "{lead}"); + } +} + +#[cfg(feature = "elixir")] +#[test] +fn elixir_pass_charges_the_collection_budget() { + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let polls = |source: &str| { + let parser = parsed(source.as_bytes()); + let before = observations().polls; + parser.documentation(&context, &options).unwrap(); + observations().polls - before + }; + // expected: the 65,536 bytes between the attribute and the definition are read one + // by one under the collection budget, which polls once per 16,384 bytes. The two + // sources have the same tree, so nothing else differs. + let source = gapped(65_535); + let checkpoints = polls(&source); + assert_eq!(checkpoints - polls(&gapped(0)), 4); + // A cancellation at any checkpoint ends the collection without an index. + let parser = parsed(source.as_bytes()); + let nodes = parser.root_node().preorder().count(); + let mut scanning = 0; + for poll in 1..=checkpoints { + let before = observations(); + let result = cancel_after(poll, || parser.documentation(&context, &options)); + assert!(matches!(result, Err(CollectionError::Cancelled))); + let after = observations(); + // The walk has entered every node and only the file is an owner: the pass is + // reading the body, before the module becomes an owner. + if after.visits - before.visits == nodes + && after.owner_projections - before.owner_projections == 1 + { + scanning += 1; + } + } + // expected: the four checkpoints of the gap. + assert_eq!(scanning, 4); + let index = cancel_after(checkpoints + 1, || parser.documentation(&context, &options)); + assert_eq!(index.unwrap().documents().len(), 1); + // The next plain collection is whole. + let rows: Rows = [ + &["module 0..52", "group 0..52: 32..48"], + &["Primary Single [17..29] \"audit\" 0..5<-23..28"], + &["0 Resolved group 0..52: 32..48 by 32..48 Unknown"], + &[], + ]; + assert_eq!( + view("defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend"), + expected(rows) + ); +} + +// The pass reads words of Elixir. A Ruby call that starts with such a word is no +// definition, and the pass must not reach it. +#[cfg(feature = "ruby")] +#[test] +fn elixir_pass_runs_for_the_elixir_profile_only() { + let source = b"defguard(x)\ndefp y\n"; + let parser = AnyParser::parse(LANG::Ruby, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.profile(), Profile::Yard); + let root = parser.ts_tree().root_node(); + assert!(!root.has_error()); + assert_eq!(root.named_child_count(), 2); + for at in 0..2 { + // Control: each statement has the shape the pass reads as a definition. + let call = root.named_child(at).unwrap(); + assert_eq!(call.kind(), "call"); + assert_eq!(call.child(0).unwrap().kind(), "identifier"); + assert!(matches!( + index.node_projection(call), + Err(OwnerError::UnsupportedOwner) + )); + } + assert_eq!(index.assessments().len(), 0); +} + +// The compiler drops a comment, so an argument list that holds only comments is the +// empty one: the attribute is read, and nothing is set. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_attribute_read_with_a_comment_sets_nothing() { + assert_views(&[ + // r01_doc_read_with_a_comment + ( + "defmodule M do\n@doc( # c\n)\ndef f(), do: :ok\nend", + [&["module 0..47", "group 0..47: 27..43"], &[], &[], &[]], + ), + // r02_moduledoc_read_with_a_comment + ( + "defmodule M do\n@moduledoc( # c\n)\ndef f(), do: :ok\nend", + [&["module 0..53", "group 0..53: 33..49"], &[], &[], &[]], + ), + // r03_typedoc_read_with_a_comment + ( + "defmodule M do\n@typedoc( # c\n)\ndef f(), do: :ok\nend", + [&["module 0..51", "group 0..51: 31..47"], &[], &[], &[]], + ), + // r04_read_with_two_comments + ( + "defmodule M do\n@doc( # a\n# b\n)\ndef f(), do: :ok\nend", + [&["module 0..51", "group 0..51: 31..47"], &[], &[], &[]], + ), + // r05_read_before_a_real_attribute + ( + concat!( + "defmodule M do\n@doc( # c\n)\n@doc \"audit\"\ndef f(), do: :ok\n", + "end" + ), + [ + &["module 0..60", "group 0..60: 40..56"], + &["Primary Single [27..39] \"audit\" 0..5<-33..38"], + &["0 Resolved group 0..60: 40..56 by 40..56 Unknown"], + &[], + ], + ), + // r06_read_after_a_real_attribute + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@doc( # c\n)\ndef f(), do: :ok\n", + "end" + ), + [ + &["module 0..60", "group 0..60: 40..56"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..60: 40..56 by 40..56 Unknown"], + &[], + ], + ), + // r07_moduledoc_read_after_a_real_one + ( + "defmodule M do\n@moduledoc \"audit\"\n@moduledoc( # c\n)\nend", + [ + &["module 0..55"], + &["FilePackage Single [15..33] \"audit\" 0..5<-27..32"], + &["0 Resolved module 0..55 by - Unknown"], + &[], + ], + ), + // r08_reads_at_file_level + ( + "@doc( # c\n)\n@moduledoc( # c\n)\n@typedoc( # c\n)\n", + [&[], &[], &[], &[]], + ), + // r09_read_in_a_quote + ("quote do\n@doc( # c\n)\nend", [&[], &[], &[], &[]]), + ]); +} + +// No count and no place of a child depends on a comment: each row publishes what it +// publishes with a line end in place of the comment. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_comment_is_no_structural_child() { + assert_views(&[ + // t01_comment_before_the_do_of_a_module + ( + "defmodule M # c\ndo\n@doc \"audit\"\ndef f(), do: :ok\nend", + [ + &["module 0..52", "group 0..52: 32..48"], + &["Primary Single [19..31] \"audit\" 0..5<-25..30"], + &["0 Resolved group 0..52: 32..48 by 32..48 Unknown"], + &[], + ], + ), + // t02_comment_before_the_do_of_a_definition + ( + "defmodule M do\n@doc \"audit\"\ndef f() # c\ndo\n:ok\nend\nend", + [ + &["module 0..54", "group 0..54: 28..50"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..54: 28..50 by 28..50 Unknown"], + &[], + ], + ), + // t03_comment_after_when + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when # c\n is_atom(x), ", + "do: x\nend" + ), + [ + &["module 0..68", "group 0..68: 28..64"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..68: 28..64 by 28..64 Unknown"], + &[], + ], + ), + // t04_comment_before_when + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) # c\n when is_atom(x), ", + "do: x\nend" + ), + [ + &["module 0..68", "group 0..68: 28..64"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..68: 28..64 by 28..64 Unknown"], + &[], + ], + ), + // t05_comment_before_the_do_of_a_guarded_definition + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when is_atom(x) # c\ndo", + "\nx\nend\nend" + ), + [ + &["module 0..69", "group 0..69: 28..65"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..69: 28..65 by 28..65 Unknown"], + &[], + ], + ), + // t06_comment_after_the_value_in_parentheses + ( + "defmodule M do\n@doc(\"audit\" # c\n)\ndef f(), do: :ok\nend", + [ + &["module 0..54", "group 0..54: 34..50"], + &["Primary Single [15..33] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..54: 34..50 by 34..50 Unknown"], + &[], + ], + ), + // t07_comment_between_the_head_and_the_keywords + ( + "defmodule M do\n@doc \"audit\"\ndef f(), # c\n do: :ok\nend", + [ + &["module 0..53", "group 0..53: 28..49"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..53: 28..49 by 28..49 Unknown"], + &[], + ], + ), + // t08_comment_before_the_do_of_a_bare_head + ( + "defmodule M do\n@doc \"audit\"\ndef f # c\n do\n:ok\nend\nend", + [ + &["module 0..53", "group 0..53: 28..49"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..53: 28..49 by 28..49 Unknown"], + &[], + ], + ), + // t09_comment_at_the_end_of_every_row + ( + concat!( + "defmodule M do # c\n@doc \"audit\" # c\ndef f(), do: :ok # c\nen", + "d" + ), + [ + &["module 0..60", "group 0..60: 36..52"], + &["Primary Single [19..31] \"audit\" 0..5<-25..30"], + &["0 Resolved group 0..60: 36..52 by 36..52 Unknown"], + &[], + ], + ), + // t10_two_comments_in_a_guarded_macro + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndefmacro m(x) # c\n when is_atom", + "(x) # d\n do\nx\nend\nend" + ), + [ + &["module 0..80", "group 0..80: 28..76"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..80: 28..76 by 28..76 Unknown"], + &[], + ], + ), + // t11_comment_in_the_parentheses_of_a_moduledoc + ( + "defmodule M do\n@moduledoc( # c\n\"audit\")\nend", + [ + &["module 0..43"], + &["FilePackage Single [15..39] \"audit\" 0..5<-32..37"], + &["0 Resolved module 0..43 by - Unknown"], + &[], + ], + ), + // t12_comment_in_an_empty_argument_list + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f( # c\n), do: :ok\ndef f(),", + " do: :error\nend" + ), + [ + &["module 0..73", "group 0..73: 28..49, 50..69"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..73: 28..49, 50..69 by 28..49 Unknown"], + &[], + ], + ), + // t13_guarded_clause_with_a_comment_joins_its_group + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) # c\n when x > 0, do: x", + "\ndef f(x), do: x\nend" + ), + [ + &["module 0..79", "group 0..79: 28..59, 60..75"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..79: 28..59, 60..75 by 28..59 Unknown"], + &[], + ], + ), + ]); +} + +// Two statements need a `;` or a line end between them. Where they have none, the second +// is not read and nothing below it is, in every node whose children are statements. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_joined_statement_and_what_it_holds_are_not_read() { + assert_views(&[ + // s01_module_after_a_module_at_file_level + ( + concat!( + "defmodule A do\n@moduledoc \"a\"\nend defmodule X do\n@moduledoc", + " \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend" + ), + [ + &["module 0..33"], + &["FilePackage Single [15..29] \"a\" 0..1<-27..28"], + &["0 Resolved module 0..33 by - Unknown"], + &[ + "Occurrence RECOVERED unary_operator 49..63 -", + "Occurrence RECOVERED unary_operator 64..76 -", + "Owner PROJECTION call 34..97 -", + ], + ], + ), + // s02_module_after_a_definition_in_a_body + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend defmodule X do\n@moduledoc ", + "\"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["group 0..101: 15..33"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 49..63 -", + "Occurrence RECOVERED unary_operator 64..76 -", + "Owner PROJECTION call 0..101 -", + "Owner PROJECTION call 34..97 -", + ], + ], + ), + // s03_module_after_an_expression_in_a_definition + ( + concat!( + "defmodule M do\ndef g() do\n:ok defmodule X do\n@moduledoc \"x\"", + "\n@doc \"audit\"\ndef f(), do: :ok\nend\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 45..59 -", + "Occurrence RECOVERED unary_operator 60..72 -", + "Owner PROJECTION call 0..101 -", + "Owner PROJECTION call 15..97 -", + "Owner PROJECTION call 30..93 -", + ], + ], + ), + // s04_module_in_a_block_of_a_call + ( + concat!( + "if true do\nfn -> :ok end defmodule X do\n@moduledoc \"x\"\n@doc", + " \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 40..54 -", + "Occurrence RECOVERED unary_operator 55..67 -", + "Owner PROJECTION call 25..88 -", + ], + ], + ), + // s05_module_in_an_after_block + ( + concat!( + "try do\n:ok\nafter\nfn -> :ok end defmodule X do\n@moduledoc \"x", + "\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 46..60 -", + "Occurrence RECOVERED unary_operator 61..73 -", + "Owner PROJECTION call 31..94 -", + ], + ], + ), + // s06_module_in_an_else_block + ( + concat!( + "if true do\n:ok\nelse\nfn -> :ok end defmodule X do\n@moduledoc ", + "\"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 49..63 -", + "Occurrence RECOVERED unary_operator 64..76 -", + "Owner PROJECTION call 34..97 -", + ], + ], + ), + // s07_module_in_a_rescue_block + ( + concat!( + "try do\n:ok\nrescue\nfn -> :ok end defmodule X do\n@moduledoc \"", + "x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 47..61 -", + "Occurrence RECOVERED unary_operator 62..74 -", + "Owner PROJECTION call 32..95 -", + ], + ], + ), + // s08_module_in_a_catch_block + ( + concat!( + "try do\n:ok\ncatch\nfn -> :ok end defmodule X do\n@moduledoc \"x", + "\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 46..60 -", + "Occurrence RECOVERED unary_operator 61..73 -", + "Owner PROJECTION call 31..94 -", + ], + ], + ), + // s09_module_in_the_body_of_a_clause + ( + concat!( + "f = fn ->\nfn -> :ok end defmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 39..53 -", + "Occurrence RECOVERED unary_operator 54..66 -", + "Owner PROJECTION call 24..87 -", + ], + ], + ), + // s10_module_in_a_parenthesized_block + ( + concat!( + "(\nfn -> :ok end defmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\n)" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 31..45 -", + "Occurrence RECOVERED unary_operator 46..58 -", + "Owner PROJECTION call 16..79 -", + ], + ], + ), + // s13_module_after_an_expression_at_file_level + ( + concat!( + "x = 1 defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(),", + " do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 21..35 -", + "Occurrence RECOVERED unary_operator 36..48 -", + "Owner PROJECTION call 6..69 -", + ], + ], + ), + // s19_module_after_a_continued_row + ( + concat!( + "x = 1 \\\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef ", + "f(), do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 23..37 -", + "Occurrence RECOVERED unary_operator 38..50 -", + "Owner PROJECTION call 8..71 -", + ], + ], + ), + // s11_clause_after_a_clause_of_an_anonymous_function + ( + concat!( + "fn\n0 -> :ok 1 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 32..46 -", + "Occurrence RECOVERED unary_operator 47..59 -", + ], + ], + ), + // s12_module_below_a_joined_definition + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend def g() do\ndefmodule X do", + "\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend\n", + "end" + ), + [ + &["group 0..116: 15..33"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 60..74 -", + "Occurrence RECOVERED unary_operator 75..87 -", + "Owner PROJECTION call 0..116 -", + "Owner PROJECTION call 34..112 -", + ], + ], + ), + // s14_module_after_a_string + ( + concat!( + "defmodule M do\n\"s\" defmodule X do\n@moduledoc \"x\"\n@doc \"a", + "udit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 34..48 -", + "Occurrence RECOVERED unary_operator 49..61 -", + "Owner PROJECTION call 0..86 -", + "Owner PROJECTION call 19..82 -", + ], + ], + ), + // s15_joined_attribute_in_a_definition + ( + "defmodule M do\ndef g() do\n:ok @doc \"audit\"\nend\nend", + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 30..42 -", + "Owner PROJECTION call 0..50 -", + "Owner PROJECTION call 15..46 -", + ], + ], + ), + // s16_quote_below_a_joined_statement + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend if true do\nquote do\n@doc ", + "\"audit\"\nend\nend\nend" + ), + [ + &["group 0..78: 15..33"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 54..66 -", + "Owner PROJECTION call 0..78 -", + ], + ], + ), + // s22_joined_quote + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend quote do\n@doc \"audit\"\ne", + "nd\nend" + ), + [ + &["group 0..63: 15..33"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 43..55 -", + "Owner PROJECTION call 0..63 -", + ], + ], + ), + // s17_joined_module_in_a_quote + ( + concat!( + "quote do\n:ok defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\n", + "def f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence TEMPLATE unary_operator 28..42 -", + "Occurrence TEMPLATE unary_operator 43..55 -", + ], + ], + ), + // s18_joined_protocol + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend defprotocol P do\n@doc \"au", + "dit\"\ndef f(x)\nend\nend" + ), + [ + &["group 0..80: 15..33"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 51..63 -", + "Owner PROJECTION call 0..80 -", + "Owner PROJECTION call 34..76 -", + ], + ], + ), + // s20_joined_guard_definition + ( + "defmodule M do\ndef x() do\n:ok\nend defguard g(x) when x\nend", + [ + &["group 0..58: 15..33"], + &[], + &[], + &[ + "Owner PROJECTION call 0..58 -", + "Owner PROJECTION call 34..54 -", + ], + ], + ), + // s21_joined_attribute_at_file_level + ( + "x = 1 @doc \"audit\"\n", + [ + &[], + &[], + &[], + &["Occurrence RECOVERED unary_operator 6..18 -"], + ], + ), + ]); +} + +// Controls of the test above: with a separator, or where the grammar asks for none, the +// module is read. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_module_that_is_apart_or_an_operand_is_read() { + assert_views(&[ + // u01_module_after_a_line_end + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend\ndefmodule X do\n@moduledoc", + " \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[ + "module 0..101", + "group 0..101: 15..33", + "module 34..97", + "group 34..97: 77..93", + ], + &[ + "FilePackage Single [49..63] \"x\" 0..1<-61..62", + "Primary Single [64..76] \"audit\" 0..5<-70..75", + ], + &[ + "0 Resolved module 34..97 by - Unknown", + "1 Resolved group 34..97: 77..93 by 77..93 Unknown", + ], + &[], + ], + ), + // u02_module_after_a_semicolon + ( + concat!( + "x = 1; defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f()", + ", do: :ok\nend" + ), + [ + &["module 7..70", "group 7..70: 50..66"], + &[ + "FilePackage Single [22..36] \"x\" 0..1<-34..35", + "Primary Single [37..49] \"audit\" 0..5<-43..48", + ], + &[ + "0 Resolved module 7..70 by - Unknown", + "1 Resolved group 7..70: 50..66 by 50..66 Unknown", + ], + &[], + ], + ), + // u03_module_after_a_comment_and_a_line_end + ( + concat!( + "x = 1 # c\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef", + " f(), do: :ok\nend" + ), + [ + &["module 10..73", "group 10..73: 53..69"], + &[ + "FilePackage Single [25..39] \"x\" 0..1<-37..38", + "Primary Single [40..52] \"audit\" 0..5<-46..51", + ], + &[ + "0 Resolved module 10..73 by - Unknown", + "1 Resolved group 10..73: 53..69 by 53..69 Unknown", + ], + &[], + ], + ), + // u04_module_as_the_right_side_of_a_match + ( + concat!( + "x = defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(), d", + "o: :ok\nend" + ), + [ + &["module 4..67", "group 4..67: 47..63"], + &[ + "FilePackage Single [19..33] \"x\" 0..1<-31..32", + "Primary Single [34..46] \"audit\" 0..5<-40..45", + ], + &[ + "0 Resolved module 4..67 by - Unknown", + "1 Resolved group 4..67: 47..63 by 47..63 Unknown", + ], + &[], + ], + ), + // u05_module_as_an_argument_of_a_call + ( + concat!( + "IO.inspect(defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef", + " f(), do: :ok\nend)" + ), + [ + &["module 11..74", "group 11..74: 54..70"], + &[ + "FilePackage Single [26..40] \"x\" 0..1<-38..39", + "Primary Single [41..53] \"audit\" 0..5<-47..52", + ], + &[ + "0 Resolved module 11..74 by - Unknown", + "1 Resolved group 11..74: 54..70 by 54..70 Unknown", + ], + &[], + ], + ), + // u07_module_after_a_semicolon_in_a_clause + ( + concat!( + "f = fn -> :ok; defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"", + "\ndef f(), do: :ok\nend end" + ), + [ + &["module 15..78", "group 15..78: 58..74"], + &[ + "FilePackage Single [30..44] \"x\" 0..1<-42..43", + "Primary Single [45..57] \"audit\" 0..5<-51..56", + ], + &[ + "0 Resolved module 15..78 by - Unknown", + "1 Resolved group 15..78: 58..74 by 58..74 Unknown", + ], + &[], + ], + ), + // u06_module_in_a_rescue_section_on_the_row_of_a_statement + ( + concat!( + "try do :ok rescue _ -> defmodule X do\n@moduledoc \"x\"\n@doc \"", + "audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 23..86", "group 23..86: 66..82"], + &[ + "FilePackage Single [38..52] \"x\" 0..1<-50..51", + "Primary Single [53..65] \"audit\" 0..5<-59..64", + ], + &[ + "0 Resolved module 23..86 by - Unknown", + "1 Resolved group 23..86: 66..82 by 66..82 Unknown", + ], + &[], + ], + ), + // u08_module_in_an_after_section_on_the_row_of_a_statement + ( + concat!( + "try do :ok after\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 17..80", "group 17..80: 60..76"], + &[ + "FilePackage Single [32..46] \"x\" 0..1<-44..45", + "Primary Single [47..59] \"audit\" 0..5<-53..58", + ], + &[ + "0 Resolved module 17..80 by - Unknown", + "1 Resolved group 17..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // u09_module_in_a_catch_section_on_the_row_of_a_statement + ( + concat!( + "try do :ok catch _ -> defmodule X do\n@moduledoc \"x\"\n@doc \"a", + "udit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 22..85", "group 22..85: 65..81"], + &[ + "FilePackage Single [37..51] \"x\" 0..1<-49..50", + "Primary Single [52..64] \"audit\" 0..5<-58..63", + ], + &[ + "0 Resolved module 22..85 by - Unknown", + "1 Resolved group 22..85: 65..81 by 65..81 Unknown", + ], + &[], + ], + ), + // u10_module_in_an_else_section_on_the_row_of_a_statement + ( + concat!( + "if true do :ok else\ndefmodule X do\n@moduledoc \"x\"\n@doc \"au", + "dit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 20..83", "group 20..83: 63..79"], + &[ + "FilePackage Single [35..49] \"x\" 0..1<-47..48", + "Primary Single [50..62] \"audit\" 0..5<-56..61", + ], + &[ + "0 Resolved module 20..83 by - Unknown", + "1 Resolved group 20..83: 63..79 by 63..79 Unknown", + ], + &[], + ], + ), + ]); +} + +// The grammar recovered inside the statement that holds the module. The module is read, +// and no association of it is resolved. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_recovery_in_a_statement_leaves_what_it_holds_unresolved() { + assert_views(&[ + // v01_expression_read_into_a_match + ( + concat!( + "1 y = defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(),", + " do: :ok\nend" + ), + [ + &["module 6..69", "group 6..69: 49..65"], + &[ + "FilePackage Single [21..35] \"x\" 0..1<-33..34", + "Primary Single [36..48] \"audit\" 0..5<-42..47", + ], + &[ + "0 Unresolved(GrammarBoundary) module 6..69 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 6..69: 49..65 by 49..65 Unkn", + "own" + ), + ], + &[], + ], + ), + // v02_call_read_into_the_next_call + ( + concat!( + "f() if true do\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit\"", + "\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 15..78", "group 15..78: 58..74"], + &[ + "FilePackage Single [30..44] \"x\" 0..1<-42..43", + "Primary Single [45..57] \"audit\" 0..5<-51..56", + ], + &[ + "0 Unresolved(GrammarBoundary) module 15..78 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 15..78: 58..74 by 58..74 Unk", + "nown" + ), + ], + &[], + ], + ), + // v03_expression_read_into_a_qualified_call + ( + concat!( + "1 IO.inspect(defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\nd", + "ef f(), do: :ok\nend)" + ), + [ + &["module 13..76", "group 13..76: 56..72"], + &[ + "FilePackage Single [28..42] \"x\" 0..1<-40..41", + "Primary Single [43..55] \"audit\" 0..5<-49..54", + ], + &[ + "0 Unresolved(GrammarBoundary) module 13..76 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 13..76: 56..72 by 56..72 Unk", + "nown" + ), + ], + &[], + ], + ), + // v07_attribute_read_into_the_next_definition + ( + concat!( + "@doc \"before\" def g() do\ndefmodule X do\n@moduledoc \"x\"\n@d", + "oc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 25..88", "group 25..88: 68..84"], + &[ + "FilePackage Single [40..54] \"x\" 0..1<-52..53", + "Primary Single [55..67] \"audit\" 0..5<-61..66", + ], + &[ + "0 Unresolved(GrammarBoundary) module 25..88 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 25..88: 68..84 by 68..84 Unk", + "nown" + ), + ], + &[ + "Occurrence OUTSIDE unary_operator 0..92 -", + "Owner PROJECTION call 14..21 -", + ], + ], + ), + // v06_recovery_among_the_clauses_of_a_function + ( + concat!( + "f = fn\n1 1 -> :ok\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &["module 23..86", "group 23..86: 66..82"], + &[ + "FilePackage Single [38..52] \"x\" 0..1<-50..51", + "Primary Single [53..65] \"audit\" 0..5<-59..64", + ], + &[ + "0 Resolved module 23..86 by - Unknown", + "1 Resolved group 23..86: 66..82 by 66..82 Unknown", + ], + &[], + ], + ), + // v04_definition_read_into_the_next_definition + ( + concat!( + "defmodule M do\ndef a(), do: :ok def g() do\ndefmodule X do\n@mo", + "duledoc \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend\nend" + ), + [ + &["module 43..106", "group 43..106: 86..102"], + &[ + "FilePackage Single [58..72] \"x\" 0..1<-70..71", + "Primary Single [73..85] \"audit\" 0..5<-79..84", + ], + &[ + "0 Unresolved(GrammarBoundary) module 43..106 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 43..106: 86..102 by 86..102 ", + "Unknown" + ), + ], + &[ + "Owner PROJECTION call 0..114 -", + "Owner PROJECTION call 15..110 -", + "Owner PROJECTION call 32..39 -", + ], + ], + ), + // v05_error_in_a_head_and_a_sound_statement_after_it + ( + concat!( + "defmodule M do\n@doc \"one\"\ndef a(, do: (\ndefmodule X do\n@mo", + "duledoc \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\n)\n@doc \"", + "two\"\ndef b(), do: :ok\nend" + ), + [ + &[ + "group 0..137: 117..133", + "module 40..103", + "group 40..103: 83..99", + ], + &[ + "FilePackage Single [55..69] \"x\" 0..1<-67..68", + "Primary Single [70..82] \"audit\" 0..5<-76..81", + "Primary Single [106..116] \"two\" 0..3<-112..115", + ], + &[ + "0 Unresolved(GrammarBoundary) module 40..103 by - Unknown", + concat!( + "1 Unresolved(GrammarBoundary) group 40..103: 83..99 by 83..99 Un", + "known" + ), + "2 Resolved group 0..137: 117..133 by 117..133 Unknown", + ], + &[ + "Owner PROJECTION call 0..137 -", + "Owner PROJECTION call 26..105 -", + "Owner UNOWNED unary_operator 15..25 -", + ], + ], + ), + ]); +} + +// The compiler pairs the quotes of a file from its start. Where the grammar dropped a quote, +// it reads the rest of the file with text and code exchanged, so no statement from there on +// is read. These are pending outcomes: the file does not compile. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_statement_behind_a_torn_literal_is_not_read() { + assert_views(&[ + // w01_string_without_its_end + ( + concat!( + "defmodule M do\nx = \"a\n@doc \"LIT\"\ndef lit, do: :ok\n@doc \"", + "REAL\"\ndef real, do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 50..61 -", + "Owner PROJECTION call 0..83 -", + "Owner PROJECTION call 33..49 -", + "Owner PROJECTION call 62..79 -", + ], + ], + ), + // w02_quoted_atom_without_its_end + ( + concat!( + "defmodule M do\nx = :\"a\n@doc \"LIT\"\ndef lit, do: :ok\n@doc ", + "\"REAL\"\ndef real, do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 51..62 -", + "Owner PROJECTION call 0..84 -", + "Owner PROJECTION call 34..50 -", + "Owner PROJECTION call 63..80 -", + ], + ], + ), + // w03_statements_before_the_tear_are_read + ( + concat!( + "defmodule M do\n@doc \"one\"\ndef a(), do: :ok\nx = \"s\n@doc \"", + "two\"\ndef b(), do: :ok\n@doc \"three\"\ndef c(), do: :ok\nend" + ), + [ + &["group 0..111: 26..42"], + &["Primary Single [15..25] \"one\" 0..3<-21..24"], + &["0 Resolved group 0..111: 26..42 by 26..42 Unknown"], + &[ + "Occurrence RECOVERED unary_operator 78..90 -", + "Owner PROJECTION call 0..111 -", + "Owner PROJECTION call 61..77 -", + "Owner PROJECTION call 91..107 -", + ], + ], + ), + // w04_doubled_quote + ( + concat!( + "defmodule M do\n@doc \"\"audit\"\ndef f(), do: :ok\n@doc \"next", + "\"\ndef g(), do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 15..45 -", + "Occurrence RECOVERED unary_operator 46..57 -", + "Owner PROJECTION call 0..78 -", + "Owner PROJECTION call 58..74 -", + ], + ], + ), + // w05_module_behind_a_tear_at_file_level + ( + concat!( + "x = \"a\ny = \"b\"\ndefmodule X do\n@moduledoc \"x\"\n@doc \"aud", + "it\"\ndef f(), do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 30..44 -", + "Occurrence RECOVERED unary_operator 45..57 -", + "Owner PROJECTION call 15..78 -", + ], + ], + ), + // w06_tear_in_the_body_of_a_definition + ( + concat!( + "defmodule M do\ndef h() do\nx = \"a\ny = \"b\"\nend\n@doc \"REAL", + "\"\ndef real(), do: :ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 45..56 -", + "Owner PROJECTION call 0..80 -", + "Owner PROJECTION call 15..44 -", + "Owner PROJECTION call 57..76 -", + ], + ], + ), + // w07_two_torn_literals + ( + concat!( + "defmodule M do\nx = \"s\n@doc \"two\"\ndef b(), do: :ok\n@doc \"", + "three\"\ndef c(), do: :ok\ny = \"t\n@doc \"four\"\ndef d(), do: ", + ":ok\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 50..62 -", + "Owner PROJECTION call 0..119 -", + "Owner PROJECTION call 33..49 -", + "Owner PROJECTION call 63..79 -", + ], + ], + ), + ]); +} + +// The tokenizer takes a line feed into `?\\` and `?`, and records no end of line +// behind `,`. A statement that only such a line feed separates from the token is +// joined, in every kind of sequence. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_line_feed_in_a_character_or_after_a_comma_joins_the_next_statement() { + assert_views(&[ + // x01_escaped_line_feed_at_file_level + ( + concat!( + "?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 20..39 -", + "Occurrence RECOVERED unary_operator 42..57 -", + "Owner PROJECTION call 3..80 -", + ], + ], + ), + // x02_escaped_line_feed_in_a_module_body + ( + concat!( + "defmodule O do\n ?\\\n defmodule M do\n @moduledoc \"module", + "\"\n @doc \"function\"\n def f(), do: :ok\n end\nend\n" + ), + [ + &["module 0..111"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 41..60 -", + "Occurrence RECOVERED unary_operator 65..80 -", + "Owner PROJECTION call 22..107 -", + ], + ], + ), + // x03_escaped_line_feed_in_a_definition_body + ( + concat!( + "defmodule O do\n def g() do\n ?\\\ndefmodule M do\n @module", + "doc \"module\"\n @doc \"function\"\n def f(), do: :ok\nend\n ", + "end\nend\n" + ), + [ + &["module 0..122", "group 0..122: 17..118"], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 52..71 -", + "Occurrence RECOVERED unary_operator 74..89 -", + "Owner PROJECTION call 35..112 -", + ], + ], + ), + // x04_escaped_line_feed_in_a_block_of_a_call + ( + concat!( + "if true do\n?\\\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 29..43 -", + "Occurrence RECOVERED unary_operator 44..56 -", + "Owner PROJECTION call 14..77 -", + ], + ], + ), + // x05_escaped_line_feed_in_an_after_block + ( + concat!( + "try do\n:ok\nafter\n?\\\ndefmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 35..49 -", + "Occurrence RECOVERED unary_operator 50..62 -", + "Owner PROJECTION call 20..83 -", + ], + ], + ), + // x06_escaped_line_feed_in_an_else_block + ( + concat!( + "if true do\n:ok\nelse\n?\\\ndefmodule X do\n@moduledoc \"x\"\n@d", + "oc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 38..52 -", + "Occurrence RECOVERED unary_operator 53..65 -", + "Owner PROJECTION call 23..86 -", + ], + ], + ), + // x07_escaped_line_feed_in_a_rescue_block + ( + concat!( + "try do\n:ok\nrescue\n?\\\ndefmodule X do\n@moduledoc \"x\"\n@doc", + " \"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 36..50 -", + "Occurrence RECOVERED unary_operator 51..63 -", + "Owner PROJECTION call 21..84 -", + ], + ], + ), + // x08_escaped_line_feed_in_a_catch_block + ( + concat!( + "try do\n:ok\ncatch\n?\\\ndefmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 35..49 -", + "Occurrence RECOVERED unary_operator 50..62 -", + "Owner PROJECTION call 20..83 -", + ], + ], + ), + // x09_escaped_line_feed_in_the_body_of_a_clause + ( + concat!( + "f = fn ->\n?\\\ndefmodule X do\n@moduledoc \"x\"\n@doc \"audit\"", + "\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 28..42 -", + "Occurrence RECOVERED unary_operator 43..55 -", + "Owner PROJECTION call 13..76 -", + ], + ], + ), + // x10_escaped_line_feed_in_parentheses + ( + concat!( + "(?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n)\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 21..40 -", + "Occurrence RECOVERED unary_operator 43..58 -", + "Owner PROJECTION call 4..81 -", + ], + ], + ), + // x11_escaped_line_feed_between_clauses_of_a_function + ( + concat!( + "fn\n1 -> ?\\\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audi", + "t\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 31..45 -", + "Occurrence RECOVERED unary_operator 46..58 -", + ], + ], + ), + // x12_escaped_line_feed_before_doc + ( + concat!( + "defmodule O do\n ?\\\n @doc \"function\"\n def f(), do: :ok\n", + "end\n" + ), + [ + &["module 0..60", "group 0..60: 40..56"], + &[], + &[], + &["Occurrence RECOVERED unary_operator 22..37 -"], + ], + ), + // x13_escaped_line_feed_after_moduledoc_before_doc + ( + concat!( + "defmodule M do\n @moduledoc \"module\"\n ?\\\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 0..82", "group 0..82: 62..78"], + &["FilePackage Single [17..36] \"module\" 0..6<-29..35"], + &["0 Resolved module 0..82 by - Unknown"], + &["Occurrence RECOVERED unary_operator 44..59 -"], + ], + ), + // x14_escaped_line_feed_between_doc_and_definition + ( + concat!( + "defmodule M do\n @doc \"function\"\n ?\\\n def f(), do: :ok\n", + "end\n" + ), + [ + &["module 0..60"], + &[], + &[], + &[ + "Owner PROJECTION call 40..56 -", + "Owner UNOWNED unary_operator 17..32 -", + ], + ], + ), + // x16_assigned_escaped_line_feed_between_doc_and_definition + ( + concat!( + "defmodule M do\n @doc \"function\"\n x = ?\\\n def f(), do: :", + "ok\nend\n" + ), + [ + &["module 0..64"], + &[], + &[], + &[ + "Owner PROJECTION call 44..60 -", + "Owner UNOWNED unary_operator 17..32 -", + ], + ], + ), + // x15_escaped_line_feed_as_the_value_of_doc + ( + "defmodule M do\n @doc ?\\\n def f(), do: :ok\nend\n", + [ + &["module 0..47"], + &[], + &[], + &[ + "Owner PROJECTION call 27..43 -", + "Owner UNOWNED unary_operator 17..24 -", + ], + ], + ), + // x17_assigned_escaped_line_feed_at_file_level + ( + concat!( + "x = ?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"funct", + "ion\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 24..43 -", + "Occurrence RECOVERED unary_operator 46..61 -", + "Owner PROJECTION call 7..84 -", + ], + ], + ), + // x18_escaped_line_feed_then_a_continued_row + ( + concat!( + "?\\\n\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"funct", + "ion\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 22..41 -", + "Occurrence RECOVERED unary_operator 44..59 -", + "Owner PROJECTION call 5..82 -", + ], + ], + ), + // x19_bare_question_mark_and_line_feed_at_file_level + ( + concat!( + "?\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 19..38 -", + "Occurrence RECOVERED unary_operator 41..56 -", + "Owner PROJECTION call 2..79 -", + ], + ], + ), + // x20_bare_question_mark_and_line_feed_in_a_module_body + ( + concat!( + "defmodule O do\n ?\n defmodule M do\n @moduledoc \"module\"", + "\n @doc \"function\"\n def f(), do: :ok\n end\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 40..59 -", + "Occurrence RECOVERED unary_operator 64..79 -", + "Owner PROJECTION call 0..110 -", + "Owner PROJECTION call 21..106 -", + ], + ], + ), + // x21_bare_question_mark_after_a_character_token + ( + concat!( + "???\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 21..40 -", + "Occurrence RECOVERED unary_operator 43..58 -", + "Owner PROJECTION call 4..81 -", + ], + ], + ), + // x22_bare_question_mark_and_line_feed_in_a_clause + ( + concat!( + "fn\n1 -> ?\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\nend" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 30..44 -", + "Occurrence RECOVERED unary_operator 45..57 -", + ], + ], + ), + // x23_line_feed_after_a_comma + ( + concat!( + "foo,\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 22..41 -", + "Occurrence RECOVERED unary_operator 44..59 -", + "Owner PROJECTION call 5..82 -", + ], + ], + ), + // x24_two_line_feeds_after_a_comma + ( + concat!( + "foo,\n\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functi", + "on\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 23..42 -", + "Occurrence RECOVERED unary_operator 45..60 -", + "Owner PROJECTION call 6..83 -", + ], + ], + ), + // x25_comment_after_a_comma + ( + concat!( + "foo, # c\ndefmodule M do\n @moduledoc \"module\"\n @doc \"func", + "tion\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 26..45 -", + "Occurrence RECOVERED unary_operator 48..63 -", + "Owner PROJECTION call 9..86 -", + ], + ], + ), + // x26_semicolon_in_a_comment_after_a_comma + ( + concat!( + "foo, # c; d\ndefmodule M do\n @moduledoc \"module\"\n @doc \"f", + "unction\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 29..48 -", + "Occurrence RECOVERED unary_operator 51..66 -", + "Owner PROJECTION call 12..89 -", + ], + ], + ), + // x27_semicolon_character_without_a_separator + ( + concat!( + "?;defmodule M do\n @moduledoc \"module\"\n @doc \"function\"\n", + " def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 19..38 -", + "Occurrence RECOVERED unary_operator 41..56 -", + "Owner PROJECTION call 2..79 -", + ], + ], + ), + // x28_continued_row_after_a_question_mark_identifier + ( + concat!( + "foo?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functi", + "on\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 23..42 -", + "Occurrence OUTSIDE unary_operator 45..60 -", + "Owner PROJECTION call 6..17 -", + "Owner PROJECTION call 63..79 -", + ], + ], + ), + ]); +} + +// Controls of the test above: a second line feed, a `;` or a comment behind the token, +// another character token, an identifier or atom ending in `?`, a string ending in +// `?\\`, a binary operator or `.` that continues the expression in one node, or a +// comma inside a list. +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_separator_behind_a_character_or_a_comma_is_read() { + assert_views(&[ + // y01_second_line_feed_after_an_escaped_line_feed + ( + concat!( + "?\\\n\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y02_semicolon_after_an_escaped_line_feed + ( + concat!( + "?\\\n;defmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y03_comment_after_an_escaped_line_feed + ( + concat!( + "?\\\n# c\ndefmodule M do\n @moduledoc \"module\"\n @doc \"func", + "tion\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 7..84", "group 7..84: 64..80"], + &[ + "FilePackage Single [24..43] \"module\" 0..6<-36..42", + "Primary Single [46..61] \"function\" 0..8<-52..60", + ], + &[ + "0 Resolved module 7..84 by - Unknown", + "1 Resolved group 7..84: 64..80 by 64..80 Unknown", + ], + &[], + ], + ), + // y04_escaped_backslash_character + ( + concat!( + "?\\\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y05_plain_character + ( + concat!( + "?a\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y06_identifier_ending_in_a_question_mark + ( + concat!( + "foo?\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 5..82", "group 5..82: 62..78"], + &[ + "FilePackage Single [22..41] \"module\" 0..6<-34..40", + "Primary Single [44..59] \"function\" 0..8<-50..58", + ], + &[ + "0 Resolved module 5..82 by - Unknown", + "1 Resolved group 5..82: 62..78 by 62..78 Unknown", + ], + &[], + ], + ), + // y07_atom_ending_in_a_question_mark + ( + concat!( + ":a?\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y08_string_ending_in_question_mark_and_backslash + ( + concat!( + "\"a?\\\\\"\ndefmodule M do\n @moduledoc \"module\"\n @doc \"fu", + "nction\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 7..84", "group 7..84: 64..80"], + &[ + "FilePackage Single [24..43] \"module\" 0..6<-36..42", + "Primary Single [46..61] \"function\" 0..8<-52..60", + ], + &[ + "0 Resolved module 7..84 by - Unknown", + "1 Resolved group 7..84: 64..80 by 64..80 Unknown", + ], + &[], + ], + ), + // y09_escaped_line_feed_inside_a_call + ( + concat!( + "f(?\\\n)\ndefmodule M do\n @moduledoc \"module\"\n @doc \"func", + "tion\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 7..84", "group 7..84: 64..80"], + &[ + "FilePackage Single [24..43] \"module\" 0..6<-36..42", + "Primary Single [46..61] \"function\" 0..8<-52..60", + ], + &[ + "0 Resolved module 7..84 by - Unknown", + "1 Resolved group 7..84: 64..80 by 64..80 Unknown", + ], + &[], + ], + ), + // y10_escaped_line_feed_then_an_operator_row + ( + concat!( + "x = ?\\\n+ 1\ndefmodule M do\n @moduledoc \"module\"\n @doc \"", + "function\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 11..88", "group 11..88: 68..84"], + &[ + "FilePackage Single [28..47] \"module\" 0..6<-40..46", + "Primary Single [50..65] \"function\" 0..8<-56..64", + ], + &[ + "0 Resolved module 11..88 by - Unknown", + "1 Resolved group 11..88: 68..84 by 68..84 Unknown", + ], + &[], + ], + ), + // y11_escaped_space_character + ( + concat!( + "?\\ \ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y12_space_character + ( + concat!( + "? \ndefmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y13_two_escaped_line_feeds_then_a_blank_row + ( + concat!( + "?\\\n?\\\n\ndefmodule M do\n @moduledoc \"module\"\n @doc \"fu", + "nction\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 7..84", "group 7..84: 64..80"], + &[ + "FilePackage Single [24..43] \"module\" 0..6<-36..42", + "Primary Single [46..61] \"function\" 0..8<-52..60", + ], + &[ + "0 Resolved module 7..84 by - Unknown", + "1 Resolved group 7..84: 64..80 by 64..80 Unknown", + ], + &[], + ], + ), + // y14_escaped_hash_character + ( + concat!( + "?\\#\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y15_hash_character + ( + concat!( + "?#\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y16_line_feed_then_a_semicolon + ( + concat!( + "1\n;defmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y17_leading_semicolon + ( + concat!( + ";defmodule M do\n @moduledoc \"module\"\n @doc \"function\"\n ", + " def f(), do: :ok\nend\n" + ), + [ + &["module 1..78", "group 1..78: 58..74"], + &[ + "FilePackage Single [18..37] \"module\" 0..6<-30..36", + "Primary Single [40..55] \"function\" 0..8<-46..54", + ], + &[ + "0 Resolved module 1..78 by - Unknown", + "1 Resolved group 1..78: 58..74 by 58..74 Unknown", + ], + &[], + ], + ), + // y18_two_semicolons + ( + concat!( + "1;;defmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y19_second_line_feed_after_a_bare_question_mark + ( + concat!( + "?\n\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y20_semicolon_after_a_bare_question_mark + ( + concat!( + "?\n;defmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y21_comment_after_a_bare_question_mark + ( + concat!( + "?\n# c\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functi", + "on\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 6..83", "group 6..83: 63..79"], + &[ + "FilePackage Single [23..42] \"module\" 0..6<-35..41", + "Primary Single [45..60] \"function\" 0..8<-51..59", + ], + &[ + "0 Resolved module 6..83 by - Unknown", + "1 Resolved group 6..83: 63..79 by 63..79 Unknown", + ], + &[], + ], + ), + // y22_pipe_operator_behind_an_escaped_line_feed + ( + concat!( + "?\\\n|> defmodule M do\n @moduledoc \"module\"\n @doc \"functi", + "on\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 6..83", "group 6..83: 63..79"], + &[ + "FilePackage Single [23..42] \"module\" 0..6<-35..41", + "Primary Single [45..60] \"function\" 0..8<-51..59", + ], + &[ + "0 Resolved module 6..83 by - Unknown", + "1 Resolved group 6..83: 63..79 by 63..79 Unknown", + ], + &[], + ], + ), + // y23_dot_call_behind_an_escaped_line_feed + ( + concat!( + "?\\\n.foo(defmodule M do\n @moduledoc \"module\"\n @doc \"func", + "tion\"\n def f(), do: :ok\nend)\n" + ), + [ + &["module 8..85", "group 8..85: 65..81"], + &[ + "FilePackage Single [25..44] \"module\" 0..6<-37..43", + "Primary Single [47..62] \"function\" 0..8<-53..61", + ], + &[ + "0 Resolved module 8..85 by - Unknown", + "1 Resolved group 8..85: 65..81 by 65..81 Unknown", + ], + &[], + ], + ), + // y24_minus_on_one_row + ( + concat!( + "?a - defmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 5..82", "group 5..82: 62..78"], + &[ + "FilePackage Single [22..41] \"module\" 0..6<-34..40", + "Primary Single [44..59] \"function\" 0..8<-50..58", + ], + &[ + "0 Resolved module 5..82 by - Unknown", + "1 Resolved group 5..82: 62..78 by 62..78 Unknown", + ], + &[], + ], + ), + // y25_access_on_one_row + ( + concat!( + "?a[defmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend]\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // y26_comma_in_a_list + ( + concat!( + "[1,\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend]\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // y27_semicolon_after_a_comma + ( + concat!( + "foo,\n;defmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 6..83", "group 6..83: 63..79"], + &[ + "FilePackage Single [23..42] \"module\" 0..6<-35..41", + "Primary Single [45..60] \"function\" 0..8<-51..59", + ], + &[ + "0 Resolved module 6..83 by - Unknown", + "1 Resolved group 6..83: 63..79 by 63..79 Unknown", + ], + &[], + ], + ), + // y28_semicolon_after_a_comment_after_a_comma + ( + concat!( + "foo, # c\n;defmodule M do\n @moduledoc \"module\"\n @doc \"fun", + "ction\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 10..87", "group 10..87: 67..83"], + &[ + "FilePackage Single [27..46] \"module\" 0..6<-39..45", + "Primary Single [49..64] \"function\" 0..8<-55..63", + ], + &[ + "0 Resolved module 10..87 by - Unknown", + "1 Resolved group 10..87: 67..83 by 67..83 Unknown", + ], + &[], + ], + ), + // y29_clause_with_a_body_before_a_module_clause + ( + concat!( + "case x do\n a -> 1\n b -> defmodule X do\n @moduledoc \"m\"", + "\n @doc \"d\"\n def f(), do: :ok\n end\nend\n" + ), + [ + &["module 26..99", "group 26..99: 77..93"], + &[ + "FilePackage Single [45..59] \"m\" 0..1<-57..58", + "Primary Single [64..72] \"d\" 0..1<-70..71", + ], + &[ + "0 Resolved module 26..99 by - Unknown", + "1 Resolved group 26..99: 77..93 by 77..93 Unknown", + ], + &[], + ], + ), + ]); +} + +// Characterization fixtures that pin today's outcome on four known differences between +// the pinned grammar and the compiler: (a) a comment with a character that the +// tokenizer rejects (`z01`: the grammar reads a comment and the document is published); +// (b) `?\\` and a CR, and `?` and a CR, which the tokenizer rejects (`z02`, `z03`: the +// grammar reads a character token and the module behind the line feed is published); +// (c) an empty clause body, which the compiler accepts with a warning (`z04`: the +// grammar fails and puts the module of the next clause under a joined node, with no +// owner and no assessment); (d) a row starting with `-`, `+` or `[` behind `?\\` and a +// line feed, which continues the expression for the compiler (`z05`: the grammar starts +// a new statement, which B6.2 joins and withholds). +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_known_differences_of_the_grammar_keep_their_outcomes() { + assert_views(&[ + // z01_comment_with_a_rejected_character + ( + "defmodule M do\n@doc \"audit\" # c\u{c} d\ndef f(), do: :ok\nend", + [ + &["module 0..55", "group 0..55: 35..51"], + &["Primary Single [15..27] \"audit\" 0..5<-21..26"], + &["0 Resolved group 0..55: 35..51 by 35..51 Unknown"], + &[], + ], + ), + // z02_escaped_carriage_return_character + ( + concat!( + "?\\\r\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 4..81", "group 4..81: 61..77"], + &[ + "FilePackage Single [21..40] \"module\" 0..6<-33..39", + "Primary Single [43..58] \"function\" 0..8<-49..57", + ], + &[ + "0 Resolved module 4..81 by - Unknown", + "1 Resolved group 4..81: 61..77 by 61..77 Unknown", + ], + &[], + ], + ), + // z03_carriage_return_character + ( + concat!( + "?\r\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + [ + &["module 3..80", "group 3..80: 60..76"], + &[ + "FilePackage Single [20..39] \"module\" 0..6<-32..38", + "Primary Single [42..57] \"function\" 0..8<-48..56", + ], + &[ + "0 Resolved module 3..80 by - Unknown", + "1 Resolved group 3..80: 60..76 by 60..76 Unknown", + ], + &[], + ], + ), + // z04_empty_clause_body + ( + concat!( + "case x do\n a ->\n b -> defmodule X do\n @moduledoc \"m\"\n", + " @doc \"d\"\n def f(), do: :ok\n end\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence OUTSIDE unary_operator 43..57 -", + "Occurrence OUTSIDE unary_operator 62..70 -", + "Owner PROJECTION call 75..91 -", + ], + ], + ), + // z05_operator_row_behind_an_escaped_line_feed + ( + concat!( + "?\\\n- defmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + [ + &[], + &[], + &[], + &[ + "Occurrence RECOVERED unary_operator 22..41 -", + "Occurrence RECOVERED unary_operator 44..59 -", + ], + ], + ), + ]); +} + +// The children of a node: their kinds, with `!` after a token that the parser invented and +// `?` after a child that holds a syntax error. +#[cfg(feature = "elixir")] +fn shape(node: tree_sitter::Node<'_>) -> String { + let mut cursor = node.walk(); + let kinds: Vec<_> = node + .children(&mut cursor) + .map(|child| { + let mark = if child.is_missing() { + "!" + } else if child.has_error() { + "?" + } else { + "" + }; + format!("{}{mark}", child.kind()) + }) + .collect(); + kinds.join(" ") +} + +// Every node of the tree, in the order of the source. +#[cfg(feature = "elixir")] +fn preorder(tree: &tree_sitter::Tree) -> Vec> { + let mut nodes = Vec::new(); + let mut stack = vec![tree.root_node()]; + while let Some(node) = stack.pop() { + nodes.push(node); + let children: Vec<_> = node.children(&mut node.walk()).collect(); + stack.extend(children.into_iter().rev()); + } + nodes +} + +#[cfg(feature = "elixir")] +#[test] +#[allow(clippy::too_many_lines)] +fn elixir_parse_shapes_the_attribute_reader_relies_on() { + // (the source, a node kind, which node of that kind in source order, its children) + let shapes: [(&str, &str, usize, &str); 95] = [ + // a module: its word, its name, its body + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "call", + 0, + "identifier arguments do_block", + ), + // a body: `do`, the statements, `end` + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator call end", + ), + // an attribute: the operator and its operand + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "unary_operator", + 0, + "@ call", + ), + // the operand: the name and the value + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "call", + 1, + "identifier arguments", + ), + // a value without parentheses + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "arguments", + 1, + "string", + ), + // a plain string + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "string", + 0, + "\" quoted_content \"", + ), + // a definition without a block + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "call", + 2, + "identifier arguments", + ), + // its head is the first child + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "arguments", + 2, + "call , keywords", + ), + // a head: the name and the argument list + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "call", + 3, + "identifier arguments", + ), + // an empty argument list + ( + "defmodule M do\n @doc \"audit\"\n def f(), do: :ok\nend", + "arguments", + 3, + "( )", + ), + // a value in parentheses + ( + "defmodule M do\n@doc(\"audit\")\ndef f(), do: :ok\nend", + "arguments", + 1, + "( string )", + ), + // after a space the parentheses are a block + ( + "defmodule M do\n@doc (\"audit\")\ndef f(), do: :ok\nend", + "arguments", + 1, + "block", + ), + // an empty string has no content + ( + "defmodule M do\n@doc \"\"\ndef f(), do: :ok\nend", + "string", + 0, + "\" \"", + ), + // a heredoc has other quotes + ( + concat!( + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\"\ndef f(), do: :ok\nen", + "d" + ), + "string", + 0, + "\"\"\" quoted_content \"\"\"", + ), + // an escape is a child + ( + "defmodule M do\n@doc \"a\\nb\"\ndef f(), do: :ok\nend", + "string", + 0, + "\" quoted_content escape_sequence quoted_content \"", + ), + // an interpolation is a child + ( + "defmodule M do\n@doc \"a#{x}b\"\ndef f(), do: :ok\nend", + "string", + 0, + "\" quoted_content interpolation quoted_content \"", + ), + // a line end inside is content + ( + "defmodule M do\n@doc \"au\ndit\"\ndef f(), do: :ok\nend", + "string", + 0, + "\" quoted_content \"", + ), + // a block after the value belongs to the operand + ( + "defmodule M do\n@doc \"audit\" do\nend\ndef f(), do: :ok\nend", + "call", + 1, + "identifier arguments do_block", + ), + // two values + ( + concat!( + "defmodule M do\n@doc \"audit\", since: \"1\"\ndef f(), do: :ok\n", + "end" + ), + "arguments", + 1, + "string , keywords", + ), + // a comment before the operand; the operand is last + ( + "defmodule M do\n@ # c\ndoc \"audit\"\ndef f(), do: :ok\nend", + "unary_operator", + 0, + "@ comment call", + ), + // a read has no call + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@impl true\n@deprecated \"x\"\n@", + "foo 1\n@doc\n@doc()\ndef f(), do: :ok\nend" + ), + "unary_operator", + 4, + "@ identifier", + ), + // a read with parentheses + ( + concat!( + "defmodule M do\n@doc \"audit\"\n@impl true\n@deprecated \"x\"\n@", + "foo 1\n@doc\n@doc()\ndef f(), do: :ok\nend" + ), + "arguments", + 5, + "( )", + ), + // a bare head + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f\ndef f(), do: :ok\ndef f w", + "hen true, do: :no\nend" + ), + "arguments", + 2, + "identifier", + ), + // a guarded head is the first child + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when x > 0, do: x\ndef ", + "f(x), do: x\nend" + ), + "arguments", + 2, + "binary_operator , keywords", + ), + // the head is the left operand of `when` + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when x > 0, do: x\ndef ", + "f(x), do: x\nend" + ), + "binary_operator", + 0, + "call when binary_operator", + ), + // a comment among the arguments + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(a, # c\n b), do: a\ndef f(", + "a, b), do: b\ndef g(a, b: 1), do: a\ndef g(a, b), do: b\ndef f(a", + "), do: a\nend" + ), + "arguments", + 3, + "( identifier , comment identifier )", + ), + // `do` on the next row belongs to the definition + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x)\ndo\nx\nend\ndef f(y) d", + "o\ny\nend\nend" + ), + "call", + 2, + "identifier arguments do_block", + ), + // a definition call in parentheses starts with `(` + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef(g(x), do: x)\ndef f(), do: :", + "ok\nend" + ), + "arguments", + 2, + "( call , keywords )", + ), + // a head without parentheses has no `(` + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef g x, y do\nx\nend\ndef f(), ", + "do: :ok\nend" + ), + "arguments", + 3, + "identifier , identifier", + ), + // the name of this head is a call + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef unquote(name)(x), do: x\ndef", + " f(), do: :ok\nend" + ), + "call", + 3, + "call arguments", + ), + // the name of this head is a `dot` + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef N.g(y), do: y\ndef f(), do: ", + ":ok\nend" + ), + "call", + 3, + "dot arguments", + ), + // the operator row is no statement + ( + "defmodule M do\n@doc \"audit\"\n|> g()\ndef f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator call end", + ), + // it belongs to the value + ( + "defmodule M do\n@doc \"audit\"\n|> g()\ndef f(), do: :ok\nend", + "arguments", + 1, + "binary_operator", + ), + // also behind a comment row + ( + concat!( + "defmodule M do\n@doc \"audit\"\n# c\n|> g()\ndef f(), do: :ok\ne", + "nd" + ), + "arguments", + 1, + "binary_operator", + ), + // `do` on the next row belongs to the operand + ( + "defmodule M do\n@doc \"audit\"\ndo\nend\ndef f(), do: :ok\nend", + "call", + 1, + "identifier arguments do_block", + ), + // a prefix operator starts a statement + ( + "defmodule M do\n@doc \"audit\"\n- 1\ndef f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator unary_operator call end", + ), + // a continued row has no node + ( + "defmodule M do\n@doc \"audit\"\n\\\ndef f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator call end", + ), + // `;` and a comment are children; a line end is none + ( + concat!( + "defmodule M do\n@doc \"audit\"; # note\n\n@spec f() :: atom()\nd", + "ef f(), do: :ok\nend" + ), + "do_block", + 0, + "do unary_operator ; comment unary_operator call end", + ), + // two statements on one row: no node shows it + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f() do\n:ok\nend def g(), do", + ": :ok\nend" + ), + "do_block", + 0, + "do unary_operator call call end", + ), + // the same after a heredoc + ( + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\" def f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator call end", + ), + // a missing `end` is an invented child + ( + concat!( + "defmodule M do\n@moduledoc \"m\"\n@doc \"audit\"\ndef f(), do: :", + "ok\n" + ), + "do_block", + 0, + "do unary_operator unary_operator call end!", + ), + // an `ERROR` child + ( + "defmodule M do\n@doc \"audit\"\n1 def f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator ERROR? call end", + ), + // an attribute that holds an error + ( + "defmodule M do\n@doc \"a\" \"b\"\ndef f(), do: :ok\nend", + "do_block", + 0, + "do unary_operator? call end", + ), + // the keyword form has no body child + ( + "defmodule M, do: (@doc \"audit\"; def f(), do: :ok)", + "call", + 0, + "identifier arguments", + ), + // a section is a child of the body + ( + concat!( + "defmodule M do\ndef f(), do: :ok\nelse\n@doc \"audit\"\ndef g(),", + " do: 1\nend" + ), + "do_block", + 0, + "do call else_block end", + ), + // a `quote` with a block + ( + concat!( + "defmodule M do\nquote do\n@doc \"audit\"\ndef f(), do: :ok\nend", + "\nend" + ), + "call", + 1, + "identifier do_block", + ), + // a qualified definition starts with a `dot` + ( + concat!( + "defmodule M do\nKernel.@(doc \"audit\")\nKernel.def f(), do: :ok", + "\nend" + ), + "call", + 3, + "dot arguments", + ), + // a read with a comment in its parentheses + ( + "defmodule M do\n@doc( # c\n)\ndef f(), do: :ok\nend", + "arguments", + 1, + "( comment )", + ), + // a comment before a value in parentheses + ( + "defmodule M do\n@doc(# c\n\"audit\")\ndef f(), do: :ok\nend", + "arguments", + 1, + "( comment string )", + ), + // a comment after the value + ( + "defmodule M do\n@doc(\"audit\" # c\n)\ndef f(), do: :ok\nend", + "arguments", + 1, + "( string comment )", + ), + // a comment before the `do` of a module + ( + "defmodule M # c\ndo\n@doc \"audit\"\ndef f(), do: :ok\nend", + "call", + 0, + "identifier arguments comment do_block", + ), + // a comment before the `do` of a definition + ( + "defmodule M do\n@doc \"audit\"\ndef f() # c\ndo\n:ok\nend\nend", + "call", + 2, + "identifier arguments comment do_block", + ), + // a comment after `when` + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) when # c\n is_atom(x), ", + "do: x\nend" + ), + "binary_operator", + 0, + "call when comment call", + ), + // a comment before `when` + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x) # c\n when is_atom(x), ", + "do: x\nend" + ), + "binary_operator", + 0, + "call comment when call", + ), + // a comment between the head and the keywords + ( + "defmodule M do\n@doc \"audit\"\ndef f(), # c\n do: :ok\nend", + "arguments", + 2, + "call , comment keywords", + ), + // a comment in an empty argument list + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f( # c\n), do: :ok\ndef f(),", + " do: :error\nend" + ), + "arguments", + 3, + "( comment )", + ), + // the file: two modules on one row are two clean children + ( + concat!( + "defmodule A do\n@moduledoc \"a\"\nend defmodule X do\n@moduledoc", + " \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend" + ), + "source", + 0, + "call call", + ), + // a body: the same, and no child shows the error + ( + concat!( + "defmodule M do\ndef x() do\n:ok\nend defmodule X do\n@moduledoc ", + "\"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "do_block", + 0, + "do call call end", + ), + // the block of a definition: the expression before is an `ERROR` + ( + concat!( + "defmodule M do\ndef g() do\n:ok defmodule X do\n@moduledoc \"x\"", + "\n@doc \"audit\"\ndef f(), do: :ok\nend\nend\nend" + ), + "do_block", + 1, + "do ERROR? call end", + ), + // a block of a call: two clean children again + ( + concat!( + "if true do\nfn -> :ok end defmodule X do\n@moduledoc \"x\"\n@doc", + " \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "do_block", + 0, + "do anonymous_function call end", + ), + // an `after` block + ( + concat!( + "try do\n:ok\nafter\nfn -> :ok end defmodule X do\n@moduledoc \"x", + "\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "after_block", + 0, + "after anonymous_function call", + ), + // an `else` block + ( + concat!( + "if true do\n:ok\nelse\nfn -> :ok end defmodule X do\n@moduledoc ", + "\"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "else_block", + 0, + "else anonymous_function call", + ), + // a `rescue` block + ( + concat!( + "try do\n:ok\nrescue\nfn -> :ok end defmodule X do\n@moduledoc \"", + "x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "rescue_block", + 0, + "rescue anonymous_function call", + ), + // a `catch` block + ( + concat!( + "try do\n:ok\ncatch\nfn -> :ok end defmodule X do\n@moduledoc \"x", + "\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "catch_block", + 0, + "catch anonymous_function call", + ), + // the body of a clause + ( + concat!( + "f = fn ->\nfn -> :ok end defmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + "body", + 0, + "anonymous_function call", + ), + // a parenthesized block + ( + concat!( + "(\nfn -> :ok end defmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\n)" + ), + "block", + 0, + "( anonymous_function call )", + ), + // an anonymous function: one clause that holds the second + ( + concat!( + "fn\n0 -> :ok 1 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\nend" + ), + "anonymous_function", + 0, + "fn stab_clause? end", + ), + // the body of that clause stands behind an `ERROR` + ( + concat!( + "fn\n0 -> :ok 1 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audit", + "\"\ndef f(), do: :ok\nend\nend" + ), + "stab_clause", + 0, + "arguments -> ERROR? body?", + ), + // a section follows the statements with no separator + ( + concat!( + "try do :ok rescue _ -> defmodule X do\n@moduledoc \"x\"\n@doc \"", + "audit\"\ndef f(), do: :ok\nend\nend" + ), + "do_block", + 0, + "do atom rescue_block end", + ), + // a `;` or a line end between two statements is no node + ( + concat!( + "defmodule M do\n@doc \"audit\"\ndef f(x)\ndef f(0), do: 0\ndef f", + "(x), do: x\nend" + ), + "do_block", + 0, + "do unary_operator call call call end", + ), + // the expression before is an `ERROR` in the operator + ( + concat!( + "x = 1 defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(),", + " do: :ok\nend" + ), + "binary_operator", + 0, + "identifier = ERROR? call", + ), + // a string read as the key of a keyword + ( + concat!( + "defmodule M do\n\"s\" defmodule X do\n@moduledoc \"x\"\n@doc \"a", + "udit\"\ndef f(), do: :ok\nend\nend" + ), + "pair", + 0, + "quoted_keyword? call", + ), + // that key holds an error which no child shows + ( + concat!( + "defmodule M do\n\"s\" defmodule X do\n@moduledoc \"x\"\n@doc \"a", + "udit\"\ndef f(), do: :ok\nend\nend" + ), + "quoted_keyword", + 0, + "\" quoted_content \"", + ), + // the expression before is the left side; the `ERROR` is the next word + ( + concat!( + "1 y = defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(),", + " do: :ok\nend" + ), + "binary_operator", + 0, + "integer ERROR? = call", + ), + // two definitions on one row: one call with the block of the second + ( + concat!( + "defmodule M do\ndef a(), do: :ok def g() do\ndefmodule X do\n@mo", + "duledoc \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend\nend" + ), + "call", + 1, + "identifier arguments? do_block", + ), + // the first body is an `ERROR` beside the second definition + ( + concat!( + "defmodule M do\ndef a(), do: :ok def g() do\ndefmodule X do\n@mo", + "duledoc \"x\"\n@doc \"audit\"\ndef f(), do: :ok\nend\nend\nend" + ), + "pair", + 0, + "keyword ERROR? call", + ), + // an attribute and a definition on one row: one attribute with the block + ( + concat!( + "@doc \"before\" def g() do\ndefmodule X do\n@moduledoc \"x\"\n@d", + "oc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "unary_operator", + 0, + "@ call?", + ), + // its string is a key that holds an error which no child shows + ( + concat!( + "@doc \"before\" def g() do\ndefmodule X do\n@moduledoc \"x\"\n@d", + "oc \"audit\"\ndef f(), do: :ok\nend\nend" + ), + "quoted_keyword", + 0, + "\" quoted_content \"", + ), + // an `ERROR` among the clauses of a function + ( + concat!( + "f = fn\n1 1 -> :ok\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc ", + "\"audit\"\ndef f(), do: :ok\nend\nend" + ), + "anonymous_function", + 0, + "fn ERROR? stab_clause stab_clause end", + ), + // an `ERROR` child of the file holds the module + ( + concat!( + "defmodule A do\n) ) (\ndefmodule M do\n@moduledoc \"m\"\n@doc \"", + "audit\"\ndef f(), do: :ok\nend\nend" + ), + "source", + 0, + "call ERROR?", + ), + // a string without its end: the third quote is a child of an `ERROR` + ( + concat!( + "defmodule M do\nx = \"a\n@doc \"LIT\"\ndef lit, do: :ok\n@doc \"", + "REAL\"\ndef real, do: :ok\nend" + ), + "ERROR", + 0, + "string sigil_name \"", + ), + // a quote too many: the same + ( + concat!( + "defmodule M do\n@doc \"\"audit\"\ndef f(), do: :ok\n@doc \"next", + "\"\ndef g(), do: :ok\nend" + ), + "ERROR", + 0, + "\" \" \"", + ), + // an `ERROR` in a string holds no quote + ( + "defmodule M do\n@doc \"a\u{0}b\"\ndef f(), do: :ok\nend", + "string", + 0, + "\" quoted_content ERROR? \"", + ), + // the right side of a match + ( + concat!( + "x = defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef f(), d", + "o: :ok\nend" + ), + "binary_operator", + 0, + "identifier = call", + ), + // an argument of a call + ( + concat!( + "IO.inspect(defmodule X do\n@moduledoc \"x\"\n@doc \"audit\"\ndef", + " f(), do: :ok\nend)" + ), + "arguments", + 0, + "( call )", + ), + // `?\` before a line feed: a two-byte `char` child before the module + ( + concat!( + "?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + "source", + 0, + "char call", + ), + // `?\` at the end of a clause gives two clean `stab_clause` children + ( + concat!( + "fn\n1 -> ?\\\n2 -> defmodule X do\n@moduledoc \"x\"\n@doc \"audi", + "t\"\ndef f(), do: :ok\nend\nend" + ), + "anonymous_function", + 0, + "fn stab_clause stab_clause end", + ), + // `x = ?\`: the `char` node is the last leaf of the operator + ( + concat!( + "x = ?\\\ndefmodule M do\n @moduledoc \"module\"\n @doc \"funct", + "ion\"\n def f(), do: :ok\nend\n" + ), + "binary_operator", + 0, + "identifier = char", + ), + // `?` before a line feed: an `ERROR` leaf of one byte + ( + concat!( + "?\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function\"", + "\n def f(), do: :ok\nend\n" + ), + "ERROR", + 0, + "ERROR", + ), + // `???` before a line feed: an `ERROR` with `char` and an inner `ERROR` + ( + concat!( + "???\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + "ERROR", + 0, + "char ERROR", + ), + // `foo,` before a line feed: the last leaf of the `ERROR` is `,` + ( + concat!( + "foo,\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + "ERROR", + 0, + "identifier ,", + ), + // `?\` before CR LF: a three-byte `char` child that holds the CR + ( + concat!( + "?\\\r\ndefmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + "source", + 0, + "char call", + ), + // `?` before CR LF: a two-byte `char` child that holds the CR + ( + concat!( + "?\r\ndefmodule M do\n @moduledoc \"module\"\n @doc \"function", + "\"\n def f(), do: :ok\nend\n" + ), + "source", + 0, + "char call", + ), + // an empty clause body: `b -> defmodule X` is a call with an `ERROR` `->` and + // `arguments` + ( + concat!( + "case x do\n a ->\n b -> defmodule X do\n @moduledoc \"m\"\n", + " @doc \"d\"\n def f(), do: :ok\n end\nend\n" + ), + "call", + 1, + "identifier ERROR? arguments do_block", + ), + // `-` on the row behind `?\` starts a `unary_operator` statement + ( + concat!( + "?\\\n- defmodule M do\n @moduledoc \"module\"\n @doc \"functio", + "n\"\n def f(), do: :ok\nend\n" + ), + "source", + 0, + "char unary_operator", + ), + ]; + for (source, kind, nth, children) in shapes { + let parser = parsed(source.as_bytes()); + let nodes = preorder(parser.ts_tree()); + let node = nodes.iter().filter(|node| node.kind() == kind).nth(nth); + assert_eq!(shape(*node.unwrap()), children, "{kind} {nth} of {source}"); + // The reader takes a child by its place among the children that are no comment. + // The grammar's field names say the same: the word of a call is its first child, + // an operand is the last child of its operator, the sides of a binary operator + // stand around it, and the quotes of a string are its first and last child. + for node in nodes.iter().filter(|node| !node.has_error()) { + let children: Vec<_> = node + .children(&mut node.walk()) + .filter(|child| child.kind() != "comment") + .collect(); + let fields: &[(&str, usize)] = match node.kind() { + "call" => &[("target", 0)], + "unary_operator" => &[("operator", 0), ("operand", children.len() - 1)], + "binary_operator" => &[("left", 0), ("operator", 1), ("right", 2)], + "string" => &[("quoted_start", 0), ("quoted_end", children.len() - 1)], + _ => &[], + }; + for (field, place) in fields { + assert_eq!( + node.child_by_field_name(field), + children.get(*place).copied(), + "{field} of {kind} in {source}" + ); + } + } + } + // Two statements on one row: the body holds a syntax error that no child shows. The + // reader therefore reads the bytes between two statements itself. + for source in [ + "defmodule M do\n@doc \"audit\"\ndef f() do\n:ok\nend def g(), do: :ok\nend", + "defmodule M do\n@doc \"\"\"\naudit\n\"\"\" def f(), do: :ok\nend", + ] { + let parser = parsed(source.as_bytes()); + let nodes = preorder(parser.ts_tree()); + let body = nodes.iter().find(|node| node.kind() == "do_block").unwrap(); + assert!(body.has_error(), "{source}"); + let mut cursor = body.walk(); + for child in body.children(&mut cursor) { + assert!(!child.has_error() && !child.is_missing(), "{source}"); + } + } +} 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..fc93f13b3 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/form_tests.rs @@ -0,0 +1,288 @@ +use crate::documentation::*; +use crate::{AnyParser, LANG}; + +#[cfg(any( + feature = "java", + feature = "kotlin", + feature = "php", + feature = "typescript", + feature = "ruby", +))] +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}"); + 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")] +#[test] +fn java_unnamed_field_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Java, + "class C { /**audit*/ int _; }", + "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_has_a_slot_in_default_queries() { + let source = b"class C {\n/**audit*/\nint x\n}"; + let parser = AnyParser::parse(LANG::Groovy, source.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 projection = index.node_projection(field.as_tree_sitter()).unwrap(); + assert!(!projection.pending()); + assert_eq!(projection.owners().len(), 1); + let slot = projection.owners().next().unwrap(); + let Owner::Slot(slot_data) = slot.get() else { + panic!("field has a slot") + }; + assert_eq!(slot_data.role, SlotRole::Field); + assert_eq!(slot_data.ordinal, 0); + assert_eq!(slot_data.source.pieces()[0].range(), 25..26); + assert_eq!(index.associations().len(), 1); + assert_eq!( + index.owner_associations(slot).unwrap().associations().len(), + 1 + ); +} + +#[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 = "php")] +#[test] +fn php_promoted_form_is_pending_in_default_queries() { + assert_pending_form( + LANG::Php, + " 1;".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert_eq!(index.associations().len(), 1); + let association = index.associations().next().unwrap(); + let owner = index.facts().associated_owner(association, 0).unwrap(); + assert!( + matches!(owner.get(), Owner::Node(node) if node.node().kind() == "variable_declarator") + ); +} +#[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_alias_forms_are_pending_in_default_queries() { + assert_pending_form(LANG::Ruby, "# audit\nalias_method :x, :y", "call"); + assert_pending_form(LANG::Ruby, "# audit\nX = 1", "assignment"); + let source = b"# audit\nalias_method :x, :y"; + let parser = AnyParser::parse(LANG::Ruby, source.to_vec(), None, None).unwrap(); + let call = parser + .root_node() + .preorder() + .find(|n| n.kind() == "call") + .unwrap(); + assert!(crate::lang_helpers::ruby::ruby_documented_call( + &call, source + )); + let alias = b"class C\n# audit\nalias b a\nend"; + let parser = AnyParser::parse(LANG::Ruby, alias.to_vec(), None, None).unwrap(); + let node = parser + .root_node() + .preorder() + .find(|n| n.kind() == "alias") + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + assert!( + index + .node_projection(node.as_tree_sitter()) + .unwrap() + .pending() + ); +} +#[cfg(feature = "lua")] +#[test] +fn lua_assignment_with_missing_value_is_pending_in_default_queries() { + let source = b"module(\"m\")\n---audit\nvalue ="; + let parser = AnyParser::parse(LANG::Lua, source.to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + for index in [ + parser.documentation(&context, &options).unwrap(), + collect( + LANG::Lua, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(), + ] { + let assignment = parser.ts_tree().root_node().named_child(2).unwrap(); + assert_eq!(assignment.kind(), "assignment_statement"); + assert!(assignment.has_error()); + assert!(index.node_projection(assignment).unwrap().pending()); + assert_eq!(index.documents().len(), 1); + assert!( + index + .assessments() + .any(|assessment| index.assessed_document(assessment).unwrap() + == index.documents().next()) + ); + assert_eq!(index.associations().len(), 1); + assert_eq!( + index.associations().next().unwrap().get().resolution, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + ); + } +} + +#[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/go_tests.rs b/big-code-analysis-ast/src/documentation/collector/go_tests.rs new file mode 100644 index 000000000..4ce8200c6 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/go_tests.rs @@ -0,0 +1,4691 @@ +//! 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)] + +#[cfg(feature = "go")] +use crate::documentation::*; +#[cfg(feature = "go")] +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}; + +/// 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. 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, +} + +/// 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 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 { + 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(piece) => Run::Copied(piece.range()), + Origin::Decoded(pieces) => Run::Decoded(span(pieces)), + Origin::Expanded(pieces) => Run::Expanded(span(pieces)), + Origin::Synthetic => Run::Synthetic, + } +} + +/// 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, 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> { + let owner = facts.associated_owner(association, 0).unwrap(); + 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. + 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| 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 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 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) + ); + 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, 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, + slots, + 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<'p>( + parser: &'p AnyParser, + options: &DocumentationOptions, +) -> [DocumentationIndex<'p>; 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!(!query.projection_pending()); + 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), + ); + // 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")] +#[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), + ); + // 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] = [ + ( + 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() + ); + } + // 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] = [ + (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() + ); + } +} + +#[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)); +} + +/// 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); +} + +#[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/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..8e7aefc07 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/groovy_tests.rs @@ -0,0 +1,1676 @@ +//! 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. Field node queries are tested separately. +#![allow(clippy::single_range_in_vec_init, clippy::naive_bytecount)] + +#[cfg(feature = "groovy")] +use crate::documentation::budget::WorkBudget; +#[cfg(feature = "groovy")] +use crate::documentation::*; +#[cfg(feature = "groovy")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "groovy")] +use Run::{Copied, Decoded}; +#[cfg(feature = "groovy")] +use std::cell::Cell; +#[cfg(feature = "groovy")] +use std::ops::Range; + +#[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, Vec)>, + evidence: Vec<(CandidateDisposition, Range)>, + pending: Vec, +} + +#[cfg(feature = "groovy")] +#[derive(Debug, PartialEq, Eq)] +enum ExpectedOwner { + Node(&'static str, Range), + Field(usize, Range, Range), +} + +#[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, + vec![ExpectedOwner::Node(kind, range)], + )], + ..View::default() + } +} + +#[cfg(feature = "groovy")] +fn field(ordinal: usize, source: Range, declaration: Range) -> ExpectedOwner { + ExpectedOwner::Field(ordinal, source, declaration) +} + +#[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(piece) => Run::Copied(piece.range()), + 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.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 owners = (0..attachment.owner_count()) + .map(|at| { + let owner = facts.associated_owner(association, at).unwrap(); + match owner.get() { + Owner::Node(declared) => { + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declared.node()) + ); + let (kind, range) = site(declared.node()); + ExpectedOwner::Node(kind, range) + } + Owner::Slot(slot) => { + assert_eq!(slot.role, SlotRole::Field); + let enclosing = facts.slot_enclosing(owner).unwrap(); + let Owner::Node(declared) = enclosing.get() else { + panic!("field enclosing owner must be a node") + }; + assert_eq!(declared.node().kind(), "field_declaration"); + assert_eq!( + attachment.binding.map(NodeEvidence::node), + Some(declared.node()) + ); + ExpectedOwner::Field( + slot.ordinal, + span(&slot.source), + declared.node().byte_range(), + ) + } + other => panic!("unexpected owner: {other:?}"), + } + }) + .collect(); + (position(document), attachment.resolution, owners) + }) + .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<'p>( + parser: &'p AnyParser, + options: &DocumentationOptions, +) -> [DocumentationIndex<'p>; 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() + ); + } + // 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, "{}", source.escape_ascii()); + expected.evidence.extend([ + (CandidateDisposition::Superseded, 0..8), + (CandidateDisposition::Superseded, 9..17), + ]); + assert_eq!(retained(source), expected, "{}", 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, + vec![ExpectedOwner::Node("enum_constant", 26..27)] + ), + ( + 1, + Resolution::Resolved, + vec![ExpectedOwner::Node("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() { + 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), + 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 + ) + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_document_owns_its_name_slot() { + assert_eq!( + view(b"class C {\n/**audit*/\nint x\n}\n"), + View { + documents: vec![comment(10..20, "audit", [(0..5, Copied(13..18))])], + owners: vec![(0, Resolution::Resolved, vec![field(0, 25..26, 21..26)])], + ..View::default() + } + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_spaces_fixture_resolves_all_five_documents() { + let source = crate::test_support::documentation::source("groovy-spaces.groovy"); + let parser = clean(&source); + let index = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&index); + assert_eq!(actual.documents.len(), 5); + assert_eq!(actual.owners.len(), 5); + assert_eq!( + actual, + View { + documents: vec![ + comment(0..13, "record", [(0..6, Copied(4..10))]), + comment(33..44, "type", [(0..4, Copied(37..41))]), + comment(59..70, "ctor", [(0..4, Copied(63..67))]), + comment(86..98, "field", [(0..5, Copied(90..95))]), + comment(113..126, "method", [(0..6, Copied(117..123))]), + ], + owners: vec![ + ( + 0, + Resolution::Resolved, + vec![ExpectedOwner::Node("record_declaration", 14..32)] + ), + ( + 1, + Resolution::Resolved, + vec![ExpectedOwner::Node("class_declaration", 45..159)] + ), + ( + 2, + Resolution::Resolved, + vec![ExpectedOwner::Node("constructor_declaration", 75..81)] + ), + (3, Resolution::Resolved, vec![field(0, 107..108, 103..108)]), + ( + 4, + Resolution::Resolved, + vec![ExpectedOwner::Node("method_declaration", 131..157)] + ), + ], + ..View::default() + } + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_two_superseded_field_blocks_keep_source_order() { + let source = b"class C {\n/** a */\n/** b */\n/** c */\nint x\n}\n"; + let actual = retained(source); + assert_eq!( + actual.documents, + [comment(28..36, "c", [(0..1, Copied(32..33))])] + ); + assert_eq!( + actual.owners, + [(0, Resolution::Resolved, vec![field(0, 41..42, 37..42)])] + ); + assert_eq!( + actual.evidence, + [ + (CandidateDisposition::Superseded, 10..18), + (CandidateDisposition::Superseded, 19..27), + ] + ); + assert_eq!(actual.pending, []); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_and_property_slots_cover_positive_forms() { + type FieldRow<'a> = (&'a [u8], Range, &'a [Range]); + let rows: [FieldRow<'_>; 6] = [ + (b"class C {\n/**audit*/\nint x\n}\n", 21..26, &[25..26]), + (b"class C {\n/**audit*/\ndef x\n}\n", 21..26, &[25..26]), + ( + b"class C {\n/**audit*/\nstatic final int X = 1\n}\n", + 21..43, + &[38..39], + ), + ( + b"class C {\n/**audit*/\nint a = 1, b = 2\n}\n", + 21..37, + &[25..26, 32..33], + ), + ( + b"class C {\n/**audit*/\n@Deprecated static int x\n}\n", + 21..45, + &[44..45], + ), + ( + "class C {\n/**audit*/\ndef café = 1\n}\n".as_bytes(), + 21..34, + &[25..30], + ), + ]; + for (source, declaration, names) in rows { + let parser = clean(source); + let indices = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&indices); + assert_eq!( + actual.documents, + [comment(10..20, "audit", [(0..5, Copied(13..18))])] + ); + assert_eq!(actual.pending, [], "{}", source.escape_ascii()); + let expected: Vec<_> = names + .iter() + .cloned() + .enumerate() + .map(|(ordinal, name)| field(ordinal, name, declaration.clone())) + .collect(); + assert_eq!(actual.owners, [(0, Resolution::Resolved, expected)]); + let field_node = node_at(&parser, "field_declaration", declaration); + let index = &indices[0]; + let projection = index.node_projection(field_node).unwrap(); + assert!(!projection.pending()); + assert_eq!(projection.owners().len(), names.len()); + let association = index.associations().next().unwrap(); + for owner in projection.owners() { + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .associations() + .next(), + Some(association) + ); + } + if names.len() == 2 { + assert!(matches!( + index.node_associations(field_node), + Err(OwnerError::MultipleOwners) + )); + } + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_enum_and_trait_fields_have_slots_in_their_own_scope() { + for (source, declaration, name) in [ + ( + b"enum E { A;\n/**audit*/\nint x\n}\n".as_slice(), + 23..28, + 27..28, + ), + (b"trait T {\n/**audit*/\ndef x\n}\n", 21..26, 25..26), + ] { + let actual = view(source); + assert_eq!(actual.documents.len(), 1); + assert_eq!( + actual.owners, + [(0, Resolution::Resolved, vec![field(0, name, declaration)])] + ); + assert_eq!(actual.pending, []); + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_comments_inside_fields_are_not_new_documents() { + let source = b"class C {\n/**audit*/\nint a, /* plain */ b\n}\n"; + let actual = view(source); + assert_eq!( + actual.documents, + [comment(10..20, "audit", [(0..5, Copied(13..18))])] + ); + assert_eq!( + actual.owners, + [( + 0, + Resolution::Resolved, + vec![field(0, 25..26, 21..41), field(1, 40..41, 21..41)] + )] + ); + assert_eq!(actual.pending, []); + let source = b"class C {\n/**audit*/\nint /** inner */ x\n}\n"; + let actual = retained(source); + assert_eq!( + actual.documents, + [comment(10..20, "audit", [(0..5, Copied(13..18))])] + ); + assert_eq!( + actual.owners, + [(0, Resolution::Resolved, vec![field(0, 38..39, 21..39)])] + ); + assert_eq!( + actual.evidence, + [(CandidateDisposition::Unattached, 25..37)] + ); + assert_eq!(actual.pending.len(), 1); + assert_eq!(actual.pending[0].axis, AssessmentAxis::Selection); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_undocumented_field_still_gets_both_slots() { + let source = b"class C { int a, b }"; + let parser = clean(source); + let indices = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&indices); + assert_eq!(actual, View::default()); + let field_node = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + let owners = indices[0].node_owners(field_node).unwrap(); + assert_eq!(owners.len(), 2); + for (ordinal, owner) in owners.enumerate() { + let Owner::Slot(slot) = owner.get() else { + panic!("slot expected") + }; + assert_eq!(slot.ordinal, ordinal); + assert_eq!(slot.role, SlotRole::Field); + assert_eq!(span(&slot.source), [14..15, 17..18][ordinal]); + let query = indices[0].owner_associations(owner).unwrap(); + assert!(!query.projection_pending()); + assert!(query.associations().next().is_none()); + } +} + +#[cfg(feature = "groovy")] +#[test] +#[allow(clippy::too_many_lines)] +fn groovy_literal_and_comment_lines_do_not_make_field_documents() { + const PENDING_OWNER: &str = "Recognized declaration requires a semantic projection"; + for (source, field_range, slot_range, pending_nodes) in [ + ( + b"class C { def s = '\n /** doc */\n int x\n' }\n".as_slice(), + 10..38, + None, + &[("field_declaration", 10..38)][..], + ), + ( + b"class C { def s = \"\n /** doc */\n int x\n\" }\n", + 10..38, + None, + &[("field_declaration", 10..38)], + ), + ( + b"class C { def s = '''\n /** doc */\n int x\n''' }\n", + 10..46, + Some(14..15), + &[], + ), + ( + b"class C { def s = \"\"\"\n /** doc */\n int x\n\"\"\" }\n", + 10..46, + Some(14..15), + &[], + ), + ( + b"class C { def s = /\n /** doc */\n int x\n/ }\n", + 10..38, + None, + &[("class_declaration", 0..44), ("field_declaration", 10..38)], + ), + ( + b"class C { def s = $/\n /** doc */\n int x\n/$ }\n", + 10..44, + Some(14..15), + &[], + ), + ( + b"class C { /*\n /** doc */\n int x\n*/ }\n", + 28..33, + Some(32..33), + &[("class_declaration", 0..38)], + ), + ] { + let parser = AnyParser::parse(LANG::Groovy, source.to_vec(), None, None).unwrap(); + let indices = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&indices); + let pending = pending_nodes + .iter() + .map(|(kind, range)| Pending { + axis: AssessmentAxis::Owner, + reason: PENDING_OWNER, + node: (kind, range.clone()), + document: None, + }) + .collect::>(); + let expected = View { + pending: unordered(pending), + ..View::default() + }; + assert_eq!(actual, expected, "{}", source.escape_ascii()); + let field_node = node_at(&parser, "field_declaration", field_range.clone()); + for index in &indices { + let projection = index.node_projection(field_node).unwrap(); + assert_eq!( + projection.pending(), + slot_range.is_none(), + "{}", + source.escape_ascii() + ); + if let Some(name) = &slot_range { + let [owner] = projection.owners().collect::>()[..] else { + panic!("one field slot: {}", source.escape_ascii()) + }; + let Owner::Slot(slot) = owner.get() else { + panic!("field slot expected") + }; + assert_eq!(slot.role, SlotRole::Field); + assert_eq!(slot.ordinal, 0); + assert_eq!(span(&slot.source), name.clone()); + let enclosing = index.facts().slot_enclosing(owner).unwrap(); + let Owner::Node(declaration) = enclosing.get() else { + panic!("enclosing declaration expected") + }; + assert_eq!( + site(declaration.node()), + ("field_declaration", field_range.clone()) + ); + } + } + let retained = agreed(&indexes( + &parser, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + )); + let evidence = if slot_range.is_none() { + vec![(CandidateDisposition::Unattached, 22..32)] + } else { + vec![] + }; + let expected = View { + evidence, + pending: expected.pending, + ..View::default() + }; + assert_eq!(retained, expected, "{}", source.escape_ascii()); + } + // Characterization: grammar recovery exposes a Groovydoc inside what Groovy + // 4.0.32's lexer reads as slashy strings. This Resolved owner is today's + // named lexer/grammar limitation, not an intended Groovy attachment. + let slashy = b"class C { def s = /a\n /** doc */\n int x\n/ }\n"; + let parser = AnyParser::parse(LANG::Groovy, slashy.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + let expected = View { + documents: vec![comment(23..33, "doc", [(0..3, Copied(27..30))])], + owners: vec![(0, Resolution::Resolved, vec![field(0, 40..41, 36..41)])], + pending: unordered([ + Pending { + axis: AssessmentAxis::Owner, + reason: PENDING_OWNER, + node: ("class_declaration", 0..45), + document: None, + }, + Pending { + axis: AssessmentAxis::Owner, + reason: PENDING_OWNER, + node: ("field_declaration", 10..20), + document: None, + }, + ]), + ..View::default() + }; + assert_eq!( + agreed(&indexes(&parser, &DocumentationOptions::default())), + expected + ); + assert_eq!( + agreed(&indexes( + &parser, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + } + )), + expected + ); + let control = b"class C {\n /** doc */\n int x\n}\n"; + assert_eq!( + view(control), + View { + documents: vec![comment(12..22, "doc", [(0..3, Copied(16..19))])], + owners: vec![(0, Resolution::Resolved, vec![field(0, 29..30, 25..30)])], + ..View::default() + } + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_local_variable_forms_are_not_field_targets() { + // Characterization: these local declarations are outside the field adapter's scope. + for (source, comment) in [ + (b"/**audit*/\ndef x\n".as_slice(), 0..10), + (b"class C {\nvoid f() {\n/**audit*/\nint x\n}\n}\n", 21..31), + ( + b"class C {\ndef f() { def q = {\n/**audit*/\nint x\n} }\n}\n", + 30..40, + ), + ] { + let parser = clean(source); + assert_eq!( + agreed(&indexes(&parser, &DocumentationOptions::default())), + View::default(), + "{}", + source.escape_ascii() + ); + let mut expected = View::default(); + expected + .evidence + .push((CandidateDisposition::Unattached, comment)); + assert_eq!( + agreed(&indexes( + &parser, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + } + )), + expected, + "{}", + source.escape_ascii() + ); + assert!( + !parser + .root_node() + .preorder() + .any(|node| node.kind() == "field_declaration") + ); + } +} + +#[cfg(feature = "groovy")] +#[derive(Default)] +struct Counting { + steps: Cell, + bytes: Cell, + fail_at: Option, +} + +#[cfg(feature = "groovy")] +impl WorkBudget for Counting { + type Error = SourceError; + #[cfg(feature = "groovy")] + 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 = "groovy")] + fn bytes(&self, count: usize) -> Result<(), SourceError> { + self.bytes.set(self.bytes.get() + count); + Ok(()) + } +} + +#[cfg(feature = "groovy")] +fn wide(width: usize) -> String { + let names: Vec<_> = (0..width).map(|at| format!("v{at}")).collect(); + format!("class C {{\n/**audit*/\nint {}\n}}", names.join(", ")) +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_declarator_scan_charges_each_child_once() { + for (source, steps, names) in [ + ( + b"class C {\n/**audit*/\nint x\n}\n".as_slice(), + 2, + vec![25..26], + ), + ( + b"class C {\n/**audit*/\nint a = 1, b = 2\n}\n", + 4, + vec![25..30, 32..37], + ), + ( + b"class C {\n/**audit*/\nint a, /* plain */ b\n}\n", + 5, + vec![25..26, 40..41], + ), + ] { + let parser = clean(source); + let index = indexes(&parser, &DocumentationOptions::default()); + let field_node = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + let id = index[0].canonical.lookup(field_node).unwrap(); + let budget = Counting::default(); + let found = super::projections::java_declarator_names(&index[0].canonical, id, &budget) + .unwrap() + .unwrap(); + assert_eq!(budget.steps.get(), steps); + assert_eq!(budget.bytes.get(), 0); + let actual: Vec<_> = found + .iter() + .map(|id| index[0].canonical.nodes[id.0].evidence.node().byte_range()) + .collect(); + // expected: the first identifier child of each variable_declarator is the name. + let names = names + .iter() + .map(|range| range.start..range.start + 1) + .collect::>(); + assert_eq!(actual, names, "{}", source.escape_ascii()); + for checkpoint in 1..=steps { + let budget = Counting { + fail_at: Some(checkpoint), + ..Counting::default() + }; + assert!(matches!( + super::projections::java_declarator_names(&index[0].canonical, id, &budget), + Err(SourceError::Cancelled) + )); + assert_eq!(budget.steps.get(), checkpoint); + } + } +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_width_has_linear_collection_cost_and_cancellation() { + for width in [64, 512] { + let source = wide(width); + let parser = clean(source.as_bytes()); + 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() + ); + assert_eq!( + after.child_batches - before.child_batches, + parser.root_node().preorder().count() + ); + 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!( + index.associations().next().unwrap().get().owner_count(), + width + ); + assert_eq!(index.facts().owners().len(), width + 3); + } + let width = 2048; + let source = wide(width); + let parser = clean(source.as_bytes()); + 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; + let mut slotting = 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}" + ); + if after.owner_projections - before.owner_projections == 2 + && after.visits - before.visits == parser.root_node().preorder().count() - 1 + { + scanning += 1; + } + if after.owner_projections - before.owner_projections == 3 + && after.intersection_searches - before.intersection_searches < width + 1 + { + slotting += 1; + } + } + // expected: 1 type + 2048 declarators + 2047 commas = 4096 child charges; + // four checkpoints per 1024 steps, plus at most one from preceding walk steps. + assert!((4..=5).contains(&scanning), "scan checkpoints: {scanning}"); + // expected: each of 2048 slots charges its loop and two range steps: 6144 + // steps, six checkpoints per 1024, plus at most one from preceding work. + assert!((6..=7).contains(&slotting), "slot checkpoints: {slotting}"); + assert_eq!( + crate::documentation::budget::cancel_after(polls + 1, || parser + .documentation(&context, &options)) + .unwrap() + .associations() + .next() + .unwrap() + .get() + .owner_count(), + width + ); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_field_excluded_bytes_remain_pending_and_gap_blocks_attachment() { + let source = b"class C {\n/**audit*/\nint a, b\n}\n"; + let parse = |ranges: &[Range]| { + 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::Groovy.tree_sitter_language().unwrap()) + .unwrap(); + parser.set_included_ranges(&ranges).unwrap(); + parser.parse(source, None).unwrap() + }; + let tree = parse(&[0..27, 28..source.len()]); + let adopted = AnyParser::from_tree(LANG::Groovy, tree, source.to_vec()).unwrap(); + let indices = indexes( + &adopted, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ); + let actual = agreed(&indices); + assert_eq!(actual.documents, []); + assert_eq!(actual.owners, []); + let field_node = adopted + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + assert!(indices[0].node_projection(field_node).unwrap().pending()); + let tree = parse(&[0..20, 21..source.len()]); + let adopted = AnyParser::from_tree(LANG::Groovy, tree, source.to_vec()).unwrap(); + let indices = indexes( + &adopted, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ); + let actual = agreed(&indices); + assert_eq!(actual.documents, []); + assert_eq!(actual.owners, []); + assert_eq!( + actual.evidence, + [(CandidateDisposition::Unattached, 10..20)] + ); + let field_node = adopted + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + assert_eq!(indices[0].node_owners(field_node).unwrap().len(), 2); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_same_row_field_block_is_unselected_but_the_field_has_a_slot() { + let source = b"class C { /**audit*/ int x }"; + let parser = clean(source); + let indices = indexes( + &parser, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ); + let actual = agreed(&indices); + assert_eq!(actual.documents, []); + assert_eq!(actual.owners, []); + assert_eq!( + actual.evidence, + [(CandidateDisposition::Unattached, 10..20)] + ); + assert_eq!(actual.pending.len(), 1); + assert_eq!(actual.pending[0].axis, AssessmentAxis::Selection); + let declaration = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + let mut owners = indices[0].node_owners(declaration).unwrap(); + assert_eq!(owners.len(), 1); + let owner = owners.next().unwrap(); + let Owner::Slot(slot) = owner.get() else { + panic!("a field slot is required") + }; + assert_eq!(slot.role, SlotRole::Field); + assert_eq!(span(&slot.source), 25..26); +} + +#[cfg(feature = "groovy")] +#[test] +fn groovy_slashy_recovery_field_is_pending_and_clean_fields_beside_errors_have_slots() { + let pending_owner = |node| Pending { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node, + document: None, + }; + let slashy = b"class C { def s = /\n /** doc */\n int x\n/ }\n"; + let parser = AnyParser::parse(LANG::Groovy, slashy.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + let indices = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&indices); + let expected = View { + pending: unordered([ + pending_owner(("class_declaration", 0..44)), + pending_owner(("field_declaration", 10..38)), + ]), + ..View::default() + }; + assert_eq!(actual, expected); + let mut retained = expected; + retained + .evidence + .push((CandidateDisposition::Unattached, 22..32)); + assert_eq!( + agreed(&indexes( + &parser, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + } + )), + retained + ); + let field_node = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + assert!(field_node.has_error()); + assert!(indices[0].node_projection(field_node).unwrap().pending()); + // In this recovered parse the invalid initializer is a sibling ERROR, not part of the field. + let source = b"class C {\n/**audit*/\nint x = ;\n}\n"; + let parser = AnyParser::parse(LANG::Groovy, source.to_vec(), None, None).unwrap(); + assert!(parser.ts_tree().root_node().has_error()); + let indices = indexes(&parser, &DocumentationOptions::default()); + let actual = agreed(&indices); + let expected = View { + documents: vec![comment(10..20, "audit", [(0..5, Copied(13..18))])], + owners: vec![(0, Resolution::Resolved, vec![field(0, 25..26, 21..26)])], + pending: vec![pending_owner(("class_declaration", 0..32))], + ..View::default() + }; + assert_eq!(actual, expected); + assert_eq!( + agreed(&indexes( + &parser, + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + } + )), + expected + ); + let declaration = parser + .root_node() + .preorder() + .find(|node| node.kind() == "field_declaration") + .unwrap() + .as_tree_sitter(); + assert!(!declaration.has_error()); + assert_eq!(indices[0].node_owners(declaration).unwrap().len(), 1); +} + +#[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!(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(); + 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/big-code-analysis-ast/src/documentation/collector/irules.rs b/big-code-analysis-ast/src/documentation/collector/irules.rs new file mode 100644 index 000000000..fd2602e2a --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules.rs @@ -0,0 +1,127 @@ +//! iRules source-only leading rows. The legacy role table is unchanged. + +use super::*; +use crate::Irules; +use crate::lang_helpers::irules::{COMMENT_KIND, LINE_FEED_KIND}; +use crate::lang_helpers::tcl_family::{ + braced_word_end, comment_spelling_end, line_continues, tcl_blank, unescaped_line_ends, +}; +use crate::lang_helpers::tcl_scan::{Command, Listed}; + +const BODY_PENDING: &str = "Initial iRules body block awaits source documentation support"; + +pub(super) fn newline(index: &DocumentationIndex<'_>, id: NodeId) -> bool { + let node = index.canonical.node(id); + node.kind_id() == LINE_FEED_KIND && !node.is_missing() +} + +pub(super) fn row( + index: &DocumentationIndex<'_>, + id: NodeId, + budget: &CollectionBudget, +) -> Result, CollectionError> { + let node = index.canonical.node(id); + if node.kind_id() != COMMENT_KIND || node.is_missing() { + return Ok(None); + } + let beginning = row_beginning(index.source.bytes(), node.start_byte(), budget)?; + row_after(index, id, beginning, budget) +} + +/// The spelling end of comment `id` when the source includes `from` through +/// the comment and only blanks stand between them: [`row`]'s test, for a row +/// whose text starts at `from`. +pub(super) fn row_after( + index: &DocumentationIndex<'_>, + id: NodeId, + from: usize, + budget: &CollectionBudget, +) -> Result, CollectionError> { + let node = index.canonical.node(id); + if node.kind_id() != COMMENT_KIND || node.is_missing() { + return Ok(None); + } + let covered = index + .source + .covers_with_budget(from..node.end_byte(), budget)?; + let horizontal = crate::documentation::byte_scan::position( + &index.source.bytes()[from..node.start_byte()], + |byte| !tcl_blank(byte), + budget, + )? + .is_none(); + Ok(if covered && horizontal { + Some(spelling_end(index, node, budget)?) + } else { + None + }) +} + +fn row_beginning( + code: &[u8], + start: usize, + budget: &CollectionBudget, +) -> Result { + Ok(crate::documentation::byte_scan::rposition( + &code[..start], + |byte| byte == b'\n' || byte == b'\r', + budget, + )? + .map_or(0, |at| at + 1)) +} + +pub(super) fn spelling_end( + index: &DocumentationIndex<'_>, + node: tree_sitter::Node<'_>, + budget: &CollectionBudget, +) -> Result { + let end = node.end_byte(); + let code = index.source.bytes(); + if end < code.len() && index.source.covers_with_budget(end..end + 1, budget)? { + Ok(comment_spelling_end(code, node.start_byte(), end)) + } else { + Ok(end) + } +} + +// An LF token can cover an arbitrarily large gap. Read its bytes instead of +// treating its kind as proof that the command above it has ended. +pub(super) fn independent_row( + index: &DocumentationIndex<'_>, + parent: NodeId, + comment: NodeId, + budget: &CollectionBudget, +) -> Result { + let before = index.canonical.children_of(parent); + let position = index.canonical.nodes[comment.0].ordinal; + let code = index.source.bytes(); + for &previous in before[..position].iter().rev() { + budget.step()?; + let above = index.canonical.node(previous); + if newline(index, previous) { + continue; + } + let end = spelling_end(index, above, budget)?; + let start = above.start_byte(); + let gap = end..index.canonical.node(comment).start_byte(); + if !index.source.covers_with_budget(gap.clone(), budget)? { + return Ok(false); + } + return independent_gap(&code[start..end], &code[gap], budget); + } + Ok(true) +} + +fn independent_gap( + spelling: &[u8], + gap: &[u8], + budget: &CollectionBudget, +) -> Result { + Ok(unescaped_line_ends(gap, line_continues(spelling, budget)?, 1, budget)? == 1) +} + +mod body; +mod command; +mod leading; +mod registration; +mod unbound; diff --git a/big-code-analysis-ast/src/documentation/collector/irules/body.rs b/big-code-analysis-ast/src/documentation/collector/irules/body.rs new file mode 100644 index 000000000..5a61d39ac --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules/body.rs @@ -0,0 +1,136 @@ +use super::*; + +impl Builder<'_> { + pub(in crate::documentation::collector) fn irules_body_assessment( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let node = self.index.canonical.node(id); + if !matches!(node.kind_id(), kind if kind == Irules::WhenEvent as u16 || kind == Irules::Procedure as u16) + { + return Ok(()); + } + let Some(body) = self.irules_body(id, budget)? else { + return Ok(()); + }; + let first = self.irules_initial_body_rows(body, budget)?; + if let Some(comment) = first { + self.irules_mark_body_pending(id, comment); + } + Ok(()) + } + + fn irules_initial_body_rows( + &mut self, + body: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let inside = self.index.canonical.children_of(body); + let Some(&open) = inside.first() else { + return Ok(None); + }; + let mut above = None; + let mut first = None; + for &child in inside { + budget.step()?; + if newline(&self.index, child) { + continue; + } + // Only the first accepted row can share the brace's row: a comment + // runs to its row's end, so every later one starts below it. + let accepted = match self.irules_brace_row(open, child, budget)? { + Some(end) => Some(end), + None => match row(&self.index, child, budget)? { + Some(end) if self.irules_next_body_row(body, open, above, child, budget)? => { + Some(end) + } + Some(_) => break, + None => None, + }, + }; + if let Some(end) = accepted { + first.get_or_insert(child); + self.irules_body_initial.insert(child); + above = Some((child, end)); + } else if self.index.canonical.node(child).kind_id() != Irules::LBRACE as u16 { + break; + } + } + Ok(first) + } + + fn irules_next_body_row( + &self, + body: NodeId, + open: NodeId, + above: Option<(NodeId, usize)>, + child: NodeId, + budget: &CollectionBudget, + ) -> Result { + if self.index.canonical.node(child).start_position().row + == self.index.canonical.node(body).start_position().row + { + return Ok(false); + } + let (prior, end) = above.unwrap_or((open, self.index.canonical.node(open).end_byte())); + self.irules_body_row(prior, end, child, above.is_none(), budget) + } + + // A comment that follows the opening brace on its row, past blanks alone, + // is the first row of the body text, as Tcl's lead block reads it. + fn irules_brace_row( + &self, + open: NodeId, + child: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let brace = self.index.canonical.node(open); + if self.index.canonical.node(child).start_position().row != brace.end_position().row { + return Ok(None); + } + super::row_after(&self.index, child, brace.end_byte(), budget) + } + + fn irules_mark_body_pending(&mut self, id: NodeId, comment: NodeId) { + let evidence = self.index.canonical.nodes[comment.0].evidence; + self.pend(id, AssessmentAxis::Occurrence, BODY_PENDING, evidence); + } + + fn irules_body_row( + &self, + prior: NodeId, + end: usize, + comment: NodeId, + first: bool, + budget: &CollectionBudget, + ) -> Result { + let following = self.index.canonical.node(comment); + let span = end..following.start_byte(); + if !self.index.source.covers_with_budget(span.clone(), budget)? { + return Ok(false); + } + let code = self.index.source.bytes(); + Ok(following.start_position().row + == self.index.canonical.node(prior).end_position().row + 1 + && unescaped_line_ends( + &code[span], + first + && line_continues( + &code[self.index.canonical.node(prior).start_byte()..end], + budget, + )?, + 2, + budget, + )? == 1 + && (!first + || independent_row( + &self.index, + self.index.canonical.nodes[comment.0] + .parent + .unwrap_or(NodeId(0)), + comment, + budget, + )?)) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules/command.rs b/big-code-analysis-ast/src/documentation/collector/irules/command.rs new file mode 100644 index 000000000..bcb0aaa36 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules/command.rs @@ -0,0 +1,162 @@ +use super::*; + +// A command gap is horizontal whitespace or backslash-line-end whitespace. +// An unescaped command separator, including a bare LF before a late body, +// means the grammar's one node is not one Tcl command. +fn word_gap( + code: &[u8], + gap: std::ops::Range, + budget: &CollectionBudget, +) -> Result { + if code[gap.clone()].is_empty() { + return Ok(false); + } + let mut slash = false; + let mut cr = false; + for &byte in &code[gap] { + budget.bytes(1)?; + if cr && byte == b'\n' { + cr = false; + continue; + } + cr = byte == b'\r'; + match byte { + b'\\' => slash = !slash, + b'\n' | b'\r' if slash => slash = false, + b' ' | b'\t' | b'\x0b' | b'\x0c' if !slash => {} + _ => return Ok(false), + } + } + Ok(!slash) +} + +impl Builder<'_> { + pub(super) fn irules_command( + &self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let children = self.index.canonical.children_of(id); + let mut listed = Command { + start: self.index.canonical.node(id).start_byte(), + ..Command::default() + }; + if children.len() < 3 { + return Ok(None); + } + if !self.irules_collect_words(children, &mut listed, budget)? { + return Ok(None); + } + if self.index.canonical.node(id).kind_id() == Irules::WhenEvent as u16 { + // A modifier is two words; without one the handler has three. + if listed.count < 3 { + return Ok(None); + } + } else if listed.count != 4 { + return Ok(None); + } + Ok(Some(listed)) + } + + fn irules_collect_words( + &self, + children: &[NodeId], + listed: &mut Command, + budget: &CollectionBudget, + ) -> Result { + let mut name_end = None; + for (position, &child) in children.iter().enumerate() { + budget.step()?; + let node = self.index.canonical.node(child); + if !self.irules_word_boundary(children, position, name_end, budget)? { + return Ok(false); + } + if Self::irules_name_word(node, position, &mut name_end, listed) { + continue; + } + if node.kind_id() == Irules::EventModifier as u16 { + if !self.irules_modifier(child, listed, budget)? { + return Ok(false); + } + } else if position < 2 + || matches!(node.kind_id(), kind if kind == Irules::Arguments as u16 || kind == Irules::BracedWord as u16) + { + push_word(listed, node.start_byte(), node.end_byte()); + } + } + Ok(true) + } + + fn irules_word_boundary( + &self, + children: &[NodeId], + position: usize, + name_end: Option, + budget: &CollectionBudget, + ) -> Result { + if position == 0 { + return Ok(true); + } + let previous = self.index.canonical.node(children[position - 1]); + let current = self.index.canonical.node(children[position]); + let joined_name = name_end == Some(previous.end_byte()) + && matches!(current.kind_id(), kind if kind == Irules::SimpleWord as u16 || kind == Irules::EscapedCharacter as u16); + Ok(joined_name || self.irules_gap(previous.end_byte()..current.start_byte(), budget)?) + } + + fn irules_name_word( + node: tree_sitter::Node<'_>, + position: usize, + name_end: &mut Option, + listed: &mut Command, + ) -> bool { + if position == 0 + || !matches!(node.kind_id(), kind if kind == Irules::SimpleWord as u16 || kind == Irules::EscapedCharacter as u16) + { + return false; + } + if name_end.is_none() { + push_word(listed, node.start_byte(), node.end_byte()); + } + *name_end = Some(node.end_byte()); + listed.words[1].1 = node.end_byte(); + true + } + + fn irules_gap( + &self, + gap: std::ops::Range, + budget: &CollectionBudget, + ) -> Result { + Ok(self.index.source.covers_with_budget(gap.clone(), budget)? + && word_gap(self.index.source.bytes(), gap, budget)?) + } + + fn irules_modifier( + &self, + modifier: NodeId, + listed: &mut Command, + budget: &CollectionBudget, + ) -> Result { + let subs = self.index.canonical.children_of(modifier); + for (offset, &sub) in subs.iter().enumerate() { + budget.step()?; + let part = self.index.canonical.node(sub); + if offset > 0 { + let prior = self.index.canonical.node(subs[offset - 1]); + if !self.irules_gap(prior.end_byte()..part.start_byte(), budget)? { + return Ok(false); + } + } + push_word(listed, part.start_byte(), part.end_byte()); + } + Ok(true) + } +} + +fn push_word(command: &mut Command, start: usize, end: usize) { + if usize::from(command.count) < 4 { + command.words[usize::from(command.count)] = (start, end); + } + command.count = command.count.saturating_add(1).min(5); +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules/leading.rs b/big-code-analysis-ast/src/documentation/collector/irules/leading.rs new file mode 100644 index 000000000..690276d89 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules/leading.rs @@ -0,0 +1,189 @@ +use super::*; + +impl Builder<'_> { + #[allow(clippy::too_many_lines)] // Reads and stores one adjacent source run. + pub(super) fn irules_leading( + &mut self, + target: NodeId, + scope: NodeId, + certainty: Option, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let members = self.irules_leading_members(target, scope, budget)?; + let Some(members) = members else { + return Ok(()); + }; + self.irules_publish_leading(target, scope, certainty, members, budget) + } + + fn irules_leading_members( + &self, + target: NodeId, + scope: NodeId, + budget: &CollectionBudget, + ) -> Result>, CollectionError> { + let last = self.irules_last_row(target, scope, budget)?; + let Some((before, comment, end)) = last else { + return Ok(None); + }; + let mut members = vec![(comment, end)]; + self.irules_preceding_rows(scope, before - 1, &mut members, budget)?; + self.irules_trim_top(scope, &mut members, budget)?; + Ok((!members.is_empty()).then_some(members)) + } + + fn irules_trim_top( + &self, + scope: NodeId, + members: &mut Vec<(NodeId, usize)>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let code = self.index.source.bytes(); + while let Some(&(top, _)) = members.last() { + budget.step()?; + if independent_row(&self.index, scope, top, budget)? { + break; + } + let mut popped = members.pop(); + while let Some((id, end)) = popped { + budget.step()?; + let start = self.index.canonical.node(id).start_byte(); + if !line_continues(&code[start..end], budget)? { + break; + } + popped = members.pop(); + } + } + Ok(()) + } + + fn irules_last_row( + &self, + target: NodeId, + scope: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let children = self.index.canonical.children_of(scope); + let mut before = self.index.canonical.nodes[target.0].ordinal; + if before > 0 && newline(&self.index, children[before - 1]) { + budget.step()?; + before -= 1; + } + let comment = before + .checked_sub(1) + .and_then(|at| children.get(at)) + .copied(); + let Some(comment) = comment else { + return Ok(None); + }; + let end = row(&self.index, comment, budget)?; + match end { + Some(end) => { + let adjacent = self.irules_adjacent(comment, end, target, budget)?; + Ok(adjacent.then_some((before, comment, end))) + } + None => Ok(None), + } + } + + fn irules_preceding_rows( + &self, + scope: NodeId, + mut at: usize, + members: &mut Vec<(NodeId, usize)>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let children = self.index.canonical.children_of(scope); + while at > 0 { + budget.step()?; + let previous = at - 1; + if newline(&self.index, children[previous]) { + at -= 1; + continue; + } + let Some(previous_end) = row(&self.index, children[previous], budget)? else { + break; + }; + let lower = members.last().map_or(children[previous], |&(id, _)| id); + if !self.irules_adjacent(children[previous], previous_end, lower, budget)? { + break; + } + members.push((children[previous], previous_end)); + at = previous; + } + Ok(()) + } + + fn irules_adjacent( + &self, + upper: NodeId, + end: usize, + lower: NodeId, + budget: &CollectionBudget, + ) -> Result { + let upper = self.index.canonical.node(upper); + let lower = self.index.canonical.node(lower); + let span = end..lower.start_byte(); + if !self.index.source.covers_with_budget(span.clone(), budget)? { + return Ok(false); + } + let gap = &self.index.source.bytes()[span]; + Ok(upper.end_position().row + 1 == lower.start_position().row + && unescaped_line_ends(gap, false, 2, budget)? == 1 + && crate::documentation::byte_scan::position( + gap, + |byte| !(matches!(byte, b'\n' | b'\r') || tcl_blank(byte)), + budget, + )? + .is_none()) + } + + fn irules_publish_leading( + &mut self, + target: NodeId, + scope: NodeId, + certainty: Option, + members: Vec<(NodeId, usize)>, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let uncertain = self + .irules_continued_run(&members, budget)? + .then_some(UnresolvedReason::GrammarBoundary) + .or(certainty); + let mut fragments = Vec::new(); + for (member, end) in members.into_iter().rev() { + budget.step()?; + let start = self.index.canonical.node(member).start_byte(); + let source = self.index.source.pieces_with_budget(start..end, budget)?; + fragments.push(self.fragment( + source, + self.index.canonical.nodes[member.0].evidence, + FragmentForm::Comment, + )); + self.irules_selected.insert(member); + } + self.drafts.push(Draft { + fragments, + target: Some(target), + scope, + binding: Some(self.index.canonical.nodes[target.0].evidence), + role: DocumentRole::LeadingComment, + unresolved: uncertain, + pending: false, + gap: false, + }); + Ok(()) + } + + fn irules_continued_run( + &self, + members: &[(NodeId, usize)], + budget: &CollectionBudget, + ) -> Result { + let Some(&(member, end)) = members.first() else { + return Ok(false); + }; + let start = self.index.canonical.node(member).start_byte(); + line_continues(&self.index.source.bytes()[start..end], budget).map_err(Into::into) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules/registration.rs b/big-code-analysis-ast/src/documentation/collector/irules/registration.rs new file mode 100644 index 000000000..3dda72afb --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules/registration.rs @@ -0,0 +1,182 @@ +use super::*; + +impl Builder<'_> { + pub(in crate::documentation::collector) fn irules_register( + &mut self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + let target_node = Node::from_tree_sitter(self.index.canonical.node(id)); + if !crate::IrulesCode::is_source_doc_target( + &target_node, + self.index.source.bytes(), + Ancestors::unknown(), + ) { + return Ok(()); + } + let scope = self.index.canonical.nodes[id.0].parent.unwrap_or(NodeId(0)); + let after = self.index.canonical.nodes[id.0].ordinal + 1; + let next = self.index.canonical.children_of(scope).get(after).copied(); + let certainty = self.irules_owner_reason(id, scope, next, budget)?; + if certainty.is_none() { + self.add_owner(id, Owner::Node(self.index.canonical.nodes[id.0].evidence)); + } else { + self.index.canonical.nodes[id.0].projection = Projection::Pending; + } + self.irules_leading(id, scope, certainty, budget) + } + + fn irules_owner_reason( + &mut self, + id: NodeId, + scope: NodeId, + next: Option, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let node = self.index.canonical.node(id); + let covered = self + .index + .source + .covers_with_budget(node.byte_range(), budget)?; + if !covered { + return Ok(Some(UnresolvedReason::ExcludedGap)); + } + if scope != NodeId(0) { + return Ok(Some(UnresolvedReason::GrammarBoundary)); + } + if node.kind_id() == Irules::Procedure as u16 + && !self.irules_static_name(self.index.canonical.children_of(id), budget)? + { + return Ok(Some(UnresolvedReason::Dynamic)); + } + let listed = self + .irules_scan + .command_at(&self.index.source, node.start_byte(), budget)?; + let expected = self.irules_command(id, budget)?; + let certainty = match (listed, expected) { + (Listed::Unknown, _) => Some(UnresolvedReason::ExcludedGap), + (Listed::Command(actual), Some(expected)) if actual == expected => None, + _ => Some(UnresolvedReason::GrammarBoundary), + }; + if certainty.is_some() { + return Ok(certainty); + } + self.irules_declaration_reason(id, next, budget) + } + + fn irules_declaration_reason( + &self, + id: NodeId, + next: Option, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + let node = self.index.canonical.node(id); + if next.is_some_and(|next| { + let follower = self.index.canonical.node(next); + follower.is_missing() && follower.start_byte() < self.index.source.bytes().len() + }) || node.has_error() + || node.is_missing() + { + return Ok(Some(UnresolvedReason::GrammarBoundary)); + } + let body = self.irules_body(id, budget)?; + if !matches!(body, Some(body) if self.irules_braces_match(id, body, budget)?) { + return Ok(Some(UnresolvedReason::GrammarBoundary)); + } + Ok(None) + } + + pub(super) fn irules_body( + &self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result, CollectionError> { + for &child in self.index.canonical.children_of(id).iter().rev() { + budget.step()?; + if self.index.canonical.node(child).kind_id() == Irules::BracedWord as u16 { + return Ok(Some(child)); + } + } + Ok(None) + } + + pub(super) fn irules_braces_match( + &self, + id: NodeId, + body: NodeId, + budget: &CollectionBudget, + ) -> Result { + let node = self.index.canonical.node(id); + let body = self.index.canonical.node(body); + let correct_body = braced_word_end( + &self.index.source.bytes()[..node.end_byte()], + body.start_byte(), + budget, + )? == Some(body.end_byte()); + if !correct_body { + return Ok(false); + } + if node.kind_id() != Irules::Procedure as u16 { + return Ok(true); + } + match self.irules_arguments(id, budget)? { + Some(argument) + if self.index.source.bytes().get(argument.start_byte()) == Some(&b'{') => + { + Ok(braced_word_end( + &self.index.source.bytes()[..argument.end_byte()], + argument.start_byte(), + budget, + )? == Some(argument.end_byte())) + } + Some(argument) => Ok(!argument.has_error() + && argument.named_child_count() == 1 + && argument + .named_child(0) + .is_some_and(|child| child.kind_id() == Irules::SimpleWord as u16)), + None => Ok(false), + } + } + + fn irules_arguments<'a>( + &'a self, + id: NodeId, + budget: &CollectionBudget, + ) -> Result>, CollectionError> { + for &child in self.index.canonical.children_of(id) { + budget.step()?; + let argument = self.index.canonical.node(child); + if argument.kind_id() == Irules::Arguments as u16 { + return Ok(Some(argument)); + } + } + Ok(None) + } + + pub(super) fn irules_static_name( + &self, + children: &[NodeId], + budget: &CollectionBudget, + ) -> Result { + let mut name = None; + for &child in children.iter().skip(1) { + budget.step()?; + let node = self.index.canonical.node(child); + if node.kind_id() == Irules::Arguments as u16 { + break; + } + if node.has_error() + || !matches!(node.kind_id(), kind if kind == Irules::SimpleWord as u16 || kind == Irules::EscapedCharacter as u16) + { + return Ok(false); + } + if let Some(end) = name + && end != node.start_byte() + { + return Ok(false); + } + name = Some(node.end_byte()); + } + Ok(name.is_some()) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules/unbound.rs b/big-code-analysis-ast/src/documentation/collector/irules/unbound.rs new file mode 100644 index 000000000..3d25f8f03 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules/unbound.rs @@ -0,0 +1,91 @@ +use super::*; + +impl<'s> Builder<'s> { + pub(in crate::documentation::collector) fn irules_continued_middle( + &self, + draft: &Draft<'s>, + budget: &CollectionBudget, + ) -> Result { + for id in draft + .fragments + .iter() + .take(draft.fragments.len().saturating_sub(1)) + { + budget.step()?; + let fragment = &self.index.facts.fragments[id.0]; + let Some(piece) = fragment.source.pieces().first() else { + continue; + }; + if line_continues(piece.bytes(), budget)? { + return Ok(true); + } + } + Ok(false) + } + + pub(in crate::documentation::collector) fn irules_unbound( + &mut self, + budget: &CollectionBudget, + ) -> Result<(), CollectionError> { + if !self.index.options.retain_unbound { + return Ok(()); + } + for id in 0..self.index.canonical.nodes.len() { + budget.step()?; + let id = NodeId(id); + if self.irules_selected.contains(&id) + || self.index.canonical.node(id).kind_id() != COMMENT_KIND + { + continue; + } + if self.irules_body_initial.contains(&id) { + continue; + } + let node = self.index.canonical.node(id); + let end = spelling_end(&self.index, node, budget)?; + let source = self + .index + .source + .pieces_with_budget(node.start_byte()..end, budget)?; + let fragment = self.fragment( + source, + self.index.canonical.nodes[id.0].evidence, + FragmentForm::Comment, + ); + self.index.evidence.push(CandidateEvidence { + fragment, + disposition: CandidateDisposition::Unattached, + }); + } + self.irules_sort_unbound(budget) + } + + fn irules_sort_unbound(&mut self, budget: &CollectionBudget) -> Result<(), CollectionError> { + let keys = self + .index + .evidence + .iter() + .enumerate() + .map(|(at, candidate)| { + let start = self.index.facts.fragments[candidate.fragment.0] + .source + .pieces() + .first() + .map_or(0, |piece| piece.range().start); + (start, at) + }) + .collect(); + let order = crate::documentation::ordering::ordered(keys, budget)?; + let mut evidence: Vec<_> = std::mem::take(&mut self.index.evidence) + .into_iter() + .map(Some) + .collect(); + for (_, at) in order { + budget.step()?; + if let Some(candidate) = evidence[at].take() { + self.index.evidence.push(candidate); + } + } + Ok(()) + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_documentation_grammar.rs b/big-code-analysis-ast/src/documentation/collector/irules_documentation_grammar.rs new file mode 100644 index 000000000..3bc81f5bc --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_documentation_grammar.rs @@ -0,0 +1,63 @@ +use crate::{AnyParser, LANG}; + +#[cfg(feature = "irules")] +#[test] +fn irules_grammar_verbatim_shapes_precede_the_gate() { + for (source, kind, has_error) in [ + ( + b"# doc\nwhen HTTP_REQUEST {}".as_slice(), + "when_event", + true, + ), + ( + b"# doc\r\nwhen HTTP_REQUEST {}\r\n".as_slice(), + "when_event", + false, + ), + (b"# doc\nproc f {} {}".as_slice(), "procedure", true), + ] { + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let root = parser.ts_tree().root_node(); + assert_eq!(root.end_byte(), source.len()); + assert_eq!(root.has_error(), has_error, "{source:?}"); + assert!( + root.children(&mut root.walk()) + .any(|child| child.kind() == kind) + ); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_grammar_included_ranges_preserve_the_parse_boundary() { + let source = b"# doc\nset x 1;when HTTP_REQUEST {}\n# kept\nwhen HTTP_RESPONSE {}\n"; + let point = |at: usize| { + let before = &source[..at]; + let row = before + .iter() + .fold(0, |count, &byte| count + usize::from(byte == b'\n')); + let column = before + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(at, |lf| at - lf - 1); + tree_sitter::Point::new(row, column) + }; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Irules.tree_sitter_language().unwrap()) + .unwrap(); + let ranges = [(0, 6), (14, source.len())].map(|(start_byte, end_byte)| tree_sitter::Range { + start_byte, + end_byte, + start_point: point(start_byte), + end_point: point(end_byte), + }); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + assert_eq!(tree.included_ranges(), ranges); + assert!( + tree.root_node() + .children(&mut tree.walk()) + .any(|node| node.kind() == "comment") + ); +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_tests.rs b/big-code-analysis-ast/src/documentation/collector/irules_tests.rs new file mode 100644 index 000000000..89c9132b0 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_tests.rs @@ -0,0 +1,1080 @@ +//! The iRules leading run and the independent owner of each occurrence. + +#![allow(clippy::single_range_in_vec_init)] + +#[cfg(feature = "irules")] +use crate::documentation::budget::{BYTE_INTERVAL, STEP_INTERVAL, cancel_after, charges}; +#[cfg(feature = "irules")] +use crate::documentation::*; +#[cfg(feature = "irules")] +use crate::{AnyParser, LANG}; +#[cfg(feature = "irules")] +use std::ops::Range; + +#[cfg(feature = "irules")] +#[derive(Debug, PartialEq, Eq)] +struct DocumentView { + role: DocumentRole, + composition: Composition, + fragments: Vec>, + text: Option, + unavailable: Option, + mappings: Vec<(Range, Option>)>, +} + +#[cfg(feature = "irules")] +#[derive(Debug, PartialEq, Eq)] +struct AssociationView { + document: usize, + resolution: Resolution, + binding: Option<(&'static str, Range)>, + scope: (&'static str, Range), + owners: Vec<(&'static str, Range)>, +} + +#[cfg(feature = "irules")] +#[derive(Debug, PartialEq, Eq)] +struct AssessmentView { + axis: AssessmentAxis, + reason: &'static str, + node: Option<(&'static str, Range)>, + document: Option, +} + +#[cfg(feature = "irules")] +#[derive(Debug, PartialEq, Eq)] +struct View { + owners: Vec<(&'static str, Range)>, + documents: Vec, + associations: Vec, + assessments: Vec, + evidence: Vec<(CandidateDisposition, Range)>, +} + +#[cfg(feature = "irules")] +fn full_view(source: &[u8], retain: bool) -> View { + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let options = DocumentationOptions { + retain_unbound: retain, + ..DocumentationOptions::default() + }; + let context = DocumentationContext::default(); + let direct = parser.documentation(&context, &options).unwrap(); + let raw = collect( + LANG::Irules, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap(); + let value = published(&direct); + assert_eq!(published(&raw), value); + value +} + +#[cfg(feature = "irules")] +#[test] +fn irules_published_leading_document_has_exact_coordinates() { + let source = b"# a\n# b\nproc f {} {}\n"; + let actual = full_view(source, false); + assert_eq!( + actual, + View { + owners: vec![("source_file", 0..source.len()), ("procedure", 8..20)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::CommentRun, + fragments: vec![0..3, 4..7], + text: Some("a\nb".to_owned()), + unavailable: None, + mappings: vec![(0..1, Some(2..3)), (1..2, None), (2..3, Some(6..7))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 8..20)), + scope: ("source_file", 0..source.len()), + owners: vec![("procedure", 8..20)], + }], + assessments: vec![], + evidence: vec![], + } + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_continued_comment_keeps_binding_and_pending_owner() { + let source = b"# doc \\\nwhen HTTP_REQUEST {}\n"; + let actual = full_view(source, false); + assert_eq!( + actual, + View { + owners: vec![("source_file", 0..source.len())], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..7], + text: Some("doc \\".to_owned()), + unavailable: None, + mappings: vec![(0..5, Some(2..7))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 8..28)), + scope: ("source_file", 0..source.len()), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 8..28)), + document: None + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 8..28)), + document: Some(0) + }, + ], + evidence: vec![], + } + ); +} + +#[cfg(feature = "irules")] +fn span(pieces: &SourcePieces<'_>) -> Range { + assert!(!pieces.has_excluded_gap()); + let parts = pieces.pieces(); + parts.first().unwrap().range().start..parts.last().unwrap().range().end +} + +#[cfg(feature = "irules")] +fn spelled(node: tree_sitter::Node<'_>) -> (&'static str, Range) { + (node.kind(), node.byte_range()) +} + +#[cfg(feature = "irules")] +fn documents(index: &DocumentationIndex<'_>) -> Vec { + let facts = index.facts(); + index + .documents() + .map(|doc| { + let complete = index.complete_text(doc).unwrap(); + DocumentView { + role: doc.get().role(), + composition: doc.get().composition(), + fragments: (0..doc.get().fragment_count()) + .map(|at| { + let fragment = facts.document_fragment(doc, at).unwrap(); + assert_eq!(fragment.get().form(), FragmentForm::Comment); + assert_eq!(fragment.get().node().unwrap().node().kind(), "comment"); + span(fragment.get().source()) + }) + .collect(), + text: complete.as_ref().map(|content| content.text().to_owned()), + unavailable: match doc.get().content() { + Content::Unavailable(reason) => Some(*reason), + _ => None, + }, + mappings: complete.map_or_else(Vec::new, |content| { + content + .mappings() + .iter() + .map(|run| { + let origin = match &run.origin { + Origin::Copied(piece) => Some(piece.range()), + Origin::Decoded(pieces) | Origin::Expanded(pieces) => { + Some(span(pieces)) + } + Origin::Synthetic => None, + }; + (run.output.range(), origin) + }) + .collect() + }), + } + }) + .collect() +} + +#[cfg(feature = "irules")] +fn associations(index: &DocumentationIndex<'_>) -> Vec { + let facts = index.facts(); + let position = |document| index.documents().position(|known| known == document); + index + .associations() + .map(|association| { + let edge = association.get(); + assert_eq!(edge.convention.name(), "irules"); + assert_eq!(edge.publication, Publication::Unknown); + AssociationView { + document: position(facts.associated_document(association).unwrap()).unwrap(), + resolution: edge.resolution, + binding: edge.binding.map(|node| spelled(node.node())), + scope: spelled(edge.lexical_scope.node()), + owners: (0..edge.owner_count()) + .map( + |at| match facts.associated_owner(association, at).unwrap().get() { + Owner::Node(node) => spelled(node.node()), + other => panic!("unexpected association owner: {other:?}"), + }, + ) + .collect(), + } + }) + .collect() +} + +#[cfg(feature = "irules")] +fn published(index: &DocumentationIndex<'_>) -> View { + let facts = index.facts(); + let owners = facts + .owners() + .map(|owner| match owner.get() { + Owner::File(node) | Owner::Node(node) => spelled(node.node()), + other => panic!("unexpected iRules owner: {other:?}"), + }) + .collect(); + let documents = documents(index); + let associations = associations(index); + let position = |document| index.documents().position(|known| known == document); + let mut assessments: Vec<_> = index + .assessments() + .map(|assessment| AssessmentView { + axis: assessment.get().axis, + reason: assessment.get().reason, + node: assessment.get().node.map(|node| spelled(node.node())), + document: index + .assessed_document(assessment) + .unwrap() + .and_then(position), + }) + .collect(); + assessments.sort_by_key(|item| { + ( + format!("{:?}", item.axis), + item.reason, + item.node + .as_ref() + .map(|(kind, range)| (*kind, range.start, range.end)), + item.document, + ) + }); + let evidence = index + .evidence() + .map(|candidate| { + ( + candidate.get().disposition, + span(index.evidence_fragment(candidate).unwrap().get().source()), + ) + }) + .collect(); + assert_eq!(index.profile(), Profile::Irules); + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); + View { + owners, + documents, + associations, + assessments, + evidence, + } +} + +#[cfg(feature = "irules")] +fn view(source: &[u8], retain: bool) -> View { + full_view(source, retain) +} + +#[path = "irules_tests/body.rs"] +mod body; +#[path = "irules_tests/command.rs"] +mod command; +#[path = "irules_tests/comment.rs"] +mod comment; +#[path = "irules_tests/nested.rs"] +mod nested; +#[path = "irules_tests/procedure.rs"] +mod procedure; + +#[cfg(feature = "irules")] +fn assert_behavior_view(source: &[u8], retain: bool) -> View { + let actual = view(source, retain); + let expected = [ + comment::expected(source, retain), + procedure::expected(source, retain), + command::expected(source, retain), + body::expected(source, retain), + nested::expected(source, retain), + ] + .into_iter() + .flatten() + .next() + .unwrap_or_else(|| panic!("unlisted iRules behavior fixture: {source:?}, retain={retain}")); + assert_eq!(actual, expected); + actual +} + +#[cfg(feature = "irules")] +#[test] +fn irules_leading_handlers_have_separate_node_owners() { + assert_behavior_view( + b"# first\nwhen HTTP_REQUEST {}\n# second\nwhen HTTP_REQUEST priority 200 {}\n", + false, + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_leading_proc_and_multirow_text() { + assert_behavior_view(b"# a\n# b\nproc f {} {}\n", false); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_blank_separates_and_retains_candidate() { + assert_eq!( + assert_behavior_view(b"# audit\n\nwhen HTTP_REQUEST {}\n", false).evidence, + [], + ); + assert_behavior_view(b"# audit\n\nwhen HTTP_REQUEST {}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_body_comment_is_pending_not_unattached() { + assert_behavior_view(b"when HTTP_REQUEST {\n# inside\n}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_continuation_and_recovery_do_not_claim_owner() { + for source in [ + b"# doc \\\nwhen HTTP_REQUEST {}\n".as_slice(), + b"# doc\nwhen HTTP_REQUEST {\nset x ]\n}\n".as_slice(), + ] { + assert_behavior_view(source, false); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_nonroot_scope_is_pending_and_literals_do_not_attach() { + assert_behavior_view(b"if { 1 } {\n# doc\nwhen HTTP_REQUEST {}\n}\n", false); + + for source in [ + b"set s {\n# doc\nwhen HTTP_REQUEST {}\n}\n".as_slice(), + b"set s \"# doc\\nwhen HTTP_REQUEST {}\"\n".as_slice(), + ] { + assert_behavior_view(source, false); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_two_hash_markers_keep_the_second() { + assert_eq!( + assert_behavior_view(b"## audit\nwhen HTTP_REQUEST {}\n", false).documents[0] + .text + .as_deref(), + Some("# audit"), + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_missing_terminator_and_later_positive_are_separate() { + assert_behavior_view( + b"# doc\nwhen HTTP_REQUEST {} priority 5\n# next\nwhen HTTP_RESPONSE {}\n", + true, + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_same_row_comment_and_semicolon_do_not_attach() { + for source in [ + b"set x 1 ;# t\n# d\nwhen HTTP_REQUEST {}\n".as_slice(), + b"# doc\n;when HTTP_REQUEST {}\n".as_slice(), + ] { + assert_behavior_view(source, true); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_nested_handler_and_proc_are_pending() { + assert_behavior_view( + b"if { 1 } {\n# a\nwhen HTTP_REQUEST {}\n# b\nproc f {} {}\n}\n", + false, + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_nested_dynamic_procedure_stays_at_the_grammar_boundary() { + let view = assert_behavior_view(b"if {1} {\n# doc\nproc f$x {} {}\n}", false); + assert_eq!(view.associations.len(), 1); + assert_eq!( + view.associations[0].resolution, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_extra_blank_rows_break_adjacency() { + assert_behavior_view(b"# doc\n\n\nwhen HTTP_REQUEST {}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_crlf_and_final_line_boundary_keep_raw_coordinates() { + assert_behavior_view(b"# audit\r\nwhen HTTP_REQUEST {}\r\n", false); + + assert_behavior_view(b"# audit\nproc f {} {}", false); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_tcl_horizontal_blank_bytes_keep_leading_rows_and_command_gaps() { + for source in [ + b"\x0b# doc\nwhen A\x0c{}\n".as_slice(), + b"\x0c# doc\nwhen A\x0b{}\n".as_slice(), + b"# doc\n\x0bwhen A\x0c{}\n".as_slice(), + b"# doc\n\x0cwhen A\x0b{}\n".as_slice(), + ] { + assert_behavior_view(source, false); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_nonadjacent_command_keeps_owner_but_no_document() { + assert_behavior_view(b"# doc\nset x 1\nwhen HTTP_REQUEST {}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_recovered_proc_and_handler_do_not_resolve() { + assert_behavior_view( + b"# doc\nproc f {} {\nset x ]\n}\n# next\nwhen HTTP_REQUEST {}\n", + false, + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_profile_gate_and_empty_source() { + let parser = AnyParser::parse(LANG::Irules, b"".to_vec(), None, None).unwrap(); + let options = DocumentationOptions::default(); + let index = parser + .documentation(&DocumentationContext::default(), &options) + .unwrap(); + assert_eq!(index.profile(), Profile::Irules); + assert_eq!(index.documents().len(), 0); + assert_eq!(index.facts().owners().len(), 1); + let incompatible = DocumentationOptions { + profile: Profile::Ruff, + ..options + }; + assert!(matches!( + parser.documentation(&DocumentationContext::default(), &incompatible), + Err(CollectionError::UnsupportedProfile { + language: LANG::Irules, + profile: Profile::Ruff + }) + )); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_directive_retention_does_not_change_prose_or_evidence() { + let source = b"# audit\nwhen HTTP_REQUEST {}\n# stray\n"; + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default().with_unbound_evidence(true); + let normal = parser.documentation(&context, &options).unwrap(); + let directives = parser + .documentation(&context, &options.with_directive_evidence(true)) + .unwrap(); + assert_eq!(published(&directives), published(&normal)); + assert_eq!(normal.documents().len(), 1); + assert_eq!(normal.evidence().len(), 1); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_directives_retention_does_not_change_collected_view() { + let source = b"# audit\nwhen HTTP_REQUEST {}\n# stray\n"; + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default().with_unbound_evidence(true); + let without = parser.documentation(&context, &options).unwrap(); + let with = parser + .documentation(&context, &options.with_directive_evidence(true)) + .unwrap(); + assert_eq!(published(&with), published(&without)); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_undocumented_owner_has_a_ready_projection() { + let source = b"when HTTP_REQUEST {}\n"; + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let root = parser.ts_tree().root_node(); + let declaration = root + .children(&mut root.walk()) + .find(|child| child.kind() == "when_event") + .unwrap(); + let query = index.node_associations(declaration).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 0); + assert_eq!(index.facts().owners().len(), 2); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_nonadjacent_command_owner_query_is_not_pending() { + let source = b"# doc\nset x 1\nwhen HTTP_REQUEST {}\n"; + assert_behavior_view(source, true); + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default().with_unbound_evidence(true), + ) + .unwrap(); + let root = parser.ts_tree().root_node(); + let declaration = root + .children(&mut root.walk()) + .find(|child| child.kind() == "when_event") + .unwrap(); + let query = index.node_associations(declaration).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 0); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_unsupported_forms_do_not_invent_documents() { + for source in [ + b"set s {\n# doc\nwhen HTTP_REQUEST {}\n}\n".as_slice(), + b"set s \"# doc\nwhen HTTP_REQUEST {}\"\n".as_slice(), + ] { + assert_behavior_view(source, true); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_comment_run_keeps_both_fragments_and_source_order() { + let parser = AnyParser::parse( + LANG::Irules, + b"# a\n# b\nwhen HTTP_REQUEST {}\n".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let doc = index.documents().next().unwrap(); + assert_eq!(doc.get().composition(), Composition::CommentRun); + assert_eq!(doc.get().fragment_count(), 2); + for (at, expected) in [(0, 0..3), (1, 4..7)] { + let fragment = index.facts().document_fragment(doc, at).unwrap(); + assert_eq!(fragment.get().source().pieces()[0].range(), expected); + assert_eq!(fragment.get().form(), FragmentForm::Comment); + } + let complete = index.complete_text(doc).unwrap().unwrap(); + assert_eq!(complete.text(), "a\nb"); + assert_eq!(complete.mappings().len(), 3); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_body_only_comment_and_leading_plus_body_are_distinct() { + assert_behavior_view(b"when HTTP_REQUEST {\n# body\n}\n", true); + + assert_behavior_view(b"# lead\nwhen HTTP_REQUEST {\n# body\n}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_comment_following_code_is_unattached_with_retain_unbound() { + assert_behavior_view(b"set x 1 ;# trailing\n# doc\nwhen HTTP_REQUEST {}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_unselected_comment_above_nested_code_is_not_a_file_document() { + assert_behavior_view( + b"# file?\nnamespace eval ns {\n# proc\nproc f {} {}\n}\n", + true, + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_comment_after_terminator_is_not_a_leading_run() { + assert_behavior_view(b"# doc\n; when HTTP_REQUEST {}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_included_gap_before_owner_blocks_leading_attachment() { + let source = b"# audit\nset a;when HTTP_REQUEST {}\n# kept\nwhen HTTP_RESPONSE {}\n"; + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&LANG::Irules.tree_sitter_language().unwrap()) + .unwrap(); + let point = |at: usize| { + let prefix = &source[..at]; + tree_sitter::Point::new( + prefix + .iter() + .fold(0, |count, &byte| count + usize::from(byte == b'\n')), + prefix + .iter() + .rposition(|&byte| byte == b'\n') + .map_or(at, |lf| at - lf - 1), + ) + }; + let ranges = [(0, 8), (14, source.len())].map(|(start_byte, end_byte)| tree_sitter::Range { + start_byte, + end_byte, + start_point: point(start_byte), + end_point: point(end_byte), + }); + parser.set_included_ranges(&ranges).unwrap(); + let tree = parser.parse(source, None).unwrap(); + let index = collect( + LANG::Irules, + &tree, + source, + &DocumentationContext::default(), + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ) + .unwrap(); + assert_eq!(index.documents().len(), 1); + let doc = index.documents().next().unwrap(); + assert_eq!(index.complete_text(doc).unwrap().unwrap().text(), "kept"); + assert_eq!( + index.associations().next().unwrap().get().resolution, + Resolution::Resolved + ); + assert_eq!(index.evidence().len(), 1); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_body_comment_in_a_nested_braced_command_remains_evidence() { + assert_behavior_view( + b"when HTTP_REQUEST {\nif {1} {\n# note\nset x 1\n}\n}\n", + true, + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_late_body_after_modifiers_is_not_one_command() { + for source in [ + b"# doc\nwhen HTTP_REQUEST priority 100 timing on\n{\n}\n".as_slice(), + b"# doc\nwhen HTTP_REQUEST priority 100\n{\n}\n".as_slice(), + b"# doc\nwhen HTTP_REQUEST priority\n100 {}\n".as_slice(), + b"# doc\nwhen A priority 1 timing on{}\n".as_slice(), + ] { + assert_behavior_view(source, false); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_two_modifiers_without_space_before_body_are_unresolved() { + let view = assert_behavior_view(b"# doc\nwhen A priority 1 timing on{}\n", false); + assert_eq!(view.associations.len(), 1); + assert_eq!( + view.associations[0].resolution, + Resolution::Unresolved(UnresolvedReason::GrammarBoundary) + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_blank_above_comment_does_not_detach_it() { + for source in [ + b"when A {}\n\n# doc\nwhen B {}\n".as_slice(), + b"set x 1\n\n# doc\nwhen HTTP_REQUEST {}\n".as_slice(), + ] { + let view = assert_behavior_view(source, true); + assert_eq!(view.documents.len(), 1); + assert_eq!(view.associations.len(), 1); + assert_eq!(view.associations[0].resolution, Resolution::Resolved); + assert_eq!(view.documents[0].text.as_deref(), Some("doc")); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_crlf_preceding_continuations_remain_unattached() { + for source in [ + b"set x 1 \\\r\n# doc\r\nwhen HTTP_REQUEST {}\r\n".as_slice(), + b"set x 1 ;# t \\\r\n# d\r\nwhen HTTP_REQUEST {}\r\n".as_slice(), + ] { + let view = assert_behavior_view(source, true); + assert_eq!(view.documents, []); + assert!( + view.evidence + .iter() + .any(|(_, range)| source[range.clone()].starts_with(b"# d")) + ); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_continued_top_row_does_not_detach_middle_or_lower_rows() { + let source = b"# a \\\n# b\nwhen HTTP_REQUEST {}\n"; + let view = assert_behavior_view(source, true); + assert_eq!(view.documents.len(), 1); + assert_eq!(view.documents[0].composition, Composition::CommentRun); + assert_eq!(view.documents[0].fragments, [0..5, 6..9]); + assert_eq!(view.documents[0].text, None); + assert_eq!( + view.documents[0].unavailable, + Some(UnavailableReason::GrammarBoundary) + ); + assert_eq!(view.associations[0].resolution, Resolution::Resolved); + assert_eq!(view.evidence, []); + + let source = b"set x 1 \\\n# a\n# b\nwhen HTTP_REQUEST {}\n"; + let view = assert_behavior_view(source, true); + assert_eq!(view.documents.len(), 1); + assert_eq!(view.documents[0].fragments, [14..17]); + assert_eq!(view.documents[0].text.as_deref(), Some("b")); + assert_eq!(view.associations[0].resolution, Resolution::Resolved); + assert_eq!(view.evidence, [(CandidateDisposition::Unattached, 10..13)]); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_initial_body_continuation_keeps_both_rows_pending() { + let view = assert_behavior_view(b"when HTTP_REQUEST {\n# a \\\n# b\n}\n", true); + assert_eq!(view.assessments.len(), 1); + assert_eq!(view.evidence, []); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_static_escaped_names_and_bare_arguments_resolve() { + for source in [ + b"# doc\nproc f args {}\n".as_slice(), + b"# doc\nproc f x {}\n".as_slice(), + b"# doc\nproc f\\ g {} {}\n".as_slice(), + ] { + let view = assert_behavior_view(source, false); + assert_eq!(view.documents.len(), 1); + assert_eq!(view.associations[0].resolution, Resolution::Resolved); + assert_eq!(view.associations[0].owners.len(), 1); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_nested_and_root_evidence_is_source_ordered() { + let source = b"when HTTP_REQUEST {\nif {1} {\n# deep\n}\n}\n# top\nset x 1\n"; + let view = assert_behavior_view(source, true); + assert_eq!( + view.evidence, + [ + (CandidateDisposition::Unattached, 29..35), + (CandidateDisposition::Unattached, 40..45), + ] + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_continued_command_before_comment_is_not_documentation() { + assert_behavior_view(b"set x 1 \\\n# doc\nwhen HTTP_REQUEST {}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_body_blank_same_row_and_multirow_assessment() { + for (source, pending, evidence) in [ + (b"when HTTP_REQUEST {\n\n# late\n}\n".as_slice(), 0, 1), + (b"when HTTP_REQUEST { # a\n}\n".as_slice(), 1, 0), + (b"when HTTP_REQUEST {\n# a\n# b\n}\n".as_slice(), 1, 0), + ] { + let view = assert_behavior_view(source, true); + assert_eq!(view.assessments.len(), pending); + assert_eq!(view.evidence.len(), evidence); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_body_comment_on_the_brace_row_opens_the_body_block() { + // Tcl's lead block (`proc f {} {# a\n# b\n}` gives `a\nb`) starts on the first row of + // the body text, which the opening brace's row holds; iRules body docs share that + // boundary, so both rows are the pending initial block and neither is unattached. + assert_behavior_view(b"when HTTP_REQUEST {# a\n# b\n}\n", true); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_dynamic_names_are_unresolved() { + for source in [ + b"# doc\nproc \"f\" {} {}\n".as_slice(), + b"# doc\nproc {f} {} {}\n".as_slice(), + b"# doc\nproc $name {} {}\n".as_slice(), + b"# doc\nproc f$x {} {}\n".as_slice(), + ] { + let view = assert_behavior_view(source, false); + assert_eq!( + view.associations[0].resolution, + Resolution::Unresolved(UnresolvedReason::Dynamic) + ); + } + assert_eq!( + assert_behavior_view(b"# doc\nproc f {} {}\n", false).associations[0].resolution, + Resolution::Resolved + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_mixed_substituted_procedure_names_are_dynamic() { + let view = assert_behavior_view(b"# doc\nproc f$x {} {}\n", false); + assert_eq!(view.associations.len(), 1); + assert_eq!( + view.associations[0].resolution, + Resolution::Unresolved(UnresolvedReason::Dynamic) + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_two_unattached_candidates_preserve_source_order() { + assert_behavior_view(b"# a\n\nset x 1\n# b\n\nwhen HTTP_REQUEST {}\n", true); + + let parser = AnyParser::parse( + LANG::Irules, + b"# a\n\nset x 1\n# b\n\nwhen HTTP_REQUEST {}\n".to_vec(), + None, + None, + ) + .unwrap(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions { + retain_unbound: true, + ..DocumentationOptions::default() + }, + ) + .unwrap(); + assert_eq!( + published(&index).evidence, + [ + (CandidateDisposition::Unattached, 0..3), + (CandidateDisposition::Unattached, 13..16), + ] + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_other_command_spellings_are_characterized() { + for spelling in [ + "::proc", "\"proc\"", "{proc}", "::when", "\"when\"", "{when}", + ] { + let source = format!("# doc\n{spelling} f {{}} {{}}\n"); + let view = assert_behavior_view(source.as_bytes(), true); + assert_eq!(view.documents, [], "{spelling}"); + } + assert_eq!( + assert_behavior_view(b"# doc\nproc f \"a b\" {}\n", true).documents, + [] + ); +} + +#[cfg(feature = "irules")] +#[test] +fn irules_collection_charges_steps_and_bytes_on_wide_inputs() { + for count in [64, 256] { + let source = format!( + "# doc\nwhen HTTP_REQUEST {{\n{} }}\n", + "set x 1\n".repeat(count) + ); + let parser = AnyParser::parse(LANG::Irules, source.into_bytes(), None, None).unwrap(); + let before = charges(); + let index = parser + .documentation( + &DocumentationContext::default(), + &DocumentationOptions::default(), + ) + .unwrap(); + let after = charges(); + assert_eq!(index.documents().len(), 1); + let steps = after.0 - before.0; + let bytes = after.1 - before.1; + // expected: the fixed root/handler setup charges 167 steps and 48 bytes; + // each repeated command adds 62 structural steps and 16 scanned bytes. + assert_eq!(steps, 62 * count + 167); + assert_eq!(bytes, 16 * count + 48); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_collection_charges_every_boundary_shape() { + for (name, source, retain, expected) in [ + ( + "single", + b"# doc\nwhen HTTP_REQUEST {}\n".as_slice(), + false, + (162, 44), + ), + ("run", b"# a\n# b\nwhen HTTP_REQUEST {}\n", false, (205, 50)), + ( + "indented", + b" # doc\nwhen HTTP_REQUEST {}\n", + false, + (162, 50), + ), + ( + "continued-run", + b"# a \\\n# b\nwhen HTTP_REQUEST {}\n", + false, + (193, 43), + ), + ( + "trim", + b"set x 1 \\\n# a\n# b\nwhen HTTP_REQUEST {}\n", + false, + (260, 61), + ), + ( + "crlf", + b"set x 1 \\\r\n# a\r\nwhen HTTP_REQUEST {}\r\n".as_slice(), + false, + (234, 50), + ), + ( + "modifier", + b"# doc\nwhen HTTP_REQUEST priority 100 timing on {}\n", + false, + (244, 71), + ), + ( + "late-modifier", + b"# doc\nwhen HTTP_REQUEST priority\n100 {}\n", + false, + (198, 49), + ), + ("bare-args", b"# doc\nproc f args {}\n", false, (193, 39)), + ( + "escaped-name", + b"# doc\nproc f\\ g {} {}\n", + false, + (235, 42), + ), + ("braced-args", b"# doc\nproc f {} {}\n", false, (205, 39)), + ( + "body", + b"when HTTP_REQUEST {\n# a \\\n# b\n}\n", + false, + (166, 54), + ), + ( + "unbound", + b"when HTTP_REQUEST {\nif {1} {\n# deep\n}\n}\n# top\nset x 1\n", + true, + (372, 63), + ), + ( + "unbound-run", + b"# a\n\nset x 1\n# b\n\nwhen HTTP_REQUEST {}\n", + true, + (246, 44), + ), + ( + "nested", + b"if {1} {\n# doc\nproc f {} {}\n}\n", + true, + (335, 16), + ), + ] { + let parser = AnyParser::parse(LANG::Irules, source.to_vec(), None, None).unwrap(); + let options = DocumentationOptions { + retain_unbound: retain, + ..DocumentationOptions::default() + }; + let before = charges(); + parser + .documentation(&DocumentationContext::default(), &options) + .unwrap(); + let after = charges(); + // expected: each input has a fixed parse tree and exact source spelling. + // The pair is total charged structural steps and visited bytes for that shape. + assert_eq!((after.0 - before.0, after.1 - before.1), expected, "{name}"); + } +} + +#[cfg(feature = "irules")] +#[test] +fn irules_collection_cancels_at_every_checkpoint() { + let source = format!( + "# doc\nwhen HTTP_REQUEST {{\n{} }}\n", + "set x 1\n".repeat(2_500) + ); + let parser = AnyParser::parse(LANG::Irules, source.into_bytes(), None, None).unwrap(); + let context = DocumentationContext::default(); + let options = DocumentationOptions::default(); + let before = charges(); + let start = observations().polls; + assert!(parser.documentation(&context, &options).is_ok()); + let (steps, bytes) = charges(); + let steps = steps - before.0; + let bytes = bytes - before.1; + assert!( + steps >= STEP_INTERVAL, + "step checkpoint not exercised: {steps}" + ); + assert!( + bytes >= BYTE_INTERVAL, + "byte checkpoint not exercised: {bytes}" + ); + let checkpoints = observations().polls - start; + assert!(checkpoints > 2); + for at in 1..=checkpoints { + assert!( + matches!( + cancel_after(at, || parser.documentation(&context, &options)), + Err(CollectionError::Cancelled) + ), + "{at}" + ); + } + assert!(cancel_after(checkpoints + 1, || parser.documentation(&context, &options)).is_ok()); +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_tests/body.rs b/big-code-analysis-ast/src/documentation/collector/irules_tests/body.rs new file mode 100644 index 000000000..b980beddb --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_tests/body.rs @@ -0,0 +1,141 @@ +use super::*; + +#[allow(clippy::too_many_lines)] // Complete expected facts for one group of source inputs. +pub(super) fn expected(source: &[u8], retain: bool) -> Option { + match (source, retain) { + (b"# lead\nwhen HTTP_REQUEST {\n# body\n}\n", true) => Some(View { + owners: vec![("source_file", 0..36), ("when_event", 7..35)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..6], + text: Some("lead".to_owned()), + unavailable: None, + mappings: vec![(0..4, Some(2..6))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 7..35)), + scope: ("source_file", 0..36), + owners: vec![("when_event", 7..35)], + }], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 27..33)), + document: None, + }], + evidence: vec![], + }), + + (b"when HTTP_REQUEST {\n\n# late\n}\n", true) => Some(View { + owners: vec![("source_file", 0..30), ("when_event", 0..29)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 21..27)], + }), + + (b"when HTTP_REQUEST {\n# a\n# b\n}\n", true) => Some(View { + owners: vec![("source_file", 0..30), ("when_event", 0..29)], + documents: vec![], + associations: vec![], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 20..23)), + document: None, + }], + evidence: vec![], + }), + + (b"when HTTP_REQUEST {\n# a \\\n# b\n}\n", true) => Some(View { + owners: vec![("source_file", 0..32), ("when_event", 0..31)], + documents: vec![], + associations: vec![], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 20..25)), + document: None, + }], + evidence: vec![], + }), + + (b"when HTTP_REQUEST {\n# body\n}\n", true) => Some(View { + owners: vec![("source_file", 0..29), ("when_event", 0..28)], + documents: vec![], + associations: vec![], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 20..26)), + document: None, + }], + evidence: vec![], + }), + + (b"when HTTP_REQUEST {\n# inside\n}\n", true) => Some(View { + owners: vec![("source_file", 0..31), ("when_event", 0..30)], + documents: vec![], + associations: vec![], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 20..28)), + document: None, + }], + evidence: vec![], + }), + + (b"when HTTP_REQUEST {\nif {1} {\n# deep\n}\n}\n# top\nset x 1\n", true) => Some(View { + owners: vec![("source_file", 0..54), ("when_event", 0..39)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![ + (CandidateDisposition::Unattached, 29..35), + (CandidateDisposition::Unattached, 40..45), + ], + }), + + (b"when HTTP_REQUEST {\nif {1} {\n# note\nset x 1\n}\n}\n", true) => Some(View { + owners: vec![("source_file", 0..48), ("when_event", 0..47)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 29..35)], + }), + + // expected: the body text starts after `{` at 18, so its first row is `# a` (20..23). + (b"when HTTP_REQUEST { # a\n}\n", true) => Some(View { + owners: vec![("source_file", 0..26), ("when_event", 0..25)], + documents: vec![], + associations: vec![], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 20..23)), + document: None, + }], + evidence: vec![], + }), + + // expected: `{` at 18, then `# a` (19..22) and `# b` (23..26) on the next row. + (b"when HTTP_REQUEST {# a\n# b\n}\n", true) => Some(View { + owners: vec![("source_file", 0..29), ("when_event", 0..28)], + documents: vec![], + associations: vec![], + assessments: vec![AssessmentView { + axis: AssessmentAxis::Occurrence, + reason: "Initial iRules body block awaits source documentation support", + node: Some(("comment", 19..22)), + document: None, + }], + evidence: vec![], + }), + + _ => None, + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_tests/command.rs b/big-code-analysis-ast/src/documentation/collector/irules_tests/command.rs new file mode 100644 index 000000000..fcc4892f8 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_tests/command.rs @@ -0,0 +1,274 @@ +use super::*; + +#[allow(clippy::too_many_lines)] // Complete expected facts for one group of source inputs. +pub(super) fn expected(source: &[u8], retain: bool) -> Option { + match (source, retain) { + ( + b"# doc\n\"proc\" f {} {}\n" + | b"# doc\n\"when\" f {} {}\n" + | b"# doc\n::proc f {} {}\n" + | b"# doc\n::when f {} {}\n", + true, + ) => Some(View { + owners: vec![("source_file", 0..21)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + (b"# doc\n; when HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..29), ("when_event", 8..28)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + (b"# doc\n;when HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..28), ("when_event", 7..27)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + (b"# doc\nset x 1\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..35), ("when_event", 14..34)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + (b"# doc\nwhen HTTP_REQUEST priority\n100 {}\n", false) => Some(View { + owners: vec![("source_file", 0..40)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 6..39)), + scope: ("source_file", 0..40), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 6..39)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 6..39)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# doc\nwhen HTTP_REQUEST priority 100\n{\n}\n", false) => Some(View { + owners: vec![("source_file", 0..41)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 6..40)), + scope: ("source_file", 0..41), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 6..40)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 6..40)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# doc\nwhen HTTP_REQUEST priority 100 timing on\n{\n}\n", false) => Some(View { + owners: vec![("source_file", 0..51)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 6..50)), + scope: ("source_file", 0..51), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 6..50)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 6..50)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + ( + b"# doc\nwhen A priority 1 timing on{}\n" | b"# doc\nwhen HTTP_REQUEST {\nset x ]\n}\n", + false, + ) => Some(View { + owners: vec![("source_file", 0..36)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 6..35)), + scope: ("source_file", 0..36), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 6..35)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 6..35)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# doc\nwhen HTTP_REQUEST {} priority 5\n# next\nwhen HTTP_RESPONSE {}\n", true) => { + Some(View { + owners: vec![("source_file", 0..67), ("when_event", 45..66)], + documents: vec![ + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }, + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![38..44], + text: Some("next".to_owned()), + unavailable: None, + mappings: vec![(0..4, Some(40..44))], + }, + ], + associations: vec![ + AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 6..26)), + scope: ("source_file", 0..67), + owners: vec![], + }, + AssociationView { + document: 1, + resolution: Resolution::Resolved, + binding: Some(("when_event", 45..66)), + scope: ("source_file", 0..67), + owners: vec![("when_event", 45..66)], + }, + ], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 6..26)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 6..26)), + document: Some(0), + }, + ], + evidence: vec![], + }) + } + + (b"# doc \\\nwhen HTTP_REQUEST {}\n", false) => Some(View { + owners: vec![("source_file", 0..29)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..7], + text: Some("doc \\".to_owned()), + unavailable: None, + mappings: vec![(0..5, Some(2..7))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 8..28)), + scope: ("source_file", 0..29), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 8..28)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 8..28)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + _ => None, + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_tests/comment.rs b/big-code-analysis-ast/src/documentation/collector/irules_tests/comment.rs new file mode 100644 index 000000000..8eafd382e --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_tests/comment.rs @@ -0,0 +1,331 @@ +use super::*; + +#[allow(clippy::too_many_lines)] // Complete expected facts for one group of source inputs. +pub(super) fn expected(source: &[u8], retain: bool) -> Option { + match (source, retain) { + (b"\x0b# doc\nwhen A\x0c{}\n" | b"\x0c# doc\nwhen A\x0b{}\n", false) => Some(View { + owners: vec![ + ("source_file", 1..source.len()), + ("when_event", 7..source.len() - 1), + ], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![1..6], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(3..6))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 7..source.len() - 1)), + scope: ("source_file", 1..source.len()), + owners: vec![("when_event", 7..source.len() - 1)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# doc\n\x0bwhen A\x0c{}\n" | b"# doc\n\x0cwhen A\x0b{}\n", false) => Some(View { + owners: vec![ + ("source_file", 0..source.len()), + ("when_event", 7..source.len() - 1), + ], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 7..source.len() - 1)), + scope: ("source_file", 0..source.len()), + owners: vec![("when_event", 7..source.len() - 1)], + }], + assessments: vec![], + evidence: vec![], + }), + (b"# a\n\nset x 1\n# b\n\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..39), ("when_event", 18..38)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![ + (CandidateDisposition::Unattached, 0..3), + (CandidateDisposition::Unattached, 13..16), + ], + }), + + (b"# a\n# b\nproc f {} {}\n", false) => Some(View { + owners: vec![("source_file", 0..21), ("procedure", 8..20)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::CommentRun, + fragments: vec![0..3, 4..7], + text: Some("a\nb".to_owned()), + unavailable: None, + mappings: vec![(0..1, Some(2..3)), (1..2, None), (2..3, Some(6..7))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 8..20)), + scope: ("source_file", 0..21), + owners: vec![("procedure", 8..20)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# a \\\n# b\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..31), ("when_event", 10..30)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::CommentRun, + fragments: vec![0..5, 6..9], + text: None, + unavailable: Some(UnavailableReason::GrammarBoundary), + mappings: vec![], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 10..30)), + scope: ("source_file", 0..31), + owners: vec![("when_event", 10..30)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# audit\n\nwhen HTTP_REQUEST {}\n", false) => Some(View { + owners: vec![("source_file", 0..30), ("when_event", 9..29)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![], + }), + + (b"# audit\n\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..30), ("when_event", 9..29)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..7)], + }), + + (b"# audit\nproc f {} {}", false) => Some(View { + owners: vec![("source_file", 0..20), ("procedure", 8..20)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..7], + text: Some("audit".to_owned()), + unavailable: None, + mappings: vec![(0..5, Some(2..7))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 8..20)), + scope: ("source_file", 0..20), + owners: vec![("procedure", 8..20)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# audit\r\nwhen HTTP_REQUEST {}\r\n", false) => Some(View { + owners: vec![("source_file", 0..31), ("when_event", 9..29)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..7], + text: Some("audit".to_owned()), + unavailable: None, + mappings: vec![(0..5, Some(2..7))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 9..29)), + scope: ("source_file", 0..31), + owners: vec![("when_event", 9..29)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# doc\n\n\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..29), ("when_event", 8..28)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + (b"## audit\nwhen HTTP_REQUEST {}\n", false) => Some(View { + owners: vec![("source_file", 0..30), ("when_event", 9..29)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..8], + text: Some("# audit".to_owned()), + unavailable: None, + mappings: vec![(0..7, Some(1..8))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 9..29)), + scope: ("source_file", 0..30), + owners: vec![("when_event", 9..29)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"set x 1\n\n# doc\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..36), ("when_event", 15..35)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![9..14], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(11..14))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 15..35)), + scope: ("source_file", 0..36), + owners: vec![("when_event", 15..35)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"set x 1 ;# t\n# d\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..38), ("when_event", 17..37)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![13..16], + text: Some("d".to_owned()), + unavailable: None, + mappings: vec![(0..1, Some(15..16))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 17..37)), + scope: ("source_file", 0..38), + owners: vec![("when_event", 17..37)], + }], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 9..12)], + }), + + (b"set x 1 ;# t \\\r\n# d\r\nwhen HTTP_REQUEST {}\r\n", true) => Some(View { + owners: vec![("source_file", 0..43), ("when_event", 21..41)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![ + (CandidateDisposition::Unattached, 9..14), + (CandidateDisposition::Unattached, 16..19), + ], + }), + + (b"set x 1 ;# trailing\n# doc\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..47), ("when_event", 26..46)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![20..25], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(22..25))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 26..46)), + scope: ("source_file", 0..47), + owners: vec![("when_event", 26..46)], + }], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 9..19)], + }), + + (b"set x 1 \\\n# a\n# b\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..39), ("when_event", 18..38)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![14..17], + text: Some("b".to_owned()), + unavailable: None, + mappings: vec![(0..1, Some(16..17))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 18..38)), + scope: ("source_file", 0..39), + owners: vec![("when_event", 18..38)], + }], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 10..13)], + }), + + (b"set x 1 \\\n# doc\nwhen HTTP_REQUEST {}\n", true) => Some(View { + owners: vec![("source_file", 0..37), ("when_event", 16..36)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 10..15)], + }), + + (b"set x 1 \\\r\n# doc\r\nwhen HTTP_REQUEST {}\r\n", true) => Some(View { + owners: vec![("source_file", 0..40), ("when_event", 18..38)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 11..16)], + }), + + (b"when A {}\n\n# doc\nwhen B {}\n", true) => Some(View { + owners: vec![ + ("source_file", 0..27), + ("when_event", 0..9), + ("when_event", 17..26), + ], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![11..16], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(13..16))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 17..26)), + scope: ("source_file", 0..27), + owners: vec![("when_event", 17..26)], + }], + assessments: vec![], + evidence: vec![], + }), + + _ => None, + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_tests/nested.rs b/big-code-analysis-ast/src/documentation/collector/irules_tests/nested.rs new file mode 100644 index 000000000..6c0195e23 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_tests/nested.rs @@ -0,0 +1,245 @@ +use super::*; + +#[allow(clippy::too_many_lines)] // Complete expected facts for one group of source inputs. +pub(super) fn expected(source: &[u8], retain: bool) -> Option { + match (source, retain) { + (b"if {1} {\n# doc\nproc f$x {} {}\n}", false) => Some(View { + owners: vec![("source_file", 0..31)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![9..14], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(11..14))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("procedure", 15..29)), + scope: ("braced_word", 7..31), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("procedure", 15..29)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("procedure", 15..29)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# file?\nnamespace eval ns {\n# proc\nproc f {} {}\n}\n", true) => Some(View { + owners: vec![("source_file", 0..50)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![28..34], + text: Some("proc".to_owned()), + unavailable: None, + mappings: vec![(0..4, Some(30..34))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("procedure", 35..47)), + scope: ("braced_word", 26..49), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("procedure", 35..47)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("procedure", 35..47)), + document: Some(0), + }, + ], + evidence: vec![(CandidateDisposition::Unattached, 0..7)], + }), + ( + b"# first\nwhen HTTP_REQUEST {}\n# second\nwhen HTTP_REQUEST priority 200 {}\n", + false, + ) => Some(View { + owners: vec![ + ("source_file", 0..72), + ("when_event", 8..28), + ("when_event", 38..71), + ], + documents: vec![ + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..7], + text: Some("first".to_owned()), + unavailable: None, + mappings: vec![(0..5, Some(2..7))], + }, + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![29..37], + text: Some("second".to_owned()), + unavailable: None, + mappings: vec![(0..6, Some(31..37))], + }, + ], + associations: vec![ + AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("when_event", 8..28)), + scope: ("source_file", 0..72), + owners: vec![("when_event", 8..28)], + }, + AssociationView { + document: 1, + resolution: Resolution::Resolved, + binding: Some(("when_event", 38..71)), + scope: ("source_file", 0..72), + owners: vec![("when_event", 38..71)], + }, + ], + assessments: vec![], + evidence: vec![], + }), + + (b"if { 1 } {\n# a\nwhen HTTP_REQUEST {}\n# b\nproc f {} {}\n}\n", false) => Some(View { + owners: vec![("source_file", 0..55)], + documents: vec![ + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![11..14], + text: Some("a".to_owned()), + unavailable: None, + mappings: vec![(0..1, Some(13..14))], + }, + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![36..39], + text: Some("b".to_owned()), + unavailable: None, + mappings: vec![(0..1, Some(38..39))], + }, + ], + associations: vec![ + AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 15..35)), + scope: ("braced_word", 9..54), + owners: vec![], + }, + AssociationView { + document: 1, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("procedure", 40..52)), + scope: ("braced_word", 9..54), + owners: vec![], + }, + ], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("procedure", 40..52)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 15..35)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("procedure", 40..52)), + document: Some(1), + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 15..35)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"if { 1 } {\n# doc\nwhen HTTP_REQUEST {}\n}\n", false) => Some(View { + owners: vec![("source_file", 0..40)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![11..16], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(13..16))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("when_event", 17..37)), + scope: ("braced_word", 9..39), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("when_event", 17..37)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("when_event", 17..37)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"set s \"# doc\nwhen HTTP_REQUEST {}\"\n", true) => Some(View { + owners: vec![("source_file", 0..35)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![], + }), + + (b"set s \"# doc\\nwhen HTTP_REQUEST {}\"\n", false) => Some(View { + owners: vec![("source_file", 0..36)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![], + }), + + (b"set s {\n# doc\nwhen HTTP_REQUEST {}\n}\n", _) => Some(View { + owners: vec![("source_file", 0..37)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![], + }), + + _ => None, + } +} diff --git a/big-code-analysis-ast/src/documentation/collector/irules_tests/procedure.rs b/big-code-analysis-ast/src/documentation/collector/irules_tests/procedure.rs new file mode 100644 index 000000000..266a3bdae --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/irules_tests/procedure.rs @@ -0,0 +1,229 @@ +use super::*; + +#[allow(clippy::too_many_lines)] // Complete expected facts for one group of source inputs. +pub(super) fn expected(source: &[u8], retain: bool) -> Option { + match (source, retain) { + (b"# doc\nproc \"f\" {} {}\n" | b"# doc\nproc {f} {} {}\n", false) => Some(View { + owners: vec![("source_file", 0..21)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::Dynamic), + binding: Some(("procedure", 6..20)), + scope: ("source_file", 0..21), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("procedure", 6..20)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("procedure", 6..20)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# doc\nproc $name {} {}\n" | b"# doc\nproc f$x {} {}\n", false) => Some(View { + owners: vec![("source_file", 0..source.len())], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::Dynamic), + binding: Some(("procedure", 6..source.len() - 1)), + scope: ("source_file", 0..source.len()), + owners: vec![], + }], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("procedure", 6..source.len() - 1)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("procedure", 6..source.len() - 1)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# doc\nproc f \"a b\" {}\n", true) => Some(View { + owners: vec![("source_file", 0..22)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + (b"# doc\nproc f args {}\n", false) => Some(View { + owners: vec![("source_file", 0..21), ("procedure", 6..20)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 6..20)), + scope: ("source_file", 0..21), + owners: vec![("procedure", 6..20)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# doc\nproc f x {}\n", false) => Some(View { + owners: vec![("source_file", 0..18), ("procedure", 6..17)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 6..17)), + scope: ("source_file", 0..18), + owners: vec![("procedure", 6..17)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# doc\nproc f {} {\nset x ]\n}\n# next\nwhen HTTP_REQUEST {}\n", false) => Some(View { + owners: vec![("source_file", 0..56), ("when_event", 35..55)], + documents: vec![ + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }, + DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![28..34], + text: Some("next".to_owned()), + unavailable: None, + mappings: vec![(0..4, Some(30..34))], + }, + ], + associations: vec![ + AssociationView { + document: 0, + resolution: Resolution::Unresolved(UnresolvedReason::GrammarBoundary), + binding: Some(("procedure", 6..27)), + scope: ("source_file", 0..56), + owners: vec![], + }, + AssociationView { + document: 1, + resolution: Resolution::Resolved, + binding: Some(("when_event", 35..55)), + scope: ("source_file", 0..56), + owners: vec![("when_event", 35..55)], + }, + ], + assessments: vec![ + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Recognized declaration requires a semantic projection", + node: Some(("procedure", 6..27)), + document: None, + }, + AssessmentView { + axis: AssessmentAxis::Owner, + reason: "Selected local or wrapper form awaits owner projection", + node: Some(("procedure", 6..27)), + document: Some(0), + }, + ], + evidence: vec![], + }), + + (b"# doc\nproc f {} {}\n", false) => Some(View { + owners: vec![("source_file", 0..19), ("procedure", 6..18)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 6..18)), + scope: ("source_file", 0..19), + owners: vec![("procedure", 6..18)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# doc\nproc f\\ g {} {}\n", false) => Some(View { + owners: vec![("source_file", 0..22), ("procedure", 6..21)], + documents: vec![DocumentView { + role: DocumentRole::LeadingComment, + composition: Composition::Single, + fragments: vec![0..5], + text: Some("doc".to_owned()), + unavailable: None, + mappings: vec![(0..3, Some(2..5))], + }], + associations: vec![AssociationView { + document: 0, + resolution: Resolution::Resolved, + binding: Some(("procedure", 6..21)), + scope: ("source_file", 0..22), + owners: vec![("procedure", 6..21)], + }], + assessments: vec![], + evidence: vec![], + }), + + (b"# doc\n{proc} f {} {}\n" | b"# doc\n{when} f {} {}\n", true) => Some(View { + owners: vec![("source_file", 0..21)], + documents: vec![], + associations: vec![], + assessments: vec![], + evidence: vec![(CandidateDisposition::Unattached, 0..5)], + }), + + _ => None, + } +} 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..b35dd0acb --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/java_tests.rs @@ -0,0 +1,2162 @@ +#![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()) +} + +#[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()); + assert_eq!( + index + .owner_associations(owner) + .unwrap() + .qualifications() + .len(), + 0 + ); + 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| { + assert_eq!(document.get().composition(), Composition::Single); + assert_eq!(document.get().role(), DocumentRole::Primary); + 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| { + assert_eq!(association.get().convention.name(), "javadoc"); + if !matches!(association.get().binding, Some(node) if node.node().kind() == "package_declaration") { + assert_eq!(association.get().publication, Publication::Unknown); + } + 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<'_>), +) { + both_context(source, &DocumentationContext::default(), options, check); +} + +#[cfg(feature = "java")] +fn both_context( + source: &str, + context: &DocumentationContext, + options: &DocumentationOptions, + check: impl Fn(tree_sitter::Node<'_>, &DocumentationIndex<'_>), +) { + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + for index in [ + parser.documentation(context, options).unwrap(), + collect( + LANG::Java, + parser.ts_tree(), + parser.code(), + context, + options, + ) + .unwrap(), + ] { + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); + check(parser.ts_tree().root_node(), &index); + } +} + +#[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 { + retain_unbound: true, + ..DocumentationOptions::default() + } +} + +#[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] +fn java_package_publication_depends_only_on_explicit_logical_filename() { + let source = "/**pkg*/\npackage p;\nclass C {}"; + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + for (filename, expected) in [ + (None, Publication::Unknown), + (Some("package-info.java"), Publication::Eligible), + (Some("Other.java"), Publication::Ineligible), + (Some("package-info.javx"), Publication::Ineligible), + (Some("dir/package-info.java"), Publication::Ineligible), + ] { + let context = DocumentationContext { + logical_filename: filename.map(str::to_owned), + }; + for index in [ + parser + .documentation(&context, &DocumentationOptions::default()) + .unwrap(), + collect( + LANG::Java, + parser.ts_tree(), + parser.code(), + &context, + &DocumentationOptions::default(), + ) + .unwrap(), + ] { + assert_eq!(index.capability(), Capability::Partial); + assert_eq!(index.qualifications().len(), 0); + assert_eq!(documents(&index), [(vec![0..8], Some("pkg".to_owned()))]); + assert_eq!( + associations(&index), + [( + 0, + Resolution::Resolved, + vec!["Node(package_declaration 9..19)".to_owned()], + Some("package_declaration 9..19".to_owned()), + "program 0..30".to_owned() + )] + ); + assert_eq!( + index.associations().next().unwrap().get().publication, + expected + ); + assert_eq!(assessments(&index, index.assessments()), []); + let target = node(parser.ts_tree().root_node(), "package_declaration", 9..19); + let query = index.node_associations(target).unwrap(); + assert!(!query.projection_pending()); + assert_eq!(query.associations().len(), 1); + } + } + for (source, filename, kind, range, text, publication) in [ + ( + "/**mod*/\nmodule m { }", + "module-info.java", + "module_declaration", + 9..21, + "mod", + Publication::Unknown, + ), + ( + "/**pkg*/\n@Deprecated\npackage p;\n", + "package-info.java", + "package_declaration", + 9..31, + "pkg", + Publication::Eligible, + ), + ] { + let context = DocumentationContext { + logical_filename: Some(filename.to_owned()), + }; + both_context( + source, + &context, + &DocumentationOptions::default(), + |root, index| { + assert!(!root.has_error()); + assert_eq!(documents(index), [(vec![0..8], Some(text.to_owned()))]); + let association = index.associations().next().unwrap(); + assert_eq!(index.associations().len(), 1); + assert_eq!(association.get().publication, publication); + let owner = index.facts().associated_owner(association, 0).unwrap(); + assert_eq!( + owner_text(index, owner), + format!("Node({kind} {}..{})", range.start, range.end) + ); + assert_eq!( + index + .node_associations(node(root, kind, range.clone())) + .unwrap() + .associations() + .len(), + 1 + ); + assert_eq!(assessments(index, index.assessments()), []); + }, + ); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_unresolved_package_retains_filename_publication() { + let context = DocumentationContext { + logical_filename: Some("package-info.java".to_owned()), + }; + both_context( + "/**p\\u0041*/\npackage p;\nclass C {}", + &context, + &DocumentationOptions::default(), + |_root, index| { + 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::GrammarBoundary) + ); + assert_eq!(association.get().publication, Publication::Eligible); + assert_eq!( + owner_text( + index, + index.facts().associated_owner(association, 0).unwrap() + ), + "Node(package_declaration 13..23)" + ); + }, + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_two_documents_only_package_publication_depends_on_filename() { + let source = "/**pkg*/\npackage p;\n/**type*/\nclass C {}"; + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + assert!(!parser.root_node().has_error()); + for (filename, expected) in [ + (None, Publication::Unknown), + (Some("package-info.java"), Publication::Eligible), + (Some("Other.java"), Publication::Ineligible), + ] { + let context = DocumentationContext { + logical_filename: filename.map(str::to_owned), + }; + both_context( + source, + &context, + &DocumentationOptions::default(), + |root, index| { + assert_eq!( + documents(index), + [ + (vec![0..8], Some("pkg".to_owned())), + (vec![20..29], Some("type".to_owned())), + ] + ); + let publications: Vec<_> = index + .associations() + .map(|edge| edge.get().publication) + .collect(); + assert_eq!(publications, [expected, Publication::Unknown]); + assert_eq!(index.associations().len(), 2); + let package = node(root, "package_declaration", 9..19); + let class = node(root, "class_declaration", 30..40); + assert_eq!( + index + .node_associations(package) + .unwrap() + .associations() + .len(), + 1 + ); + assert_eq!( + index.node_associations(class).unwrap().associations().len(), + 1 + ); + }, + ); + } +} + +#[cfg(feature = "java")] +#[test] +fn java_broken_package_has_text_but_no_publication_edge() { + let context = DocumentationContext { + logical_filename: Some("package-info.java".to_owned()), + }; + let options = DocumentationOptions::default(); + let valid = AnyParser::parse( + LANG::Java, + b"/**pkg*/\npackage p;\nclass C {}".to_vec(), + None, + None, + ) + .unwrap(); + let valid_index = valid.documentation(&context, &options).unwrap(); + assert_eq!(valid_index.associations().len(), 1); + assert_eq!( + valid_index.associations().next().unwrap().get().publication, + Publication::Eligible + ); + let broken = AnyParser::parse(LANG::Java, b"/**pkg*/\npackage p".to_vec(), None, None).unwrap(); + let target = node(broken.ts_tree().root_node(), "package_declaration", 9..18); + assert!(target.has_error()); + assert!(node(broken.ts_tree().root_node(), ";", 18..18).is_missing()); + both_context("/**pkg*/\npackage p", &context, &options, |root, index| { + assert!(node(root, "package_declaration", 9..18).has_error()); + assert_eq!(documents(index), [(vec![0..8], Some("pkg".to_owned()))]); + assert_eq!(index.associations().len(), 0); + let query = index + .node_associations(node(root, "package_declaration", 9..18)) + .unwrap(); + assert!(query.projection_pending()); + assert_eq!(query.assessments().count(), 2); + }); +} + +#[cfg(feature = "java")] +#[test] +fn java_excluded_gap_before_package_prevents_attachment() { + let source = "/**pkg*/\npackage p;\nclass C {}"; + let context = DocumentationContext { + logical_filename: Some("package-info.java".to_owned()), + }; + let included = restricted(source, &[0..source.len()]); + let control = collect( + LANG::Java, + &included, + source.as_bytes(), + &context, + &unbound(), + ) + .unwrap(); + assert_eq!(control.documents().len(), 1); + assert_eq!( + control.associations().next().unwrap().get().publication, + Publication::Eligible + ); + let tree = restricted(source, &[0..8, 9..source.len()]); + let index = collect(LANG::Java, &tree, source.as_bytes(), &context, &unbound()).unwrap(); + assert_eq!(documents(&index), []); + assert_eq!(index.associations().len(), 0); + assert_eq!(evidence(&index), [(CandidateDisposition::Unattached, 0..8)]); + let target = node(tree.root_node(), "package_declaration", 9..19); + assert_eq!( + index + .node_associations(target) + .unwrap() + .associations() + .len(), + 0 + ); +} + +// test-lang-gates: hand-written(java) — exercises the Java-only publication helper directly. +#[cfg(feature = "java")] +#[test] +fn java_package_filename_comparison_charges_every_compared_byte() { + let budget = Counting::default(); + assert_eq!( + super::assembly::java_package_publication(None, &budget).unwrap(), + Publication::Unknown + ); + assert_eq!(budget.bytes.get(), 0); + for (name, expected, compared) in [ + ("Other.java", Publication::Ineligible, 0), + ("package-info.javx", Publication::Ineligible, 17), + ("package-info.java", Publication::Eligible, 17), + ] { + let budget = Counting::default(); + assert_eq!( + super::assembly::java_package_publication(Some(name), &budget).unwrap(), + expected + ); + assert_eq!(budget.bytes.get(), compared); + } + let budget = Counting { + fail_bytes_at: Some(1), + ..Counting::default() + }; + assert!(matches!( + super::assembly::java_package_publication(Some("package-info.java"), &budget), + Err(SourceError::Cancelled) + )); +} + +#[cfg(feature = "java")] +#[test] +fn java_package_publication_comparison_observes_collection_cancellation() { + let source = "/**pkg*/\npackage p;\nclass C {}"; + let parser = AnyParser::parse(LANG::Java, source.as_bytes().to_vec(), None, None).unwrap(); + let options = DocumentationOptions::default(); + for raw in [false, true] { + let collect_with = |name: &str| { + let context = DocumentationContext { + logical_filename: Some(name.to_owned()), + }; + let before = crate::documentation::byte_scan::bytes_read::observed(); + let before_charges = observations().byte_charges; + let publication = if raw { + collect( + LANG::Java, + parser.ts_tree(), + parser.code(), + &context, + &options, + ) + .unwrap() + .associations() + .next() + .unwrap() + .get() + .publication + } else { + parser + .documentation(&context, &options) + .unwrap() + .associations() + .next() + .unwrap() + .get() + .publication + }; + ( + publication, + crate::documentation::byte_scan::bytes_read::observed() - before, + observations().byte_charges - before_charges, + ) + }; + let (ineligible, baseline_bytes, baseline_charges) = collect_with("Other.java"); + let (eligible, charged_bytes, charged_calls) = collect_with("package-info.java"); + let (same_length, _, same_length_charges) = collect_with("Package-info.java"); + assert_eq!(ineligible, Publication::Ineligible); + assert_eq!(eligible, Publication::Eligible); + assert_eq!(same_length, Publication::Ineligible); + // expected: equal source scans; only the 17-byte exact filename is compared. + assert_eq!(charged_bytes - baseline_bytes, b"package-info.java".len()); + // expected: the equal-length context copy costs the same; the first + // differing byte of Package-info.java costs one instead of seventeen. + assert_eq!( + charged_calls - same_length_charges, + b"package-info.java".len() - 1 + ); + // expected: Other.java copies seven fewer characters and compares none. + assert_eq!( + charged_calls - baseline_charges, + b"package-info.java".len() + 7 + ); + } + + let context = DocumentationContext { + logical_filename: Some("package-info.java".to_owned()), + }; + let before = observations(); + let complete = parser.documentation(&context, &options).unwrap(); + assert_eq!( + complete.associations().next().unwrap().get().publication, + Publication::Eligible + ); + let polls = observations().polls - before.polls; + assert!(polls > 0); + for checkpoint in 1..=polls { + let result = crate::documentation::budget::cancel_after(checkpoint, || { + parser.documentation(&context, &options) + }); + assert!( + matches!(result, Err(CollectionError::Cancelled)), + "{checkpoint}" + ); + } + let complete = crate::documentation::budget::cancel_after(polls + 1, || { + parser.documentation(&context, &options) + }) + .unwrap(); + assert_eq!( + complete.associations().next().unwrap().get().publication, + Publication::Eligible + ); +} + +#[cfg(feature = "java")] +#[test] +fn java_forms_fixtures_and_four_star_document_keep_their_text() { + for (source, fragment, owner, text, superseded) in [ + ( + include_str!("../../../../tests/fixtures/documentation/sources/java-selection.java"), + 19..23, + 24..34, + "", + Some(0..18), + ), + ( + include_str!("../../../../tests/fixtures/documentation/sources/java-empty.java"), + 0..4, + 5..15, + "", + None, + ), + ( + include_str!("../../../../tests/fixtures/documentation/sources/java-record.java"), + 0..17, + 18..36, + "Record doc", + None, + ), + ( + include_str!("../../../../tests/fixtures/documentation/sources/java-compact.java"), + 0..17, + 18..42, + "Record doc", + None, + ), + ("/****/\nclass C {}", 0..6, 7..17, "*", None), + ] { + both(source, &unbound(), |root, index| { + assert_eq!(index.documents().len(), 1); + let document = index.documents().next().unwrap(); + assert_eq!( + documents(index), + [(vec![fragment.clone()], Some(text.to_owned()))] + ); + let kind = if source.contains("record R") { + "record_declaration" + } else { + "class_declaration" + }; + let expected_owner = format!("{kind} {}..{}", owner.start, owner.end); + assert_eq!( + associations(index), + [( + 0, + Resolution::Resolved, + vec![format!("Node({expected_owner})")], + Some(expected_owner), + format!("program 0..{}", source.len()) + )] + ); + assert_eq!( + index.associations().next().unwrap().get().publication, + Publication::Unknown + ); + assert_eq!(assessments(index, index.assessments()), []); + let target = node(root, kind, owner.clone()); + assert_eq!( + index + .node_associations(target) + .unwrap() + .associations() + .len(), + 1 + ); + let expected = superseded.clone().map_or_else(Vec::new, |range| { + vec![(CandidateDisposition::Superseded, range)] + }); + assert_eq!(evidence(index), expected); + assert_eq!(document.get().fragment_count(), 1); + }); + } +} + +#[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); +} + +#[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 [ + ("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.clone())), + Err(OwnerError::UnsupportedOwner) + )); + assert!(matches!( + index.node_owners(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); + }); + // 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")] +#[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, + fail_bytes_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); + if self.fail_bytes_at == Some(self.bytes.get()) { + Err(SourceError::Cancelled) + } else { + 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", + // 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::>>, + ), + ] { + 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(); + // 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); + 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; + 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; + 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) + }) + .unwrap(); + assert_eq!( + index.associations().next().unwrap().get().owner_count(), + width + ); +} 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..62ede6e72 --- /dev/null +++ b/big-code-analysis-ast/src/documentation/collector/js_tests.rs @@ -0,0 +1,1732 @@ +//! 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(piece) => Run::Copied(piece.range()), + 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.kind() == "variable_declarator" { + let declaration = node.parent(); + if declaration.is_some_and(|parent| { + parent + .parent() + .is_some_and(|outer| outer.kind() == "export_statement") + }) { + declaration.and_then(|parent| parent.parent()) + } else { + declaration + } + } else 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<'p>( + language: LANG, + parser: &'p AnyParser, + options: &DocumentationOptions, +) -> [DocumentationIndex<'p>; 2] { + let context = DocumentationContext::default(); + [ + parser.documentation(&context, options).unwrap(), + collect(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(language, &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(language, &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"))] +#[allow(clippy::too_many_lines)] +fn variable_binding_owns_first_declarator(language: LANG) { + // bca: suppress(abc, halstead) -- one shared table checks both grammars and entry points. + // expected: each declaration contributes only its first declarator, even with a second name. + let rows: &[(&[u8], &str, &str)] = &[ + ( + b"/**audit*/\nconst f = () => 1;\n", + "lexical_declaration", + "f", + ), + ( + b"/**audit*/\nconst a = 1, b = 2;\n", + "lexical_declaration", + "a", + ), + (b"/**audit*/\nlet u;\n", "lexical_declaration", "u"), + ( + b"/**audit*/\nvar v = function () {};\n", + "variable_declaration", + "v", + ), + (b"/**audit*/\nusing u = f();\n", "using_declaration", "u"), + ( + b"/**audit*/\nexport const e = 3;\n", + "lexical_declaration", + "e", + ), + ( + b"/**audit*/\nconst /* c */ a = 1;\n", + "lexical_declaration", + "a", + ), + ( + b"/**audit*/\nconst a /* c */ = 1;\n", + "lexical_declaration", + "a", + ), + ( + b"/**audit*/\nconst `, 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); } - 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]) + 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); + } + } + } + Ok(Some(&rest[..len])) } /// A preprocessor conditional or one of its branches, under any alias of @@ -283,12 +347,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 @@ -299,6 +373,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(); @@ -308,7 +383,7 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest outer, own, }); - answers.push(children_declare::( + answers.push(children_declare::( &conditional, ancestors, memo, @@ -318,7 +393,8 @@ pub(crate) fn conditional_declares(node: &Node, ancestors: Ancest outer: Some(own), }); }, - )); + budget, + )?); } Visit::Answer { conditional, @@ -332,7 +408,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. @@ -359,26 +435,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 @@ -470,12 +548,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 @@ -486,17 +577,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, } } @@ -504,8 +615,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 @@ -517,7 +633,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 @@ -533,10 +653,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 @@ -554,8 +691,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 @@ -571,11 +712,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 @@ -605,13 +753,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)] @@ -894,7 +1055,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/irules.rs b/big-code-analysis-ast/src/lang_helpers/irules.rs index 696c9d2e2..b90de2d2f 100644 --- a/big-code-analysis-ast/src/lang_helpers/irules.rs +++ b/big-code-analysis-ast/src/lang_helpers/irules.rs @@ -18,3 +18,7 @@ pub(crate) const BRACED_WORD_KINDS: BracedWordKinds = BracedWordKinds { namespace: Irules::Namespace as u16, open_brace: Irules::LBRACE as u16, }; + +/// iRules comment and terminator ids for the source-only row reader. +pub(crate) const COMMENT_KIND: u16 = Irules::Comment as u16; +pub(crate) const LINE_FEED_KIND: u16 = Irules::LF as u16; diff --git a/big-code-analysis-ast/src/lang_helpers/perl.rs b/big-code-analysis-ast/src/lang_helpers/perl.rs index 7420ce73f..02b386432 100644 --- a/big-code-analysis-ast/src/lang_helpers/perl.rs +++ b/big-code-analysis-ast/src/lang_helpers/perl.rs @@ -4,6 +4,8 @@ //! section after `__END__`, which the grammar leaves as one leaf. use crate::Perl; +use crate::documentation::budget::{NoBudget, WorkBudget, infallible}; +use crate::documentation::byte_scan as scan; use crate::lang_helpers::doc_comment::pod_comment_region; use crate::node::{Ancestors, Node}; @@ -95,19 +97,24 @@ fn pod_rows( /// POD block outside one. Perl's `\s` takes a vertical tab, which /// `is_ascii_whitespace` does not. fn opens_pod(line: &[u8]) -> bool { + infallible(opens_pod_with_budget(line, &NoBudget)) +} + +pub(crate) fn opens_pod_with_budget( + line: &[u8], + budget: &B, +) -> Result { let Some(rest) = line.strip_prefix(b"=") else { - return false; + return Ok(false); }; - let word = rest - .iter() - .position(|byte| !byte.is_ascii_alphanumeric()) - .unwrap_or(rest.len()); + let word = + scan::position(rest, |byte| !byte.is_ascii_alphanumeric(), budget)?.unwrap_or(rest.len()); let (command, after) = rest.split_at(word); - command.first().is_some_and(u8::is_ascii_alphabetic) + Ok(command.first().is_some_and(u8::is_ascii_alphabetic) && command != b"cut" && after .first() - .is_none_or(|byte| byte.is_ascii_whitespace() || *byte == b'\x0b') + .is_none_or(|byte| byte.is_ascii_whitespace() || *byte == b'\x0b')) } /// Whether `and`, a Perl `and` token whose parent is `parent`, is the diff --git a/big-code-analysis-ast/src/lang_helpers/python.rs b/big-code-analysis-ast/src/lang_helpers/python.rs index fa6e8f52c..416cf0716 100644 --- a/big-code-analysis-ast/src/lang_helpers/python.rs +++ b/big-code-analysis-ast/src/lang_helpers/python.rs @@ -2,8 +2,10 @@ //! of a docstring. use crate::Python; +use crate::documentation::budget::{NoBudget, WorkBudget, child, infallible}; use crate::lang_helpers::doc_comment::node_bytes; use crate::node::{AncestorIter, Ancestors, Cursor, FoldLane, Node}; +use std::ops::Range; /// Whether `node` is a Python `lambda` expression, under either of the /// grammar's two aliased kind_ids: `Lambda` (196, the concrete @@ -206,26 +208,45 @@ fn enclosing_statement<'a, 'c>( /// `node` with at most [`MAX_PARENTHESES`] parentheses around it removed: /// the expression inside, skipping the comments a parenthesized /// expression may hold. One cursor serves every layer. -fn unparenthesized(node: Node) -> Node { +fn unparenthesized_with_budget<'a, B: WorkBudget>( + node: Node<'a>, + budget: &B, +) -> Result, B::Error> { let mut cursor = node.cursor(); let mut value = node; for _ in 0..MAX_PARENTHESES { - let Some(inner) = unparenthesized_once(&value, &mut cursor) else { + let Some(inner) = unparenthesized_once_with_budget(&value, &mut cursor, budget)? else { break; }; value = inner; } - value + Ok(value) } /// The expression one `parenthesized_expression` holds, or `None` when /// `node` is not one, read with `cursor`: its first named child that is /// no extra, so an `ERROR` the grammar recovered to is still its value. fn unparenthesized_once<'a>(node: &Node<'a>, cursor: &mut Cursor<'a>) -> Option> { + infallible(unparenthesized_once_with_budget(node, cursor, &NoBudget)) +} + +/// [`unparenthesized_once`] under a budget: one step for each child read, +/// the returned one included. +fn unparenthesized_once_with_budget<'a, B: WorkBudget>( + node: &Node<'a>, + cursor: &mut Cursor<'a>, + budget: &B, +) -> Result>, B::Error> { if node.kind_id() != Python::ParenthesizedExpression { - return None; + return Ok(None); } - node.children_with(cursor).find(not_extra) + for inner in node.children_with(cursor) { + budget.step()?; + if not_extra(&inner) { + return Ok(Some(inner)); + } + } + Ok(None) } /// Whether `node` is one of the grammar's two extras, a `#` comment or @@ -262,15 +283,27 @@ pub fn python_is_bare_string_statement(statement: &Node) -> bool { /// The string a bare string statement holds, past any parentheses. fn statement_string<'a>(statement: &Node<'a>) -> Option> { + infallible(statement_string_with_budget(statement, &NoBudget)) +} + +/// [`statement_string`] under a budget, charged by the descent through +/// the parentheses. +fn statement_string_with_budget<'a, B: WorkBudget>( + statement: &Node<'a>, + budget: &B, +) -> Result>, B::Error> { if !is_bare_statement(statement) { - return None; + return Ok(None); } - statement.child(0).map(unparenthesized).filter(|value| { - matches!( - value.kind_id().into(), - Python::String | Python::ConcatenatedString - ) - }) + let Some(inner) = statement.child(0) else { + return Ok(None); + }; + let value = unparenthesized_with_budget(inner, budget)?; + Ok(matches!( + value.kind_id().into(), + Python::String | Python::ConcatenatedString + ) + .then_some(value)) } /// Whether `node` is a bare string statement's `string`: the statement's @@ -355,31 +388,75 @@ fn documentation_run<'a>( code: &[u8], ancestors: Ancestors<'a, '_>, ) -> Option> { - // The literal test is the cheap one; `body_attributes` may read the + infallible(docstring_run_with_budget(value, code, ancestors, &NoBudget)).map(|run| run.first) +} + +/// The documentation-string run that the bare string statement holding a +/// value belongs to, as the one backward scan finds it. +#[derive(Clone, Copy, Debug)] +pub(crate) struct DocstringRun<'a> { + /// The run's first member statement. + pub(crate) first: Node<'a>, + /// The statement holding the value the scan started from. + pub(crate) last: Node<'a>, + /// The `module`, `class_definition` or `function_definition` whose body + /// holds the run. + pub(crate) owner: Node<'a>, + /// The accepted statement an attribute run follows; `None` for a run + /// that opens its body. + pub(crate) after: Option>, +} + +/// The one backward scan behind [`documentation_run`], under a budget: +/// the run of the bare string statement holding `value`, or `None` when +/// that statement is not documentation. It charges one step for each +/// sibling it takes, the one that ends the scan included, and the +/// predicates charge their own loops. With [`NoBudget`] the answer and the +/// scan count are those of the unbudgeted reader. +pub(crate) fn docstring_run_with_budget<'a, B: WorkBudget>( + value: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result>, B::Error> { + // bca: suppress(nexits) -- the unbudgeted reader's exits and one for each charged call. + // The literal test is the cheap one; the body's owner may read the // enclosing `__init__`'s name and parameters. - if !is_str_literal(value, code) { - return None; + if !is_str_literal_with_budget(value, code, budget)? { + return Ok(None); } - let ((statement, statement_ancestors), up) = enclosing_statement(value, ancestors)?; + let Some(((statement, statement_ancestors), up)) = enclosing_statement(value, ancestors) else { + return Ok(None); + }; // A string of a discarded tuple (`"a", "b"`) is no docstring: the // statement holds two values. Checked here, the one place, so the // row and the run helper cannot differ on it. if !is_bare_statement(&statement) { - return None; + return Ok(None); } docstring_runs_scanned::record(); - let attributes = body_attributes(up, code)?; - let mut first = statement; - for sibling in statement_ancestors - .siblings_before(&statement) - .filter(not_extra) - { - if !is_string_statement(&sibling, code) { - return attributes.documented_by(&sibling, code).then_some(first); + let Some((owner, attributes)) = body_owner_with_budget(up, code, budget)? else { + return Ok(None); + }; + let mut run = DocstringRun { + first: statement, + last: statement, + owner, + after: None, + }; + for sibling in statement_ancestors.siblings_before_with_budget(&statement, budget)? { + budget.step()?; + if !not_extra(&sibling) { + continue; + } + if !is_string_statement_with_budget(&sibling, code, budget)? { + let documented = attributes.documented_by_with_budget(&sibling, code, budget)?; + run.after = Some(sibling); + return Ok(documented.then_some(run)); } - first = sibling; + run.first = sibling; } - Some(first) + Ok(Some(run)) } /// Credits a consecutive run of documentation strings at its last string. @@ -391,30 +468,79 @@ pub fn python_documentation_string_run( ancestors: Ancestors<'_, '_>, mut credit: impl FnMut(usize, usize), ) { + infallible(completed_docstring_run_with_budget( + value, + code, + ancestors, + &NoBudget, + |statement, _| credit_documentation_rows(statement, &mut credit), + )); +} + +/// The run that `value` completes, under a budget: `None` unless `value` +/// is the value of a run's final member. `member` is called with each +/// member statement and its value, first to last. One look-ahead decides +/// whether the statement is the final member, and only then does the one +/// backward scan run ([`docstring_run_with_budget`]). The look-ahead, the +/// scan and the walk each charge one step for each sibling they take. +pub(crate) fn completed_docstring_run_with_budget<'a, B: WorkBudget>( + value: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, + mut member: impl FnMut(Node<'a>, Node<'a>), +) -> Result>, B::Error> { + // bca: suppress(nargs, nexits) -- the legacy walk's arguments and a budget; a pass can cancel. let Some(((statement, outer), _)) = enclosing_statement(value, ancestors) else { - return; + return Ok(None); }; - if outer - .siblings_after(&statement) - .find(not_extra) - .is_some_and(|next| is_string_statement(&next, code)) - { - return; + if !is_bare_statement(&statement) { + return Ok(None); } - // The run's final member. `documentation_run` is the backward scan - // the `Docstring` row's gate reads (#1699) and the one this needs for - // the run's first member, so it runs once, here: the row's verdict - // is `first.is_some()` by construction, the gate being this call. - let Some(first) = documentation_run(value, code, ancestors) else { - return; + if string_statement_follows(&statement, code, outer, budget)? { + return Ok(None); + } + // The run's final member. `docstring_run_with_budget` is the backward + // scan the `Docstring` row's gate reads (#1699) and the one this needs + // for the run's first member, so it runs once, here: the row's verdict + // is `Some` by construction, the gate being this call. + let Some(run) = docstring_run_with_budget(value, code, ancestors, budget)? else { + return Ok(None); }; - for member in std::iter::once(first) - .chain(outer.siblings_after(&first)) - .take_while(|member| member.start_byte() <= statement.start_byte()) - .filter(|member| is_string_statement(member, code)) + for item in + std::iter::once(run.first).chain(outer.siblings_after_with_budget(&run.first, budget)?) { - credit_documentation_rows(member, &mut credit); + budget.step()?; + if item.start_byte() > run.last.start_byte() { + break; + } + if not_extra(&item) + && let Some(string) = statement_string_with_budget(&item, budget)? + && is_str_literal_with_budget(&string, code, budget)? + { + member(item, string); + } } + Ok(Some(run)) +} + +/// Whether the next statement after `statement` is a string statement: +/// the look-ahead that tells a run's final member from an earlier one. +/// It charges one step for each sibling it takes, the one it tests +/// included. +fn string_statement_follows<'a, B: WorkBudget>( + statement: &Node<'a>, + code: &[u8], + ancestors: Ancestors<'a, '_>, + budget: &B, +) -> Result { + for next in ancestors.siblings_after_with_budget(statement, budget)? { + budget.step()?; + if not_extra(&next) { + return is_string_statement_with_budget(&next, code, budget); + } + } + Ok(false) } /// Credits the rows of a string statement's value and of the `(` and `)` @@ -462,27 +588,61 @@ impl Attributes<'_> { /// Whether `statement`, directly before a string statement, makes that /// string an attribute docstring. fn documented_by(&self, statement: &Node, code: &[u8]) -> bool { + infallible(self.documented_by_with_budget(statement, code, &NoBudget)) + } + + /// [`Self::documented_by`] under a budget, charged by the walk of the + /// target and by the comparison of each receiver spelling. + fn documented_by_with_budget( + &self, + statement: &Node, + code: &[u8], + budget: &B, + ) -> Result { // A `type X = …` alias (PEP 695) declares the name it binds, and // Sphinx's `VariableCommentPicker` reads it like an assignment // (`AssignmentLikeType` holds `ast.TypeAlias`): a docstring after // it or a `#:` comment on or above it documents `X`. It never // binds an attribute of `self`. if statement.kind_id() == Python::TypeAliasStatement { - return matches!(self, Self::Names); + return Ok(matches!(self, Self::Names)); } let Some(target) = assignment_target(statement) else { - return false; + return Ok(false); }; match self { - Self::Names => binds(&target, |leaf| leaf.kind_id() == Python::Identifier), - Self::OfSelf(name) => binds(&target, |leaf| { - leaf.kind_id() == Python::Attribute - && leaf.child_by_field_name("object").is_some_and(|object| { - object.kind_id() == Python::Identifier && node_bytes(&object, code) == *name - }) - }), - Self::Nothing => false, + Self::Names => binds_with_budget( + &target, + |leaf| Ok(leaf.kind_id() == Python::Identifier), + budget, + ), + Self::OfSelf(receiver) => binds_with_budget( + &target, + |leaf| is_attribute_of(leaf, receiver, code, budget), + budget, + ), + Self::Nothing => Ok(false), + } + } +} + +/// Whether `leaf` is an attribute of the name `receiver` spells: +/// `self.x` for the receiver `self`. The two spellings are compared under +/// the budget ([`same_spelling`]). +fn is_attribute_of( + leaf: &Node, + receiver: &[u8], + code: &[u8], + budget: &B, +) -> Result { + if leaf.kind_id() != Python::Attribute { + return Ok(false); + } + match leaf.child_by_field_name("object") { + Some(object) if object.kind_id() == Python::Identifier => { + same_spelling(node_bytes(&object, code), receiver, budget) } + _ => Ok(false), } } @@ -490,15 +650,30 @@ impl Attributes<'_> { /// the statement: `None` when the body holds no documentation at all (an /// `if` or loop body). fn body_attributes<'code>( - mut up: AncestorIter<'_, '_>, + up: AncestorIter<'_, '_>, code: &'code [u8], ) -> Option> { - let (container, _) = up.next()?; + infallible(body_owner_with_budget(up, code, &NoBudget)).map(|(_, attributes)| attributes) +} + +/// [`body_attributes`] under a budget, with the node that owns the body: +/// the `module`, or the class or function definition a `block` belongs to. +fn body_owner_with_budget<'a, 'code, B: WorkBudget>( + mut up: AncestorIter<'a, '_>, + code: &'code [u8], + budget: &B, +) -> Result, Attributes<'code>)>, B::Error> { + let Some((container, _)) = up.next() else { + return Ok(None); + }; if container.kind_id() == Python::Module { - return Some(Attributes::Names); + return Ok(Some((container, Attributes::Names))); } - let (owner, _) = up.next().filter(|_| python_is_block(&container))?; - owner_attributes(&owner, up, code) + let Some((owner, _)) = up.next().filter(|_| python_is_block(&container)) else { + return Ok(None); + }; + Ok(owner_attributes_with_budget(&owner, up, code, budget)? + .map(|attributes| (owner, attributes))) } /// What the body of `owner` — a class or function definition — makes of @@ -509,15 +684,30 @@ fn owner_attributes<'code>( up: AncestorIter<'_, '_>, code: &'code [u8], ) -> Option> { + infallible(owner_attributes_with_budget(owner, up, code, &NoBudget)) +} + +/// [`owner_attributes`] under a budget, charged by the search for the +/// receiver of `__init__`. +fn owner_attributes_with_budget<'code, B: WorkBudget>( + owner: &Node, + up: AncestorIter<'_, '_>, + code: &'code [u8], + budget: &B, +) -> Result>, B::Error> { if owner.kind_id() == Python::ClassDefinition { - Some(Attributes::Names) + Ok(Some(Attributes::Names)) } else if owner.kind_id() == Python::FunctionDefinition { - let receiver = is_class_init(owner, up, code) - .then(|| first_parameter_name(owner, code)) - .flatten(); - Some(receiver.map_or(Attributes::Nothing, Attributes::OfSelf)) + let receiver = if is_class_init(owner, up, code) { + first_parameter_name_with_budget(owner, code, budget)? + } else { + None + }; + Ok(Some( + receiver.map_or(Attributes::Nothing, Attributes::OfSelf), + )) } else { - None + Ok(None) } } @@ -545,40 +735,93 @@ fn is_class_init(function: &Node, up: AncestorIter<'_, '_>, code: &[u8]) -> bool /// are named, and formatters put a comment right after the `(` of an /// exploded signature (`def __init__( # noqa: PLR0913`), a `\` too /// (`def __init__( \`), so both are skipped. -fn first_parameter_name<'code>(function: &Node, code: &'code [u8]) -> Option<&'code [u8]> { - let first = function - .child_by_field_name("parameters")? - .children() - .find(not_extra)?; +/// +/// Charged one step for each child read on the way to the name. +fn first_parameter_name_with_budget<'code, B: WorkBudget>( + function: &Node, + code: &'code [u8], + budget: &B, +) -> Result, B::Error> { + let Some(parameters) = function.child_by_field_name("parameters") else { + return Ok(None); + }; + let Some(first) = child(¶meters, not_extra, budget)? else { + return Ok(None); + }; let name = if first.kind_id() == Python::TypedParameter { - first.children().find(Node::is_named)? + child(&first, Node::is_named, budget)? } else { - first + Some(first) }; - (name.kind_id() == Python::Identifier).then(|| node_bytes(&name, code)) + Ok(name + .filter(|name| name.kind_id() == Python::Identifier) + .map(|name| node_bytes(&name, code))) +} + +/// Whether two spellings are the same bytes, compared under the budget. +/// Spellings of different length differ at no charge. Otherwise each pair +/// of bytes is charged before it is compared, and the first pair that +/// differs ends the comparison. With [`NoBudget`] the answer is that of +/// `==`. +fn same_spelling(left: &[u8], right: &[u8], budget: &B) -> Result { + if left.len() != right.len() { + return Ok(false); + } + for (left, right) in left.iter().zip(right) { + budget.bytes(1)?; + if left != right { + return Ok(false); + } + } + Ok(true) } /// Whether `value` is a literal Python stores as a docstring: a `str`, not /// an f-string, a template string or bytes — a prefix holding `f`, `t` or /// `b` in either case makes the statement none, and one fragment of an /// implicit concatenation is enough. -fn is_str_literal(value: &Node, code: &[u8]) -> bool { - let is_str = |literal: &Node| { - !node_bytes(literal, code) - .iter() - .take_while(|byte| byte.is_ascii_alphabetic()) - .any(|byte| matches!(byte.to_ascii_lowercase(), b'f' | b't' | b'b')) - }; +/// +/// Charged one step for each child of a concatenation and one byte for +/// each prefix letter read. +fn is_str_literal_with_budget( + value: &Node, + code: &[u8], + budget: &B, +) -> Result { if value.kind_id() == Python::ConcatenatedString { - value - .children() - .filter(|fragment| fragment.kind_id() == Python::String) - .all(|fragment| is_str(&fragment)) + for fragment in value.children() { + budget.step()?; + if fragment.kind_id() == Python::String + && !has_str_prefix_with_budget(&fragment, code, budget)? + { + return Ok(false); + } + } + Ok(true) } else { - is_str(value) + has_str_prefix_with_budget(value, code, budget) } } +/// Whether the leading ASCII letters of `literal` hold none of `f`, `t` +/// and `b`, in either case: the prefix of a `str` literal. +fn has_str_prefix_with_budget( + literal: &Node, + code: &[u8], + budget: &B, +) -> Result { + for byte in node_bytes(literal, code) { + if !byte.is_ascii_alphabetic() { + break; + } + budget.bytes(1)?; + if matches!(byte.to_ascii_lowercase(), b'f' | b't' | b'b') { + return Ok(false); + } + } + Ok(true) +} + /// An `expression_statement` holding one value and nothing else: the /// discarded-value shape a docstring takes. fn is_bare_statement(statement: &Node) -> bool { @@ -587,8 +830,15 @@ fn is_bare_statement(statement: &Node) -> bool { /// A bare statement whose value is a `str` literal: a docstring, when it /// opens its body. -fn is_string_statement(statement: &Node, code: &[u8]) -> bool { - statement_string(statement).is_some_and(|value| is_str_literal(&value, code)) +fn is_string_statement_with_budget( + statement: &Node, + code: &[u8], + budget: &B, +) -> Result { + match statement_string_with_budget(statement, budget)? { + Some(value) => is_str_literal_with_budget(&value, code, budget), + None => Ok(false), + } } /// Whether an assignment target binds what Sphinx records an attribute @@ -597,19 +847,93 @@ fn is_string_statement(statement: &Node, code: &[u8]) -> bool { /// starred target binds when any element does. Walked with an explicit /// stack, so a target nested thousands of brackets deep cannot exhaust the /// thread's stack (#1597). -fn binds(target: &Node, leaf: impl Fn(&Node) -> bool) -> bool { +/// +/// Charged one step for the target and one for each child of every node +/// the walk expands; `leaf` charges what it reads itself. +fn binds_with_budget( + target: &Node, + leaf: impl Fn(&Node) -> Result, + budget: &B, +) -> Result { + budget.step()?; let mut pending = vec![*target]; while let Some(node) = pending.pop() { match node.kind_id().into() { Python::Identifier | Python::Subscript | Python::Attribute => { - if leaf(&node) { - return true; + if leaf(&node)? { + return Ok(true); + } + } + _ => { + for inner in node.children() { + budget.step()?; + if inner.is_named() { + pending.push(inner); + } } } - _ => pending.extend(node.children().filter(Node::is_named)), } } - false + Ok(false) +} + +/// Whether `node` owns a body docstring: a function or class definition. +/// The module owns one too and is the file's owner already. +#[must_use] +pub(crate) fn python_is_docstring_owner(node: &Node) -> bool { + matches!( + node.kind_id().into(), + Python::FunctionDefinition | Python::ClassDefinition + ) +} + +/// What a `string` node spells between its quotes. +#[derive(Clone, Debug)] +pub(crate) struct StringLiteral { + /// The bytes between `string_start` and `string_end`. + pub(crate) interior: Range, + /// Whether the prefix holds `r` or `R`, so no escape is decoded. + pub(crate) raw: bool, +} + +/// The interior and the raw flag of `string`, or `None` when the node is +/// no clean `string` between a `string_start` and a `string_end` inside +/// `code`. No parsed source gives the `None` arms on the node's own shape +/// (a `string` with an error, with fewer than two children or with other +/// first and last children); they are kept because a tree and a buffer +/// are separate arguments. Charged one byte for each prefix letter read. +pub(crate) fn python_string_literal( + string: &Node, + code: &[u8], + budget: &B, +) -> Result, B::Error> { + let children = string.child_count(); + if string.kind_id() != Python::String || string.has_error() || children < 2 { + return Ok(None); + } + let (Some(start), Some(end)) = (string.child(0), string.child(children - 1)) else { + return Ok(None); + }; + let interior = start.end_byte()..end.start_byte(); + if start.kind_id() != Python::StringStart + || end.kind_id() != Python::StringEnd + || interior.start > interior.end + || code.get(interior.clone()).is_none() + { + return Ok(None); + } + let mut raw = false; + for byte in node_bytes(&start, code) { + if !byte.is_ascii_alphabetic() { + break; + } + budget.bytes(1)?; + if byte.eq_ignore_ascii_case(&b'r') { + raw = true; + break; + } + } + Ok(Some(StringLiteral { interior, raw })) } /// The target of the assignment `statement` holds, annotated or not. @@ -992,4 +1316,533 @@ mod tests { .into() ); } + + /// The budgeted docstring reader: what it answers, what it reports and what + /// it charges. One gate for the module, as every test here parses Python. + #[cfg(feature = "python")] + mod reader { + use super::*; + use crate::documentation::SourceError; + use crate::langs::PythonCode; + use crate::test_support::for_each_node_with_chain; + use std::cell::Cell; + + /// Counts `step` calls and sums `bytes` charges, and can fail on one of either. + #[derive(Default)] + struct Counting { + steps: Cell, + bytes: Cell, + fail_at_step: Option, + fail_at_byte: Option, + } + + impl Counting { + fn failing_at_step(step: usize) -> Self { + Self { + fail_at_step: Some(step), + ..Self::default() + } + } + + fn failing_at_byte(byte: usize) -> Self { + Self { + fail_at_byte: Some(byte), + ..Self::default() + } + } + } + + impl WorkBudget for Counting { + type Error = SourceError; + + fn checkpoint(&self) -> Result<(), SourceError> { + Ok(()) + } + + fn step(&self) -> Result<(), SourceError> { + self.steps.set(self.steps.get() + 1); + if self.fail_at_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_at_byte + .is_some_and(|limit| self.bytes.get() >= limit) + { + Err(SourceError::Cancelled) + } else { + Ok(()) + } + } + } + + /// A run as `(first start, last start, owner kind, owner start, after start)`. + type Run = (usize, usize, &'static str, usize, Option); + + /// What one completed-run call gave: the run, the members as + /// `(statement start, value start)`, the steps, the bytes and the scans. + type Completed = ( + Result, SourceError>, + Vec<(usize, usize)>, + usize, + usize, + usize, + ); + + fn run_tuple(run: DocstringRun<'_>) -> Run { + ( + run.first.start_byte(), + run.last.start_byte(), + run.owner.kind(), + run.owner.start_byte(), + run.after.map(|after| after.start_byte()), + ) + } + + /// Asks `ask` of the one node of `kind` that starts at `start`. + fn at_node( + source: &[u8], + kind: &str, + start: usize, + mut ask: impl FnMut(&Node<'_>, Ancestors<'_, '_>) -> R, + ) -> R { + let mut answers = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + if node.kind() == kind && node.start_byte() == start { + answers.push(ask(node, Ancestors::known(chain))); + } + }); + assert_eq!(answers.len(), 1, "one {kind} at {start}"); + answers.remove(0) + } + + fn completed_with( + value: &Node<'_>, + code: &[u8], + ancestors: Ancestors<'_, '_>, + budget: &Counting, + ) -> Completed { + let mut members = Vec::new(); + let scans = docstring_runs_scanned::observed(); + let result = completed_docstring_run_with_budget( + value, + code, + ancestors, + budget, + |statement, value| { + members.push((statement.start_byte(), value.start_byte())); + }, + ) + .map(|run| run.map(run_tuple)); + ( + result, + members, + budget.steps.get(), + budget.bytes.get(), + docstring_runs_scanned::observed() - scans, + ) + } + + /// The completed-run call at the one node of `kind` at `start`, counted. + fn completed(source: &[u8], kind: &str, start: usize) -> Completed { + at_node(source, kind, start, |value, ancestors| { + completed_with(value, source, ancestors, &Counting::default()) + }) + } + + /// The same call cancelled at each step from 1 to `steps`, and then one step + /// later, where it must give `expected`. + fn completed_fails_at_each_step( + source: &[u8], + kind: &str, + start: usize, + steps: usize, + expected: Option, + ) { + at_node(source, kind, start, |value, ancestors| { + for step in 1..=steps { + let (result, ..) = + completed_with(value, source, ancestors, &Counting::failing_at_step(step)); + assert_eq!(result, Err(SourceError::Cancelled), "step {step}"); + } + let (result, _, counted, ..) = completed_with( + value, + source, + ancestors, + &Counting::failing_at_step(steps + 1), + ); + assert_eq!(result, Ok(expected)); + assert_eq!(counted, steps); + }); + } + + #[test] + fn docstring_run_record_names_owner_members_and_assignment() { + let source = concat!( + "\"\"\"a\"\"\"\n\"\"\"b\"\"\"\n# c\n\"\"\"c\"\"\"\nx = 1\n\"\"\"d\"\"\"\n", + "class C:\n \"\"\"k\"\"\"\n def m(self):\n \"\"\"m\"\"\"\n" + ) + .as_bytes(); + assert_eq!(source.len(), 96); + let mut runs = Vec::new(); + for_each_node_with_chain::(source, |node, chain| { + if node.kind() == "string" { + let run = infallible(docstring_run_with_budget( + node, + source, + Ancestors::known(chain), + &NoBudget, + )); + runs.push((node.start_byte(), run.map(run_tuple))); + } + }); + assert_eq!( + runs, + [ + (0, Some((0, 0, "module", 0, None))), + (8, Some((0, 8, "module", 0, None))), + (20, Some((0, 20, "module", 0, None))), + (34, Some((34, 34, "module", 0, Some(28)))), + (55, Some((55, 55, "class_definition", 42, None))), + (88, Some((88, 88, "function_definition", 67, None))), + ] + ); + } + + #[test] + fn completed_docstring_run_polls_once_per_sibling_and_reports_members() { + let source: &[u8] = + b"\"\"\"a\"\"\"\n\"\"\"b\"\"\"\n# c\n\"\"\"c\"\"\"\nx = 1\n\"\"\"d\"\"\"\n"; + // expected: the look-ahead takes `b`, a string statement. + assert_eq!(completed(source, "string", 0), (Ok(None), vec![], 1, 0, 0)); + // expected: the look-ahead takes `# c` and `c`. + assert_eq!(completed(source, "string", 8), (Ok(None), vec![], 2, 0, 0)); + // expected: 9 = 1 (look-ahead: `x = 1`) + 3 (scan: `# c`, `b`, `a`) + // + 5 (walk: `a`, `b`, `# c`, `c` and the `x = 1` that ends it). + let run = Some((0, 20, "module", 0, None)); + assert_eq!( + completed(source, "string", 20), + (Ok(run), vec![(0, 0), (8, 8), (20, 20)], 9, 0, 1) + ); + completed_fails_at_each_step(source, "string", 20, 9, run); + // expected: 3 = 1 (scan: `x = 1`) + 1 (the assignment target) + 1 (walk: `d`). + assert_eq!( + completed(source, "string", 34), + ( + Ok(Some((34, 34, "module", 0, Some(28)))), + vec![(34, 34)], + 3, + 0, + 1 + ) + ); + } + + #[test] + fn docstring_run_skips_unnamed_siblings() { + // A `;` between two statements is an unnamed sibling: each pass takes it at + // the cost of one step and goes on. + let source: &[u8] = b"\"a\";\n\"b\"\nx = 1\n"; + assert_eq!(completed(source, "string", 0), (Ok(None), vec![], 2, 0, 0)); + // expected: 7 = 1 (look-ahead: `x = 1`) + 2 (scan: `;`, `a`) + // + 4 (walk: `a`, `;`, `b` and the `x = 1` that ends it). + assert_eq!( + completed(source, "string", 5), + ( + Ok(Some((0, 5, "module", 0, None))), + vec![(0, 0), (5, 5)], + 7, + 0, + 1 + ) + ); + // expected: 4 = 2 (scan: `;`, `x = 1`) + 1 (the assignment target) + 1 (walk). + for source in [&b"x = 1;\n\"x doc\"\n"[..], b"x = 1; \"attribute\"\n"] { + assert_eq!( + completed(source, "string", 7), + ( + Ok(Some((7, 7, "module", 0, Some(0)))), + vec![(7, 7)], + 4, + 0, + 1 + ) + ); + } + let source: &[u8] = b"def f():\n \"a\"; \"b\"\n return 1\n"; + assert_eq!(completed(source, "string", 13), (Ok(None), vec![], 2, 0, 0)); + // expected: 7 = 1 (look-ahead: `return 1`) + 2 (scan) + 4 (walk). + assert_eq!( + completed(source, "string", 18), + ( + Ok(Some((13, 18, "function_definition", 0, None))), + vec![(13, 13), (18, 18)], + 7, + 0, + 1 + ) + ); + let source: &[u8] = b"\"\"\"a\nA\"\"\"; \"\"\"b\nB\"\"\"\n"; + assert_eq!(completed(source, "string", 0), (Ok(None), vec![], 2, 0, 0)); + // expected: 5 = 0 (look-ahead: no sibling) + 2 (scan: `;`, `a`) + // + 3 (walk: `a`, `;`, `b`). + assert_eq!( + completed(source, "string", 11), + ( + Ok(Some((0, 11, "module", 0, None))), + vec![(0, 0), (11, 11)], + 5, + 0, + 1 + ) + ); + } + + #[test] + fn string_literal_test_polls_per_fragment_and_prefix_letter() { + for fragments in [3, 1_500] { + let source = format!("{}\n", vec!["\"a\""; fragments].join(" ")); + let source = source.as_bytes(); + // expected: 2n + 1 = n (the reader's prefix test: one for each fragment) + // + 1 (walk: the statement) + n (the walk's prefix test). + let steps = 2 * fragments + 1; + let run = Some((0, 0, "module", 0, None)); + assert_eq!( + completed(source, "concatenated_string", 0), + (Ok(run), vec![(0, 0)], steps, 0, 1) + ); + completed_fails_at_each_step(source, "concatenated_string", 0, steps, run); + // A fragment is not the value of its statement. + for fragment in 0..fragments { + assert_eq!( + completed(source, "string", 4 * fragment), + (Ok(None), vec![], 0, 0, 0) + ); + } + } + // expected: 2 steps (fragments `"a"` and `Rb"b"`) and 2 bytes (`R`, `b`). + assert_eq!( + completed(b"\"a\" Rb\"b\" \"c\"\n", "concatenated_string", 0), + (Ok(None), vec![], 2, 2, 0) + ); + // expected: 3 steps (look-ahead: `y = 1`; walk: the statement and the + // `y = 1` that ends it) and 16 bytes (8 prefix letters, read by the reader + // and by the walk). + assert_eq!( + completed(b"rrrruuuu\"x\"\ny = 1\n", "string", 0), + (Ok(Some((0, 0, "module", 0, None))), vec![(0, 0)], 3, 16, 1) + ); + } + + #[test] + fn rejected_assignment_target_is_traversed_under_the_budget() { + for (targets, string) in [(3, 21), (1_500, 12_393)] { + let names: Vec<_> = (0..targets).map(|at| format!("a.x{at}")).collect(); + let source = format!("{} = v\n\"no\"\n", names.join(", ")); + let source = source.as_bytes(); + // expected: 2n + 1 = 1 (scan: the assignment) + 1 (the target) + // + (2n - 1) (the children of the `pattern_list`: n attributes and + // n - 1 commas). No attribute is a name, so the run is rejected. + let steps = 2 * targets + 1; + assert_eq!( + completed(source, "string", string), + (Ok(None), vec![], steps, 0, 1) + ); + completed_fails_at_each_step(source, "string", string, steps, None); + } + } + + #[test] + fn parenthesized_value_is_found_past_extras_under_the_budget() { + for (comments, string) in [(3, 14), (1_500, 6_002)] { + let source = format!("(\n{}\"doc\"\n)\n", "# c\n".repeat(comments)); + let source = source.as_bytes(); + // expected: n + 3 = 1 (walk: the statement) + (n + 2) (the children of + // the parentheses up to the value: `(`, n comments and the string). + let steps = comments + 3; + let run = Some((0, 0, "module", 0, None)); + assert_eq!( + completed(source, "string", string), + (Ok(run), vec![(0, 2 + 4 * comments)], steps, 0, 1) + ); + assert_eq!(string, 2 + 4 * comments); + completed_fails_at_each_step(source, "string", string, steps, run); + } + } + + #[test] + fn docstring_run_rejects_a_prefixed_literal_before_the_scan() { + let read = |source: &[u8], kind: &str, start: usize| { + at_node(source, kind, start, |value, ancestors| { + let budget = Counting::default(); + let scans = docstring_runs_scanned::observed(); + let run = docstring_run_with_budget(value, source, ancestors, &budget) + .map(|run| run.map(run_tuple)); + ( + run, + budget.steps.get(), + budget.bytes.get(), + docstring_runs_scanned::observed() - scans, + ) + }) + }; + // expected: one prefix letter is read, and no sibling. + for source in [ + &b"def f():\n b\"audit\"\n pass"[..], + b"def f():\n f\"audit\"\n pass", + ] { + assert_eq!(read(source, "string", 13), (Ok(None), 0, 1, 0)); + } + assert_eq!( + read(b"x = 1\nf\"audit\"\n", "string", 6), + (Ok(None), 0, 1, 0) + ); + // expected: 2 steps (fragments `"a"` and `b"b"`) and 1 byte (`b`). + assert_eq!( + read( + b"def f():\n \"a\" b\"b\"\n pass\n", + "concatenated_string", + 13 + ), + (Ok(None), 2, 1, 0) + ); + // The control: `r` is read and is no rejection. + assert_eq!( + read(b"def f():\n r\"audit\"\n pass", "string", 13), + (Ok(Some((13, 13, "function_definition", 0, None))), 0, 1, 1) + ); + } + + #[test] + fn init_receiver_is_found_past_extras_under_the_budget() { + for (comments, string, assignment) in [(2, 93, 74), (1_500, 18_069, 18_050)] { + let source = format!( + "class C:\n def __init__(\n{} self):\n{}", + " # c\n".repeat(comments), + " self.a = 1\n \"a doc\"\n" + ); + let source = source.as_bytes(); + // expected: n + 5 = (n + 2) (the children of `parameters` up to the + // receiver: `(`, n comments and `self`) + 1 (scan: the assignment) + // + 1 (the target) + 1 (walk: the statement). + // expected: 4 bytes, the four pairs of `self` and `self`. + let steps = comments + 5; + let run = Some((string, string, "function_definition", 13, Some(assignment))); + assert_eq!( + completed(source, "string", string), + (Ok(run), vec![(string, string)], steps, 4, 1) + ); + completed_fails_at_each_step(source, "string", string, steps, run); + } + // A typed receiver: its name is the first named child of the parameter. + // expected: 6 = 2 (`(` and the typed parameter) + 1 (the name inside it) + // + 1 (scan) + 1 (the target) + 1 (walk). + let source: &[u8] = + b"class C:\n def __init__(self: \"C\"):\n self.a = 1\n \"a doc\"\n"; + let string = source.len() - 8; + let run = Some((string, string, "function_definition", 13, Some(string - 19))); + assert_eq!( + completed(source, "string", string), + (Ok(run), vec![(string, string)], 6, 4, 1) + ); + completed_fails_at_each_step(source, "string", string, 6, run); + } + + #[test] + fn init_receiver_spelling_is_compared_under_the_budget() { + let receiver = "s".repeat(20_000); + // The receiver of `__init__` and the object of the assignment target. + let source = |object: &str| { + format!( + "class C:\n def __init__({receiver}):\n {object}.a = 1\n{}", + " \"a doc\"\n" + ) + }; + let ask = |object: &str, budget: &Counting| { + let source = source(object); + let string = source.len() - 8; + let assignment = string - 15 - object.len(); + let completed = at_node(source.as_bytes(), "string", string, |value, ancestors| { + completed_with(value, source.as_bytes(), ancestors, budget) + }); + (completed, string, assignment) + }; + // Equal spellings: every pair is charged. + // expected: 5 steps = 2 (`(` and the receiver) + 1 (scan: the assignment) + // + 1 (the target) + 1 (walk: the statement). + let (completed, string, assignment) = ask(&receiver, &Counting::default()); + let run = Some((string, string, "function_definition", 13, Some(assignment))); + assert_eq!(completed, (Ok(run), vec![(string, string)], 5, 20_000, 1)); + // Both sides of the count: the last pair is charged before it is compared, + // and no charge follows it. + let (completed, ..) = ask(&receiver, &Counting::failing_at_byte(20_000)); + assert_eq!(completed.0, Err(SourceError::Cancelled)); + let (completed, ..) = ask(&receiver, &Counting::failing_at_byte(20_001)); + assert_eq!((completed.0, completed.3), (Ok(run), 20_000)); + // A late mismatch: pair 19,999 of 20,000 differs and one equal pair follows. + // expected: 19,999 bytes, the pair that differs included and nothing after it; + // 4 steps, as the rejected run has no walk. + let late = format!("{}x{}", "s".repeat(19_998), "s"); + assert_eq!(late.len(), receiver.len()); + let (completed, ..) = ask(&late, &Counting::default()); + assert_eq!(completed, (Ok(None), vec![], 4, 19_999, 1)); + let (completed, ..) = ask(&late, &Counting::failing_at_byte(19_999)); + assert_eq!(completed.0, Err(SourceError::Cancelled)); + let (completed, ..) = ask(&late, &Counting::failing_at_byte(20_000)); + assert_eq!((completed.0, completed.3), (Ok(None), 19_999)); + // Spellings of different length, each a prefix of the other: no pair is + // compared and nothing is charged. + for object in [format!("{receiver}s"), "s".repeat(19_999)] { + let (completed, ..) = ask(&object, &Counting::default()); + assert_eq!(completed, (Ok(None), vec![], 4, 0, 1)); + } + } + + #[test] + fn string_literal_reader_checks_bounds_and_polls_per_prefix_letter() { + let read = |source: &[u8], code: &[u8], kind: &str, start: usize| { + at_node(source, kind, start, |string, _| { + let budget = Counting::default(); + let literal = python_string_literal(string, code, &budget) + .map(|literal| literal.map(|literal| (literal.interior, literal.raw))); + (literal, budget.steps.get(), budget.bytes.get()) + }) + }; + // expected: 4 bytes, all four letters, none of them `r`. + let source: &[u8] = b"UuUu\"x\"\ny = 1\n"; + assert_eq!( + read(source, source, "string", 0), + (Ok(Some((5..6, false))), 0, 4) + ); + // expected: 1 byte, the reading stops at the first `r`. + let source: &[u8] = b"rrrruuuu\"x\"\ny = 1\n"; + assert_eq!( + read(source, source, "string", 0), + (Ok(Some((9..10, true))), 0, 1) + ); + let source: &[u8] = b"def f():\n \"\"\n \"extra\"\n return 1\n"; + assert_eq!( + read(source, source, "string", 13), + (Ok(Some((14..14, false))), 0, 0) + ); + // A buffer shorter than the tree it is read with: no interior, and no panic. + let source: &[u8] = b"def f():\n \"audit\"\n pass"; + assert_eq!( + read(source, source, "string", 13), + (Ok(Some((14..19, false))), 0, 0) + ); + assert_eq!(read(source, &source[..15], "string", 13), (Ok(None), 0, 0)); + // A concatenation is no `string`. + let source: &[u8] = b"def f():\n R\"a\\nb\" u\"c\"\n"; + assert_eq!( + read(source, source, "concatenated_string", 13), + (Ok(None), 0, 0) + ); + } + } } diff --git a/big-code-analysis-ast/src/lang_helpers/ruby.rs b/big-code-analysis-ast/src/lang_helpers/ruby.rs index 9675215b5..9af10a2c7 100644 --- a/big-code-analysis-ast/src/lang_helpers/ruby.rs +++ b/big-code-analysis-ast/src/lang_helpers/ruby.rs @@ -10,9 +10,48 @@ //! 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_with_budget( + node: &Node<'_>, + code: &[u8], + budget: &B, +) -> Result { + let bytes = node_bytes(node, code); + let hashes = crate::documentation::byte_scan::position(bytes, |byte| byte != b'#', budget)? + .unwrap_or(bytes.len()); + if hashes == 0 { + return Ok(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 Ok(false); + }; + let mut found = false; + while let Some(byte) = identifier.first() { + budget.bytes(2)?; + if !byte.is_ascii_alphanumeric() && *byte != b'_' { + break; + } + found = true; + identifier = &identifier[1..]; + if identifier.first() == Some(&b'.') { + identifier = &identifier[1..]; + } + } + Ok(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 @@ -49,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, @@ -62,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 @@ -129,6 +178,27 @@ pub(crate) fn ruby_yard_reads<'a>( scope: &Node<'a>, ancestors: Ancestors<'a, '_>, ) -> bool { + yard_reads(needs, scope, ancestors, false) +} + +fn yard_reads<'a>( + needs: YardScope, + scope: &Node<'a>, + ancestors: Ancestors<'a, '_>, + source: bool, +) -> bool { + infallible(yard_reads_with_budget( + needs, scope, ancestors, source, &NoBudget, + )) +} + +pub(crate) fn yard_reads_with_budget<'a, B: WorkBudget>( + needs: YardScope, + scope: &Node<'a>, + ancestors: Ancestors<'a, '_>, + source: 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 @@ -139,48 +209,61 @@ pub(crate) fn ruby_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, - 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() { - // 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/lang_helpers/shdoc.rs b/big-code-analysis-ast/src/lang_helpers/shdoc.rs new file mode 100644 index 000000000..41e34768f --- /dev/null +++ b/big-code-analysis-ast/src/lang_helpers/shdoc.rs @@ -0,0 +1,303 @@ +//! shdoc source rules for Bash: which function a tagged comment run +//! documents, which rows of a run are not prose, and which nodes of the +//! grammar stand where Bash reads a comment or a command. Only the +//! documentation collector reads this module; no role row and no legacy +//! `Checker` answer does. + +pub(crate) mod scan; + +use crate::documentation::budget::WorkBudget; +use crate::documentation::streaming::positional::{ + OpenerReason, RunContext, RunSelection, SourceRun, +}; +use crate::documentation::{SourceContext, SourceError, UnresolvedReason}; +use crate::lang_helpers::doc_comment::node_bytes; +use crate::lang_helpers::doc_text::{ + ShdocRow, shdoc_row_with_budget, shellcheck_directive_with_budget, +}; +use crate::node::Node; +use scan::{Place, Scan}; + +/// A function definition, in either spelling. +pub(crate) fn target(node: &Node<'_>) -> bool { + crate::roles::bash::func_opener::OWNERS.contains(&node.kind_id()) +} + +/// A row that is not prose: the `#!` row at the first byte of the source, +/// or a ShellCheck directive. `comment` holds the bytes of `node`. +pub(crate) fn directive_with_budget( + node: &Node<'_>, + comment: &[u8], + budget: &B, +) -> Result { + Ok((node.start_byte() == 0 && comment.starts_with(b"#!")) + || shellcheck_directive_with_budget(comment, budget)?) +} + +/// What shdoc reads in the rows of a run, its directive rows left out: the +/// class of the first row, whether a row is a tag line, and whether one +/// is a file tag line. +#[derive(Default)] +struct RunRows { + opening: Option, + tagged: bool, + file: bool, +} + +fn run_rows(run: &RunContext<'_, '_>, budget: &B) -> Result { + let mut rows = RunRows::default(); + for member in run.members { + budget.step()?; + let comment = node_bytes(member, run.code); + if !directive_with_budget(member, comment, budget)? { + let row = shdoc_row_with_budget(comment, budget)?; + rows.opening.get_or_insert(row); + rows.tagged |= row != ShdocRow::Text; + rows.file |= row == ShdocRow::FileTag; + } + } + Ok(rows) +} + +/// What the run `run` is, read as shdoc reads its rows: nothing, the +/// documentation of the function directly below it, or a document whose +/// owner this profile does not decide yet. Whether its rows and the +/// function stand where Bash reads them is `Reading::confirm`'s question. +pub(crate) fn opener_with_budget( + run: &RunContext<'_, '_>, + budget: &B, +) -> Result, B::Error> { + let rows = run_rows(run, budget)?; + if !rows.tagged { + return Ok(None); + } + if rows.file || rows.opening == Some(ShdocRow::Text) { + return Ok(Some(OpenerReason::Explicit)); + } + Ok(match &run.below { + Some(below) if target(below) => Some(OpenerReason::FollowingItem), + // A node with a syntax error may be a function the grammar could + // not read (`f() for …`): the document stays, without an owner. + Some(below) if below.has_error() || below.is_missing() => Some(OpenerReason::Explicit), + _ => None, + }) +} + +/// What the walk of the collector reads of a Bash source. The scan runs +/// with the walk: before the walk reads a node, the scan has read every +/// byte before it, and it says what Bash reads at the node's first byte. +/// The walk visits nodes in source order, so the scan reads each byte once. +pub(crate) struct Reading<'s> { + scan: Option>, + /// What the scan reads at the first byte of the node the walk entered. + here: Place, + /// The comment nodes entered since the last node of another kind, by + /// first byte: the members of the run that the last of them ends. + rows: Vec<(usize, Place)>, +} + +impl Default for Reading<'_> { + fn default() -> Self { + Self { + scan: None, + here: Place::Unknown, + rows: Vec::new(), + } + } +} + +impl<'s> Reading<'s> { + /// The scan of `source`, at its first byte, over its included bytes. + fn open( + source: &SourceContext<'s>, + budget: &B, + ) -> Result, SourceError> { + let code = source.bytes(); + let mut ranges: Vec> = Vec::new(); + match source.pieces_with_budget(0..code.len(), budget) { + Ok(included) => { + for piece in included.pieces() { + budget.step().map_err(Into::into)?; + match ranges.last_mut() { + Some(last) if last.end == piece.range().start => { + last.end = piece.range().end; + } + _ => ranges.push(piece.range()), + } + } + } + Err(SourceError::Cancelled) => return Err(SourceError::Cancelled), + // An empty source, or one without an included byte. + Err(_) => {} + } + Ok(Scan::new(code, ranges)) + } + + /// Takes the next node of the walk, in source order. The first call + /// starts the scan of `source`. + pub(crate) fn enter( + &mut self, + source: &SourceContext<'s>, + node: &Node<'_>, + comment: bool, + budget: &B, + ) -> Result<(), SourceError> { + let scan = match &mut self.scan { + Some(scan) => scan, + unopened => unopened.insert(Self::open(source, budget)?), + }; + let start = node.start_byte(); + if comment { + scan.read(start, budget).map_err(Into::into)?; + } else { + scan.advance(start, budget).map_err(Into::into)?; + } + if node.is_error() || node.is_missing() { + // A recovery node may stand at the opener of a literal. + scan.stop_at(start); + } + self.here = scan.place(start); + if comment { + // The node is a row only where the scan reads the same comment. + if matches!(self.here, Place::Comment { end, .. } if end != node.end_byte()) { + self.here = Place::Text; + } + self.rows.push((start, self.here)); + } else { + self.rows.clear(); + } + Ok(()) + } + + /// Leaves a node. The answer is why the end of a function is not + /// confirmed: at the byte where the grammar ends it, the scan stands + /// inside a string, a text or a form, or it stopped before that byte. + pub(crate) fn leave( + &mut self, + node: &Node<'_>, + budget: &B, + ) -> Result, B::Error> { + let Some(scan) = self.scan.as_mut() else { + return Ok(None); + }; + scan.advance(node.end_byte(), budget)?; + let open = target(node) && scan.inside(node.end_byte()); + Ok(open.then(|| scan.stopped().unwrap_or(UnresolvedReason::GrammarBoundary))) + } + + /// Whether the node the walk entered stands inside a comment, a quoted + /// string or the text of a here-document: it is not read. + pub(crate) fn text(&self) -> bool { + self.here == Place::Text + } + + /// Whether the comment node the walk entered is no comment for Bash. + pub(crate) fn unread(&self) -> bool { + matches!(self.here, Place::Text | Place::Form | Place::Code { .. }) + } + + /// Whether the node the walk entered stands at or behind the place + /// where the scan stopped. + pub(crate) fn withheld(&self) -> bool { + matches!(self.here, Place::Behind(_)) + } + + /// Whether a function the walk entered waits for a later decision: it + /// stands in a substitution or another form that the scan read on its + /// row, in back quotes, behind the place where the scan stopped, or + /// where Bash starts no word. + pub(crate) fn waits(&self) -> bool { + matches!( + self.here, + Place::Form | Place::Unknown | Place::Behind(_) | Place::Code { word: false, .. } + ) + } + + /// What the scan read at the comment node that starts at `start`. + fn row(&self, start: usize, budget: &B) -> Result { + let at = crate::documentation::budget::binary_search_end( + self.rows.len(), + |at| self.rows[at].0 < start, + budget, + )?; + Ok(match self.rows.get(at) { + Some((found, place)) if *found == start => *place, + _ => Place::Text, + }) + } + + /// Keeps the members of `run` that are comments for Bash. The answer + /// is whether a row of the document does not open a line of its own + /// or stands behind excluded bytes; `None`: a member among the rows of + /// the document is no comment for Bash. + fn rows( + &self, + run: &mut SourceRun<'s>, + budget: &B, + ) -> Result, B::Error> { + let (mut started, mut loose) = (false, false); + let mut members = Vec::new(); + for member in std::mem::take(&mut run.members) { + budget.step()?; + started |= member.selected; + match self.row(member.node.node().start_byte(), budget)? { + Place::Comment { line, .. } => loose |= member.selected && !line, + Place::Unknown => loose |= member.selected, + _ if started => return Ok(None), + _ => continue, + } + members.push(member); + } + run.members = members; + Ok(Some(loose)) + } + + /// Whether Bash starts a command line at `start`. Behind the place + /// where the scan stopped the answer is yes: there the function's own + /// qualification says that its reading is not confirmed. + fn opens_line(&mut self, start: usize, budget: &B) -> Result { + let Some(scan) = self.scan.as_mut() else { + return Ok(true); + }; + scan.advance(start, budget)?; + let (word, line) = (true, true); + let place = scan.place(start); + Ok(matches!(place, Place::Behind(_)) || place == Place::Code { word, line }) + } + + /// Confirms the run that the shared path decided at the comment node + /// the walk entered. A member that is no comment for Bash is left + /// out; if it stands among the rows of the document, the run is not + /// read. If a row of the document or the function does not open a + /// line of its own, or stands behind excluded bytes, the run is not + /// selected. + pub(crate) fn confirm( + &mut self, + mut run: SourceRun<'s>, + retain_unbound: bool, + budget: &B, + ) -> Result>, B::Error> { + if self.scan.is_none() { + return Ok(Some(run)); + } + let Some(mut loose) = self.rows(&mut run, budget)? else { + return Ok(None); + }; + if let (RunSelection::Opener(OpenerReason::FollowingItem), Some(function)) = + (run.selection, run.target) + { + loose |= !self.opens_line(function.node().start_byte(), budget)?; + } + if loose { + if !retain_unbound { + return Ok(None); + } + // Without a selected member the run gives no document; its + // rows are candidates. + for member in &mut run.members { + member.selected = false; + } + } + Ok(Some(run)) + } +} diff --git a/big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs b/big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs new file mode 100644 index 000000000..b45299fc0 --- /dev/null +++ b/big-code-analysis-ast/src/lang_helpers/shdoc/scan.rs @@ -0,0 +1,727 @@ +//! One forward scan of a Bash source by Bash's quoting rules. For the +//! byte a node of the grammar starts at, it says what Bash reads there: a +//! command, a comment, a quoted string, the text of a here-document, or a +//! form that the scan read on its row. Where no rule below reads a byte, +//! the scan stops, and nothing at or behind that place is read. +//! +//! The rules are those of Bash's lexer. Over rows the scan reads `'…'`, +//! `"…"`, `$'…'`, `$"…"`, back quotes and here-document texts. Every +//! other form that can hold a line end is read only where it closes on +//! its row. Bash decides some forms by the state of its parser, which +//! the scan does not know (`((`, a subscript, an extended pattern, the +//! word after `=~`): those are read only where the form and the plain +//! commands that the same bytes would be for Bash leave the same state. + +mod forms; + +use std::collections::VecDeque; +use std::ops::Range; + +use crate::documentation::UnresolvedReason; +use crate::documentation::budget::WorkBudget; + +// The work of the scan: the bytes it read, and the entries it pushed on +// its stack of open forms and on its queue of here-documents. +crate::observation::counter!(bytes_scanned, cfg(test)); +crate::observation::counter!(forms_opened, cfg(test)); + +const LF: u8 = b'\n'; + +fn blank(byte: u8) -> bool { + matches!(byte, b' ' | b'\t') +} + +/// A byte that ends a word for Bash. +fn breaks(byte: u8) -> bool { + blank(byte) || matches!(byte, LF | b'|' | b'&' | b';' | b'(' | b')' | b'<' | b'>') +} + +fn name(byte: u8, first: bool) -> bool { + byte == b'_' || byte.is_ascii_alphabetic() || (!first && byte.is_ascii_digit()) +} + +/// What the scan reads at a byte. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Place { + /// At command level. `word`: a word starts at the byte. `line`: only + /// blanks stand before it on its line. + Code { word: bool, line: bool }, + /// The `#` of a comment that the scan read to `end`. + Comment { end: usize, line: bool }, + /// Inside a comment, a quoted string or the text of a here-document. + Text, + /// Inside a form that the scan read on its row, or inside back quotes. + Form, + /// Behind an excluded byte, before the state is known again. + Unknown, + /// At or behind the place where the scan stopped. + Behind(UnresolvedReason), +} + +/// How far the word at command level is read. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Word { + /// No word is being read: one may start. + None, + /// A word that is a name so far: `[` behind it opens a subscript. + Name, + Other, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Code, + Single, + Ansi, + Double, + /// Back quotes, and whether they stand inside a double-quoted string. + Back(bool), + Text, +} + +/// What the last byte at command level can still combine with. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Prev { + None, + Dollar, + Less, + LessLess, + Greater, + Amp, + AmpGreater, + Bar, + Semi, + SemiSemi, + /// `(` read as an operator: a second one may open `((`. + Open, + /// `=` behind a byte of its word: `(` opens a compound assignment. + Equal, + /// One of `@ ? * + !`: `(` opens an extended pattern. + Pattern, + /// `=` where a word starts, then `=~`, then the blanks behind it. + EqualFirst, + Tilde, + Regexp, + /// `<&` or `>&`: a `-` behind it is a token of its own. + Dup, + /// The `)` of an extended pattern or of a compound assignment: the + /// word goes on for one reading of Bash, a word starts for the other. + Shut, + /// `<<` or `<<-`: the delimiter word follows. + Operator(bool), +} + +/// A form that must close on its row. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Frame { + /// `$( )`, `<( )`, `>( )`: Bash's reader of a command substitution. + Command, + /// `$(( ))`: parentheses and quotes only. + Balanced, + /// A parenthesis that is a form for one reading of Bash and commands + /// for another. + Guarded, + Subscript, + Brace, + Bracket, + Single, + /// `'…'` in `${ }` in a double-quoted string: a quoted string for + /// Bash and plain bytes for its POSIX mode. + Plain, + Ansi, + Double, + Back, +} + +impl Frame { + /// The byte that closes the form. + fn closer(self) -> u8 { + match self { + Self::Command | Self::Balanced | Self::Guarded => b')', + Self::Subscript | Self::Bracket => b']', + Self::Brace => b'}', + Self::Single | Self::Plain | Self::Ansi => b'\'', + Self::Double => b'"', + Self::Back => b'`', + } + } + + /// Whether Bash's command reader reads the bytes of the form for one + /// of its readings: where a word starts matters in it. + fn commands(self) -> bool { + matches!(self, Self::Command | Self::Guarded | Self::Subscript) + } +} + +/// An open form: whether a word is being read in it, and whether it +/// stands in a double-quoted string as Bash's reader of `${ }` sees it. +#[derive(Clone, Copy)] +struct Entry { + frame: Frame, + word: bool, + quoted: bool, +} + +struct Heredoc { + word: Vec, + tabs: bool, + quoted: bool, +} + +/// The text of a here-document, read a byte at a time: how much of the +/// delimiter the bytes of the line match so far. +struct Text { + heredoc: Heredoc, + matched: Option, + start: bool, + slash: bool, +} + +impl Text { + fn new(heredoc: Heredoc) -> Self { + Self { + heredoc, + matched: Some(0), + start: true, + slash: false, + } + } + + fn feed(&mut self, byte: u8) { + if self.start && self.heredoc.tabs && byte == b'\t' { + return; + } + self.start = false; + self.matched = self + .matched + .filter(|at| self.heredoc.word.get(*at) == Some(&byte)) + .map(|at| at + 1); + } +} + +#[allow(clippy::struct_excessive_bools)] +pub(crate) struct Scan<'s> { + code: &'s [u8], + ranges: Vec>, + range: usize, + /// The next byte to read, and the end of the included bytes it lies in. + at: usize, + end: usize, + /// Behind an excluded byte the state is unknown until an unescaped + /// line feed that the post-gap reading reaches at command level: + /// the run of backslashes since the gap and whether a byte precedes it. + unknown: Option<(usize, usize, bool)>, + opened_tentative: bool, + mode: Mode, + word: Word, + /// A compound assignment is open: `[` where a word starts opens a + /// subscript, and its `)` ends more than a subshell. + array: bool, + dollar: bool, + line: bool, + prev: Prev, + waiting: VecDeque, + text: Option, + /// The open forms of the form being read on its row, and how many of + /// them are guarded parentheses. + stack: Vec, + guards: usize, + balanced: usize, + /// The last thing read that is more than one byte, and what a byte + /// inside it is. + unit: (Range, Place), + stop: Option<(usize, UnresolvedReason)>, +} + +type Read = Result, E>; + +impl<'s> Scan<'s> { + /// `ranges` are the included bytes of `code`, in order, without gaps + /// inside a range. + pub(crate) fn new(code: &'s [u8], ranges: Vec>) -> Self { + let first = ranges.first().cloned().unwrap_or(code.len()..code.len()); + Self { + code, + ranges, + range: 0, + at: first.start, + end: first.end, + unknown: (first.start > 0 || first.is_empty() && !code.is_empty()) + .then_some((0, 0, false)), + opened_tentative: false, + mode: Mode::Code, + word: Word::None, + array: false, + dollar: false, + line: true, + prev: Prev::None, + waiting: VecDeque::new(), + text: None, + stack: Vec::new(), + guards: 0, + balanced: 0, + unit: (0..0, Place::Text), + stop: None, + } + } + + /// Reads every byte before `to`. + pub(crate) fn advance(&mut self, to: usize, budget: &B) -> Result<(), B::Error> { + while self.at < to && self.at < self.end && self.stop.is_none() { + self.step(budget)?; + } + Ok(()) + } + + /// Reads the thing that starts at `at`, if the scan stands there. + pub(crate) fn read(&mut self, at: usize, budget: &B) -> Result<(), B::Error> { + self.advance(at, budget)?; + if self.at == at && self.at < self.end && self.stop.is_none() { + self.step(budget)?; + } + Ok(()) + } + + /// What the scan reads at `at`. `at` is not before the byte of the + /// last answer: the scan does not go back. + pub(crate) fn place(&self, at: usize) -> Place { + match (self.stop, self.unknown) { + (Some((stop, reason)), _) if at >= stop => Place::Behind(reason), + (_, Some((from, ..))) if at >= from => Place::Unknown, + _ if at < self.at && self.unit.0.contains(&at) => match self.unit.1 { + Place::Comment { .. } if at != self.unit.0.start => Place::Text, + inside => inside, + }, + _ => match (self.mode, self.prev) { + (Mode::Code, Prev::Operator(_) | Prev::Tilde | Prev::Regexp) + | (Mode::Back(_), _) => Place::Form, + (Mode::Code, _) => Place::Code { + word: self.word == Word::None, + line: self.line, + }, + _ => Place::Text, + }, + } + } + + /// Whether the scan, with every byte before `at` read, stands inside + /// a string, a text or a form at `at`. + pub(crate) fn inside(&self, at: usize) -> bool { + self.unknown.is_none() && (self.at != at || self.mode != Mode::Code) + } + + pub(crate) fn stopped(&self) -> Option { + self.stop.map(|(_, reason)| reason) + } + + /// Stops the scan at `at`, where the grammar could not read the + /// source: what it reads from there on is no ground for a rule. + pub(crate) fn stop_at(&mut self, at: usize) { + self.stop + .get_or_insert((at, UnresolvedReason::GrammarBoundary)); + } + + fn step(&mut self, budget: &B) -> Result<(), B::Error> { + let at = self.at; + let next = match (self.unknown.is_some(), self.mode) { + (true, _) => self.resume(at, budget)?, + (_, Mode::Code) => self.command(at, budget)?, + (_, Mode::Text) => self.text_byte(at, budget)?, + (_, Mode::Double) => self.double(at, budget)?, + _ => self.literal(at, budget)?, + }; + if let Some(next) = next { + self.at = next.min(self.end); + if self.at == self.end { + self.leave_range(); + } + } + Ok(()) + } + + /// The included bytes end at `self.end`. If more follow behind + /// excluded ones, the state is unknown there; if something is open, + /// it is never known again. + fn leave_range(&mut self) { + if self.end == self.code.len() { + return; + } + let waits = matches!(self.prev, Prev::LessLess | Prev::Operator(_)); + if self.unknown.is_none() + && (self.mode != Mode::Code || !self.waiting.is_empty() || self.array || waits) + { + self.stop = Some((self.end, UnresolvedReason::ExcludedGap)); + return; + } + self.unknown = Some((self.unknown.map_or(self.end, |(from, ..)| from), 0, false)); + self.opened_tentative = false; + (self.mode, self.word, self.prev) = (Mode::Code, Word::None, Prev::None); + (self.array, self.dollar, self.line) = (false, false, true); + self.range += 1; + let next = self.ranges.get(self.range).cloned(); + let next = next.unwrap_or(self.code.len()..self.code.len()); + (self.at, self.end) = (next.start, next.end); + } + + /// Tentatively reads the included bytes after a gap as commands. + /// A construct opened in those bytes prevents resumption at its + /// first line feed. Only a proven, unescaped line feed at command level can + /// restore the state; an open construct there stops with ExcludedGap. + fn resume(&mut self, at: usize, budget: &B) -> Read { + // bca: suppress(abc, cognitive, cyclomatic, halstead) -- recovery must check every + // construct opened while tentatively reading the gap before accepting a line feed. + let Some((from, slashes, seen)) = self.unknown else { + return Ok(Some(at + 1)); + }; + self.unknown = None; + let byte = self.code[at]; + if !seen && byte == b'\\' { + self.stop = Some((at, UnresolvedReason::ExcludedGap)); + return Ok(None); + } + let in_comment = matches!(self.unit.1, Place::Comment { end, .. } if at < end); + let was_open = self.mode != Mode::Code + || !self.waiting.is_empty() + || self.array + || !matches!(self.prev, Prev::None) + || !self.stack.is_empty(); + self.unknown = Some((from, slashes, seen)); + let next = self.command(at, budget)?; + self.unknown = None; + self.opened_tentative |= self.mode != Mode::Code + || !self.waiting.is_empty() + || self.array + || !self.stack.is_empty() + || matches!(self.prev, Prev::LessLess | Prev::Operator(_)); + if self.stop.is_some() || next.is_none() || self.opened_tentative { + self.stop = Some((at, UnresolvedReason::ExcludedGap)); + return Ok(None); + } + if byte == LF && seen && slashes.is_multiple_of(2) { + if was_open + || self.mode != Mode::Code + || !self.waiting.is_empty() + || self.array + || !matches!(self.prev, Prev::None) + || !self.stack.is_empty() + { + self.stop = Some((at, UnresolvedReason::ExcludedGap)); + return Ok(None); + } + self.unit = (from..at + 1, Place::Unknown); + self.opened_tentative = false; + } else { + let (slashes, seen) = if in_comment { + (0, seen) + } else if byte == b'\\' { + (slashes + 1, seen) + } else { + (0, true) + }; + self.unknown = Some((from, slashes, seen)); + } + Ok(next) + } + + /// Reads the byte at `at`: one charge. A NUL byte is read by no rule. + fn take(&mut self, at: usize, budget: &B) -> Result, B::Error> { + budget.bytes(1)?; + bytes_scanned::record(); + let byte = self.code[at]; + if byte == 0 { + self.stop = Some((at, UnresolvedReason::GrammarBoundary)); + return Ok(None); + } + Ok(Some(byte)) + } + + /// Looks at the byte at `at` without reading it, if it is included. + fn peek(&self, at: usize) -> Option { + (at < self.end).then(|| self.code[at]) + } + + fn halt(&mut self, at: usize) -> Option { + self.stop = Some((at, UnresolvedReason::GrammarBoundary)); + None + } + + /// A thing that must end on its row met the end of the included + /// bytes: behind excluded bytes nobody knows whether it ends. + fn cut(&mut self, opener: usize) -> Option { + if self.end < self.code.len() { + self.stop = Some((self.end, UnresolvedReason::ExcludedGap)); + None + } else { + self.halt(opener) + } + } + + /// A backslash at `at` and the byte it takes. + fn escaped(&mut self, at: usize, inside: Place, budget: &B) -> Read { + if at + 1 < self.end && self.take(at + 1, budget)?.is_none() { + return Ok(None); + } + self.unit = (at..at + 2, inside); + Ok(Some(at + 2)) + } + + /// One byte of `'…'`, of `$'…'` or of back quotes: nothing nests. + fn literal(&mut self, at: usize, budget: &B) -> Read { + let Some(byte) = self.take(at, budget)? else { + return Ok(None); + }; + match (self.mode, byte) { + (Mode::Back(true), b'`') => self.mode = Mode::Double, + (Mode::Single | Mode::Ansi, b'\'') | (Mode::Back(false), b'`') => { + self.mode = Mode::Code; + } + (Mode::Back(_), b'\\') => return self.escaped(at, Place::Form, budget), + (Mode::Ansi, b'\\') => return self.escaped(at, Place::Text, budget), + _ => {} + } + Ok(Some(at + 1)) + } + + /// One byte of a double-quoted string. + fn double(&mut self, at: usize, budget: &B) -> Read { + let Some(byte) = self.take(at, budget)? else { + return Ok(None); + }; + let dollar = std::mem::take(&mut self.dollar); + match byte { + b'"' => self.mode = Mode::Code, + b'`' => self.mode = Mode::Back(true), + b'$' => self.dollar = !dollar, + b'\\' => { + // A backslash and line feed are no bytes for Bash: `$` and + // `(` around them are `$(`. + self.dollar = dollar && self.peek(at + 1) == Some(LF); + return self.escaped(at, Place::Text, budget); + } + b'(' | b'{' | b'[' if dollar => { + let frame = self.dollar_frame(byte, at); + return self.form(at, frame, budget); + } + _ => {} + } + Ok(Some(at + 1)) + } + + fn dollar_frame(&self, byte: u8, at: usize) -> Frame { + match byte { + b'(' if self.peek(at + 1) == Some(b'(') => Frame::Balanced, + b'(' => Frame::Command, + b'{' => Frame::Brace, + _ => Frame::Bracket, + } + } + + /// One thing at command level. + fn command(&mut self, at: usize, budget: &B) -> Read { + let Some(byte) = self.take(at, budget)? else { + return Ok(None); + }; + if byte == b'\\' && self.peek(at + 1) == Some(LF) { + // The pair is no byte for Bash: what stands around it still + // combines, and the row below goes on with the line. It opens + // a line of its own only if blanks alone stand before the pair. + return self.escaped(at, Place::Text, budget); + } + if self.prev == Prev::LessLess && !matches!(byte, b'<' | b'-') { + // `<<` is the whole operator: the byte is the first behind it. + self.prev = Prev::Operator(false); + } + self.combined(at, byte, budget) + } + + /// The byte at `at` behind the byte it may combine with: the next + /// byte of an operator, the opener of a form, or a byte as any other. + fn combined(&mut self, at: usize, byte: u8, budget: &B) -> Read { + // bca: suppress(halstead) -- Bash's operators of two and three bytes, one arm per pair. + self.prev = match (self.prev, byte) { + (Prev::Less, b'<') => Prev::LessLess, + (Prev::LessLess, b'-') => Prev::Operator(true), + (Prev::Amp, b'>') => Prev::AmpGreater, + (Prev::Semi, b';') => Prev::SemiSemi, + (Prev::EqualFirst, b'~') => Prev::Tilde, + (Prev::Less | Prev::Greater, b'&') | (Prev::Dup, b' ' | b'\t') => Prev::Dup, + (Prev::Operator(tabs), b' ' | b'\t') => Prev::Operator(tabs), + // The last byte of an operator, or of `$$`. + (Prev::Less | Prev::Greater | Prev::AmpGreater, b'>') + | (Prev::LessLess, b'<') + | (Prev::Greater | Prev::Bar, b'|') + | (Prev::Amp | Prev::Bar | Prev::Semi | Prev::SemiSemi, b'&') + | (Prev::Dollar, b'$') => Prev::None, + (Prev::Tilde | Prev::Regexp, b' ' | b'\t') => { + self.word = Word::None; + Prev::Regexp + } + (Prev::Dup, b'-') => { + self.word = Word::None; + Prev::None + } + (Prev::Dollar, b'\'' | b'"') => { + self.mode = if byte == b'"' { + Mode::Double + } else { + Mode::Ansi + }; + Prev::None + } + (Prev::Equal, b'(') => { + (self.array, self.word) = (true, Word::None); + Prev::None + } + _ => return self.opened(at, byte, budget), + }; + Ok(Some(at + 1)) + } + + /// The byte at `at` where it opens a form behind the byte before it, + /// or stands where no rule reads it; else a byte as any other. + fn opened(&mut self, at: usize, byte: u8, budget: &B) -> Read { + match (std::mem::replace(&mut self.prev, Prev::None), byte) { + (Prev::Shut, b'#') => Ok(self.halt(at)), + (Prev::Operator(tabs), _) => self.delimiter(at, byte, tabs, budget), + (Prev::Tilde, b'(' | b'|') => self.pattern(at, byte, budget), + (Prev::Regexp, _) if !matches!(byte, LF | b'#' | b';' | b'&' | b')' | b'<' | b'>') => { + self.pattern(at, byte, budget) + } + (Prev::Less | Prev::Greater, b'(') => self.word_form(at, Frame::Command, budget), + (Prev::Dollar, b'(' | b'{' | b'[') => { + let frame = self.dollar_frame(byte, at); + self.word_form(at, frame, budget) + } + (Prev::Open, b'(') => self.arithmetic(at, budget), + (Prev::Pattern, b'(') => { + let end = self.form(at, Frame::Guarded, budget)?; + (self.word, self.prev) = (Word::Other, Prev::Shut); + Ok(end) + } + _ => self.plain(at, byte, budget), + } + } + + /// The byte at `at`, behind nothing it combines with. + fn plain(&mut self, at: usize, byte: u8, budget: &B) -> Read { + // bca: suppress(cyclomatic, halstead) -- one arm per class of byte at command level. + let (word, line) = (self.word, self.line); + (self.word, self.line) = (Word::None, false); + match byte { + LF => match self.waiting.pop_front() { + Some(heredoc) => (self.mode, self.text) = (Mode::Text, Some(Text::new(heredoc))), + None => self.line = true, + }, + b' ' | b'\t' => self.line = line, + b'#' if word == Word::None => return self.comment(at, line, budget), + b'\\' => { + self.word = Word::Other; + return self.escaped(at, Place::Text, budget); + } + b'<' => self.prev = Prev::Less, + b'>' => self.prev = Prev::Greater, + b'&' => self.prev = Prev::Amp, + b'|' => self.prev = Prev::Bar, + b';' => self.prev = Prev::Semi, + b'(' => self.prev = Prev::Open, + b')' if self.array => (self.array, self.prev) = (false, Prev::Shut), + b')' => {} + b'\'' | b'"' | b'`' => { + self.word = Word::Other; + self.mode = match byte { + b'\'' => Mode::Single, + b'"' => Mode::Double, + _ => Mode::Back(false), + }; + } + b'[' if word == Word::Name || (word == Word::None && self.array) => { + return self.word_form(at, Frame::Subscript, budget); + } + _ => { + self.word = match word { + Word::None if name(byte, true) => Word::Name, + Word::Name if name(byte, false) => Word::Name, + _ => Word::Other, + }; + self.prev = match byte { + b'=' if word == Word::None => Prev::EqualFirst, + b'=' => Prev::Equal, + b'$' => Prev::Dollar, + b'@' | b'?' | b'*' | b'+' | b'!' => Prev::Pattern, + _ => Prev::None, + }; + } + } + Ok(Some(at + 1)) + } + + /// A form that is part of a word. + fn word_form(&mut self, at: usize, frame: Frame, budget: &B) -> Read { + let end = self.form(at, frame, budget)?; + (self.word, self.line, self.prev) = (Word::Other, false, Prev::None); + Ok(end) + } + + /// A comment from the `#` at `at` to the end of its row. + fn comment(&mut self, at: usize, line: bool, budget: &B) -> Read { + let mut end = at + 1; + while self.peek(end).is_some_and(|byte| byte != LF) { + if self.take(end, budget)?.is_none() { + return Ok(None); + } + end += 1; + } + self.unit = (at..end, Place::Comment { end, line }); + Ok(Some(end)) + } + + /// `((`: the second parenthesis is at `at`. Read only where `)` + /// follows its pair. Where none does, Bash reads the bytes again as + /// nested subshells, and no rule here says what its reader holds then. + fn arithmetic(&mut self, at: usize, budget: &B) -> Read { + let Some(end) = self.form(at, Frame::Guarded, budget)? else { + return Ok(None); + }; + if self.peek(end) != Some(b')') { + return Ok(self.halt(at)); + } + if self.take(end, budget)?.is_none() { + return Ok(None); + } + self.unit.0.end = end + 1; + (self.word, self.prev) = (Word::None, Prev::None); + Ok(Some(end + 1)) + } + + /// One byte of the text of a here-document. For an unquoted + /// delimiter a backslash and line feed are no bytes of the line. + fn text_byte(&mut self, at: usize, budget: &B) -> Read { + let Some(byte) = self.take(at, budget)? else { + return Ok(None); + }; + let Some(text) = self.text.as_mut() else { + return Ok(Some(at + 1)); + }; + let slash = std::mem::take(&mut text.slash); + match (slash, byte) { + (true, LF) => {} + (true, _) => { + text.feed(b'\\'); + text.feed(byte); + } + (false, b'\\') if !text.heredoc.quoted => text.slash = true, + (false, LF) if text.matched != Some(text.heredoc.word.len()) => { + (text.matched, text.start) = (Some(0), true); + } + (false, LF) => { + self.text = self.waiting.pop_front().map(Text::new); + if self.text.is_none() { + (self.mode, self.prev) = (Mode::Code, Prev::None); + (self.word, self.line) = (Word::None, true); + } + } + (false, _) => text.feed(byte), + } + Ok(Some(at + 1)) + } +} diff --git a/big-code-analysis-ast/src/lang_helpers/shdoc/scan/forms.rs b/big-code-analysis-ast/src/lang_helpers/shdoc/scan/forms.rs new file mode 100644 index 000000000..794f48264 --- /dev/null +++ b/big-code-analysis-ast/src/lang_helpers/shdoc/scan/forms.rs @@ -0,0 +1,429 @@ +//! The forms that the scan reads only where they close on their row, the +//! word behind `=~` and the delimiter word of a here-document. + +use super::{ + Entry, Frame, Heredoc, LF, Mode, Place, Prev, Read, Scan, Word, breaks, forms_opened, name, +}; +use crate::documentation::budget::WorkBudget; + +/// What the byte before the one read can still combine with. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Before { + Other, + Dollar, + /// `<` or `>`: a `(` behind it opens a process substitution. + Angle, + /// `<&` or `>&`, possibly followed by blanks: `-` ends the token. + Dup, +} + +/// What one byte does to the innermost open form. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Step { + /// A byte of a word. + Word(Before), + /// A byte that ends a word for the command reading. + Break(Before), + /// A backslash: it takes the byte behind it. + Escape, + /// `<<<`: two more bytes of the operator follow. + Here, + Open(Frame), + Close, + /// No rule reads the form. + Halt, +} + +/// The quoted string that `byte` opens where quotes nest. `plain`: in +/// `${ }` in a double-quoted string, where a single quote is a quote for +/// Bash and a byte for its POSIX mode. +fn quote(byte: u8, dollar: bool, plain: bool) -> Option { + match byte { + b'\'' if plain => Some(Frame::Plain), + b'\'' if dollar => Some(Frame::Ansi), + b'\'' => Some(Frame::Single), + b'"' => Some(Frame::Double), + b'`' => Some(Frame::Back), + _ => None, + } +} + +fn halt_if(halts: bool) -> Step { + if halts { + Step::Halt + } else { + Step::Word(Before::Other) + } +} + +impl Scan<'_> { + /// One entry of the stack for a form that opens: one charge. + fn push( + &mut self, + frame: Frame, + quoted: bool, + budget: &B, + ) -> Result<(), B::Error> { + budget.step()?; + forms_opened::record(); + self.guards += usize::from(frame == Frame::Guarded); + self.balanced += usize::from(frame == Frame::Balanced); + self.stack.push(Entry { + frame, + word: !matches!(frame, Frame::Command | Frame::Guarded), + quoted: match frame { + Frame::Double => true, + Frame::Brace | Frame::Bracket => quoted, + _ => false, + }, + }); + Ok(()) + } + + /// The innermost form closes with `byte`. + fn pop(&mut self, byte: u8) { + if let Some(closed) = self.stack.pop() { + self.guards -= usize::from(closed.frame == Frame::Guarded); + self.balanced -= usize::from(closed.frame == Frame::Balanced); + } + if let Some(outer) = self.stack.last_mut() + && outer.frame.commands() + { + // Behind `)` a word starts for the command reading. + outer.word = byte != b')'; + } + } + + /// Reads the byte at `at` of the form or word that starts at `opener` + /// and must end on its row. `None`: the scan stopped. + fn on_row( + &mut self, + opener: usize, + at: usize, + budget: &B, + ) -> Result, B::Error> { + match self.peek(at) { + None => self.cut(opener), + Some(LF) => self.halt(opener), + Some(_) => return self.take(at, budget), + }; + Ok(None) + } + + /// Reads the form whose opening byte, at `at`, is read: to the byte + /// that closes it on its row. + pub(super) fn form( + &mut self, + at: usize, + frame: Frame, + budget: &B, + ) -> Read { + // bca: suppress(cognitive, halstead, nexits) -- one loop over one stack of open forms; + // each exit is a place where the scan stops, or a charge. + if self.unknown.is_some() { + self.opened_tentative = true; + } + self.stack.clear(); + self.guards = 0; + self.balanced = 0; + self.push(frame, self.mode == Mode::Double, budget)?; + let mut before = Before::Other; + let mut next = at + 1; + while let Some(&top) = self.stack.last() { + let Some(byte) = self.on_row(at, next, budget)? else { + return Ok(None); + }; + let step = self.in_form(next, top, byte, before); + let mut word = top.word; + before = Before::Other; + match step { + Step::Halt => return Ok(self.halt(at)), + Step::Word(then) => (word, before) = (true, then), + Step::Break(then) => (word, before) = (false, then), + Step::Escape | Step::Here => { + // The byte a backslash takes, or the rest of `<<<`. + let more = if step == Step::Here { 2 } else { 1 }; + for ahead in 1..=more { + if self.on_row(at, next + ahead, budget)?.is_none() { + return Ok(None); + } + } + (word, next) = (step == Step::Escape, next + more); + } + Step::Open(frame) => word |= !frame.commands(), + Step::Close => {} + } + next += 1; + if let Some(entry) = self.stack.last_mut() { + entry.word = word; + } + match step { + Step::Open(frame) => self.push(frame, top.quoted, budget)?, + Step::Close => self.pop(byte), + _ => {} + } + } + self.unit = (at..next, Place::Form); + Ok(Some(next)) + } + + /// What the byte at `at` does to the innermost open form `top`. + fn in_form(&self, at: usize, top: Entry, byte: u8, before: Before) -> Step { + // bca: suppress(cyclomatic, halstead, nexits) -- one arm per open form and class of byte. + let (dollar, guarded) = (before == Before::Dollar, self.guards > 0); + if byte == b'#' && self.balanced > 0 { + return Step::Halt; + } + if byte == top.frame.closer() { + return Step::Close; + } + if byte == b'\\' { + return match top.frame { + Frame::Single => Step::Word(Before::Other), + Frame::Plain | Frame::Bracket => Step::Halt, + _ => Step::Escape, + }; + } + let open = match top.frame { + Frame::Single | Frame::Ansi | Frame::Back => return Step::Word(Before::Other), + // Bytes that the reader of `${ }` does not read as plain. + Frame::Plain => return halt_if(b"\"`${}()<>".contains(&byte)), + Frame::Bracket => { + let parenthesis = guarded && matches!(byte, b'(' | b')'); + return halt_if(parenthesis || b"'\"$[`".contains(&byte)); + } + Frame::Double if byte == b'`' => Some(Frame::Back), + Frame::Double => None, + Frame::Brace => quote(byte, dollar, top.quoted), + _ => quote(byte, dollar, false), + }; + match (open, top.frame, byte) { + (Some(frame), ..) => Step::Open(frame), + (_, _, b'$') if !dollar => Step::Word(Before::Dollar), + (_, _, b'(' | b'{' | b'[') if dollar => Step::Open(self.dollar_frame(byte, at)), + (_, Frame::Balanced, b'(') => Step::Open(Frame::Balanced), + (_, Frame::Balanced | Frame::Double, _) => Step::Word(Before::Other), + (_, Frame::Brace, _) => Self::in_braces(byte, before, guarded), + _ => self.in_commands(at, top, byte, before), + } + } + + /// A byte of `${ }` that opens no string and no `$` form. + fn in_braces(byte: u8, before: Before, guarded: bool) -> Step { + match byte { + b'{' => Step::Halt, + b'(' if before == Before::Angle => Step::Open(Frame::Command), + b'(' | b')' if guarded => Step::Halt, + b'<' | b'>' if before != Before::Angle => Step::Word(Before::Angle), + _ => Step::Word(Before::Other), + } + } + + /// A byte of a form that Bash's command reader reads for one of its + /// readings, where the byte opens no string and no `$` form. + fn in_commands(&self, at: usize, top: Entry, byte: u8, before: Before) -> Step { + // bca: suppress(cyclomatic, halstead) -- one arm per class of byte of Bash's command reader. + let subscript = top.frame == Frame::Subscript; + match byte { + b'&' if before == Before::Angle => Step::Break(Before::Dup), + b' ' | b'\t' if before == Before::Dup => Step::Break(Before::Dup), + b'-' if before == Before::Dup => Step::Break(Before::Other), + b'[' if subscript => Step::Open(Frame::Subscript), + b'(' if !subscript => Step::Open(top.frame), + // In a subscript `<(` is a substitution; any other parenthesis + // is a byte for one reading and a token for the other. + b'(' if before == Before::Angle => Step::Open(Frame::Command), + b'(' => Step::Open(Frame::Guarded), + // `<` and `<<<` are operators; `<<` opens a here-document for + // the command reading. + b'<' => match (1..4) + .take_while(|ahead| self.peek(at + ahead) == Some(b'<')) + .count() + { + 0 => Step::Break(Before::Angle), + 2 => Step::Here, + _ => Step::Halt, + }, + // A comment for the command reading: it hides the close. + b'#' if !top.word => Step::Halt, + b'>' if before != Before::Angle => Step::Break(Before::Angle), + b' ' | b'\t' | b'|' | b'&' | b';' | b'>' | b')' => Step::Break(Before::Other), + b'c' | b'e' if !top.word && !subscript && self.case_word(at) => Step::Halt, + _ => Step::Word(Before::Other), + } + } + + /// Whether the word `case` or `esac` stands at `at`: Bash's reader of + /// a command substitution then counts no parenthesis. + fn case_word(&self, at: usize) -> bool { + let word = self.code.get(at..(at + 4).min(self.end)); + matches!(word, Some(b"case" | b"esac")) && self.peek(at + 4).is_none_or(breaks) + } + + /// What the byte at `at` of the word behind `=~` does. `named`: the + /// bytes of the word before it start with a name. + fn in_pattern(&self, at: usize, byte: u8, before: Before, named: bool) -> Step { + let dollar = before == Before::Dollar; + match byte { + b'\\' => Step::Escape, + // For the command reading `|` ends the word. + b'|' => Step::Halt, + b'(' | b'{' | b'[' if dollar => Step::Open(self.dollar_frame(byte, at)), + b'(' if before == Before::Angle => Step::Open(Frame::Command), + // A name, `=` and `(` are a compound assignment for the + // command reading. + b'(' if named && self.code[at - 1] == b'=' => Step::Halt, + b'(' => Step::Open(Frame::Guarded), + b'$' if !dollar => Step::Word(Before::Dollar), + b'<' | b'>' => Step::Word(Before::Angle), + _ => quote(byte, dollar, false).map_or(Step::Word(Before::Other), Step::Open), + } + } + + /// Reads the word behind `=~`, whose first byte, at `at`, is read: + /// to the blank or operator that ends it for both readings of Bash. + pub(super) fn pattern( + &mut self, + at: usize, + first: u8, + budget: &B, + ) -> Read { + // bca: suppress(cognitive, cyclomatic, halstead, nexits) -- one word read once for two + // readings of Bash; each exit is a place where the scan stops, or a charge. + if self.array { + return Ok(self.halt(at)); + } + let (mut next, mut byte) = (at, first); + let (mut word, mut named, mut before) = (false, false, Before::Other); + loop { + let step = self.in_pattern(next, byte, before, word && named); + before = Before::Other; + next += 1; + match step { + Step::Open(frame) => { + let Some(end) = self.form(next - 1, frame, budget)? else { + return Ok(None); + }; + if frame == Frame::Guarded && self.peek(end) == Some(b'#') { + return Ok(self.halt(end)); + } + (next, word, named) = (end, frame != Frame::Guarded, false); + } + Step::Escape => { + if self.on_row(at, next, budget)?.is_none() { + return Ok(None); + } + (next, word, named) = (next + 1, true, false); + } + Step::Word(then) => { + named = if word { named } else { name(byte, true) }; + (word, before) = (true, then); + } + _ => return Ok(self.halt(at)), + } + match self.peek(next) { + None if self.end < self.code.len() => return Ok(self.cut(at)), + None => break, + Some(b'<' | b'>') if self.peek(next + 1) == Some(b'(') => {} + Some(ahead) if breaks(ahead) && !matches!(ahead, b'(' | b'|') => break, + Some(_) => {} + } + match self.take(next, budget)? { + Some(read) => byte = read, + None => return Ok(None), + } + } + (self.word, self.line, self.prev) = (Word::Other, false, Prev::None); + self.unit = (at..next, Place::Form); + Ok(Some(next)) + } + + /// Reads a quoted part of the delimiter word that starts at `opener`, + /// from the quote at `at` to the quote that closes it, and adds its + /// bytes to `word`. The answer is the place of the closing quote. + fn delimiter_quote( + &mut self, + opener: usize, + at: usize, + word: &mut Vec, + budget: &B, + ) -> Read { + let quote = self.code[at]; + let mut next = at + 1; + loop { + let Some(byte) = self.on_row(opener, next, budget)? else { + return Ok(None); + }; + if byte == quote { + return Ok(Some(next)); + } + let expands = quote == b'"' && matches!(byte, b'\\' | b'$' | b'`'); + if expands || matches!(byte, 1 | 0x7f) { + return Ok(self.halt(opener)); + } + word.push(byte); + next += 1; + } + } + + /// Reads the delimiter word of a here-document, whose first byte, at + /// `at`, is read: its bytes after quote removal, and whether a part + /// of it was quoted. The scan stops at a word whose quote removal + /// needs a shell, and at the two bytes Bash keeps for its own quoting. + pub(super) fn delimiter( + &mut self, + at: usize, + first: u8, + tabs: bool, + budget: &B, + ) -> Read { + // bca: suppress(abc, cognitive, cyclomatic, halstead, nexits) -- one arm per spelling of + // a delimiter word; each exit is a place where the scan stops, or a charge. + let mut word = Vec::new(); + let (mut next, mut byte, mut quoted) = (at, first, false); + if breaks(first) || first == b'#' { + return Ok(self.halt(at)); + } + loop { + match byte { + 1 | 0x7f | b'`' => return Ok(self.halt(at)), + b'$' if matches!(self.peek(next + 1), Some(b'(' | b'{' | b'[' | b'\'' | b'"')) => { + return Ok(self.halt(at)); + } + b'\'' | b'"' => { + let Some(close) = self.delimiter_quote(at, next, &mut word, budget)? else { + return Ok(None); + }; + (next, quoted) = (close, true); + } + b'\\' => match self.on_row(at, next + 1, budget)? { + None => return Ok(None), + Some(1 | 0x7f) => return Ok(self.halt(at)), + Some(taken) => { + word.push(taken); + (next, quoted) = (next + 1, true); + } + }, + _ => word.push(byte), + } + next += 1; + match self.peek(next) { + None if self.end < self.code.len() => return Ok(self.cut(at)), + Some(b'(') => return Ok(self.halt(at)), + Some(ahead) if !breaks(ahead) => {} + _ => break, + } + match self.take(next, budget)? { + Some(read) => byte = read, + None => return Ok(None), + } + } + budget.step()?; + forms_opened::record(); + let tabs = tabs && word.first() != Some(&b'\t'); + self.waiting.push_back(Heredoc { word, tabs, quoted }); + (self.word, self.line, self.prev) = (Word::None, false, Prev::None); + self.unit = (at..next, Place::Form); + Ok(Some(next)) + } +} diff --git a/big-code-analysis-ast/src/lang_helpers/tcl.rs b/big-code-analysis-ast/src/lang_helpers/tcl.rs index d59dfbbd5..6ecc4f45f 100644 --- a/big-code-analysis-ast/src/lang_helpers/tcl.rs +++ b/big-code-analysis-ast/src/lang_helpers/tcl.rs @@ -2,7 +2,9 @@ //! braced-word kind ids. use crate::Tcl; +use crate::documentation::budget::WorkBudget; use crate::getter::BracedWordKinds; +use crate::lang_helpers::tcl_family::{BodyRowKinds, RowMark}; use crate::node::{Ancestors, Node, WordSlot}; /// The braced-word kinds `Getter::is_subsumed_braced_word`, @@ -37,6 +39,38 @@ pub(crate) const BRACED_WORD_KINDS: BracedWordKinds = BracedWordKinds { open_brace: Tcl::LBRACE as u16, }; +/// The kinds a reader of a `proc` body's comment rows is instantiated with. +pub(crate) const BODY_ROW_KINDS: BodyRowKinds = BodyRowKinds { + comment: Tcl::Comment as u16, + line_feed: Tcl::LF as u16, +}; + +/// The directive that opens a Ruff! documentation block. +pub(crate) const RUFF_MARKER: &[u8] = b"#ruff"; + +const RUFF_OPTIONS: &[u8] = b"#ruffopt"; + +/// How Ruff! 3.0.4 reads a comment row, from the row's first word. `#ruff` +/// and `#ruffopt` are directives only as whole words: the end of the row, a +/// space or a tab follows. Any other row is an ordinary comment, also one +/// whose first word only starts with `#ruff`, which Ruff! itself rejects. +pub(crate) fn ruff_row(spelling: &[u8], budget: &B) -> Result { + // The longer directive and the byte after it are all that is read. + budget.bytes(spelling.len().min(RUFF_OPTIONS.len() + 1))?; + let word = |directive: &[u8]| { + spelling + .strip_prefix(directive) + .is_some_and(|rest| matches!(rest.first(), None | Some(b' ' | b'\t'))) + }; + Ok(if word(RUFF_MARKER) { + RowMark::Opens + } else if word(RUFF_OPTIONS) { + RowMark::Silent + } else { + RowMark::Text + }) +} + /// Reads the leading word of a Tcl `command` node when it is a plain /// `simple_word` (`switch`, `for`, `puts`, …). Returns `None` for any other /// node kind, for commands whose leading word is computed (`$cmd`, `[cmd]` diff --git a/big-code-analysis-ast/src/lang_helpers/tcl_family.rs b/big-code-analysis-ast/src/lang_helpers/tcl_family.rs index c337efc05..db8a6b8c4 100644 --- a/big-code-analysis-ast/src/lang_helpers/tcl_family.rs +++ b/big-code-analysis-ast/src/lang_helpers/tcl_family.rs @@ -16,8 +16,17 @@ //! [`Getter::is_value_braced_word`]: crate::getter::Getter::is_value_braced_word //! [`Getter::is_braced_literal_slot`]: crate::getter::Getter::is_braced_literal_slot +use crate::documentation::budget::WorkBudget; +use crate::documentation::byte_scan; use crate::getter::{BracedWordKinds, node_text}; use crate::node::{Ancestors, Cursor, MemoQuestion, Node}; +use std::cell::Cell; + +/// Tcl's horizontal blank between words: space, tab, vertical tab and form +/// feed. A line end is not one, because it ends a command. +pub(crate) const fn tcl_blank(byte: u8) -> bool { + matches!(byte, b' ' | b'\t' | 0x0b | 0x0c) +} // The sibling scan `argument_slots_are_readable` runs, counted so a // test can see that a walk lending a `FoldCache` runs it once per @@ -511,6 +520,295 @@ fn switch_subject_index<'t>( None } +/// The kind ids a reader of a script's comments and lines needs. Both +/// dialects spell a comment `#[^\n]*` and end a command with a line-feed +/// token, under ids of their own. +#[derive(Clone, Copy)] +pub(crate) struct BodyRowKinds { + /// `comment`. + pub(crate) comment: u16, + /// The line-feed terminator. One token can cover several line ends. + pub(crate) line_feed: u16, +} + +/// How a dialect reads one comment that starts a row of its own. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum RowMark { + /// Documentation while a block is open, and otherwise nothing. + Text, + /// Opens a block wherever it stands, and is its first row. + Opens, + /// No text and no boundary: a block neither starts nor ends at it. + Silent, +} + +/// What one direct child of a script body is to the body's documentation. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum BodyRow { + /// Not documentation: a line end, a command, a comment outside every block. + Outside, + /// A row of a block. Its spelling ends at this byte. + Member(usize), + /// A [`RowMark::Silent`] row. Its spelling ends at this byte. + Directive(usize), + /// A recovery node that may hold documentation rows. + Obscured, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Block { + // No command and no documentation row yet: blank rows do not matter. + Leading, + Open, + Closed, +} + +// A child that is no line end, as the child after it sees it. +#[derive(Clone, Copy)] +struct Line { + start: usize, + spelling_end: usize, + end: usize, + first_row: usize, + last_row: usize, + continues: bool, + member: bool, +} + +/// Reads the direct children of a script body, in order, for its lead +/// block and for the later blocks a dialect's [`RowMark`] opens. +/// +/// The lead block is the first run of comment rows. Blank rows may precede +/// it; a blank row or a command ends it. Only a child that is a `comment` +/// can be a row, so a comment row nested in a command is not read. Where a +/// comment stands is read from the bytes between it and the child before +/// it, because a line that continues shows in no node. +pub(crate) struct BodyRows<'a, B> { + code: &'a [u8], + kinds: BodyRowKinds, + budget: &'a B, + block: Block, + above: Option, +} + +impl<'a, B: WorkBudget> BodyRows<'a, B> { + /// A reader standing after the opening brace of a body. + pub(crate) fn new(code: &'a [u8], kinds: BodyRowKinds, budget: &'a B) -> Self { + Self { + code, + kinds, + budget, + block: Block::Leading, + above: None, + } + } + + /// Classifies the next child between the braces. `mark` is asked at + /// most once, for a comment that starts a row of its own. + pub(crate) fn read( + &mut self, + child: tree_sitter::Node<'_>, + mark: impl FnOnce(&[u8], &B) -> Result, + ) -> Result { + // A zero-width token is one the parser invented while recovering. + let real = child.start_byte() < child.end_byte(); + if real && child.kind_id() == self.kinds.line_feed { + return Ok(BodyRow::Outside); + } + let here = self.line(child)?; + let above = self.above.replace(here); + let comment = real && child.kind_id() == self.kinds.comment; + // A comment runs to its line end. One that stops before it was cut + // short by the parser, at a NUL byte. + let cut = comment && self.code.get(here.end).is_some_and(|&next| next != b'\n'); + if comment && !cut { + return self.comment(here, above, mark); + } + Ok(self.ends_block(here, above, cut || child.is_error())) + } + + // What the child after this one needs to know of it. + fn line(&self, child: tree_sitter::Node<'_>) -> Result { + let start = child.start_byte(); + let spelling_end = comment_spelling_end(self.code, start, child.end_byte()); + Ok(Line { + start, + spelling_end, + end: child.end_byte(), + first_row: child.start_position().row, + last_row: child.end_position().row, + continues: line_continues(&self.code[start..spelling_end], self.budget)?, + member: false, + }) + } + + // A command, a `;` or a recovery node ends the block. A recovery node + // may hold rows that the parser did not read as comments: the next rows + // of the block when it starts a row with `#`, and a row that opens a + // block, wherever it stands, when it reaches a later row. The rows are + // physical here: a continued row counts as a row, which can only + // withhold more. + fn ends_block(&mut self, here: Line, above: Option, recovery: bool) -> BodyRow { + self.block = Block::Closed; + let own_row = above.is_none_or(|above| here.first_row > above.last_row); + let comment = own_row && self.code.get(here.start) == Some(&b'#'); + if recovery && (comment || here.last_row > here.first_row) { + BodyRow::Obscured + } else { + BodyRow::Outside + } + } + + fn comment( + &mut self, + here: Line, + above: Option, + mark: impl FnOnce(&[u8], &B) -> Result, + ) -> Result { + let Some(above) = above else { + return self.marked(here, mark); + }; + // The line ends between the child above and this comment say where + // the comment stands. A backslash before a line end joins the rows. + let gap = &self.code[above.spelling_end..here.start]; + match unescaped_line_ends(gap, above.continues, 2, self.budget)? { + // On the Tcl line of the child above: the rest of a comment, or + // a `#` that starts no command of its own row. + 0 if above.member => Ok(self.member(here.spelling_end)), + 0 => Ok(BodyRow::Outside), + 1 => self.marked(here, mark), + // A blank row lies between. + _ => { + if self.block == Block::Open { + self.block = Block::Closed; + } + self.marked(here, mark) + } + } + } + + fn marked( + &mut self, + here: Line, + mark: impl FnOnce(&[u8], &B) -> Result, + ) -> Result { + Ok( + match mark(&self.code[here.start..here.spelling_end], self.budget)? { + RowMark::Silent => BodyRow::Directive(here.spelling_end), + RowMark::Text if self.block == Block::Closed => BodyRow::Outside, + RowMark::Opens | RowMark::Text => self.member(here.spelling_end), + }, + ) + } + + fn member(&mut self, spelling_end: usize) -> BodyRow { + self.block = Block::Open; + if let Some(above) = &mut self.above { + above.member = true; + } + BodyRow::Member(spelling_end) + } +} + +/// The end of the spelling of a node that ends its row, as a `comment` +/// does: the node's end, without a carriage return that a line feed follows. +/// Both grammars put the CR of a CRLF into the comment token. +/// +/// The bytes `start..=end` must be included in the parse. +pub(crate) fn comment_spelling_end(code: &[u8], start: usize, end: usize) -> usize { + if end > start && code.get(end) == Some(&b'\n') && code.get(end - 1) == Some(&b'\r') { + end - 1 + } else { + end + } +} + +/// Whether a line with this spelling continues on the next row: it ends in +/// an odd run of backslashes. An even run is escaped backslashes. The same +/// reading as `continuing_backslash` in the root crate's LOC metric, which +/// this crate cannot call. +pub(crate) fn line_continues(spelling: &[u8], budget: &B) -> Result { + let run = match byte_scan::rposition(spelling, |byte| byte != b'\\', budget)? { + Some(last) => spelling.len() - 1 - last, + None => spelling.len(), + }; + Ok(run % 2 == 1) +} + +/// Counts the line ends in `gap` that no backslash escapes, and stops at +/// `limit`. `gap` is the bytes between two nodes of one script level: white +/// space, line ends and backslash-newline pairs. `escaped` says whether the +/// node before the gap ends in an odd run of backslashes. +/// +/// A line end is what Tcl takes for one when it reads a script file: LF, +/// CR LF, or a CR alone. The count says how Tcl reads the node after the +/// gap: 0, it stands on the line of the node before it; 1, it starts the +/// next row; 2, a blank row lies between. +pub(crate) fn unescaped_line_ends( + gap: &[u8], + escaped: bool, + limit: usize, + budget: &B, +) -> Result { + let escaped = Cell::new(escaped); + let after_cr = Cell::new(false); + let found = Cell::new(0); + byte_scan::position( + gap, + |byte| { + let lf_of_crlf = after_cr.replace(byte == b'\r') && byte == b'\n'; + match byte { + b'\\' => escaped.set(!escaped.get()), + // Counted, or escaped, with its carriage return. + b'\n' if lf_of_crlf => {} + b'\n' | b'\r' => found.set(found.get() + usize::from(!escaped.replace(false))), + _ => escaped.set(false), + } + found.get() == limit + }, + budget, + )?; + Ok(found.get()) +} + +/// Where Tcl ends the braced word whose `{` stands at `start`: after the `}` +/// at which the raw brace count returns to zero. A backslash hides the next +/// byte. Nothing else is special for Tcl inside the word: a `}` in a +/// comment, in a quoted word or in a bracket closes a level. A grammar that +/// reads those first ends its node elsewhere than Tcl ends the word. +/// +/// `None` if the count does not return to zero before `code` ends. A caller +/// that asks only whether the word ends at one place passes the bytes up to +/// that place, and no byte behind it is read. +pub(crate) fn braced_word_end( + code: &[u8], + start: usize, + budget: &B, +) -> Result, B::Error> { + let depth = Cell::new(0_usize); + let hidden = Cell::new(false); + let stop = byte_scan::position( + &code[start..], + |byte| { + if hidden.replace(false) { + return false; + } + match byte { + b'\\' => hidden.set(true), + b'{' => depth.set(depth.get() + 1), + b'}' => { + depth.set(depth.get().saturating_sub(1)); + return depth.get() == 0; + } + _ => {} + } + false + }, + budget, + )?; + Ok(stop.map(|at| start + at + 1)) +} + #[cfg(test)] #[cfg(feature = "tcl")] mod tests { diff --git a/big-code-analysis-ast/src/lang_helpers/tcl_scan.rs b/big-code-analysis-ast/src/lang_helpers/tcl_scan.rs new file mode 100644 index 000000000..5b740ef51 --- /dev/null +++ b/big-code-analysis-ast/src/lang_helpers/tcl_scan.rs @@ -0,0 +1,351 @@ +//! One forward scan of a Tcl script by Tcl's own rules for commands and +//! words (Tcl(n), rules 1 to 12, as far as they say where a command and a +//! word end). It lists the commands of the script's own level. +//! +//! Both dialects' grammars read a comment, a quoted word and a bracket +//! wherever they stand, so a node can start or end where no command or word +//! of Tcl does, and the tree need not hold an error node. The scan reads +//! bytes only: it takes no node and no kind id. +//! +//! It reads a file as `source` does. The first byte `0x1a` ends the file. +//! CR LF, a CR alone and LF are each one line end. A byte order mark is a +//! byte like any other, so it is part of the first word. + +use crate::documentation::budget::WorkBudget; +use crate::documentation::{SourceContext, SourceError, SourcePieces, byte_scan}; +use std::cell::Cell; +use std::ops::Range; + +mod machine; +use machine::{At, Machine, Mark, Nest, Signal, Text}; + +/// A command of the script's own level. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Command { + /// Its first byte. + pub(crate) start: usize, + /// The first four of its words, each from its first byte to the byte + /// after its last. + pub(crate) words: [(usize, usize); 4], + /// How many words it has. Five stands for five or more. + pub(crate) count: u8, + /// One of its words has the expansion prefix `{*}`. + pub(crate) expands: bool, +} + +/// What the scan says about one byte of the source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Listed { + /// A command of the script's own level starts at the byte, and the scan + /// has read it to its end. + Command(Command), + /// No such command starts there: the byte stands in a command, a word + /// or a comment that started earlier, the command that starts there has + /// a parse error, or the scan had stopped before the byte. + Nothing, + /// Excluded bytes hide the answer: the state of the scan is not known + /// at the byte, or the command that starts there reaches an excluded + /// byte before it ends. + Unknown, +} + +// A bracket or an array index that is open around the place of the scan. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Frame { + bracket: bool, + // The text the scan returns to when it closes. + resume: Text, +} + +// What became of the command that started last. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Fate { + #[default] + Unseen, + Open, + Done, + // It reached an excluded byte before it ended. + Cut, + // It has a parse error. + Broken, +} + +/// The commands of a script's own level, listed by one forward scan of the +/// included bytes. The scan goes on only as far as a question needs, so +/// questions are asked in source order. +/// +/// It stops at the first parse error of Tcl and at the end of the file, and +/// lists no command at or after that place. At an excluded byte its state +/// is not known. It is known again after the first later line end that the +/// included bytes prove unescaped, unless a brace, a quote, a bracket or an +/// index was open at the excluded byte: then it is never known again. +#[derive(Debug, Default)] +pub(crate) struct CommandScan<'s> { + // The included bytes, once the first question has been asked. + pieces: Option>, + // The piece that holds the next byte, and that byte. + piece: usize, + at: usize, + machine: Machine, + // One entry for each bracket and each array index that is open. + open: Vec, + // The command of the script's own level that started last. + command: Command, + fate: Fate, + // The first byte since which the state is not known. + dark: Option, + // The last run of bytes at which it was not known, and is known again. + lost: Range, +} + +impl<'s> CommandScan<'s> { + /// What the scan lists at the byte `start`. It reads on to that byte, + /// and to the end of the command that starts there. For a byte that it + /// has passed it reads nothing: it still knows the command that started + /// last, and answers [`Listed::Nothing`] for the start of an earlier one. + pub(crate) fn command_at( + &mut self, + source: &SourceContext<'s>, + start: usize, + budget: &B, + ) -> Result { + let end = source.bytes().len(); + if self.pieces.is_none() { + self.pieces = Some(source.pieces_with_budget(0..end, budget)?); + } + // Every round reads a byte, leaves a piece or ends the scan, and a + // scan that has ended answers. + loop { + if let Some(listed) = self.answer(start) { + return Ok(listed); + } + self.advance(end, start, budget).map_err(Into::into)?; + } + } + + // The answer, if the scan has read far enough to give it. A backslash at + // the byte starts a word unless a line end follows: the next byte says. + fn answer(&self, start: usize) -> Option { + if self.command.start == start && self.fate != Fate::Unseen { + return self.fated(); + } + let slash = matches!(self.machine.at, At::Slash { .. }) && start + 1 == self.at; + match self.machine.at { + _ if start < self.at && !slash => Some(self.passed(start)), + At::Dead => Some(Listed::Unknown), + At::Stopped => Some(Listed::Nothing), + _ => None, + } + } + + // What became of the command that started last, once that is known. + fn fated(&self) -> Option { + match self.fate { + Fate::Done => Some(Listed::Command(self.command)), + Fate::Cut => Some(Listed::Unknown), + Fate::Broken => Some(Listed::Nothing), + Fate::Open | Fate::Unseen => None, + } + } + + // A byte the scan has passed, at which no command of this level starts. + fn passed(&self, byte: usize) -> Listed { + if self.dark.is_some_and(|from| from <= byte) || self.lost.contains(&byte) { + Listed::Unknown + } else { + Listed::Nothing + } + } +} + +// Reading on. +impl<'s> CommandScan<'s> { + // The piece that holds the next byte, if an included byte is left. + fn piece(&self) -> Option<(Range, &'s [u8])> { + let piece = self.pieces.as_ref()?.pieces().get(self.piece)?; + Some((piece.range(), piece.bytes())) + } + + // Reads on: to the next byte that changes the list, to the byte asked + // for, or, in the command that starts there, to the end of the piece. + fn advance( + &mut self, + end: usize, + asked: usize, + budget: &B, + ) -> Result<(), B::Error> { + let Some((range, bytes)) = self.piece() else { + self.run_out(end); + return Ok(()); + }; + if self.at < range.start { + self.hide(); + self.at = range.start; + return Ok(()); + } + let following = self.fate == Fate::Open && self.command.start == asked; + let until = if following { + range.end + } else { + range.end.min(asked.max(self.at) + 1) + }; + let rest = &bytes[self.at - range.start..until - range.start]; + if let Some(signal) = self.read(rest, budget)? { + self.signal(signal, self.at - 1, budget)?; + } + self.piece += usize::from(self.at == range.end); + Ok(()) + } + + // Reads these bytes up to the first that changes more than the place of + // the scan, and says what that byte does. + fn read( + &mut self, + bytes: &[u8], + budget: &B, + ) -> Result, B::Error> { + let machine = Cell::new(self.machine); + let signal = Cell::new(Signal::default()); + let stop = byte_scan::position( + bytes, + |byte| { + let (next, made) = machine.get().feed(byte); + machine.set(next); + signal.set(made); + made != Signal::default() + }, + budget, + )?; + self.machine = machine.get(); + self.at += stop.map_or(bytes.len(), |read| read + 1); + Ok(stop.map(|_| signal.get())) + } + + // No included byte is left: excluded bytes follow, or the source ends. + fn run_out(&mut self, end: usize) { + if self.at < end { + self.hide(); + self.at = end; + } else { + self.ends(end); + } + } + + // The byte at `self.at` is excluded. + fn hide(&mut self) { + match self.machine.at { + At::Dead | At::Stopped => return, + At::Dark { .. } => {} + _ => { + if self.fate == Fate::Open { + self.fate = Fate::Cut; + } + self.dark = Some(self.at); + } + } + let open = !self.open.is_empty() || self.machine.holds(); + let at = if open { + At::Dead + } else { + At::Dark { seen: 0, run: 0 } + }; + self.machine = Machine { + at, + ..Machine::default() + }; + } + + // The file ends at `at`: at its last byte, or at the byte `0x1a`. + fn ends(&mut self, at: usize) { + let last = self.machine.last().filter(|_| self.open.is_empty()); + self.machine.at = At::Stopped; + for mark in last.into_iter().flatten() { + self.mark(mark, at); + } + // A command that is still open holds a word or a bracket that never + // closes. No command is open once the scan has ended. + if self.fate == Fate::Open { + self.fate = Fate::Broken; + } + } + + fn signal( + &mut self, + signal: Signal, + at: usize, + budget: &B, + ) -> Result<(), B::Error> { + self.mark(signal.mark, at); + match signal.nest { + Nest::None => {} + Nest::Bracket(resume) | Nest::Index(resume) => { + budget.step()?; + let bracket = matches!(signal.nest, Nest::Bracket(_)); + self.open.push(Frame { bracket, resume }); + self.enter(bracket); + } + Nest::Shut => { + if let Some(frame) = self.open.pop() { + self.machine.at = At::Text(frame.resume); + self.machine.nested = self.open.last().is_some_and(|frame| frame.bracket); + } + } + Nest::Fault => { + self.machine.at = At::Stopped; + if self.fate == Fate::Open { + self.fate = Fate::Broken; + } + } + Nest::End => self.ends(at), + // The line end itself was read while the state was not known. + Nest::Dawn => self.lost = self.dark.take().unwrap_or(at)..at + 1, + } + Ok(()) + } + + // The scan enters a bracket, where a script starts, or an array index. + fn enter(&mut self, bracket: bool) { + self.machine.nested = bracket; + self.machine.at = if bracket { + At::Lead + } else { + At::Text(Text::Index) + }; + } + + // Records what a byte at `at` does to the command of this level. What + // stands in a bracket or in an index is no word of this level. + fn mark(&mut self, mark: Mark, at: usize) { + if !self.open.is_empty() { + return; + } + let word = self.command.words.get_mut(usize::from(self.command.count)); + match mark { + Mark::None => {} + Mark::Starts(back) if self.fate == Fate::Open => { + if let Some(word) = word { + word.0 = at - back; + } + } + Mark::Starts(back) => { + self.fate = Fate::Open; + self.command = Command { + start: at - back, + ..Command::default() + }; + self.command.words[0].0 = at - back; + } + Mark::Ends(back) | Mark::Closes(back) => { + if let Some(word) = word { + word.1 = at - back; + } + self.command.count = self.command.count.saturating_add(1).min(5); + if matches!(mark, Mark::Closes(_)) { + self.fate = Fate::Done; + } + } + Mark::Over => self.fate = Fate::Done, + Mark::Expands => self.command.expands = true, + } + } +} diff --git a/big-code-analysis-ast/src/lang_helpers/tcl_scan/machine.rs b/big-code-analysis-ast/src/lang_helpers/tcl_scan/machine.rs new file mode 100644 index 000000000..2c69a25f8 --- /dev/null +++ b/big-code-analysis-ast/src/lang_helpers/tcl_scan/machine.rs @@ -0,0 +1,400 @@ +//! Tcl's rules for where a command and a word end, as a state machine over +//! the bytes of a script: the state at one byte, and what the byte does to +//! the list of commands and to the brackets and array indexes around it. +//! +//! The machine keeps no list and no stack. [`super::CommandScan`] feeds it +//! the bytes, keeps both, and enters and leaves a bracket's script for it. + +use crate::lang_helpers::tcl_family::tcl_blank; + +const END_OF_FILE: u8 = 0x1a; + +// The three kinds of text in which Tcl substitutes. Tcl reads all of them +// with one loop; they differ in the byte that ends them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Text { + // A word with no quote and no brace around it. White space, a line end + // or `;` ends it, and so does `]` in a bracket. + Bare, + // Between two `"`. + Quoted, + // The index of an array element, after `$name(`. Only `)` ends it. + Index, +} + +// Where the scan is in a variable reference. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Var { + // Directly after `$`. + Dollar, + Name, + // After one `:`. Only two or more are part of a name. + Colon, + Colons, + // After `${`: everything to the next `}` is the name. + Braced, +} + +// What a braced word has held so far. Only `{*}` can be an expansion prefix. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Inside { + Nothing, + Star, + More, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Brace { + depth: usize, + // A backslash hides this byte. + hidden: bool, + inside: Inside, +} + +// Where the scan stands. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum At { + // Before a command: white space, line ends, `;` and comments. + #[default] + Lead, + Comment { + hidden: bool, + }, + // In a command, between two words. + Gap, + // After a backslash where a word may start. With a line end the two are + // white space; any other byte makes the backslash the start of a word. + Slash { + lead: bool, + }, + Braced(Brace), + // Directly after the `"` or `}` that closes a word. `star` says that + // the word is `{*}` and may be an expansion prefix; `slash`, that a + // backslash followed. + Closed { + star: bool, + slash: bool, + }, + Text(Text), + // After a backslash in such text. + Hidden(Text), + Var(Var, Text), + // Behind an excluded byte. `seen` counts the bytes read since the last + // excluded one, and `run` the backslashes directly before this byte. + Dark { + seen: usize, + run: usize, + }, + // Behind an excluded byte that a brace, a quote, a bracket or an index + // reached: the state is never known again. + Dead, + // After a parse error or the end of the file. + Stopped, +} + +// What a byte does to the list of commands. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Mark { + #[default] + None, + // A word starts this many bytes before the byte. + Starts(usize), + // The word ends this many bytes before the byte. + Ends(usize), + // The word and the command end. + Closes(usize), + // The command ends; its last word has ended before. + Over, + // The word has the expansion prefix. + Expands, +} + +// What a byte does to the state around the list. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) enum Nest { + #[default] + None, + // `[` opens a script in text of this kind. + Bracket(Text), + // `(` opens an array index in text of this kind. + Index(Text), + // `]` or `)` closes what was opened last. + Shut, + // A parse error of Tcl. + Fault, + // The byte that ends the file. + End, + // The state is known again after this byte. + Dawn, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Signal { + pub(super) mark: Mark, + pub(super) nest: Nest, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct Machine { + pub(super) at: At, + // The byte before was a carriage return: a line feed belongs to it. + pub(super) after_cr: bool, + // The script being read stands in a bracket, and `]` ends it. + pub(super) nested: bool, + // The word being read has had its expansion prefix. + pub(super) expanded: bool, +} + +impl Machine { + fn to(self, at: At) -> (Self, Signal) { + (Self { at, ..self }, Signal::default()) + } + + fn marks(self, at: At, mark: Mark) -> (Self, Signal) { + let nest = Nest::None; + (Self { at, ..self }, Signal { mark, nest }) + } + + fn nests(self, nest: Nest) -> (Self, Signal) { + let mark = Mark::None; + (self, Signal { mark, nest }) + } + + // Reads one byte of the file as `source` reads it: the byte `0x1a` ends + // the file, and a carriage return, with or without a line feed after it, + // is one line feed. + pub(super) fn feed(mut self, byte: u8) -> (Self, Signal) { + if byte == END_OF_FILE { + return self.nests(Nest::End); + } + let after_cr = std::mem::replace(&mut self.after_cr, byte == b'\r'); + if after_cr && byte == b'\n' { + return self.to(self.at); + } + self.step(if byte == b'\r' { b'\n' } else { byte }) + } + + fn step(self, byte: u8) -> (Self, Signal) { + match self.at { + At::Lead | At::Gap => self.between(byte), + At::Comment { hidden } => self.comment(hidden, byte), + At::Slash { lead } => self.slash(lead, byte), + At::Braced(brace) => self.braced(brace, byte), + At::Closed { star, slash: false } => self.closed(star, byte), + At::Closed { star, slash: true } => self.closed_slash(star, byte), + At::Text(kind) => self.text(kind, byte), + At::Hidden(kind) => self.hidden(kind, byte), + At::Var(var, kind) => self.variable(var, kind, byte), + At::Dark { seen, run } => self.dark(seen, run, byte), + At::Dead | At::Stopped => self.to(self.at), + } + } + + // Where a command or a word may start. + fn between(self, byte: u8) -> (Self, Signal) { + let lead = self.at == At::Lead; + match byte { + _ if tcl_blank(byte) => self.to(self.at), + b'\n' | b';' if lead => self.to(At::Lead), + b'\n' | b';' => self.marks(At::Lead, Mark::Over), + b'#' if lead => self.to(At::Comment { hidden: false }), + b'\\' => self.to(At::Slash { lead }), + b']' if self.nested => self.nests(Nest::Shut), + _ => self.word(byte, Mark::Starts(0)), + } + } + + // A comment runs to the first line end that no backslash hides. + fn comment(self, hidden: bool, byte: u8) -> (Self, Signal) { + match byte { + _ if hidden => self.to(At::Comment { hidden: false }), + b'\\' => self.to(At::Comment { hidden: true }), + b'\n' => self.to(At::Lead), + _ => self.to(self.at), + } + } + + fn slash(self, lead: bool, byte: u8) -> (Self, Signal) { + match byte { + b'\n' if lead => self.to(At::Lead), + b'\n' => self.to(At::Gap), + // The backslash started a bare word, and hides this byte. + _ => self.fresh().marks(At::Text(Text::Bare), Mark::Starts(1)), + } + } + + fn fresh(self) -> Self { + let expanded = false; + Self { expanded, ..self } + } + + // The first byte of a word, or of what an expansion prefix expands. + fn word(self, byte: u8, mark: Mark) -> (Self, Signal) { + let word = if mark == Mark::Expands { + self + } else { + self.fresh() + }; + match byte { + b'"' => word.marks(At::Text(Text::Quoted), mark), + b'{' => { + let brace = Brace { + depth: 1, + hidden: false, + inside: Inside::Nothing, + }; + word.marks(At::Braced(brace), mark) + } + _ => { + let (next, signal) = word.text(Text::Bare, byte); + (next, Signal { mark, ..signal }) + } + } + } + + // The state is known again after a line end that the bytes read prove + // unescaped: an even run of backslashes stands before it, and that run + // and the byte before it were read. + fn dark(self, seen: usize, run: usize, byte: u8) -> (Self, Signal) { + let seen = seen.saturating_add(1); + match byte { + b'\n' if run.is_multiple_of(2) && seen > run + 1 => { + let known = Self { + at: At::Lead, + after_cr: self.after_cr, + ..Self::default() + }; + known.nests(Nest::Dawn) + } + b'\\' => self.to(At::Dark { seen, run: run + 1 }), + _ => self.to(At::Dark { seen, run: 0 }), + } + } +} + +// In a word. +impl Machine { + // In a braced word Tcl counts braces and nothing else. A backslash + // hides the next byte. + fn braced(self, brace: Brace, byte: u8) -> (Self, Signal) { + let Brace { depth, inside, .. } = brace; + let (depth, hidden, inside) = match byte { + _ if brace.hidden => (depth, false, Inside::More), + b'\\' => (depth, true, Inside::More), + b'{' => (depth + 1, false, Inside::More), + b'}' if depth == 1 => { + let star = inside == Inside::Star && !self.expanded; + return self.to(At::Closed { star, slash: false }); + } + b'}' => (depth - 1, false, Inside::More), + b'*' if inside == Inside::Nothing => (depth, false, Inside::Star), + _ => (depth, false, Inside::More), + }; + self.to(At::Braced(Brace { + depth, + hidden, + inside, + })) + } + + // After a closing `"` or `}` Tcl accepts white space or the end of the + // command. After `{*}` any other byte starts the word that the prefix + // expands; after any other word it is a parse error. + fn closed(self, star: bool, byte: u8) -> (Self, Signal) { + let expanded = true; + match byte { + _ if tcl_blank(byte) => self.marks(At::Gap, Mark::Ends(0)), + b'\n' | b';' => self.marks(At::Lead, Mark::Closes(0)), + b']' if self.nested => self.nests(Nest::Shut), + b'\\' => self.to(At::Closed { star, slash: true }), + _ if star => Self { expanded, ..self }.word(byte, Mark::Expands), + _ => self.nests(Nest::Fault), + } + } + + // The byte after a backslash that follows a closed word. With a line + // end the two are white space. Any other byte is a word byte: of the + // expanded word after `{*}`, and a parse error after any other word. + fn closed_slash(self, star: bool, byte: u8) -> (Self, Signal) { + let expanded = true; + match byte { + b'\n' => self.marks(At::Gap, Mark::Ends(1)), + _ if star => Self { expanded, ..self }.marks(At::Text(Text::Bare), Mark::Expands), + _ => self.nests(Nest::Fault), + } + } + + fn text(self, kind: Text, byte: u8) -> (Self, Signal) { + match (kind, byte) { + (_, b'$') => self.to(At::Var(Var::Dollar, kind)), + (_, b'[') => self.nests(Nest::Bracket(kind)), + (_, b'\\') => self.to(At::Hidden(kind)), + (Text::Bare, _) if tcl_blank(byte) => self.marks(At::Gap, Mark::Ends(0)), + (Text::Bare, b'\n' | b';') => self.marks(At::Lead, Mark::Closes(0)), + (Text::Bare, b']') if self.nested => self.nests(Nest::Shut), + (Text::Quoted, b'"') => { + let (star, slash) = (false, false); + self.to(At::Closed { star, slash }) + } + (Text::Index, b')') => self.nests(Nest::Shut), + _ => self.to(At::Text(kind)), + } + } + + // The byte after a backslash stands for itself. Only a line end after a + // bare word does not: the two are white space, and the word ended + // before the backslash. + fn hidden(self, kind: Text, byte: u8) -> (Self, Signal) { + if kind == Text::Bare && byte == b'\n' { + self.marks(At::Gap, Mark::Ends(1)) + } else { + self.to(At::Text(kind)) + } + } + + // A name is ASCII letters, digits, `_` and runs of two or more `:`. A + // `(` after it opens an array index, also after no name at all. + fn variable(self, var: Var, kind: Text, byte: u8) -> (Self, Signal) { + let name = byte.is_ascii_alphanumeric() || byte == b'_'; + match (var, byte) { + (Var::Braced, b'}') => self.to(At::Text(kind)), + (Var::Braced, _) => self.to(self.at), + (Var::Dollar, b'{') => self.to(At::Var(Var::Braced, kind)), + (Var::Dollar | Var::Name | Var::Colons, _) if name => self.to(At::Var(Var::Name, kind)), + (Var::Dollar | Var::Name, b':') => self.to(At::Var(Var::Colon, kind)), + (Var::Colon | Var::Colons, b':') => self.to(At::Var(Var::Colons, kind)), + (Var::Dollar | Var::Name | Var::Colons, b'(') => self.nests(Nest::Index(kind)), + // The reference has ended, or was a `$` alone: the byte is text. + _ => self.text(kind, byte), + } + } +} + +// Where the bytes that can be read end. +impl Machine { + // Whether a brace, a quote or an index is open at this place. + pub(super) fn holds(self) -> bool { + match self.at { + At::Braced(_) | At::Var(Var::Braced, _) => true, + At::Text(kind) | At::Hidden(kind) | At::Var(_, kind) => kind != Text::Bare, + _ => false, + } + } + + // What the end of the file does to the command being read: the marks + // it makes, or nothing if a word is still open. + pub(super) fn last(self) -> Option<[Mark; 2]> { + let word = Some([Mark::None, Mark::Closes(0)]); + match self.at { + At::Lead | At::Comment { .. } | At::Dark { .. } | At::Dead | At::Stopped => { + Some([Mark::None; 2]) + } + At::Gap => Some([Mark::None, Mark::Over]), + At::Slash { .. } => Some([Mark::Starts(1), Mark::Closes(0)]), + At::Closed { slash: false, .. } | At::Text(Text::Bare) | At::Hidden(Text::Bare) => word, + At::Var(var, Text::Bare) if var != Var::Braced => word, + At::Closed { star: true, .. } => Some([Mark::Expands, Mark::Closes(0)]), + _ => None, + } + } +} 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..7365a976b 100644 --- a/big-code-analysis-ast/src/macros/mod.rs +++ b/big-code-analysis-ast/src/macros/mod.rs @@ -389,6 +389,27 @@ 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()) + } + + /// 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<'_> { @@ -716,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 b2b3dd5bf..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}; @@ -87,7 +89,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 +113,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 } } @@ -135,6 +148,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. /// @@ -477,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) } @@ -492,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) } @@ -529,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) } @@ -767,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 025564905..93352469a 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(); @@ -453,6 +508,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 +536,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 @@ -538,14 +595,24 @@ 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, + /// Ruby source view: whether YARD finds a comment block for a statement + /// on the two rows above it, which a chain of trailing comments decides + /// for every statement of the chain at once. + YardLeading, } impl MemoQuestion { /// How many memos a [`FoldCache`] holds; one per variant above. - const COUNT: usize = 11; + const COUNT: usize = 15; } -const _: () = assert!(MemoQuestion::InConstBinding as usize + 1 == MemoQuestion::COUNT); +const _: () = assert!(MemoQuestion::YardLeading as usize + 1 == MemoQuestion::COUNT); /// The per-node questions the metric crate memoises through /// [`Ancestors::memoised_answer`], one per [`MemoQuestion`] memo of the @@ -669,14 +736,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 @@ -695,6 +766,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() } @@ -724,41 +796,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) } } @@ -768,6 +847,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 ed6fff982..d91841708 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, binary_search_end, 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,15 +209,42 @@ 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 first = binary_search_end( + children.len(), + |at| { + sibling_slot_probes::record(); + children[at].start_byte() < node.start_byte() + }, + budget, + )?; + for (at, child) in children.iter().enumerate().skip(first) { + budget.step()?; + sibling_slot_probes::record(); + if child.start_byte() != node.start_byte() { + break; + } + if child.id() == node.id() { + return Ok(Some(at)); + } + } + 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 @@ -227,24 +282,59 @@ 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> { + 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; + 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/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..7b2a5dbd4 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, @@ -101,17 +114,45 @@ fn get_fake_code( } } +/// Whether the pinned Kotlin grammar needs a final `\n` to finish parsing `code`. +/// +/// tree-sitter-kotlin-ng 1.1.0's external scanner has two loops in its `@` +/// arm (`src/scanner.c:317` and `:334`) that never stop at the end of input: +/// the first stops at whitespace, the second too, except that inside an +/// annotation's parentheses it stops only at `\n`. So source with no `\n` +/// after its last `@` never finishes, and `ParseCancel` cannot interrupt a +/// scanner. A `\n` stops both loops; trailing whitespace would not +/// (`@A(x y `). [`Parser::new`] appends one; a caller that hands Kotlin bytes to the +/// grammar itself must do the same or skip the input. Remove this once the pin +/// moves to a release whose scanner stops at the end of input there. +#[must_use] +pub fn kotlin_needs_final_newline(code: &[u8]) -> bool { + code.iter() + .rev() + .find(|&&byte| byte == b'\n' || byte == b'@') + == Some(&b'@') +} + +/// Append the `\n` [`kotlin_needs_final_newline`] asks for: the final newline +/// the CLI's `read_file_with_eol` gives every file. +fn end_kotlin_annotation_line(code: &mut Vec) { + if T::lang() == LANG::Kotlin && kotlin_needs_final_newline(code) { + code.push(b'\n'); + } +} + impl ParserTrait for Parser { type Checker = T; type Getter = T; fn new(code: Vec, path: &Path, pr: Option>) -> Self { let fake_code = get_fake_code::(&code, path, pr); - let code = if let Some(fake) = fake_code { + let mut code = if let Some(fake) = fake_code { fake } else { code }; + end_kotlin_annotation_line::(&mut code); let tree = Tree::new::(&code); @@ -234,6 +275,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 +296,30 @@ 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() + } + + /// 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)] @@ -272,6 +339,48 @@ mod tests { count(&parse_python(source), &[filter.to_string()]).0 } + /// Kotlin with no `\n` after its last `@` gains one, so both scanner + /// loops see it and stop; other input is parsed as given. Each parse + /// runs on its own thread, so a regression fails here instead of + /// hanging the suite. + #[cfg(all(feature = "c", feature = "cpp", feature = "kotlin", feature = "mozcpp"))] + #[test] + fn kotlin_source_ending_in_an_annotation_line_is_parsed_with_a_final_newline() { + use crate::langs::KotlinParser; + // How long a parse of a few bytes may take before it counts as hung. + const HUNG_AFTER: std::time::Duration = std::time::Duration::from_secs(10); + for (source, padded) in [ + // The annotation-name loop, which stops only at whitespace. + ("class C\n@Ann", true), + // The getter/setter loop, which after `(` stops only at `\n`. + ("val p = 1\n@A(x y", true), + // The guard does not lex, so a comment's `@` is padded too. + ("fun f() = 1 // @see g", true), + ("class C\n@Ann\n", false), + ("@file:JvmName(\"A\")\nclass C", false), + ("class C", false), + ] { + let (sender, receiver) = std::sync::mpsc::channel(); + let input = source.as_bytes().to_vec(); + std::thread::spawn(move || { + let parser = KotlinParser::new(input, &PathBuf::from("t.kt"), None); + let _ = sender.send((parser.code().to_vec(), parser.root().end_byte())); + }); + let (code, root_end) = receiver + .recv_timeout(HUNG_AFTER) + .unwrap_or_else(|_| panic!("{source:?}: the parse did not return")); + let mut expected = source.as_bytes().to_vec(); + if padded { + expected.push(b'\n'); + } + assert_eq!(code, expected, "{source:?}"); + assert!( + root_end <= code.len(), + "{source:?}: the tree outruns the source" + ); + } + } + // Regression for #293: a named filter that is not a hardcoded // keyword (`all`/`call`/`comment`/`error`/`string`/`function`) and // not a numeric `kind_id` must match `node.kind()` exactly, not via 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..010c5f83c 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 + | $lang::UsingDeclaration => 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..40d3ec78f 100644 --- a/big-code-analysis-ast/src/roles/php.rs +++ b/big-code-analysis-ast/src/roles/php.rs @@ -32,29 +32,59 @@ 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!( - child.kind_id().into(), - Php::FunctionCallExpression | Php::ParenthesizedExpression - ) - }); - } - expression + 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 expression = crate::documentation::budget::child( + ¤t, + |child| { + matches!( + child.kind_id().into(), + Php::FunctionCallExpression | Php::ParenthesizedExpression + ) + }, + budget, + )?; + 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-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..dd3a338b6 --- /dev/null +++ b/big-code-analysis-ast/src/test_support/documentation.rs @@ -0,0 +1,424 @@ +//! 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. +//! 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 checkout-only inventory is missing, unreadable, or not valid JSON. +#[must_use] +pub fn inventory() -> serde_json::Value { + 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`, +/// `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. +/// +/// # 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 => { + let actual = result.expect("source adapter must produce declaration text"); + assert_eq!( + actual, + serde_json::json!([{ + "fragments": expected["fragments"], "owner": expected["owner"], + "owner_kind": expected["selected_owner_kind"], "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 checkout-only 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("raw documentation fixtures require a repository checkout") +} + +/// 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()]; + assert_eq!(entry["path"], primary(lang), "{lang}: fixture routing"); + 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}"); + 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; + } + 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],"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],"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() + ); + } + } + + #[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() { + 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)]); + } + + #[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/big-code-analysis-ast/tests/python_documentation_grammar.rs b/big-code-analysis-ast/tests/python_documentation_grammar.rs new file mode 100644 index 000000000..84fa7613f --- /dev/null +++ b/big-code-analysis-ast/tests/python_documentation_grammar.rs @@ -0,0 +1,640 @@ +//! Pinned Python grammar evidence for the docstring adapter: the shape of a string, +//! of the owners and runs the reader walks, of parser recovery around a string, and +//! of parses with excluded ranges, with carriage returns and without a final line feed. +#![cfg(feature = "python")] +#![allow( + clippy::naive_bytecount, + clippy::single_range_in_vec_init, + clippy::too_many_lines +)] + +use std::ops::Range; +use tree_sitter::{Node, Tree}; + +const STRING: u16 = 231; +const STRING_START: u16 = 104; +const STRING_CONTENT: u16 = 232; +const STRING_END: u16 = 107; + +/// Parses `source`, whole when `included` is empty and otherwise with exactly those +/// byte ranges. A point is the number of line feeds before the offset and the bytes +/// since the last one. +fn parse(source: &[u8], included: &[Range]) -> Tree { + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&tree_sitter_python::LANGUAGE.into()) + .unwrap(); + if !included.is_empty() { + 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<_> = 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(); + parser.set_included_ranges(&ranges).unwrap(); + } + let tree = parser.parse(source, None).unwrap(); + if std::env::var_os("BCA_DUMP_PYTHON_DOC_GRAMMAR").is_some() { + dump(source, &tree); + } + tree +} + +fn whole(source: &[u8]) -> Tree { + parse(source, &[]) +} + +fn dump(source: &[u8], tree: &Tree) { + println!("SOURCE {source:?} INCLUDED {:?}", tree.included_ranges()); + for (depth, node) in preorder(tree) { + println!( + "{depth}: {} id={} named={} bytes={:?} has_error={} is_error={} missing={}", + node.kind(), + node.kind_id(), + node.is_named(), + node.byte_range(), + node.has_error(), + node.is_error(), + node.is_missing(), + ); + } +} + +/// Every node of `tree` with its depth, parents before children. +fn preorder(tree: &Tree) -> Vec<(usize, Node<'_>)> { + let mut nodes = Vec::new(); + let mut cursor = tree.walk(); + let mut depth = 0; + loop { + nodes.push((depth, cursor.node())); + if cursor.goto_first_child() { + depth += 1; + } else { + while !cursor.goto_next_sibling() { + if !cursor.goto_parent() { + return nodes; + } + depth -= 1; + } + } + } +} + +/// The one node of `kind` with exactly `range`. +fn node<'t>(tree: &'t Tree, kind: &str, range: Range) -> Node<'t> { + let found: Vec<_> = preorder(tree) + .into_iter() + .map(|(_, node)| node) + .filter(|node| node.kind() == kind && node.byte_range() == range) + .collect(); + assert_eq!(found.len(), 1, "{kind} {range:?}"); + found[0] +} + +fn count(tree: &Tree, kind: &str) -> usize { + preorder(tree) + .iter() + .filter(|(_, node)| node.kind() == kind) + .count() +} + +/// The direct children of `node`: kind and byte range, in order. +fn children(node: Node<'_>) -> Vec<(&'static str, Range)> { + let mut cursor = node.walk(); + node.children(&mut cursor) + .map(|child| (child.kind(), child.byte_range())) + .collect() +} + +/// No node of `tree` is an `ERROR`, is missing or holds either. +fn clean(tree: &Tree) { + for (_, node) in preorder(tree) { + assert!(!node.has_error(), "{} {:?}", node.kind(), node.byte_range()); + assert!(!node.is_error(), "{} {:?}", node.kind(), node.byte_range()); + assert!( + !node.is_missing(), + "{} {:?}", + node.kind(), + node.byte_range() + ); + } +} + +/// A `string` with exactly `range` whose children are a `string_start`, an optional +/// `string_content` and a `string_end` with the given ranges. +fn string(tree: &Tree, range: Range, parts: &[Range]) { + let string = node(tree, "string", range); + assert_eq!(string.kind_id(), STRING); + let kinds: &[(&str, u16)] = if parts.len() == 3 { + &[ + ("string_start", STRING_START), + ("string_content", STRING_CONTENT), + ("string_end", STRING_END), + ] + } else { + &[("string_start", STRING_START), ("string_end", STRING_END)] + }; + assert_eq!(parts.len(), kinds.len()); + let mut cursor = string.walk(); + let found: Vec<_> = string.children(&mut cursor).collect(); + assert_eq!(found.len(), kinds.len()); + for ((child, (kind, id)), part) in found.iter().zip(kinds).zip(parts) { + assert_eq!(child.kind(), *kind); + assert_eq!(child.kind_id(), *id); + assert_eq!(child.byte_range(), *part); + } +} + +const P1: &[u8] = b"def f():\n \"audit\"\n pass"; +const P2A: &[u8] = b"class C:\n \"audit\"\n pass"; +const P2B: &[u8] = b"\"audit\"\nx = 1"; +const P3: &[u8] = b"def f():\n \"\"\n \"extra\"\n return 1\n"; +const P4A: &[u8] = b"def f():\n (\"@au\" # ordinary\n \"dit\")\n"; +const P4B: &[u8] = b"def f():\n R\"a\\nb\" u\"c\"\n"; +const P5A: &[u8] = b"\"a\\x40b\"\nx = 1"; +const P5B: &[u8] = b"def f():\n r\"a\\nb\"\n pass"; +const P5F: &[u8] = b"def f():\n u\"a\\x40b\"\n"; +const P7A: &[u8] = b"def f():\n \"\"\"First.\n\n Second.\n \"\"\"\n"; +const P8A: &[u8] = b"def f():\r\n \"\"\"First.\r\n\r\n Second.\r\n \"\"\"\r\n"; +const P8B: &[u8] = b"def f():\n \"\"\"a\rb\"\"\"\n"; +const P8C: &[u8] = b"def f():\n (\"a\"\n \"\"\"b\rc\"\"\")\n"; +const P8D: &[u8] = b"def f():\n \"\"\"a\rb\"\"\"\n def g():\n return 1\n"; +const P9A: &[u8] = b"\"\"\"a\"\"\"\n\"\"\"b\"\"\"\n# c\n\"\"\"c\"\"\"\nx = 1\n\"\"\"d\"\"\"\n"; +const P9C: &[u8] = b"x = 1\n\"x doc\"\n\"more\"\ndef f():\n return 1\n"; +const P9D: &[u8] = b"class C:\n x = 1\n \"x doc\"\n y = = 2\n"; +const P11A: &[u8] = b"@d\ndef f():\n \"outer\"\n def g():\n \"inner\""; +const P11C: &[u8] = b"async def f():\n \"audit\"\n"; +const P14A: &[u8] = b"def f():\n \"audit\"\n x = = 1\n"; +const P14B: &[u8] = b"def f():\n \"audit\"\n x = (\n"; +const P14C: &[u8] = b"\"doc\"\nx = = 1\n"; +const P14D: &[u8] = b"x = [\ndef f():\n \"doc\"\n"; +const P17A: &[u8] = b"\"au\0dit\"\nx = 1"; +const P17B: &[u8] = b"\"c\0d\" \"\"\"a\rb\"\"\"\nx = 1"; +const P18A: &[u8] = b"\"a\";\n\"b\"\nx = 1\n"; +const P18C: &[u8] = b"def f():\n \"a\"; \"b\"\n return 1\n"; +const P18E: &[u8] = b"x = 1; \"attribute\"\n"; +const P20A: &[u8] = b"\"a\"\nx = 1\n\"b\"\ny = 2\n"; +const P20B: &[u8] = b"x = 1\n\"doc\"\ndef f():\n \"inner\"\n"; +const P20C: &[u8] = b"def f():\n x = 1\n \"doc\"\n return 1\n"; +const P21: &[u8] = b"\"a\" + \"b\"\nx = 1\n"; +const P22: &[u8] = b"def f():\n (\"First.\\n \" \"Second.\")\n"; +const P23A: &[u8] = b"\"\"\"a\"\"\"\n(1 . \"b\")\ny = 2\n"; +const P23B: &[u8] = b"x = 1\n(1 . \"b\")\n"; +const P24A: &[u8] = b"(\"a\" 1 \"b\")\nx = 1\n"; +const P24B: &[u8] = b"(\"a\" \"b\" 1)\nx = 1\n"; +const CONTINUATION: &[u8] = + include_bytes!("../../tests/fixtures/documentation/sources/python-continuation.py"); + +#[test] +fn python_documentation_grammar_string_shapes() { + let tree = whole(P1); + assert_eq!(tree.root_node().end_byte(), 29); + string(&tree, 13..20, &[13..14, 14..19, 19..20]); + // The empty string has no `string_content` child. + string(&whole(P3), 13..15, &[13..14, 14..15]); + // A raw literal: the escape is plain content, with no child. + let tree = whole(P5B); + string(&tree, 13..20, &[13..15, 15..19, 19..20]); + assert_eq!(node(&tree, "string_content", 15..19).child_count(), 0); + let tree = whole(P4B); + assert_eq!(node(&tree, "concatenated_string", 13..25).kind_id(), 230); + node(&tree, "string_start", 13..15); + node(&tree, "string_start", 21..23); + let tree = whole(P5A); + assert_eq!( + children(node(&tree, "string_content", 1..7)), + [("escape_sequence", 2..6)] + ); + assert_eq!(node(&tree, "escape_sequence", 2..6).kind_id(), 89); + let tree = whole(P5F); + node(&tree, "string_start", 13..15); + node(&tree, "escape_sequence", 16..20); + let tree = whole(P7A); + assert_eq!(tree.root_node().end_byte(), 44); + string(&tree, 13..43, &[13..16, 16..40, 40..43]); + // With its carriage returns, as the collector tests parse it. + let tree = whole(P8A); + assert_eq!(tree.root_node().end_byte(), 49); + clean(&tree); + node(&tree, "function_definition", 0..47); + string(&tree, 14..47, &[14..17, 17..44, 44..47]); + let tree = whole(P8B); + assert_eq!(tree.root_node().end_byte(), 23); + clean(&tree); + node(&tree, "function_definition", 0..22); + node(&tree, "string", 13..22); + for prefix in ["f", "t", "b"] { + let source = format!("def f():\n {prefix}\"audit\"\n pass"); + let tree = whole(source.as_bytes()); + node(&tree, "string", 13..21); + node(&tree, "string_start", 13..15); + } + let tree = whole(b"\"a\" Rb\"b\" \"c\"\n"); + assert_eq!( + children(node(&tree, "concatenated_string", 0..13)), + [("string", 0..3), ("string", 4..9), ("string", 10..13)] + ); + node(&tree, "string_start", 4..7); + let tree = whole(b"rrrruuuu\"x\"\ny = 1\n"); + node(&tree, "string", 0..11); + node(&tree, "string_start", 0..9); + let tree = whole(b"UuUu\"x\"\ny = 1\n"); + node(&tree, "string", 0..7); + node(&tree, "string_start", 0..5); + // The grammar takes any run of prefix letters: 20,000 of them are one `string`. + let source = format!("{}\"x\"\n", "r".repeat(20_000)); + let tree = whole(source.as_bytes()); + clean(&tree); + assert_eq!(count(&tree, "string"), 1); + node(&tree, "string", 0..20_003); + node(&tree, "string_start", 0..20_001); + let tree = whole(P22); + assert_eq!(tree.root_node().end_byte(), 40); + assert_eq!( + children(node(&tree, "concatenated_string", 14..38)), + [("string", 14..28), ("string", 29..38)] + ); + let escape = node(&tree, "escape_sequence", 21..23); + let content = escape.parent().unwrap(); + assert_eq!(content.kind(), "string_content"); + assert_eq!(content.parent().unwrap().byte_range(), 14..28); +} + +#[test] +fn python_documentation_grammar_owner_and_run_shapes() { + let tree = whole(P4A); + assert_eq!(tree.root_node().end_byte(), 43); + let paren = node(&tree, "parenthesized_expression", 13..42); + assert_eq!(paren.parent().unwrap().kind(), "expression_statement"); + let value = node(&tree, "concatenated_string", 14..41); + assert_eq!(value.parent().unwrap().id(), paren.id()); + assert_eq!( + children(value), + [("string", 14..19), ("comment", 20..30), ("string", 36..41)] + ); + // Without a final line feed every range that ends the file ends at its length. + let tree = whole(P11A); + assert_eq!(tree.root_node().end_byte(), 52); + let decorated = node(&tree, "decorated_definition", 0..52); + assert_eq!(decorated.kind_id(), 158); + let outer = node(&tree, "function_definition", 3..52); + assert_eq!(outer.kind_id(), 145); + assert_eq!(outer.parent().unwrap().id(), decorated.id()); + let inner = node(&tree, "function_definition", 28..52); + let block = node(&tree, "block", 45..52); + assert_eq!(block.kind_id(), 160); + assert_eq!(block.parent().unwrap().id(), inner.id()); + node(&tree, "string", 45..52); + let tree = whole(P1); + assert_eq!(tree.root_node().end_byte(), 29); + node(&tree, "function_definition", 0..29); + node(&tree, "block", 13..29); + let tree = whole(P2A); + assert_eq!(tree.root_node().end_byte(), 29); + let class = node(&tree, "class_definition", 0..29); + assert_eq!(class.kind_id(), 154); + assert_eq!( + node(&tree, "block", 13..29).parent().unwrap().id(), + class.id() + ); + assert_eq!(whole(P2B).root_node().byte_range(), 0..13); + let tree = whole(P11C); + let function = node(&tree, "function_definition", 0..26); + assert_eq!(function.child(0).unwrap().kind(), "async"); + let tree = whole(P9A); + assert_eq!(tree.root_node().end_byte(), 42); + assert_eq!(tree.root_node().kind_id(), 108); + assert_eq!( + children(tree.root_node()), + [ + ("expression_statement", 0..7), + ("expression_statement", 8..15), + ("comment", 16..19), + ("expression_statement", 20..27), + ("expression_statement", 28..33), + ("expression_statement", 34..41), + ] + ); + // A `\` row before a statement is no node here, and the unindented `return` + // after the body is a child of the module. + let tree = whole(CONTINUATION); + assert_eq!(count(&tree, "line_continuation"), 0); + node(&tree, "function_definition", 0..51); + node(&tree, "block", 19..51); + let stray = node(&tree, "return_statement", 56..64); + assert_eq!(stray.parent().unwrap().kind(), "module"); + let tree = whole(P18A); + assert_eq!(tree.root_node().end_byte(), 15); + assert_eq!( + children(tree.root_node()), + [ + ("expression_statement", 0..3), + (";", 3..4), + ("expression_statement", 5..8), + ("expression_statement", 9..14), + ] + ); + let semicolon = node(&tree, ";", 3..4); + assert_eq!(semicolon.kind_id(), 2); + assert!(!semicolon.is_named()); + assert!(!semicolon.is_extra()); + assert_eq!( + children(whole(P18E).root_node()), + [ + ("expression_statement", 0..5), + (";", 5..6), + ("expression_statement", 7..18), + ] + ); + assert_eq!( + children(node(&whole(P18C), "block", 13..34)), + [ + ("expression_statement", 13..16), + (";", 16..17), + ("expression_statement", 18..21), + ("return_statement", 26..34), + ] + ); + // With its carriage return, as the collector tests parse it. + let tree = whole(P8C); + assert_eq!(tree.root_node().end_byte(), 34); + clean(&tree); + node(&tree, "function_definition", 0..33); + let paren = node(&tree, "parenthesized_expression", 13..33); + let value = node(&tree, "concatenated_string", 14..32); + assert_eq!(value.parent().unwrap().id(), paren.id()); + assert_eq!(children(value), [("string", 14..17), ("string", 23..32)]); + let tree = whole(P8D); + assert_eq!(tree.root_node().end_byte(), 53); + clean(&tree); + let outer = node(&tree, "function_definition", 0..52); + let body = outer.child_by_field_name("body").unwrap(); + assert_eq!( + children(body), + [ + ("expression_statement", 13..22), + ("function_definition", 27..52), + ] + ); + assert_eq!( + children(whole(P9C).root_node()), + [ + ("expression_statement", 0..5), + ("expression_statement", 6..13), + ("expression_statement", 14..20), + ("function_definition", 21..42), + ] + ); + // The generated sources of the reader tests: every list is flat. + for fragments in [3, 1_500] { + let source = format!("{}\n", vec!["\"a\""; fragments].join(" ")); + let tree = whole(source.as_bytes()); + clean(&tree); + let value = node(&tree, "concatenated_string", 0..source.len() - 1); + assert_eq!(value.child_count(), fragments); + assert!(children(value).iter().all(|(kind, _)| *kind == "string")); + } + let tree = whole(b"a.x0, a.x1, a.x2 = v\n\"no\"\n"); + let targets = node(&tree, "pattern_list", 0..16); + assert_eq!(targets.parent().unwrap().kind(), "assignment"); + assert_eq!( + children(targets) + .iter() + .map(|(kind, _)| *kind) + .collect::>(), + ["attribute", ",", "attribute", ",", "attribute"] + ); + let tree = whole(b"(\n# c\n# c\n# c\n\"doc\"\n)\n"); + assert_eq!( + children(node(&tree, "parenthesized_expression", 0..21)), + [ + ("(", 0..1), + ("comment", 2..5), + ("comment", 6..9), + ("comment", 10..13), + ("string", 14..19), + (")", 20..21), + ] + ); + let source = format!( + "class C:\n def __init__(\n{} self):\n self.a = 1\n \"a doc\"\n", + " # c\n".repeat(2) + ); + let tree = whole(source.as_bytes()); + assert_eq!(tree.root_node().end_byte(), 101); + assert_eq!( + children(node(&tree, "parameters", 25..64)), + [ + ("(", 25..26), + ("comment", 35..38), + ("comment", 47..50), + ("identifier", 59..63), + (")", 63..64), + ] + ); +} + +#[test] +fn python_documentation_grammar_recovery_and_range_shapes() { + let tree = whole(P14A); + assert_eq!(tree.root_node().end_byte(), 33); + let function = node(&tree, "function_definition", 0..32); + assert!(function.has_error()); + assert!(!function.is_error()); + assert!(node(&tree, "ERROR", 29..30).is_error()); + let tree = whole(b"def f(:\n \"audit\"\n pass\n"); + let missing: Vec<_> = preorder(&tree) + .into_iter() + .map(|(_, node)| node) + .filter(Node::is_missing) + .collect(); + assert_eq!(missing.len(), 1); + assert_eq!((missing[0].kind(), missing[0].byte_range()), (")", 6..6)); + let function = preorder(&tree) + .into_iter() + .map(|(_, node)| node) + .find(|node| node.kind() == "function_definition") + .unwrap(); + assert!(function.has_error()); + assert!(whole(P14B).root_node().is_error()); + let tree = whole(b"def f():\n \"audit\n pass\n"); + assert_eq!(count(&tree, "string"), 0); + assert_eq!( + node(&tree, "string_start", 13..14).parent().unwrap().kind(), + "ERROR" + ); + let tree = whole(P14C); + assert_eq!(tree.root_node().kind(), "module"); + assert!(tree.root_node().has_error()); + assert!(!node(&tree, "string", 0..5).has_error()); + let tree = whole(P14D); + assert_eq!( + children(tree.root_node()), + [("ERROR", 0..5), ("function_definition", 6..24)] + ); + assert!(!node(&tree, "function_definition", 6..24).has_error()); + let tree = whole(b"def f():\n (\"a\"\n \"b\"\n"); + assert_eq!(count(&tree, "concatenated_string"), 1); + let value = preorder(&tree) + .into_iter() + .map(|(_, node)| node) + .find(|node| node.kind() == "concatenated_string") + .unwrap(); + assert_eq!(value.parent().unwrap().kind(), "ERROR"); + assert_eq!(count(&tree, "expression_statement"), 0); + let tree = whole(P9D); + assert_eq!(tree.root_node().end_byte(), 43); + let class = node(&tree, "class_definition", 0..42); + assert!(class.has_error()); + let body = children(class.child_by_field_name("body").unwrap()); + assert_eq!(body.len(), 3); + assert_eq!(body[0], ("expression_statement", 13..18)); + assert_eq!(body[1], ("expression_statement", 23..30)); + assert!(!node(&tree, "expression_statement", 23..30).has_error()); + assert_eq!(body[2].0, "expression_statement"); + assert!(node(&tree, "expression_statement", body[2].1.clone()).has_error()); + // An `ERROR` before a string inside the parentheses: the string is a direct + // child of the parentheses, and not their first named child. + let tree = whole(P23A); + assert_eq!(tree.root_node().end_byte(), 24); + let statement = node(&tree, "expression_statement", 8..17); + assert_eq!(children(statement), [("parenthesized_expression", 8..17)]); + assert_eq!( + children(node(&tree, "parenthesized_expression", 8..17)), + [ + ("(", 8..9), + ("ERROR", 9..12), + ("string", 13..16), + (")", 16..17), + ] + ); + let tree = whole(P23B); + assert_eq!(tree.root_node().end_byte(), 16); + assert_eq!( + children(node(&tree, "expression_statement", 6..15)), + [("parenthesized_expression", 6..15)] + ); + assert_eq!( + children(node(&tree, "parenthesized_expression", 6..15)), + [ + ("(", 6..7), + ("ERROR", 7..10), + ("string", 11..14), + (")", 14..15), + ] + ); + // An `ERROR` inside the value, and one beside it. + let tree = whole(P24A); + assert_eq!(tree.root_node().end_byte(), 18); + let value = node(&tree, "concatenated_string", 1..10); + assert!(value.has_error()); + assert!(!value.is_error()); + assert_eq!( + value.parent().unwrap().byte_range(), + node(&tree, "parenthesized_expression", 0..11).byte_range() + ); + assert_eq!( + children(value), + [("string", 1..4), ("ERROR", 5..6), ("string", 7..10)] + ); + let tree = whole(P24B); + assert_eq!(tree.root_node().end_byte(), 18); + assert!(!node(&tree, "concatenated_string", 1..8).has_error()); + assert_eq!( + children(node(&tree, "parenthesized_expression", 0..11)), + [ + ("(", 0..1), + ("concatenated_string", 1..8), + ("ERROR", 9..10), + (")", 10..11), + ] + ); + // The empty source. + let tree = whole(b""); + clean(&tree); + assert_eq!(tree.root_node().kind(), "module"); + assert_eq!(tree.root_node().byte_range(), 0..0); + assert_eq!(tree.root_node().child_count(), 0); + // Parses with excluded ranges. + let tree = parse(P17A, &[0..3, 4..14]); + assert_eq!(tree.root_node().end_byte(), 14); + clean(&tree); + assert_eq!(tree.root_node().kind(), "module"); + string(&tree, 0..8, &[0..1, 1..7, 7..8]); + let tree = parse(P17B, &[0..2, 3..21]); + assert_eq!(tree.root_node().end_byte(), 21); + clean(&tree); + assert_eq!( + children(node(&tree, "concatenated_string", 0..15)), + [("string", 0..5), ("string", 6..15)] + ); + let tree = parse(P20A, &[0..4, 10..20]); + assert_eq!(tree.root_node().end_byte(), 20); + clean(&tree); + assert_eq!( + children(tree.root_node()), + [ + ("expression_statement", 0..3), + ("expression_statement", 10..13), + ("expression_statement", 14..19), + ] + ); + node(&tree, "string", 0..3); + node(&tree, "string", 10..13); + let tree = parse(P20B, &[6..33]); + assert_eq!(tree.root_node().end_byte(), 33); + clean(&tree); + assert_eq!( + children(tree.root_node()), + [ + ("expression_statement", 6..11), + ("function_definition", 12..32), + ] + ); + assert_eq!( + children(node(&tree, "block", 25..32)), + [("expression_statement", 25..32)] + ); + let tree = parse(P20C, &[0..9, 19..42]); + assert_eq!(tree.root_node().end_byte(), 42); + clean(&tree); + let function = node(&tree, "function_definition", 0..41); + let block = node(&tree, "block", 23..41); + assert_eq!(block.parent().unwrap().id(), function.id()); + assert_eq!( + children(block), + [ + ("expression_statement", 23..28), + ("return_statement", 33..41), + ] + ); + let tree = parse(P21, &[0..4, 5..16]); + assert_eq!(tree.root_node().end_byte(), 16); + clean(&tree); + assert_eq!( + children(tree.root_node()), + [ + ("expression_statement", 0..9), + ("expression_statement", 10..15), + ] + ); + let value = node(&tree, "concatenated_string", 0..9); + assert_eq!( + value.parent().unwrap().byte_range(), + node(&tree, "expression_statement", 0..9).byte_range() + ); + assert_eq!(children(value), [("string", 0..3), ("string", 6..9)]); +} 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..670aa6aac --- /dev/null +++ b/big-code-analysis-ast/tests/rust_documentation_grammar.rs @@ -0,0 +1,321 @@ +//! Pinned Rust grammar evidence for direct documentation literals and recovery. +#![cfg(feature = "rust")] + +use std::ops::Range; + +#[allow(clippy::naive_bytecount)] +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 + .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(); + 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; + 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() { + return; + } + 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 = 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(); + 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() {}", + ] { + 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), + ); + } +} diff --git a/big-code-analysis-bench/Cargo.toml b/big-code-analysis-bench/Cargo.toml index 5470b1084..ea6a77429 100644 --- a/big-code-analysis-bench/Cargo.toml +++ b/big-code-analysis-bench/Cargo.toml @@ -34,15 +34,14 @@ 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"] } +# 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 [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. -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. @@ -50,6 +49,7 @@ criterion = { version = "^0.8", features = ["html_reports"] } # Test-only: the corpus-selection tests build symlinked fixture trees # rather than depending on the shape of the checked-out submodules. tempfile.workspace = true +sha2.workspace = true # The library-level zero-drift oracle (#1744): `cargo build -p # big-code-analysis-bench --bin verbatim-oracle`, driven by @@ -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..82d89829d --- /dev/null +++ b/big-code-analysis-bench/benches/documentation.rs @@ -0,0 +1,38 @@ +//! Criterion measurements over the same registry as the source scaling gate. + +use big_code_analysis_bench::cli::HARNESS_ERROR; +use big_code_analysis_bench::documentation::{Parsed, Prepared, REGISTRY}; +use criterion::{BenchmarkId, Criterion}; + +fn main() { + let mut criterion = Criterion::default().configure_from_args(); + for probe in REGISTRY { + let Some((group_name, name)) = probe.id.rsplit_once('/') else { + eprintln!("invalid documentation benchmark ID: {}", probe.id); + std::process::exit(i32::from(HARNESS_ERROR)); + }; + 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(i32::from(HARNESS_ERROR)); + } + }); + }); + Ok::<_, big_code_analysis_bench::documentation::HarnessError>(()) + })(); + if let Err(error) = result { + eprintln!("{} size {size}: {error}", probe.id); + std::process::exit(i32::from(HARNESS_ERROR)); + } + } + group.finish(); + } + criterion.final_summary(); +} diff --git a/big-code-analysis-bench/benches/scaling.rs b/big-code-analysis-bench/benches/scaling.rs index 48795fc10..edcd080d5 100644 --- a/big-code-analysis-bench/benches/scaling.rs +++ b/big-code-analysis-bench/benches/scaling.rs @@ -1,49 +1,18 @@ -//! 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, HARNESS_ERROR, Mode, Scope, USAGE, parse_args}; +use big_code_analysis_bench::documentation::{ + REGISTRY, + combined::{CombinedReport, source_outcome}, + 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 +21,89 @@ fn main() -> ExitCode { print!("{USAGE}"); return ExitCode::SUCCESS; } - Err(message) => { - eprintln!("{message}\n\n{USAGE}"); + Err(error) => { + eprintln!("{error}\n{USAGE}"); return ExitCode::from(HARNESS_ERROR); } }; - - // 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) + 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 legacy = if args.scope == Scope::Source { + None } else { - (PROBES, VCS_PROBES) + 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() + }; + match scaling::run(&probes, args.rounds) { + Ok(mut report) => { + report.probes.extend(vcs::run(&ranking, args.rounds).probes); + print!("{report}"); + Some(report) + } + Err(error) => return harness_error(&error.to_string(), None, mode), + } }; - - let mut report = match scaling::run(probes, args.rounds) { - Ok(report) => report, - Err(error) => { - eprintln!("scaling harness could not run: {error}"); - return ExitCode::from(HARNESS_ERROR); + let source = if args.scope == Scope::Legacy { + None + } else { + match source_outcome(runner::run(REGISTRY, args.rounds, mode), mode, optimized) { + Ok(Ok(report)) => { + print!("{report}"); + Some(Ok(report)) + } + Ok(Err(abandoned)) => { + eprintln!("{abandoned}"); + Some(Err(abandoned)) + } + Err(error) => return harness_error(&error.to_string(), legacy, mode), } }; - // 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 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(); + if let Err(error) = report.validate(args.scope, &legacy_ids, &source_ids) { + return harness_error(&error.to_string(), report.legacy, mode); } + print!("{}", report.final_summary(mode)); + ExitCode::from(report.exit_code(mode, optimized)) +} - 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, - ); - } +/// Exit for a harness that could not run, first printing any legacy verdict +/// already measured so a source failure cannot hide it. +fn harness_error(error: &str, legacy: Option, mode: Mode) -> ExitCode { + if legacy.is_some() { + let measured = CombinedReport { + legacy, + source: None, + }; + print!("{}", measured.final_summary(mode)); } - 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) + eprintln!("scaling harness could not run: {error}"); + ExitCode::from(HARNESS_ERROR) } 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..9fa4f3898 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-audit.json @@ -0,0 +1,36 @@ +{ + "cwd": ".", + "provenance": { + "starting_checkpoint": "a4397339f872647d672e44e056a043502e13527f", + "status": "Executed at 50de7925; results recorded in documentation-results-50de7925.json.", + "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-calibration.json b/big-code-analysis-bench/perturbations/documentation-calibration.json new file mode 100644 index 000000000..91ed40ab2 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-calibration.json @@ -0,0 +1,181 @@ +{ + "cwd": ".", + "provenance": { + "starting_checkpoint": "2eb9b8103477d1d02e76620c4475b47b0a37a5d2", + "proposal_sha256": "4d50b20c066ec4b405745c1afe40b51cb5e376492d926c318c8488f96663ca47", + "status": "Executed at c456af09; results recorded in documentation-results-c456af09.json.", + "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": "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", + "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", + "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/perturbations/documentation-remediation.json b/big-code-analysis-bench/perturbations/documentation-remediation.json new file mode 100644 index 000000000..be6fe0e70 --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-remediation.json @@ -0,0 +1,75 @@ +{ + "cwd": ".", + "provenance": { + "starting_checkpoint": "e0b375e35dfe4c83038425652dd3e53cf350cc39", + "status": "Executed at 50de7925; results recorded in documentation-results-50de7925.json.", + "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/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} + ] + } + ] +} 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-results-c456af09.json b/big-code-analysis-bench/perturbations/documentation-results-c456af09.json new file mode 100644 index 000000000..0009aa37b --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation-results-c456af09.json @@ -0,0 +1,346 @@ +{ + "checkpoint": "c456af09adae9f15d73fb33190b3e44533c381fb", + "command": [ + "cargo", + "test", + "-p", + "big-code-analysis-bench", + "-p", + "big-code-analysis-ast", + "--all-features", + "--lib", + "documentation", + "--no-fail-fast" + ], + "provenance": { + "rustc": "1.99.1 (58cf8f9c3 2026-10-13)", + "cargo": "1.99.1 (5f94df478 2026-08-27)", + "python": "3.12.13", + "driver": "python3 -I utils/perturb.py, one sub-manifest per source manifest", + "scope": "Sequential local behavioral sweeps on a clean committed revision: the whole calibration manifest, never swept before, and the three documentation.json rows re-anchored or added since 50de7925. Every case compiled and failed its intended tests; sources restored. These results are not performance qualification.", + "rebase": "Swept at 71ee6519; later autosquash folds rebased it to c456af09, whose tree differs only by rustfmt whitespace in fuzz/src, a doc comment in big-code-analysis-bench/src/shapes.rs and two .bca-baseline.toml values, none of which a swept row targets." + }, + "sweeps": [ + { + "manifest": "documentation-calibration.json", + "results": [ + { + "name": "skip scheduled budget during report revalidation", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::combined::tests::validation_rechecks_every_scheduled_batch_against_retained_budget" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "omit calibrated repetition writeback", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cell_coordinator_stores_each_selected_repetition_count" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "cap decision uses first sample", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "cap-limited outcome accepted below cap", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_limited_trace_requires_the_iteration_cap" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "final summary uses first stage", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::calibration_formatter_preserves_sample_order_and_integer_nanoseconds" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "calibrate with one operation instead of the declared batch count", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples", + "documentation::runner::calibration_tests::cap_outcomes_use_the_three_sample_median_and_exact_boundaries", + "documentation::runner::calibration_tests::cell_coordinator_stores_each_selected_repetition_count", + "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", + "documentation::runner::calibration_tests::real_calibration_batches_execute_three_times_each_tested_count", + "documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample", + "documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling", + "documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "take only two calibration samples", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples", + "documentation::runner::calibration_tests::cap_outcomes_use_the_three_sample_median_and_exact_boundaries", + "documentation::runner::calibration_tests::cell_coordinator_stores_each_selected_repetition_count", + "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", + "documentation::runner::calibration_tests::first_qualified_stage_stops_after_exactly_three_samples", + "documentation::runner::calibration_tests::real_calibration_batches_execute_three_times_each_tested_count", + "documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample", + "documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling", + "documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "select fastest calibration sample", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::calibration_formatter_preserves_sample_order_and_integer_nanoseconds", + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples", + "documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "select slowest calibration sample", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples", + "documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "skip intermediate powers of two", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples", + "documentation::runner::calibration_tests::cap_outcomes_use_the_three_sample_median_and_exact_boundaries", + "documentation::runner::calibration_tests::cell_coordinator_stores_each_selected_repetition_count", + "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", + "documentation::runner::calibration_tests::real_calibration_batches_execute_three_times_each_tested_count", + "documentation::runner::calibration_tests::slow_first_call_does_not_freeze_or_select_the_fastest_sample", + "documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling", + "documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "continue after the first qualifying stage", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cell_coordinator_stores_each_selected_repetition_count", + "documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix", + "documentation::runner::calibration_tests::first_qualified_stage_stops_after_exactly_three_samples", + "documentation::runner::tests::scheduler_executes_and_records_unequal_frozen_counts" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "accept unresolved cap median", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::cap_decision_uses_the_median_of_distinct_samples", + "documentation::runner::calibration_tests::cap_outcomes_use_the_three_sample_median_and_exact_boundaries", + "documentation::runner::tests::calibration_caps_zero_and_preserves_ceiling" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "skip post-completion calibration budget check", + "verdict": "caught", + "detail": "", + "failed": [ + "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" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "discard the offending calibration budget sample", + "verdict": "caught", + "detail": "", + "failed": [ + "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" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "invent zero duration for failed calibration operation", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix", + "documentation::runner::calibration_tests::first_operation_failure_retains_an_empty_stage_and_stops" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "discard earlier completed calibration cells on failure", + "verdict": "caught", + "detail": "", + "failed": [ + "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" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "trust frozen count without matching the final tested count", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement", + "documentation::runner::tests::report_revalidates_batches_counts_and_statistic" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "accept skipped or reordered calibration counts", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "trust a trace that continued after qualifying", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "accept sub-target target-reached outcome", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "accept below-minimum cap-limited trace", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::trace_validation_rejects_forged_decisions_and_count_disagreement" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "ignore custom calibration budget during revalidation", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::custom_budget_is_checked_for_every_observation_before_the_next_call", + "documentation::runner::tests::report_revalidates_batches_counts_and_statistic" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "allow smoke to claim a calibration ladder", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::smoke_records_one_setup_and_never_claims_calibration" + ], + "missing_expected": [], + "rc": 101 + }, + { + "name": "print rounded calibration trace durations", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::runner::calibration_tests::calibration_formatter_preserves_sample_order_and_integer_nanoseconds", + "documentation::runner::calibration_tests::failures_preserve_previous_cells_stages_and_exact_observed_prefix" + ], + "missing_expected": [], + "rc": 101 + } + ] + }, + { + "manifest": "documentation.json", + "results": [ + { + "name": "ignore gate exit failure", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::combined::tests::abandoned_source_cell_is_a_gate_failure_beside_legacy", + "documentation::combined::tests::combined_membership_and_source_failure_cannot_hide_behind_legacy_pass" + ], + "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": "abandoned source run is not a failure", + "verdict": "caught", + "detail": "", + "failed": [ + "documentation::combined::tests::abandoned_source_cell_is_a_gate_failure_beside_legacy" + ], + "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..39035df0e --- /dev/null +++ b/big-code-analysis-bench/perturbations/documentation.json @@ -0,0 +1,135 @@ +{ + "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": " Some(Ok(report)) => report.failures().len(),", + "new": " Some(Ok(_)) => 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": "if mode == Mode::Gate && optimized && self.failures() > 0 {", + "new": "if 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(|&AssociationId(ordinal)| {", + "new": " for association in self.index.associations() { std::hint::black_box(association); }\n self.associations.iter().map(|&AssociationId(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"] + }, + { + "name": "abandoned source run is not a failure", + "file": "big-code-analysis-bench/src/documentation/combined.rs", + "old": " Some(Err(_)) => 1,", + "new": " Some(Err(_)) => 0,", + "expect": ["documentation::combined::tests::abandoned_source_cell_is_a_gate_failure_beside_legacy"] + }, + { + "name": "abandoned cell is a verdict outside a gate", + "file": "big-code-analysis-bench/src/documentation/combined.rs", + "old": " Err(error) if mode == Mode::Gate && optimized && error.is_abandoned_cell() => {", + "new": " Err(error) if optimized && error.is_abandoned_cell() => {", + "expect": ["documentation::combined::tests::only_an_optimized_gate_counts_an_abandoned_cell"] + } + ] +} 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/cli.rs b/big-code-analysis-bench/src/cli.rs index ba455205d..9b36cc029 100644 --- a/big-code-analysis-bench/src/cli.rs +++ b/big-code-analysis-bench/src/cli.rs @@ -6,15 +6,30 @@ //! executed. The parsing below decides whether the process gates or //! not, which is worth more than a test that silently does nothing. -use crate::scaling::DEFAULT_ROUNDS; +use crate::scaling::{DEFAULT_ROUNDS, MAX_ROUNDS}; + +/// 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. +pub const GATE_FAILURE: u8 = 1; + +/// Exit code for "the harness could not produce a measurement": bad +/// arguments, a language not compiled into this build, or a workload +/// whose setup or validation failed. +pub const HARNESS_ERROR: u8 = 2; /// Usage text for `benches/scaling.rs`. 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 +39,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 +53,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 +90,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 +112,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 > MAX_ROUNDS { + return Err(format!("--rounds must be in 1..={MAX_ROUNDS}")); } // Same invariant the `DEFAULT_ROUNDS` const assert // holds: an even count makes every median the average @@ -109,7 +148,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 +156,13 @@ pub fn parse_args(argv: impl IntoIterator) -> Result Args { match parse_args(args.iter().map(|a| (*a).to_owned())) { @@ -155,11 +195,31 @@ 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()); + } + } + + /// The help text spells the bound by hand; the parser reads the constant. + #[test] + fn rounds_bound_is_the_documented_one() { + use super::{MAX_ROUNDS, USAGE}; + assert!(USAGE.contains(&format!("1..={MAX_ROUNDS}")), "{USAGE}"); + assert_eq!( + parse(&["--rounds", &MAX_ROUNDS.to_string()]).rounds, + MAX_ROUNDS + ); + let over = (MAX_ROUNDS + 2).to_string(); + assert!(parse_args(["--rounds", over.as_str()].map(str::to_owned)).is_err()); } #[test] @@ -180,6 +240,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/attachment_validation.rs b/big-code-analysis-bench/src/documentation/attachment_validation.rs new file mode 100644 index 000000000..33ae4270e --- /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, + SourcePiece, 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", + )?; + exact_source(&pieces.pieces()[0], range, bytes) +} + +fn exact_source( + piece: &SourcePiece<'_>, + range: Range, + bytes: &[u8], +) -> Result<(), HarnessError> { + 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.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(piece) = &mapping.origin else { + return Err(HarnessError( + "combined fixture origin must be copied".into(), + )); + }; + exact_source(piece, 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.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.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.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 new file mode 100644 index 000000000..428490247 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/combined.rs @@ -0,0 +1,618 @@ +//! Combined membership and exit semantics without changing legacy report types. + +use super::runner::SourceReport; +use super::{HarnessError, require}; +use crate::cli::{GATE_FAILURE, Mode, Scope}; +use crate::scaling; +use std::fmt::Write; + +/// Independent result collections from the two scaling methods. +pub struct CombinedReport { + /// Legacy exponents, preserving their library contract. + pub legacy: Option, + /// Typed source statistics. + /// `Err` is a source cell over its work budget, which ends the source run + /// before it has a report: a performance failure in a gate, like an + /// abandoned legacy walk. + pub source: Option>, +} + +/// What a scaling gate makes of a source run: its report, an abandoned run that +/// counts as one performance failure, or a harness error. A cell over its work +/// budget is a verdict only in an optimized gate run, as for a legacy walk; +/// anywhere else it stays a harness error, like every other source failure. +/// +/// # Errors +/// Returns the run's error unless it is a gate's abandoned cell. +pub fn source_outcome( + result: Result, + mode: Mode, + optimized: bool, +) -> Result, HarnessError> { + match result { + Ok(report) => Ok(Ok(report)), + Err(error) if mode == Mode::Gate && optimized && error.is_abandoned_cell() => { + Ok(Err(error)) + } + Err(error) => Err(error), + } +} + +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(Ok(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()) + + match &self.source { + Some(Ok(report)) => report.failures().len(), + Some(Err(_)) => 1, + None => 0, + } + } + + /// [`GATE_FAILURE`] for a performance failure in gate mode, otherwise 0. + /// Harness errors are represented by failed construction/validation and use + /// [`crate::cli::HARNESS_ERROR`] upstream. + #[must_use] + pub fn exit_code(&self, mode: Mode, optimized: bool) -> u8 { + if mode == Mode::Gate && optimized && self.failures() > 0 { + GATE_FAILURE + } else { + 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 + ); + } + } + } + match &self.source { + Some(Ok(report)) => { + for result in report.failures() { + let _ = writeln!( + output, + "FAIL source {}: {} > bound {:.2}; policy: {}", + result.id, result.statistic, result.bound, result.policy + ); + } + } + Some(Err(error)) => { + let cause = error.0.lines().next().unwrap_or_default(); + let _ = writeln!(output, "FAIL source run abandoned: {cause}"); + } + None => {} + } + 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)] +mod tests { + use super::super::runner::calibration_tests::target_trace; + 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, + calibration: target_trace(1), + budget: scaling::MAX_CELL_WALK, + 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, + } + } + + #[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(Ok(source)), + }; + report.validate(Scope::Source, &[], &ids).unwrap(); + + let cell = &mut report.source.as_mut().unwrap().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. + 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(Ok(source)), + }; + let full = format!( + "{}{}{}", + report.legacy.as_ref().unwrap(), + report.source.as_ref().unwrap().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(Ok(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); + } + + /// expected: a source cell over its budget ends the source run with no + /// report, yet in a gate it is one performance failure (exit 1) with a + /// FAIL row beside the passing legacy verdict, not a harness error. + #[test] + fn abandoned_source_cell_is_a_gate_failure_beside_legacy() { + use std::time::Duration; + + 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 abandoned = super::super::runner::check_budget( + "probe", + 32, + Duration::from_nanos(1), + 1, + Duration::ZERO, + ) + .unwrap_err(); + let abandoned = HarnessError(format!( + "source probe size 32: {abandoned}\nretained source batches:" + )); + assert!(abandoned.is_abandoned_cell()); + assert!(!HarnessError("CalibrationUnresolved: probe".into()).is_abandoned_cell()); + let report = CombinedReport { + legacy: Some(legacy), + source: Some(Err(abandoned)), + }; + report + .validate(Scope::All, &["legacy"], &["probe"]) + .unwrap(); + assert!(report.validate(Scope::Legacy, &["legacy"], &[]).is_err()); + assert_eq!(report.failures(), 1); + assert_eq!(report.exit_code(Mode::Gate, true), GATE_FAILURE); + let summary = report.final_summary(Mode::Gate); + assert!(summary.contains( + "FAIL source run abandoned: source probe size 32: AbandonedCell: probe size 32" + )); + assert!(summary.ends_with("combined gate: 1 performance failures\n")); + } + + /// expected: only an optimized gate turns an abandoned cell into a + /// verdict; smoke, report-only and debug runs, and any other source error, + /// stay harness errors (exit 2). + #[test] + fn only_an_optimized_gate_counts_an_abandoned_cell() { + use std::time::Duration; + + let abandoned = || { + super::super::runner::check_budget( + "probe", + 32, + Duration::from_nanos(1), + 1, + Duration::ZERO, + ) + .unwrap_err() + }; + assert!(matches!( + source_outcome(Err(abandoned()), Mode::Gate, true), + Ok(Err(error)) if error.is_abandoned_cell() + )); + for (mode, optimized) in [ + (Mode::Gate, false), + (Mode::ReportOnly, true), + (Mode::Smoke, true), + ] { + assert!( + matches!(source_outcome(Err(abandoned()), mode, optimized), Err(error) if error.is_abandoned_cell()), + "{mode:?} optimized={optimized}" + ); + } + let unresolved = HarnessError("CalibrationUnresolved: probe".into()); + assert!(matches!( + source_outcome(Err(unresolved), Mode::Gate, true), + Err(error) if !error.is_abandoned_cell() + )); + } + + #[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, + calibration: target_trace(1), + budget: scaling::MAX_CELL_WALK, + 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(Ok(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().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..9bae61a53 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/fixtures.rs @@ -0,0 +1,786 @@ +//! Stable workload identities and source generators; shared by both timing methods. + +use big_code_analysis_ast::LANG; +use big_code_analysis_ast::documentation::DocumentationOptions; +use std::fmt::Write; + +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, + MapPieces, + 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 | Operation::MapPieces => 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 workloads followed by infrastructure and Rust literal ladders. +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 recovered field-list has 32 documented siblings and one invalid token", + ), + 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, 16_384], + ..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", + ), + 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, 16_384], + ..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, 16_384], + ..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)", + ), + probe( + "documentation/remediation/doxygen-trailing-enumerators", + "trailing-enumerators", + LANG::C, + true, + Operation::Collect, + "grow enumerators/trailing ///< docs/D=E=n; one enum, depth fixed", + ), +]; + +impl SourceProbe { + /// The explicit options used by both runners. + #[must_use] + pub fn options(&self) -> DocumentationOptions { + DocumentationOptions::default() + .with_unbound_evidence(self.evidence && self.key != "directives") + .with_directive_evidence(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. + #[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, + "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).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) + ), + "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).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) + ), + "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)) + } + "trailing-enumerators" => { + let mut source = String::from("enum E {\n"); + for at in 0..size { + let _ = writeln!(source, "A{at}, ///< audit"); + } + source.push_str("};\n"); + source + } + _ => { + 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..8236e909d --- /dev/null +++ b/big-code-analysis-bench/src/documentation/mod.rs @@ -0,0 +1,50 @@ +//! Shared source-documentation registry, operations and class-specific gate. + +mod attachment_validation; +pub mod combined; +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))] +mod workflow_tests; + +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 {} + +impl HarnessError { + /// Whether a cell exceeded its work budget, however much context was added. + #[must_use] + pub fn is_abandoned_cell(&self) -> bool { + self.0.contains(runner::ABANDONED_CELL) + } +} + +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..8dff514f4 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/operation.rs @@ -0,0 +1,547 @@ +//! 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, OriginView, Owner, SourcePiece, 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" | "rust-escapes-split" + ) { + 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()) + } + + #[allow(clippy::trivially_copy_pass_by_ref)] // Preserve the borrowed production options boundary inside timing. + 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.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::MapPieces + | 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 = match self.probe.key { + "width" => (size - 1) * 19 + 9, + "rust-mixed" => 30 * size, + _ => 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()?; + } + 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(()) + } + + /// 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)?, + ); + } + 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(()) + } + + /// 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 + } +} + +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 new file mode 100644 index 000000000..e08ae0891 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/runner.rs @@ -0,0 +1,1054 @@ +//! 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}; + +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. +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); + +/// 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, + /// 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. + 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 { + 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, + id: result.id, + size: cell.size, + bytes: cell.bytes, + segments: cell.segments, + iterations: cell.iterations, + calibration: cell.calibration.clone(), + budget: cell.budget, + 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 + )?; + writeln!(f, "source-calibration-policy: {SOURCE_CALIBRATION_POLICY}")?; + 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)?; + write_calibration(f, &cell.calibration, cell.budget)?; + writeln!(f, " dimensions: {:?}", cell.counts)?; + } + } + Ok(()) + } +} + +#[derive(Clone, Debug)] +struct RawCell { + counts: SourceCounts, + id: &'static str, + size: usize, + bytes: usize, + segments: usize, + iterations: u32, + calibration: Calibration, + budget: Duration, + 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, which this returns as an error in +/// every mode; the scaling gate's [`super::combined::source_outcome`] then counts +/// it as a performance failure in an optimized gate run. +#[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]; + raw.push(RawCell { + counts: operation.counts(), + id: probe.id, + size, + bytes: parsed[at].source().len(), + segments: operation.segments(), + 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| 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( + 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) + .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| retained_error(context(cell.id, cell.size, error), raw))?; + if round >= WARMUP_ROUNDS { + raw[at].batches.push(Batch { + round: round - WARMUP_ROUNDS, + elapsed, + }); + } + } + Ok(()) +} + +fn batch(operation: &Prepared<'_, '_>, iterations: u32) -> Result { + let start = Instant::now(); + for _ in 0..iterations { + operation.execute()?; + } + Ok(start.elapsed()) +} + +#[allow(clippy::needless_pass_by_value)] // map_err transfers ownership of the original diagnostic. +fn context(id: &str, size: usize, error: HarnessError) -> HarnessError { + HarnessError(format!("{id} size {size}: {error}")) +} + +/// Marks a cell whose work exceeded its budget: the regression the gate exists +/// to catch, so [`HarnessError::is_abandoned_cell`] lets the gate count it as a +/// performance failure rather than a broken harness. +pub const ABANDONED_CELL: &str = "AbandonedCell: "; + +pub(super) fn check_budget( + id: &str, + size: usize, + elapsed: Duration, + iterations: u32, + budget: Duration, +) -> Result<(), HarnessError> { + require( + elapsed.as_nanos() <= budget.as_nanos() * u128::from(iterations), + format!( + "{ABANDONED_CELL}{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 <= crate::scaling::MAX_ROUNDS, + format!( + "source rounds must be odd in 1..={}", + crate::scaling::MAX_ROUNDS + ), + ) +} + +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), + )?; + 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), + )?; + 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), + )?; + check_budget(raw.id, raw.size, batch.elapsed, raw.iterations, raw.budget)?; + 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, + calibration: raw.calibration, + budget: raw.budget, + batches: raw.batches, + batch_min: times[0], + batch_median: median, + batch_max: times[rounds - 1], + ns_per_operation: ns, + }) +} + +pub(super) 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::calibration_tests::target_trace; + 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, + calibration: target_trace(1), + budget: MAX_CELL_WALK, + batches: (0..3) + .map(|round| Batch { + round, + elapsed: Duration::from_nanos(ns), + }) + .collect(), + }) + .collect() + } + + #[test] + fn calibration_caps_zero_and_preserves_ceiling() { + 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] + 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; + 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()); + 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] + 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]); + 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, + 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; + 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); + 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 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; + cell.calibration = target_trace(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]; + 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()); + } + + /// The runner reports an abandoned cell as an error in every mode; whether + /// the gate counts it as a verdict is `combined::source_outcome`'s decision. + #[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..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(), + 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}"); + } + } + + #[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 = 4; + cell.calibration = target_trace(4); + 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 / 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::>(), + [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(), 58); + assert_eq!( + report.results.iter().map(|r| r.cells.len()).sum::(), + 174 + ); + 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 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 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 + .iter() + .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 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, + size, + 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(); + // 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!( + cell.batches.iter().map(|b| b.round).collect::>(), + [0, 1, 2] + ); + } + } +} 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..4c68d3115 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/runner/calibration_tests.rs @@ -0,0 +1,647 @@ +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); + let (stages, remainder) = calls.as_chunks::<3>(); + assert_eq!(remainder, [] as [u32; 0]); + for (at, samples) in stages.iter().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 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]; + 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 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] { + 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" + ) + ); + + 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" + ) + ); +} 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..1100edbaa --- /dev/null +++ b/big-code-analysis-bench/src/documentation/rust_tests.rs @@ -0,0 +1,271 @@ +use super::*; +use big_code_analysis_ast::documentation::*; + +/// The Rust unit-1 ladder's place in `REGISTRY`; later probes are other languages. +const RUST_LADDER: std::ops::Range = 46..57; + +#[test] +fn rust_unit1_full_rungs_validate_source_text_maps_and_identity() { + let probes = ®ISTRY[RUST_LADDER]; + 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[RUST_LADDER].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(), 58); + for (probe, (id, operation, sizes)) in REGISTRY[RUST_LADDER].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, 48), + (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.unbound_evidence(), + options.directive_evidence(), + 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..4bc81d226 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/rust_validation.rs @@ -0,0 +1,705 @@ +//! 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, NodeEvidence, 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)) => { + piece_slice(std::slice::from_ref(actual), range.clone(), source, split)?; + } + (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.range() == (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>>; + +#[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, + 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<'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, + "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.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| evidence.matches(EvidenceRole::Binding, node, function)) + && evidence.matches(EvidenceRole::Scope, fact.lexical_scope, scope), + "Rust binding/scope identity", + )?; + let owner = index.associated_owner(association, 0).map_err(failure)?; + require( + matches!(owner.get(), Owner::Node(node) if evidence.matches(EvidenceRole::FunctionOwner, *node, function)), + "Rust canonical function owner", + )?; + publication(index, expected, nodes, evidence)?; + 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 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 evidence.matches(EvidenceRole::ModuleOwner, *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<'s>( + index: &DocumentationIndex<'s>, + expected: &Expected, + nodes: &Nodes<'_>, + evidence: &EvidenceCheck) -> NodeEvidence<'s>>, +) -> 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| evidence.matches(EvidenceRole::Publication, e, 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> { + 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( + 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(), + evidence, + )?; + 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.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()))?; + require( + evidence.matches( + EvidenceRole::Fragment, + 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, + ) +} + +#[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/big-code-analysis-bench/src/documentation/tests.rs b/big-code-analysis-bench/src/documentation/tests.rs new file mode 100644 index 000000000..ca81ebd22 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/tests.rs @@ -0,0 +1,637 @@ +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", + "@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!( + crate::shapes::PROBES.len() + crate::vcs::VCS_PROBES.len(), + 141 + ); + 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.unbound_evidence() && !options.directive_evidence()); + } + assert_eq!(REGISTRY.len() - 31, 27); +} + +#[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" + | "trailing-enumerators" + ) { + 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] +#[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] { + 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.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, + 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::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); + } + _ => 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() { + use big_code_analysis_ast::documentation::streaming::{markers, positional}; + + 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(); + 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()); + 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 } + ); + // 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 } + ); + } +} + +#[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 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 [ + ( + "#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..f47121670 --- /dev/null +++ b/big-code-analysis-bench/src/documentation/validation.rs @@ -0,0 +1,604 @@ +//! 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.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.range().start == end, "map coverage start")?; + end = portion.output.range().end; + if let OriginView::Copied(piece) = portion.origin { + require( + piece.bytes() == &expected.as_bytes()[portion.output.range()], + "copied origin bytes", + )?; + } + } + require(end == expected.len(), "map coverage end")?; + for position in 0..owners { + let owner = index + .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 probe.key.starts_with("rust-") { + return super::rust_validation::validate(probe, size, parsed, index); + } + 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")?, + "trailing-enumerators" => { + documents(index, size, 1, 1, "audit")?; + require(count("enumerator") == size, "trailing enumerator width")?; + for association in index.associations() { + let owner = index.associated_owner(association, 0).map_err(failure)?; + require( + matches!(owner.get(), Owner::Node(node) if node.node().kind() == "enumerator"), + "a trailing comment documents the enumerator before its comma", + )?; + } + } + "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") == size + 31, + "nested struct fields plus recovery sibling width", + )?; + require(count("struct_specifier") == size, "recovery struct depth")?; + require( + nodes.iter().any(|(node, depth)| { + node.kind() == "field_declaration_list" + && node.has_error() + && node.child_count() >= 64 + && *depth >= size + }), + "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( + count("struct_specifier") == size && count("preproc_if") == size, + "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")?; + 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.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() == usize::from(probe.key == "rejected"), + "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.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.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/documentation/workflow_tests.rs b/big-code-analysis-bench/src/documentation/workflow_tests.rs new file mode 100644 index 000000000..e4586c53a --- /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 words: Vec<_> = call.split_whitespace().collect(); + let separator = words.iter().position(|arg| *arg == "--").unwrap(); + assert_eq!( + &words[..separator], + [ + "bench", + "-p", + "big-code-analysis-bench", + "--bench", + "scaling" + ] + ); + let args = std::iter::once("--bench".to_owned()) + .chain(words[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/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/big-code-analysis-bench/src/scaling.rs b/big-code-analysis-bench/src/scaling.rs index 1167e1c86..a5048b347 100644 --- a/big-code-analysis-bench/src/scaling.rs +++ b/big-code-analysis-bench/src/scaling.rs @@ -64,6 +64,13 @@ pub const DEFAULT_ROUNDS: usize = 7; // the median is there to remove. const _: () = assert!(DEFAULT_ROUNDS % 2 == 1); +/// The most measurement rounds a run accepts. Both the command line and +/// the source runner reject more, so a mistyped count cannot schedule an +/// effectively unbounded run. +pub const MAX_ROUNDS: usize = 1_023; + +const _: () = assert!(MAX_ROUNDS % 2 == 1 && DEFAULT_ROUNDS <= MAX_ROUNDS); + /// Rounds discarded before measurement starts. /// /// The first pass over a cell pays for cold instruction cache, lazy diff --git a/big-code-analysis-bench/src/shapes.rs b/big-code-analysis-bench/src/shapes.rs index 4d0073527..a2d8dad1c 100644 --- a/big-code-analysis-bench/src/shapes.rs +++ b/big-code-analysis-bench/src/shapes.rs @@ -1,6 +1,6 @@ //! Synthetic scaling inputs, and the probes built from them. //! -//! # The two axes +//! # The axes //! //! A tree grows in two directions, and a walk can be linear in one //! while being quadratic in the other. [`Axis::Depth`] shapes nest: the @@ -9,7 +9,9 @@ //! under one fixed-depth parent. #1100 is why both are here — the fix //! it originally proposed was linear on every nesting shape and made a //! flat 2 000-item file 94x slower by that issue's measurement, which -//! no depth probe can see. +//! no depth probe can see. [`Axis::Length`] shapes keep the tree fixed +//! and lengthen one token, where a scan inside the token can be +//! quadratic though no tree walk is. //! //! # Why every generator is affine in its size //! @@ -30,7 +32,8 @@ use big_code_analysis::{ }; /// Renders a source shape at a given size — a nesting depth on -/// [`Axis::Depth`], a sibling count on [`Axis::Width`]. +/// [`Axis::Depth`], a sibling count on [`Axis::Width`], a token length on +/// [`Axis::Length`]. /// /// Every implementation must be affine in that size: `len(n)` is /// `base + per_unit * n`. See the module docs for why. @@ -547,6 +550,17 @@ pub fn c_comment_chain(width: usize) -> String { format!("{}\nint z;\n", "/* c */ \\\n\\\n".repeat(width)) } +/// C: one Doxygen block comment whose single line repeats a backtick and an +/// `x` `width` times, above the declaration it documents. +/// +/// Released LOC (2.6.x) looked for each inline code span's closing backtick +/// in the rest of the comment split at the line end, so every opening +/// backtick scanned to the end of the line: quadratic in the spans on one line. +#[must_use] +pub fn doxygen_inline_code_spans(width: usize) -> String { + format!("/**{} */\nint f(void);\n", "`x".repeat(width)) +} + /// C: `width` units, each a `{` that never closes, a row of three block /// comments ending in `\`, a row holding only `\`, and an empty row. /// @@ -1993,6 +2007,9 @@ pub enum Axis { /// The size parameter is the number of siblings under one parent, /// at a depth that does not change with it. Width, + /// The size parameter is the length of one token, in a tree whose + /// shape does not change with it. + Length, } /// One scaling probe: a shape, the axis it grows along, the workload @@ -2090,6 +2107,10 @@ const SPACE_MERGE_WIDTHS: [usize; 3] = [4_000, 8_000, 16_000]; /// a `--gate` run the space-merge probes pay. const SLOT_SCAN_WIDTHS: [usize; 3] = SPACE_MERGE_WIDTHS; +/// Spans on one comment line for [`doxygen_inline_code_spans`]: its quadratic +/// term is a rescan over a cheap byte scan, the [`SPACE_MERGE_WIDTHS`] case. +const INLINE_SPAN_WIDTHS: [usize; 3] = SPACE_MERGE_WIDTHS; + /// Parenthesis counts for `dump/tcl-expr-parens`. /// /// Set by measurement. On [`LINEAR_WIDTHS`] the climb is still small @@ -3193,6 +3214,26 @@ pub const PROBES: &[Probe] = &[ owner scans the root's children each time. The reading \ is the comment rows, half of them the bare ones.", }, + Probe { + name: "loc/doxygen-inline-code-spans", + lang: LANG::C, + axis: Axis::Length, + workload: Workload::Metrics { + exclude_tests: false, + selection: &[Metric::Loc], + reading: |m| m.loc.dloc(), + }, + render: doxygen_inline_code_spans, + sizes: INLINE_SPAN_WIDTHS, + max_exponent: LINEAR_BOUND, + rationale: "One Doxygen comment line of `width` inline code spans. \ + Released 2.6.1 found each span's closing backtick by \ + scanning to the line end; with that scan restored this \ + probe fits 1.98 (3.0 / 11.8 / 46.9 ms, 7 rounds) against \ + 0.98 with the linear scan. The documentation API's byte \ + counters cannot see that form, so this guards the LOC \ + path. The reading is the comment's DLOC row.", + }, Probe { name: "loc/python-long-bare-run", lang: LANG::Python, @@ -5400,6 +5441,20 @@ mod tests { } } + /// Every length shape keeps its tree: doubling the size changes + /// neither the node count nor the depth, so the probe times the scan + /// inside the growing token rather than a walk over more nodes. + #[test] + fn shapes_lengthen_a_token_in_a_fixed_tree() { + let count = |ast: &Ast| ast.as_tree_sitter().root_node().descendant_count(); + for probe in probes_on(Axis::Length) { + let (short, long) = (parse(probe, 16), parse(probe, 32)); + assert_eq!(count(&short), count(&long), "{}: the tree grew", probe.name); + assert_eq!(ast_depth(&short), ast_depth(&long), "{}", probe.name); + assert!(long.source().len() > short.source().len(), "{}", probe.name); + } + } + /// Every probe's workload produces a non-zero reading on its own /// shape, at the smallest size the gate measures it at. /// @@ -6211,6 +6266,7 @@ mod tests { let measure = match probe.axis { Axis::Width => exported_nodes, Axis::Depth => exported_depth, + Axis::Length => panic!("{}: a dump export cannot grow along one token", probe.name), }; let (a, b) = (measure(narrow.root.as_ref()), measure(wide.root.as_ref())); assert!( diff --git a/big-code-analysis-bench/src/verbatim.rs b/big-code-analysis-bench/src/verbatim.rs index 6bc5539e4..47fe9b4bb 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_eq!(out, b""); + } + } + + #[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_eq!(out, b""); + } + let mut out = Vec::new(); + assert!( + run("rust", std::iter::empty::<&str>(), &mut out) + .expect_err("zero files") + .starts_with("no input files") + ); + assert_eq!(out, b""); + } + /// 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/big-code-analysis-book/po/ja.po b/big-code-analysis-book/po/ja.po index 987553c19..347bb488b 100644 --- a/big-code-analysis-book/po/ja.po +++ b/big-code-analysis-book/po/ja.po @@ -2,7 +2,7 @@ msgid "" msgstr "" "Project-Id-Version: big-code-analysis Documentation\n" -"POT-Creation-Date: 2026-10-30T15:44:04-07:00\n" +"POT-Creation-Date: 2026-11-29T16:05:29-08:00\n" "PO-Revision-Date: 2026-07-21\n" "Last-Translator: big-code-analysis maintainers\n" "Language-Team: Japanese\n" @@ -45,8 +45,8 @@ msgstr "コマンド" msgid "Metrics" msgstr "メトリクス" -#: src/SUMMARY.md:10 src/SUMMARY.md:46 src/commands/vcs.md:1 -#: src/commands/rest.md:612 src/python/vcs.md:1 +#: src/SUMMARY.md:10 src/SUMMARY.md:47 src/commands/vcs.md:1 +#: src/commands/rest.md:619 src/python/vcs.md:1 msgid "Change-history (VCS) metrics" msgstr "変更履歴(VCS)メトリクス" @@ -118,7 +118,7 @@ msgstr "REST API の操作" msgid "Using as a Library" msgstr "ライブラリとしての利用" -#: src/SUMMARY.md:28 src/SUMMARY.md:40 src/commands/vcs.md:17 +#: src/SUMMARY.md:28 src/SUMMARY.md:41 src/commands/vcs.md:17 #: src/commands/report.md:25 src/library/quick-start.md:1 #: src/python/quick-start.md:1 msgid "Quick start" @@ -140,72 +140,77 @@ msgstr "一度のパースで複数回メトリクスを実行" msgid "Walking the AST directly" msgstr "AST を直接たどる" -#: src/SUMMARY.md:33 src/library/selecting-metrics.md:1 +#: src/SUMMARY.md:33 src/library/documentation.md:1 +#, fuzzy +msgid "Extracting source documentation" +msgstr "コードドキュメント" + +#: src/SUMMARY.md:34 src/library/selecting-metrics.md:1 msgid "Selecting metrics" msgstr "メトリクスの選択" -#: src/SUMMARY.md:34 src/library/cargo-features.md:1 +#: src/SUMMARY.md:35 src/library/cargo-features.md:1 msgid "Per-language Cargo features" msgstr "言語ごとの Cargo フィーチャ" -#: src/SUMMARY.md:35 +#: src/SUMMARY.md:36 msgid "Walking FuncSpace results" msgstr "FuncSpace 結果をたどる" -#: src/SUMMARY.md:36 src/SUMMARY.md:47 src/library/error-handling.md:1 +#: src/SUMMARY.md:37 src/SUMMARY.md:48 src/library/error-handling.md:1 #: src/python/errors.md:1 msgid "Error handling" msgstr "エラー処理" -#: src/SUMMARY.md:37 src/library/stability.md:1 +#: src/SUMMARY.md:38 src/library/stability.md:1 msgid "Stability and versioning" msgstr "安定性とバージョニング" -#: src/SUMMARY.md:38 src/python/index.md:1 +#: src/SUMMARY.md:39 src/python/index.md:1 msgid "Python Bindings" msgstr "Python バインディング" -#: src/SUMMARY.md:39 src/commands/index.md:12 src/python/installation.md:1 +#: src/SUMMARY.md:40 src/commands/index.md:12 src/python/installation.md:1 msgid "Installation" msgstr "インストール" -#: src/SUMMARY.md:41 src/python/batch.md:1 +#: src/SUMMARY.md:42 src/python/batch.md:1 msgid "Batch processing" msgstr "バッチ処理" -#: src/SUMMARY.md:42 src/python/flat-records.md:1 +#: src/SUMMARY.md:43 src/python/flat-records.md:1 msgid "Flat-record iteration" msgstr "フラットレコードの反復処理" -#: src/SUMMARY.md:43 src/python/metrics.md:1 +#: src/SUMMARY.md:44 src/python/metrics.md:1 msgid "Metric selection" msgstr "メトリクス選択" -#: src/SUMMARY.md:44 src/python/traversal.md:1 +#: src/SUMMARY.md:45 src/python/traversal.md:1 msgid "AST traversal" msgstr "AST トラバーサル" -#: src/SUMMARY.md:45 src/python/sarif.md:1 +#: src/SUMMARY.md:46 src/python/sarif.md:1 msgid "SARIF output" msgstr "SARIF 出力" -#: src/SUMMARY.md:48 src/python/async.md:1 +#: src/SUMMARY.md:49 src/python/async.md:1 msgid "Async patterns" msgstr "非同期パターン" -#: src/SUMMARY.md:49 src/developers/index.md:1 +#: src/SUMMARY.md:50 src/developers/index.md:1 msgid "Developers Guide" msgstr "開発者ガイド" -#: src/SUMMARY.md:50 +#: src/SUMMARY.md:51 msgid "How-to: Add a new language" msgstr "ハウツー:新しい言語の追加" -#: src/SUMMARY.md:51 +#: src/SUMMARY.md:52 msgid "How-to: Implement LoC" msgstr "ハウツー:LoC の実装" -#: src/SUMMARY.md:52 +#: src/SUMMARY.md:53 msgid "How-to: Update grammars" msgstr "ハウツー:文法の更新" @@ -340,7 +345,7 @@ msgstr "" "features.md) に記載された、対応する言語別 Cargo フィーチャの背後にゲートされ" "ています。" -#: src/languages.md:9 src/metrics.md:157 src/recipes/thresholds.md:103 +#: src/languages.md:9 src/metrics.md:166 src/recipes/thresholds.md:103 msgid "Bash" msgstr "Bash" @@ -352,19 +357,19 @@ msgstr "C" msgid "C/C++" msgstr "C/C++" -#: src/languages.md:12 src/recipes/thresholds.md:106 +#: src/languages.md:12 src/metrics.md:2182 src/recipes/thresholds.md:106 msgid "C#" msgstr "C#" -#: src/languages.md:13 src/metrics.md:163 src/recipes/thresholds.md:107 +#: src/languages.md:13 src/metrics.md:172 src/recipes/thresholds.md:107 msgid "Elixir" msgstr "Elixir" -#: src/languages.md:14 src/metrics.md:162 src/recipes/thresholds.md:108 +#: src/languages.md:14 src/metrics.md:171 src/recipes/thresholds.md:108 msgid "Go" msgstr "Go" -#: src/languages.md:15 src/recipes/thresholds.md:109 +#: src/languages.md:15 src/metrics.md:2181 src/recipes/thresholds.md:109 msgid "Groovy" msgstr "Groovy" @@ -372,7 +377,7 @@ msgstr "Groovy" msgid "Irules" msgstr "Irules" -#: src/languages.md:17 src/recipes/thresholds.md:110 +#: src/languages.md:17 src/metrics.md:2179 src/recipes/thresholds.md:110 msgid "Java" msgstr "Java" @@ -380,8 +385,8 @@ msgstr "Java" msgid "JavaScript" msgstr "JavaScript" -#: src/languages.md:19 src/metrics.md:158 src/metrics.md:160 -#: src/recipes/thresholds.md:112 +#: src/languages.md:19 src/metrics.md:167 src/metrics.md:169 +#: src/metrics.md:2180 src/recipes/thresholds.md:112 msgid "Kotlin" msgstr "Kotlin" @@ -401,7 +406,7 @@ msgstr "Mozjs" msgid "Objective-C" msgstr "Objective-C" -#: src/languages.md:24 src/metrics.md:167 src/metrics.md:168 +#: src/languages.md:24 src/metrics.md:176 src/metrics.md:177 #: src/recipes/thresholds.md:115 msgid "Perl" msgstr "Perl" @@ -414,7 +419,7 @@ msgstr "Php" msgid "Python" msgstr "Python" -#: src/languages.md:27 src/metrics.md:148 src/metrics.md:155 src/metrics.md:161 +#: src/languages.md:27 src/metrics.md:157 src/metrics.md:164 src/metrics.md:170 #: src/recipes/thresholds.md:118 msgid "Ruby" msgstr "Ruby" @@ -423,7 +428,7 @@ msgstr "Ruby" msgid "Rust" msgstr "Rust" -#: src/languages.md:29 src/metrics.md:150 src/recipes/thresholds.md:120 +#: src/languages.md:29 src/metrics.md:159 src/recipes/thresholds.md:120 msgid "Tcl" msgstr "Tcl" @@ -551,6 +556,265 @@ msgstr "`Preproc` — C/C++ のプリプロセッサマクロに特化してい #: src/languages.md:109 #, fuzzy +msgid "Documentation profiles" +msgstr "コードドキュメント" + +#: src/languages.md:111 +msgid "" +"`DocumentationOptions::default()` selects the profile below for each `LANG` " +"variant; the profile column is `Profile::name()`. The implemented adapters " +"have partial support: check pending assessments and content states rather " +"than inferring that every form is supported. See [Extracting source " +"documentation](library/documentation.md)." +msgstr "" +"`DocumentationOptions::default()` は `LANG` バリアントごとに下表のプロファイ" +"ルを選択します。プロファイルの列は `Profile::name()` の値です。実装済みのアダ" +"プターの対応は部分的です。すべての形式に対応していると推測せず、保留中の評価" +"と内容の状態を確認してください。[ソース文書の抽出](library/documentation.md)" +"を参照してください。" + +#: src/languages.md:116 +msgid "`LANG` variant" +msgstr "" + +#: src/languages.md:116 +msgid "Default `Profile::name()`" +msgstr "" + +#: src/languages.md:116 +msgid "Adapter" +msgstr "" + +#: src/languages.md:118 +#, fuzzy +msgid "`Bash`" +msgstr "`bash`" + +#: src/languages.md:118 +msgid "`shdoc`" +msgstr "" + +#: src/languages.md:118 src/languages.md:119 src/languages.md:120 +#: src/languages.md:121 src/languages.md:122 src/languages.md:123 +#: src/languages.md:124 src/languages.md:125 src/languages.md:126 +#: src/languages.md:127 src/languages.md:128 src/languages.md:129 +#: src/languages.md:130 src/languages.md:131 src/languages.md:132 +#: src/languages.md:133 src/languages.md:134 src/languages.md:135 +#: src/languages.md:136 src/languages.md:137 src/languages.md:138 +#: src/languages.md:139 src/languages.md:140 +#, fuzzy +msgid "Partial" +msgstr "artifacts" + +#: src/languages.md:119 +#, fuzzy +msgid "`C`" +msgstr "`0`" + +#: src/languages.md:119 src/languages.md:120 src/languages.md:130 +#: src/languages.md:132 +msgid "`doxygen`" +msgstr "`doxygen`" + +#: src/languages.md:120 +msgid "`Cpp` (C++)" +msgstr "" + +#: src/languages.md:121 +#, fuzzy +msgid "`Csharp`" +msgstr "`csharp`" + +#: src/languages.md:121 +msgid "`csharp-xml`" +msgstr "`csharp-xml`" + +#: src/languages.md:122 +#, fuzzy +msgid "`Elixir`" +msgstr "`elixir`" + +#: src/languages.md:122 src/library/cargo-features.md:47 +msgid "`elixir`" +msgstr "`elixir`" + +#: src/languages.md:123 +msgid "`Go`" +msgstr "" + +#: src/languages.md:123 +msgid "`godoc`" +msgstr "`godoc`" + +#: src/languages.md:124 +#, fuzzy +msgid "`Groovy`" +msgstr "`groovy`" + +#: src/languages.md:124 +msgid "`groovydoc`" +msgstr "`groovydoc`" + +#: src/languages.md:125 +#, fuzzy +msgid "`Irules`" +msgstr "`irules`" + +#: src/languages.md:125 src/library/cargo-features.md:50 +msgid "`irules`" +msgstr "`irules`" + +#: src/languages.md:126 +#, fuzzy +msgid "`Java`" +msgstr "`java`" + +#: src/languages.md:126 +msgid "`javadoc`" +msgstr "`javadoc`" + +#: src/languages.md:127 +#, fuzzy +msgid "`Javascript`" +msgstr "`javascript`" + +#: src/languages.md:127 src/languages.md:131 +msgid "`jsdoc`" +msgstr "`jsdoc`" + +#: src/languages.md:128 +#, fuzzy +msgid "`Kotlin`" +msgstr "`kotlin`" + +#: src/languages.md:128 +msgid "`kdoc`" +msgstr "`kdoc`" + +#: src/languages.md:129 +msgid "`Lua`" +msgstr "" + +#: src/languages.md:129 +msgid "`ldoc`" +msgstr "`ldoc`" + +#: src/languages.md:130 +#, fuzzy +msgid "`Mozcpp`" +msgstr "`mozcpp`" + +#: src/languages.md:131 +#, fuzzy +msgid "`Mozjs`" +msgstr "`mozjs`" + +#: src/languages.md:132 +#, fuzzy +msgid "`Objc`" +msgstr "`objc`" + +#: src/languages.md:133 +#, fuzzy +msgid "`Perl`" +msgstr "`perl`" + +#: src/languages.md:133 +msgid "`pod`" +msgstr "`pod`" + +#: src/languages.md:134 +msgid "`Php`" +msgstr "" + +#: src/languages.md:134 +msgid "`bca-php-source`" +msgstr "`bca-php-source`" + +#: src/languages.md:135 +#, fuzzy +msgid "`Python`" +msgstr "`python`" + +#: src/languages.md:135 src/library/cargo-features.md:60 +msgid "`python`" +msgstr "`python`" + +#: src/languages.md:136 +#, fuzzy +msgid "`Ruby`" +msgstr "`ruby`" + +#: src/languages.md:136 +msgid "`yard`" +msgstr "`yard`" + +#: src/languages.md:137 +#, fuzzy +msgid "`Rust`" +msgstr "`rust`" + +#: src/languages.md:137 src/library/cargo-features.md:62 +msgid "`rust`" +msgstr "`rust`" + +#: src/languages.md:138 +msgid "`Tcl`" +msgstr "" + +#: src/languages.md:138 +msgid "`ruff`" +msgstr "`ruff`" + +#: src/languages.md:139 +msgid "`Tsx`" +msgstr "" + +#: src/languages.md:139 src/languages.md:140 +msgid "`bca-typescript-source`" +msgstr "`bca-typescript-source`" + +#: src/languages.md:140 +#, fuzzy +msgid "`Typescript`" +msgstr "`typescript`" + +#: src/languages.md:141 +#, fuzzy +msgid "`Ccomment`" +msgstr "\"comment\"" + +#: src/languages.md:141 src/languages.md:142 +msgid "`helper`" +msgstr "`helper`" + +#: src/languages.md:141 src/languages.md:142 +msgid "No declaration model" +msgstr "" + +#: src/languages.md:142 +msgid "`Preproc`" +msgstr "" + +#: src/languages.md:144 +msgid "" +"The `phpdocumentor` profile for `Php` and `rdoc` for `Ruby` are recognized " +"alternates that return `CollectionError::AdapterUnavailable`, which does not " +"mean the source has no documentation. A profile for another language returns " +"`UnsupportedProfile`. The [form inventory](https://github.com/dekobon/big-" +"code-analysis/blob/main/docs/development/documentation_extraction_cases.md) " +"lists required forms; it is not a claim that every adapter implements them." +msgstr "" +"`Php` の `phpdocumentor` プロファイルと `Ruby` の `rdoc` プロファイルは、認識" +"される代替プロファイルですが `CollectionError::AdapterUnavailable` を返しま" +"す。これはソースに文書がないことを意味しません。他の言語のプロファイルを指定" +"すると `UnsupportedProfile` が返ります。[形式の一覧](https://github.com/" +"dekobon/big-code-analysis/blob/main/docs/development/" +"documentation_extraction_cases.md)は必要な形式を列挙したもので、すべてのアダ" +"プターがそれらを実装しているという意味ではありません。" + +#: src/languages.md:150 +#, fuzzy msgid "" "**Note:** Since #720 the Mozilla/Gecko C++ dialect is exposed as the " "`Mozcpp` `LANG` variant (backed by the vendored `bca-tree-sitter-mozcpp` " @@ -634,7 +898,7 @@ msgstr "一覧" #: src/metrics.md:32 src/metrics-vcs.md:51 src/commands/check.md:76 #: src/recipes/thresholds.md:19 src/library/selecting-metrics.md:53 -#: src/python/metrics.md:110 +#: src/python/metrics.md:116 msgid "Metric" msgstr "メトリクス" @@ -799,7 +1063,7 @@ msgstr "クラスの全メソッドにわたる循環的複雑度の合計" msgid "Chidamber & Kemerer, 1994" msgstr "Chidamber & Kemerer, 1994" -#: src/metrics.md:48 src/python/metrics.md:116 +#: src/metrics.md:48 src/python/metrics.md:122 msgid "ABC" msgstr "ABC" @@ -1036,6 +1300,18 @@ msgid "Figure 3, Rule 7 / Figure 4, Rule 9" msgstr "Figure 3、Rule 7 / Figure 4、Rule 9" #: src/metrics.md:120 +msgid "" +"Each language has a _role table_, a declaration in the source of which tree-" +"sitter node kinds play each syntactic role ([/big-code-analysis-ast/src/" +"roles/](https://github.com/dekobon/big-code-analysis/tree/main/big-code-" +"analysis-ast/src/roles)). Which kinds are a comparison, a short-circuit " +"operator, a ternary or a null-safe operator are its `Comparison`, " +"`ShortCircuit`, `Ternary` and `NullSafe` rows, and the counting rules in the " +"table above read those rows: a row says what a construct _is_; the rule says " +"which occurrence pays." +msgstr "" + +#: src/metrics.md:129 #, fuzzy msgid "" "The short-circuit logical operators (`&&`, `||`, and the per-language " @@ -1052,7 +1328,7 @@ msgstr "" "**寄与しません**。代わりに、単項条件規則によって比較でない各オペランドが 1 条" "件として寄与します。論文はこれを 2 か所で明示しています。" -#: src/metrics.md:129 +#: src/metrics.md:138 #, fuzzy msgid "" "**Listing 2** annotates `(am >= 0 && am <= 0xF) ? '/' : 'C'` as `accc`: one " @@ -1064,7 +1340,7 @@ msgstr "" "ます — 代入 1 つと条件 3 つで、3 つの条件は 2 つの比較(`>=`、`<=`)と三項演" "算子(`?`)です。`&&` 自体の寄与はゼロです。" -#: src/metrics.md:133 +#: src/metrics.md:142 msgid "" "**Rule 7 / Rule 9** instead counts each operand: for `if (x || y) " "printf(\"test failure\\n\");` the paper writes \"there are two unary " @@ -1076,11 +1352,11 @@ msgstr "" "て評価されるため、単項条件は 2 つある」と記しています。ここでも `||` の寄与は" "ゼロで、`x` と `y` がそれぞれ 1 ずつ寄与します。" -#: src/metrics.md:139 src/metrics.md:367 +#: src/metrics.md:148 src/metrics.md:397 msgid "Per-language deviations" msgstr "言語別の逸脱" -#: src/metrics.md:141 +#: src/metrics.md:150 msgid "" "Per-language `impl Abc` blocks narrow the paper rule set where the language " "has no equivalent construct, or where strict literal application would over-" @@ -1090,27 +1366,27 @@ msgstr "" "規則を字義どおり適用すると過剰カウントになる場合に、規則集合を絞り込んでいま" "す。" -#: src/metrics.md:145 src/recipes/thresholds.md:101 +#: src/metrics.md:154 src/metrics.md:2177 src/recipes/thresholds.md:101 msgid "Language" msgstr "言語" -#: src/metrics.md:145 +#: src/metrics.md:154 msgid "Deviation" msgstr "逸脱" -#: src/metrics.md:145 +#: src/metrics.md:154 msgid "Reason" msgstr "理由" -#: src/metrics.md:147 +#: src/metrics.md:156 msgid "C, Go, Rust" msgstr "C、Go、Rust" -#: src/metrics.md:147 +#: src/metrics.md:156 msgid "`try` / `catch` omitted" msgstr "`try` / `catch` を省略" -#: src/metrics.md:147 +#: src/metrics.md:156 msgid "" "No `try`/`catch` keyword in the grammar; error-handling uses `errno` / " "`Result` / `Result`\\-like sums." @@ -1118,11 +1394,11 @@ msgstr "" "文法に `try`/`catch` キーワードがありません。エラー処理には `errno` / " "`Result` / `Result` 系の直和型を使います。" -#: src/metrics.md:148 +#: src/metrics.md:157 msgid "`Rescue` substitutes for `catch`" msgstr "`catch` の代わりに `Rescue`" -#: src/metrics.md:148 +#: src/metrics.md:157 msgid "" "Ruby's exception-handling keyword is `rescue`; the AST node `Rescue` plays " "the role of Java's `catch`." @@ -1130,15 +1406,15 @@ msgstr "" "Ruby の例外処理キーワードは `rescue` であり、AST ノード `Rescue` が Java の " "`catch` の役割を果たします。" -#: src/metrics.md:149 +#: src/metrics.md:158 msgid "All languages" msgstr "全言語" -#: src/metrics.md:149 +#: src/metrics.md:158 msgid "`default` / `_` wildcard arm excluded from the condition set" msgstr "`default` / `_` ワイルドカードアームを条件集合から除外" -#: src/metrics.md:149 +#: src/metrics.md:158 #, fuzzy msgid "" "Fitzpatrick's Figure 2 lists `default`, but it falls through " @@ -1151,7 +1427,7 @@ msgstr "" "`C` が膨らみます。big-code-analysis はすべての言語でこれを省略します(Rust " "の `_ =>` アームや Java の `default:` アームも含みます)。" -#: src/metrics.md:150 src/metrics.md:151 +#: src/metrics.md:159 src/metrics.md:160 msgid "" "Chain-operand, bare-truthy and ternary slots wired; argument and `return` " "slots are not" @@ -1159,7 +1435,7 @@ msgstr "" "チェーンオペランド・裸の真偽値・三項演算子のスロットは実装済み。引数と " "`return` のスロットは未実装" -#: src/metrics.md:150 +#: src/metrics.md:159 #, fuzzy msgid "" "Each operand of a `&&` / `\\|\\|` chain inside `expr {…}` counts as one " @@ -1182,11 +1458,11 @@ msgstr "" "ロットはルーティングされないままです。独立した `expr {…}` コマンド経由でのみ" "到達される否定は依然として 0 を報告します。" -#: src/metrics.md:151 +#: src/metrics.md:160 msgid "iRules" msgstr "iRules" -#: src/metrics.md:151 +#: src/metrics.md:160 #, fuzzy msgid "" "Each operand of a `&&` / `\\|\\|` / `and` / `or` chain counts as one " @@ -1205,7 +1481,7 @@ msgstr "" "致します(#1180)— 引き続き未配線の引数と `return` のスロットを含め、共通の詳" "細はその行を参照してください。" -#: src/metrics.md:152 +#: src/metrics.md:161 #, fuzzy msgid "" "Java, Groovy, C#, Rust, Go, JavaScript, TypeScript, TSX, Mozjs, PHP, C, C++, " @@ -1214,11 +1490,11 @@ msgstr "" "Phase 2 の全言語(Java、Groovy、C#、Rust、Go、JavaScript、TypeScript、TSX、" "Mozjs、PHP、C、C++、Objective-C、Mozcpp、Python、Perl、Lua)" -#: src/metrics.md:152 +#: src/metrics.md:161 msgid "`if (true) {}`, `m(!a, !b)`, `return !x` count their operand(s)" msgstr "`if (true) {}`、`m(!a, !b)`、`return !x` はそのオペランドをカウント" -#: src/metrics.md:152 +#: src/metrics.md:161 msgid "" "These implementations pass `if`, `while`, `do-while`, argument-list and " "`return` expressions through the same condition walker, so the rule applies " @@ -1233,7 +1509,7 @@ msgid "" "Java's array index does." msgstr "" -#: src/metrics.md:153 +#: src/metrics.md:162 msgid "" "Ternary slots: Java, Groovy, C#, C, C++, Objective-C, Mozcpp, JavaScript, " "TypeScript, TSX, Mozjs, PHP, Perl, Ruby, Python, Tcl, iRules" @@ -1241,11 +1517,11 @@ msgstr "" "三項演算子のスロット: Java、Groovy、C#、C、C++、Objective-C、Mozcpp、" "JavaScript、TypeScript、TSX、Mozjs、PHP、Perl、Ruby、Python、Tcl、iRules" -#: src/metrics.md:153 +#: src/metrics.md:162 msgid "`a ? !b : !c` counts its condition and both branch operands" msgstr "`a ? !b : !c` はその条件と両方の分岐被演算子をカウント" -#: src/metrics.md:153 +#: src/metrics.md:162 msgid "" "The same walker also runs over a ternary's three operand slots, so `a ? !" "b : !c` reports 4 (the `?` plus three unary conditions) rather than 1. Tcl " @@ -1268,7 +1544,7 @@ msgstr "" "同様に 4 を報告します。三項演算子を持たない言語(Rust、Go、Kotlin、Lua、" "Elixir)は影響を受けません。" -#: src/metrics.md:154 +#: src/metrics.md:163 #, fuzzy msgid "" "`for` header condition slot: Java, Groovy, C#, C, C++, Objective-C, Mozcpp, " @@ -1277,11 +1553,11 @@ msgstr "" "三項演算子のスロット: Java、Groovy、C#、C、C++、Objective-C、Mozcpp、" "JavaScript、TypeScript、TSX、Mozjs、PHP、Perl、Ruby、Python、Tcl、iRules" -#: src/metrics.md:154 +#: src/metrics.md:163 msgid "`for (; a; )` counts one condition; `for (;;)` counts none" msgstr "" -#: src/metrics.md:154 +#: src/metrics.md:163 msgid "" "The loop header's condition is a decision-bearing slot like an `if` " "predicate, so `for (; a; )`, `for (; !a; )` and `for (; (a); )` each report " @@ -1299,7 +1575,7 @@ msgid "" "carry no boolean-expression slot to route (grammar-dispatch §9) (#1276)." msgstr "" -#: src/metrics.md:155 +#: src/metrics.md:164 msgid "" "Bare-predicate `if` / `unless` / `while` / `until` (block and modifier " "forms) count one condition" @@ -1307,7 +1583,7 @@ msgstr "" "裸の述語の `if` / `unless` / `while` / `until`(ブロック形式と修飾子形式)は " "1 条件としてカウント" -#: src/metrics.md:155 +#: src/metrics.md:164 #, fuzzy msgid "" "Idiomatic Ruby favours bare predicates (`if flag`, `x if flag`); counting " @@ -1325,7 +1601,7 @@ msgstr "" "`&&` / `\\|\\|` チェーンは、それ自身の演算子 / ウォーカーのアームでカウントさ" "れ、二重カウントはされません。" -#: src/metrics.md:156 +#: src/metrics.md:165 #, fuzzy msgid "" "Python, JavaScript, TypeScript, TSX, Mozjs, C, C++, Objective-C, Mozcpp, " @@ -1334,13 +1610,13 @@ msgstr "" "三項演算子のスロット: Java、Groovy、C#、C、C++、Objective-C、Mozcpp、" "JavaScript、TypeScript、TSX、Mozjs、PHP、Perl、Ruby、Python、Tcl、iRules" -#: src/metrics.md:156 +#: src/metrics.md:165 msgid "" "A boolean slot pays one condition unless something inside its predicate " "already counts it" msgstr "" -#: src/metrics.md:156 +#: src/metrics.md:165 msgid "" "Every `if` / `while` / `do` / `for` condition, ternary condition, guard and " "`&&` / `\\|\\|` operand scores the way Ruby's has since #1520: one " @@ -1363,14 +1639,14 @@ msgid "" "slot 1. Go still pays a slot through an operand list (#1526)." msgstr "" -#: src/metrics.md:157 +#: src/metrics.md:166 msgid "" "`if` / `elif` / `while` and each non-wildcard `case` arm count one condition" msgstr "" "`if` / `elif` / `while` と、ワイルドカードでない各 `case` アームは 1 条件とし" "てカウント" -#: src/metrics.md:157 +#: src/metrics.md:166 #, fuzzy msgid "" "A Bash predicate is a _command_, so the branch keyword itself, not an " @@ -1392,11 +1668,11 @@ msgstr "" "も加算しません。分岐キーワードを持たないため、規則の隙間から漏れるのではな" "く、規則群の対象外に位置づけられているのです。" -#: src/metrics.md:158 +#: src/metrics.md:167 msgid "`try` counts a condition alongside `catch`" msgstr "`catch` に加えて `try` も 1 条件としてカウント" -#: src/metrics.md:158 +#: src/metrics.md:167 msgid "" "Fitzpatrick counts both keywords, and Java / C# / C++ / Groovy already count " "both; Kotlin previously counted only the catch block." @@ -1405,16 +1681,16 @@ msgstr "" "両方をカウントしています。Kotlin は以前は catch ブロックのみをカウントしてい" "ました。" -#: src/metrics.md:159 +#: src/metrics.md:168 msgid "C#, Java, Rust, Python, Ruby, Elixir" msgstr "" -#: src/metrics.md:159 +#: src/metrics.md:168 msgid "" "A pattern-match guard is a condition slot, scoring one however it is spelled" msgstr "" -#: src/metrics.md:159 +#: src/metrics.md:168 msgid "" "A guard is a branch: the pattern can match while the guard fails. The " "guard's expression is scored exactly as an `if` condition is (one for a " @@ -1437,13 +1713,13 @@ msgid "" "classify (#1454)." msgstr "" -#: src/metrics.md:160 +#: src/metrics.md:169 msgid "" "A subject-less `when` arm scores through the predicate slot; a subject-ful " "arm scores per entry" msgstr "" -#: src/metrics.md:160 +#: src/metrics.md:169 msgid "" "A subject-less arm's condition (`when { x > 5 -> … }`) is an ordinary " "boolean expression, compiled as an `if` predicate, so the comparison inside " @@ -1454,13 +1730,13 @@ msgid "" "entry itself pays for it (#1421)." msgstr "" -#: src/metrics.md:161 +#: src/metrics.md:170 msgid "" "A subject-less `case` scores each `when` pattern as an `\\|\\|` operand; a " "subject-ful `case` scores per clause" msgstr "" -#: src/metrics.md:161 +#: src/metrics.md:170 msgid "" "A subject-less clause (`case; when x > 5`) lists ordinary boolean " "expressions, evaluated like an `if` predicate, and several patterns (`when " @@ -1472,13 +1748,13 @@ msgid "" "nothing in the source spells, so the clause pays once (#1453)." msgstr "" -#: src/metrics.md:162 +#: src/metrics.md:171 msgid "" "A tagless `switch` scores each case expression as an `\\|\\|` operand; a " "tagged `switch` scores per case" msgstr "" -#: src/metrics.md:162 +#: src/metrics.md:171 msgid "" "A tagless switch (`switch { case x > 5: }`, with or without an init " "statement) is `switch true`: each case expression is an ordinary boolean " @@ -1490,14 +1766,14 @@ msgid "" "case pays once; type-switch and `select` cases are unchanged (#1523)." msgstr "" -#: src/metrics.md:163 +#: src/metrics.md:172 msgid "" "An `if` / `unless` predicate and each `cond` clause are condition slots; " "every other clause construct scores per clause; an `if` / `unless` `else` " "scores one" msgstr "" -#: src/metrics.md:163 +#: src/metrics.md:172 msgid "" "An `if` predicate scores one condition unless an operator inside it already " "counts it, as Ruby's does: `if x > 5` and `if b` each score 1, and `if a && " @@ -1544,17 +1820,17 @@ msgid "" "one (#1581)." msgstr "" -#: src/metrics.md:164 +#: src/metrics.md:173 msgid "" "C++, Objective-C, Mozcpp, Rust, Go, Java, Groovy, C#, Kotlin, TypeScript, " "TSX, JavaScript, Mozjs, Lua, Perl, Ruby, Bash, Elixir" msgstr "" -#: src/metrics.md:164 +#: src/metrics.md:173 msgid "A `<` or `>` that is not a comparison is not a condition" msgstr "" -#: src/metrics.md:164 +#: src/metrics.md:173 msgid "" "Every one of these grammars spells at least one non-comparison construct " "with the same bare `<` / `>` token a comparison uses, so the comparison rule " @@ -1605,15 +1881,15 @@ msgid "" "meant to disagree here (#1395); see [the Halstead delimiter rule](#halstead)." msgstr "" -#: src/metrics.md:165 +#: src/metrics.md:174 msgid "Java, Groovy, C#, TypeScript, TSX" msgstr "" -#: src/metrics.md:165 +#: src/metrics.md:174 msgid "A `?` used as type syntax is not a ternary" msgstr "" -#: src/metrics.md:165 +#: src/metrics.md:174 msgid "" "In each of these grammars the ternary `?` and the type-syntax `?` are the " "_same_ anonymous token, so the ternary rule above is gated on the token's " @@ -1627,17 +1903,17 @@ msgid "" "while the other languages spell theirs as a distinct one." msgstr "" -#: src/metrics.md:166 +#: src/metrics.md:175 msgid "C#, Java, Groovy, Kotlin, Ruby, Elixir, Perl" msgstr "" -#: src/metrics.md:166 +#: src/metrics.md:175 msgid "" "A relational operator scores by use; a value-bearing operand scores in a " "boolean slot" msgstr "" -#: src/metrics.md:166 +#: src/metrics.md:175 msgid "" "Five of these grammars spell at least one relational construct as its own " "production rather than as a binary expression with an operator token: C#'s " @@ -1672,13 +1948,13 @@ msgid "" "slot reads them as a predicate (#1461)." msgstr "" -#: src/metrics.md:167 +#: src/metrics.md:176 msgid "" "A comparison's right operand is not a condition, although the grammar parses " "it as one" msgstr "" -#: src/metrics.md:167 +#: src/metrics.md:176 msgid "" "tree-sitter-perl 1.1.2 lets a chaining comparison (`<`, `>`, `<=`, `>=`, " "`lt`, `gt`, `le`, `ge`, `==`, `!=`, `eq`, `ne`) take everything of lower " @@ -1693,11 +1969,11 @@ msgid "" "goes when the grammar is fixed upstream (#1273)." msgstr "" -#: src/metrics.md:168 +#: src/metrics.md:177 msgid "An auto-quoted hash key is a string, not a call" msgstr "" -#: src/metrics.md:168 +#: src/metrics.md:177 msgid "" "Perl quotes a bareword before `=>` and alone in a hash subscript, a leading " "`-` included, so `(name => 1)`, `new(name => $x)`, `(-name => 1)` and `$h{-" @@ -1713,11 +1989,11 @@ msgid "" "when the grammar is fixed upstream (#1571, #1572)." msgstr "" -#: src/metrics.md:170 +#: src/metrics.md:179 msgid "Where a constructor call lands" msgstr "" -#: src/metrics.md:172 +#: src/metrics.md:181 msgid "" "Fitzpatrick's branch rule is \"function invocation **or object creation**\", " "so object construction and constructor delegation count as branches even " @@ -1726,13 +2002,13 @@ msgid "" "md#semantic-filters)." msgstr "" -#: src/metrics.md:178 +#: src/metrics.md:187 msgid "" "Which _space_ a constructor call is charged to depends on how it is spelled, " "and C# 12 and Kotlin both let you spell it two ways:" msgstr "" -#: src/metrics.md:181 +#: src/metrics.md:190 msgid "" "```csharp\n" "class Sub(int x) : Base(x) { } // charged to the class space\n" @@ -1742,125 +2018,128 @@ msgid "" "```" msgstr "" -#: src/metrics.md:188 +#: src/metrics.md:197 msgid "" -"A primary constructor has no body. Its superclass call sits in the class " -"header (C#'s `base_list`, Kotlin's `delegation_specifiers`), outside every " -"member, so no function space encloses it and the branch belongs to the " -"class. The classic spelling puts the same call inside a constructor " -"declaration, which does open a function space." +"A primary constructor's function space is its parameter list (see [Primary " +"constructors](#nargs-primary-constructors)) and nothing more. Its superclass " +"call sits beside that list in the class header (C#'s `base_list`, Kotlin's " +"`delegation_specifiers`), outside every member, so no function space " +"encloses it and the branch belongs to the class. The classic spelling puts " +"the same call inside a constructor declaration, whose function space does " +"enclose it." msgstr "" -#: src/metrics.md:194 +#: src/metrics.md:205 msgid "" "File-level `abc.branches` is identical either way, so nothing shifts at the " "aggregate. Per-function figures do: `branches_max`, `branches_average`, and " "a per-space `bca check --threshold abc=N` all see the primary-constructor " "form on a class row and never on a function row. A codebase migrating to " "primary constructors will therefore see its per-function ABC distribution " -"move without any behaviour change. That is the intended reading: there is no " -"function to attribute the call to." +"move without any behaviour change. That is the intended reading: the " +"constructor's space holds its parameters, and the call to the base is not " +"among them." msgstr "" -#: src/metrics.md:202 +#: src/metrics.md:214 msgid "Worked example" msgstr "実例" -#: src/metrics.md:204 +#: src/metrics.md:216 msgid "Consider this C function:" msgstr "次の C 関数を考えます。" -#: src/metrics.md:210 +#: src/metrics.md:222 msgid "'/'" msgstr "'/'" -#: src/metrics.md:212 src/metrics.md:235 +#: src/metrics.md:224 src/metrics.md:247 msgid "'C'" msgstr "'C'" -#: src/metrics.md:218 +#: src/metrics.md:230 msgid "Walking the function body:" msgstr "関数本体を走査すると、次のようになります。" -#: src/metrics.md:220 +#: src/metrics.md:232 msgid "Token / construct" msgstr "トークン / 構文" -#: src/metrics.md:220 +#: src/metrics.md:232 msgid "Component" msgstr "コンポーネント" -#: src/metrics.md:220 +#: src/metrics.md:232 msgid "Why" msgstr "理由" -#: src/metrics.md:222 +#: src/metrics.md:234 msgid "`am >= 0`" msgstr "`am >= 0`" -#: src/metrics.md:222 src/metrics.md:223 src/metrics.md:225 +#: src/metrics.md:234 src/metrics.md:235 src/metrics.md:237 msgid "C += 1" msgstr "C += 1" -#: src/metrics.md:222 +#: src/metrics.md:234 msgid "Comparison (Rule 5, `>=`)" msgstr "比較(Rule 5、`>=`)" -#: src/metrics.md:223 +#: src/metrics.md:235 msgid "`am <= 0xF`" msgstr "`am <= 0xF`" -#: src/metrics.md:223 +#: src/metrics.md:235 msgid "Comparison (Rule 5, `<=`)" msgstr "比較(Rule 5、`<=`)" -#: src/metrics.md:224 +#: src/metrics.md:236 msgid "`&&`" msgstr "`&&`" -#: src/metrics.md:224 +#: src/metrics.md:236 msgid "(none)" msgstr "" -#: src/metrics.md:224 +#: src/metrics.md:236 #, fuzzy msgid "Logical operator; does not contribute on its own." msgstr "論理演算子 — 単独では寄与しません。" -#: src/metrics.md:225 +#: src/metrics.md:237 msgid "`if`/`else`" msgstr "`if`/`else`" -#: src/metrics.md:225 +#: src/metrics.md:237 msgid "`else` keyword (Rule 5)" msgstr "`else` キーワード(Rule 5)" -#: src/metrics.md:226 +#: src/metrics.md:238 msgid "`c = '/'`" msgstr "`c = '/'`" -#: src/metrics.md:226 src/metrics.md:227 +#: src/metrics.md:238 src/metrics.md:239 msgid "A += 1" msgstr "A += 1" -#: src/metrics.md:226 src/metrics.md:227 +#: src/metrics.md:238 src/metrics.md:239 msgid "Assignment (Rule 1)" msgstr "代入(Rule 1)" -#: src/metrics.md:227 +#: src/metrics.md:239 msgid "`c = 'C'`" msgstr "`c = 'C'`" -#: src/metrics.md:229 +#: src/metrics.md:241 msgid "Total: ` = <2, 0, 3>`, magnitude `√13 ≈ 3.61`." msgstr "合計: ` = <2, 0, 3>`、マグニチュードは `√13 ≈ 3.61` です。" -#: src/metrics.md:231 +#: src/metrics.md:243 #, fuzzy msgid "If the same body is rewritten with a unary conditional:" msgstr "同じ本体を単項条件を使って書き換えると —" -#: src/metrics.md:239 +#: src/metrics.md:251 msgid "" "the walker counts `am_in_range` and `force_letter` once each (Rule 7 / 9 " "unary conditional). The `||` operator itself contributes zero. This matches " @@ -1874,11 +2153,11 @@ msgstr "" "` — 「x と y の両方が条件式として評価されるため、単項条件は 2 つある」— と一" "致します。" -#: src/metrics.md:246 +#: src/metrics.md:258 msgid "Comparison with other ABC tools" msgstr "他の ABC ツールとの比較" -#: src/metrics.md:248 +#: src/metrics.md:260 #, fuzzy msgid "" "The project follows Fitzpatrick's original paper for `&&` / `||`: the " @@ -1899,15 +2178,15 @@ msgstr "" "す。ツール間で ABC の数値を比較するとき、同じソースに対する食い違いの最大の原" "因は、この演算子カウントの選択です。" -#: src/metrics.md:258 src/metrics.md:312 src/metrics.md:472 src/metrics.md:1040 -#: src/metrics.md:1438 src/metrics.md:1886 src/metrics-vcs.md:82 -#: src/metrics-vcs.md:121 src/metrics-vcs.md:184 src/metrics-vcs.md:226 -#: src/metrics-vcs.md:295 src/metrics-vcs.md:335 src/metrics-vcs.md:482 -#: src/metrics-vcs.md:523 +#: src/metrics.md:270 src/metrics.md:330 src/metrics.md:525 src/metrics.md:1134 +#: src/metrics.md:1568 src/metrics.md:2264 src/metrics-vcs.md:82 +#: src/metrics-vcs.md:125 src/metrics-vcs.md:188 src/metrics-vcs.md:230 +#: src/metrics-vcs.md:299 src/metrics-vcs.md:339 src/metrics-vcs.md:488 +#: src/metrics-vcs.md:529 msgid "Algorithm" msgstr "アルゴリズム" -#: src/metrics.md:260 +#: src/metrics.md:272 #, fuzzy msgid "" "The metric walk passes syntax-tree nodes to the language's `Abc` " @@ -1920,13 +2199,13 @@ msgstr "" "か?分岐か?条件か?_ — を尋ね、一致したカウンタをインクリメントします。4 つ" "の主要値は次のとおりです。" -#: src/metrics.md:265 +#: src/metrics.md:277 msgid "" "the three components themselves, `assignments`, `branches`, `conditions`;" msgstr "" "3 つのコンポーネントそのもの(`assignments`、`branches`、`conditions`)。" -#: src/metrics.md:267 +#: src/metrics.md:279 msgid "" "the **magnitude** `|| = √(A² + B² + C²)`, which is the way " "Fitzpatrick recommends summarising the vector as a single number." @@ -1934,7 +2213,7 @@ msgstr "" "**マグニチュード** `|| = √(A² + B² + C²)`。Fitzpatrick がベクトルを単" "一の数値へ要約する方法として推奨しているものです。" -#: src/metrics.md:270 +#: src/metrics.md:282 #, fuzzy msgid "" "The full serialised output (`src/metrics/abc.rs`) emits these four together " @@ -1954,18 +2233,18 @@ msgstr "" "フィールドになります。このメトリクスは `src/languages/language_*.rs` で言語ご" "とに特殊化されています。" -#: src/metrics.md:279 src/metrics.md:348 src/metrics.md:565 src/metrics.md:994 -#: src/metrics.md:1289 src/metrics.md:1453 src/metrics.md:1593 -#: src/metrics.md:1635 src/metrics.md:1683 src/metrics.md:1774 -#: src/metrics.md:1815 src/metrics.md:1852 src/metrics.md:1898 -#: src/metrics-vcs.md:94 src/metrics-vcs.md:129 src/metrics-vcs.md:154 -#: src/metrics-vcs.md:195 src/metrics-vcs.md:235 src/metrics-vcs.md:263 -#: src/metrics-vcs.md:306 src/metrics-vcs.md:346 src/metrics-vcs.md:414 -#: src/metrics-vcs.md:444 src/metrics-vcs.md:492 src/metrics-vcs.md:546 +#: src/metrics.md:291 src/metrics.md:378 src/metrics.md:658 src/metrics.md:1088 +#: src/metrics.md:1419 src/metrics.md:1583 src/metrics.md:1917 +#: src/metrics.md:1961 src/metrics.md:2040 src/metrics.md:2131 +#: src/metrics.md:2193 src/metrics.md:2230 src/metrics.md:2276 +#: src/metrics-vcs.md:98 src/metrics-vcs.md:133 src/metrics-vcs.md:158 +#: src/metrics-vcs.md:199 src/metrics-vcs.md:239 src/metrics-vcs.md:267 +#: src/metrics-vcs.md:310 src/metrics-vcs.md:350 src/metrics-vcs.md:418 +#: src/metrics-vcs.md:450 src/metrics-vcs.md:498 src/metrics-vcs.md:552 msgid "How to read it" msgstr "読み方" -#: src/metrics.md:281 +#: src/metrics.md:293 #, fuzzy msgid "" "ABC is a _size_ metric, not a complexity metric: a long, dull function with " @@ -1978,7 +2257,7 @@ msgstr "" "は、マグニチュードを相対的な物差しとして使うことでした。すなわち、ファイル内" "の関数を ABC マグニチュードで順位付けし、上位 1 割に注目します。" -#: src/metrics.md:287 +#: src/metrics.md:299 #, fuzzy msgid "" "In practice the Ruby community adopted ABC most widely; the [`rubocop` " @@ -1997,11 +2276,11 @@ msgstr "" "固有です — 明示的なゲッター / セッター代入をより多用する C++ や Java では、よ" "り高い値になると考えてください。" -#: src/metrics.md:296 +#: src/metrics.md:308 msgid "Cognitive Complexity" msgstr "認知的複雑度" -#: src/metrics.md:298 +#: src/metrics.md:310 #, fuzzy msgid "" "G. Ann Campbell at [SonarSource](https://www.sonarsource.com/) introduced " @@ -2009,7 +2288,12 @@ msgid "" "new way of measuring understandability_](https://www.sonarsource.com/docs/" "CognitiveComplexity.pdf) and the follow-up IEEE TechDebt 2018 paper " "[_Cognitive Complexity: An Overview and Evaluation_](https://ieeexplore.ieee." -"org/document/8595102/)." +"org/document/8595102/). The white paper's link always serves the latest " +"revision, and the rules have been reworded since 2017: v1.5 made the multi-" +"level `break` / `continue` increment explicit. This chapter and the source " +"cite it at v1.7, 29 August 2023, where Appendix B's §B1 lists the " +"increments, §B2 the structures that raise the nesting level, and §B3 the " +"ones that pay a nesting increment." msgstr "" "**認知的複雑度**は、SonarSource の G. Ann Campbell が 2017 年のホワイトペー" "パー _Cognitive Complexity — A new way of measuring understandability_ と、そ" @@ -2019,7 +2303,7 @@ msgstr "" "(https://www.sonarsource.com/docs/CognitiveComplexity.pdf) として入手できま" "す。" -#: src/metrics.md:305 +#: src/metrics.md:323 #, fuzzy msgid "" "The metric was designed as a replacement for Cyclomatic Complexity in code-" @@ -2036,14 +2320,14 @@ msgstr "" "になりますが、人間の読み手にとってはネストしたコードの方がはるかに追いにくい" "のです。" -#: src/metrics.md:314 +#: src/metrics.md:332 msgid "" "Cognitive Complexity starts at zero and applies three rules as it walks the " "tree:" msgstr "" "認知的複雑度はゼロから始まり、木を走査しながら次の 3 つの規則を適用します。" -#: src/metrics.md:317 +#: src/metrics.md:335 #, fuzzy msgid "" "**Ignore \"shorthand\" control flow.** Constructs that route to a single " @@ -2056,7 +2340,7 @@ msgstr "" "ヘッダ、`?:` 三項演算子 — は、それぞれ基本の `+1` を加えますが、そのパターン" "自体へのペナルティはありません。" -#: src/metrics.md:321 +#: src/metrics.md:339 msgid "" "**Penalise breaks in linear flow.** Conditionals, switches, loops, `catch` " "clauses and labeled jumps add increments under the rules below. A `try` " @@ -2065,7 +2349,7 @@ msgid "" "recursive call costs nothing (see the per-language deviations below)." msgstr "" -#: src/metrics.md:327 +#: src/metrics.md:345 msgid "" "**Punish nesting.** Every time control flow appears _inside_ an already-" "nested block, the metric adds an extra `+1` _per level of nesting_. An `if` " @@ -2078,7 +2362,8 @@ msgstr "" "内の外側の `if` の中の `for` の中の `if` は `1 + 2 + 3 = 6` になりますが、同" "じ 3 つの構文をフラットに並べた場合は `1 + 1 + 1 = 3` です。" -#: src/metrics.md:333 +#: src/metrics.md:351 +#, fuzzy msgid "" "Sequences of identical boolean operators (`a && b && c`) score `+1` for the " "whole run, on the grounds that a chain of `&&`s is no harder to read than a " @@ -2087,22 +2372,40 @@ msgid "" "same logical operation, not the same token: where a language spells " "conjunction and disjunction both ways (C++, Ruby, PHP, Perl, Elixir, " "iRules), `a && b and c` is one sequence. Precedence still decides what nests " -"where, so Ruby's `a || b and c` is `(a || b) and c` and scores two. `??` and " -"Perl's `//` are operations of their own; `xor`, like `^`, is no sequence." +"where, so Ruby's `a || b and c` is `(a || b) and c` and scores two. `xor`, " +"like `^`, is no sequence." +msgstr "" +"同一のブール演算子の連なり(`a && b && c`)は、`&&` の連鎖は単一の `&&` より" +"読みにくいわけではないという理由で、連なり全体で `+1` になります。演算子が切" +"り替わる(`a && b || c`)ところで認知負荷が跳ね上がるため、2 つ目の演算子は独" +"自の `+1` を得ます。" + +#: src/metrics.md:362 +msgid "" +"The null-coalescing operators are not sequences either, or anything else: " +"the paper's \"Ignore shorthand\" section (v1.7, page 6) sets them aside as a " +"one-line spelling of `if (x == null) …`, and so does big-code-analysis. `??` " +"in the JavaScript family, C# and PHP, the Elvis `?:` of Kotlin and Groovy, " +"Perl's defined-or `//`, the compound `??=` / `//=` and every safe navigation " +"(`?.`, `&.`, `?->`) score nothing. Until #1800 the coalescing operators were " +"folded into the boolean sequence for parity with cyclomatic complexity, " +"which still counts each of them as a decision." msgstr "" -#: src/metrics.md:344 +#: src/metrics.md:372 #, fuzzy msgid "" "big-code-analysis exports the per-space structural score as `value` along " -"with the subtree `sum`, `min`, `max`, and a per-function `average`. The " -"implementation is in `src/metrics/cognitive.rs`." +"with the subtree `sum` and a per-function `average`, `min` and `max`; the " +"[aggregate population](#aggregate-population) section below says exactly " +"which spaces those three read. The implementation is in `src/metrics/" +"cognitive.rs`." msgstr "" "big-code-analysis は、関数ごとの構造スコアに加えて、ファイル全体の `sum`、" "`min`、`max` と関数ごとの `average` を出力します。実装は `src/metrics/" "cognitive.rs` にあります。" -#: src/metrics.md:350 +#: src/metrics.md:380 #, fuzzy msgid "" "A Cognitive Complexity of `0` means the function is purely linear: no " @@ -2119,7 +2422,7 @@ msgstr "" "滑らかにスケールします。判断の数が同じでも、深くネストしたコードはフラットな" "コードより大幅に高いスコアになります。" -#: src/metrics.md:358 +#: src/metrics.md:388 #, fuzzy msgid "" "The common use is **refactoring guidance during code review**: because the " @@ -2138,21 +2441,38 @@ msgstr "" "クスはその後、Sonar エコシステム外のいくつかの言語サーバーやコードレビュープ" "ラットフォームにも採用されています。" -#: src/metrics.md:369 +#: src/metrics.md:399 msgid "" -"**No language** scores the recursion increment (B3): the metric walk " +"What follows is where the implementation and the paper's Appendix B part, or " +"where the paper has nothing to say. Null coalescing is _not_ on this list " +"since #1800: it follows the paper now (see the paragraph above). The " +"numbered `break N` / `continue N` of PHP and Bash is listed below only " +"because the paper's §B1 names it and a reader may not expect a level to " +"count as a label." +msgstr "" + +#: src/metrics.md:406 +msgid "" +"**No language** scores the recursion increment (B1): the metric walk " "resolves no calls, so a function calling itself costs nothing beyond its " "explicit control flow." msgstr "" -#: src/metrics.md:372 +#: src/metrics.md:409 +msgid "" +"**Ruby**'s `redo` and `retry` add `+1` each. §B1's jump bullet names only " +"`goto` and a `break` / `continue` to a label or number; these two are scored " +"by analogy with it, as unstructured jumps with no structured spelling." +msgstr "" + +#: src/metrics.md:413 msgid "" "**Elixir** does not score jump statements either. Elixir control flow " "(`if` / `unless` / `cond` / `case` / `with` / `receive`) is built from macro-" "shaped `Call` nodes rather than dedicated grammar productions, and the " "language has no `break` / `continue` / `goto`. The implementation therefore " "scores only the nesting-bearing constructs it can identify and omits the " -"unstructured-jump (B2) increments that the SonarSource specification adds " +"unstructured-jump (B1) increments that the SonarSource specification adds " "for languages that expose those shapes syntactically. A `with` expression's " "`else` clauses act like `case` arms. The `with` expression already " "contributes the nesting increment, so its `else` adds nothing, just as " @@ -2165,7 +2485,7 @@ msgid "" "scores nothing (#1581)." msgstr "" -#: src/metrics.md:390 +#: src/metrics.md:431 #, fuzzy msgid "" "For every language with a syntactic function-definition node, a nested " @@ -2181,19 +2501,25 @@ msgstr "" "外側の関数のネストではなく、ネストした関数自身の深さに対してスコアされます。" "したがって、バイト単位で等価な構文は言語間で同一のスコアになります。" -#: src/metrics.md:397 +#: src/metrics.md:438 +#, fuzzy msgid "" "A lambda or closure (`x -> …`, `|x| …`, `lambda x: …`, a Ruby block, an " "Objective-C block) is not a function boundary in that sense. It adds a " "surcharge _on top of_ the enclosing nesting instead of replacing it, so a " -"decision inside a lambda written inside an `if` is charged for both." +"decision inside a lambda written inside an `if` is charged for both. Which " +"kinds are a closure, and which open a function boundary, are each language's " +"`Closure` and `FuncOpener` rows in its role table (see [Conditions]" +"(#conditions) above for what a role table is); a kind can be on both " +"(Elixir's `fn … end` opens a space and is a closure), and the surcharge rule " +"reads the `Closure` row." msgstr "" "ラムダやクロージャ(`x -> …`、`|x| …`、`lambda x: …`、Ruby のブロック、" "Objective-C のブロック)は、その意味での関数境界ではありません。外側のネスト" "を置き換えるのではなく、その「上に」上乗せ分を追加するため、`if` の内側に書か" "れたラムダの中の決定には両方の分が課されます。" -#: src/metrics.md:402 +#: src/metrics.md:448 #, fuzzy msgid "" "That surcharge stops at the next function boundary. A function _declared " @@ -2213,7 +2539,17 @@ msgstr "" "C++、PHP、C# ではスコアが異なっていました。Python はこの形をそもそも表現でき" "ません。`def` は文であり、ラムダ本体は単一の式だからです。" -#: src/metrics.md:411 +#: src/metrics.md:457 +msgid "" +"**PHP and Bash** score `break N` / `continue N`, the only non-default jump " +"argument either has, at a flat `+1` for any explicit level, `break 1` " +"included — §B1's `break NUMBER` / `continue NUMBER`, and what sonar-php " +"does. A bare `break` / `continue` adds nothing. Before #1765 the numeric " +"form scored `+0` in both as a structured loop-level exit; Bash's parses as a " +"plain `command`, so it is read by its leading word." +msgstr "" + +#: src/metrics.md:464 msgid "" "**Rust**'s `let`\\-`else` (`let Some(a) = y else { continue };`) postdates " "the specification. It is scored as the `if let` it replaces: `+1` plus the " @@ -2224,7 +2560,7 @@ msgid "" "so that `for` scored 2." msgstr "" -#: src/metrics.md:419 +#: src/metrics.md:472 msgid "" "**Python** charges a boolean operator an extra `+1` for each enclosing " "`lambda`, on top of the `+1` the boolean sequence itself earns. No other " @@ -2247,60 +2583,60 @@ msgstr "" "うため、1 つのラムダ内の混合連鎖は増分 2 つと上乗せ分 1 つを支払います。実測" "値は次のとおりです。" -#: src/metrics.md:431 +#: src/metrics.md:484 msgid "Python source" msgstr "Python ソース" -#: src/metrics.md:431 +#: src/metrics.md:484 msgid "`cognitive.sum`" msgstr "`cognitive.sum`" -#: src/metrics.md:433 +#: src/metrics.md:486 msgid "`g = a and b`" msgstr "`g = a and b`" -#: src/metrics.md:433 src/metrics.md:438 +#: src/metrics.md:486 src/metrics.md:491 msgid "1" msgstr "1" -#: src/metrics.md:434 +#: src/metrics.md:487 msgid "`g = lambda y: y and a`" msgstr "`g = lambda y: y and a`" -#: src/metrics.md:434 src/metrics.md:435 +#: src/metrics.md:487 src/metrics.md:488 msgid "2" msgstr "2" -#: src/metrics.md:435 +#: src/metrics.md:488 msgid "`g = lambda y: y and a and b`" msgstr "`g = lambda y: y and a and b`" -#: src/metrics.md:436 +#: src/metrics.md:489 msgid "`g = lambda y: y and a or b`" msgstr "`g = lambda y: y and a or b`" -#: src/metrics.md:436 src/metrics.md:437 +#: src/metrics.md:489 src/metrics.md:490 msgid "3" msgstr "3" -#: src/metrics.md:437 +#: src/metrics.md:490 msgid "`g = lambda x: (lambda y: y and a)`" msgstr "`g = lambda x: (lambda y: y and a)`" -#: src/metrics.md:438 +#: src/metrics.md:491 msgid "`k = lambda q: (yield a and b, c)`" msgstr "`k = lambda q: (yield a and b, c)`" -#: src/metrics.md:439 +#: src/metrics.md:492 msgid "`def f(a): g = lambda x: x`" msgstr "`def f(a): g = lambda x: x`" -#: src/metrics.md:439 src/recipes/thresholds.md:412 -#: src/recipes/thresholds.md:413 +#: src/metrics.md:492 src/recipes/thresholds.md:500 +#: src/recipes/thresholds.md:501 msgid "0" msgstr "0" -#: src/metrics.md:441 +#: src/metrics.md:494 msgid "" "The last two rows are the boundaries. The parenthesised `yield` puts an " "`expression_list` between the operator and the `lambda`, ending the walk " @@ -2312,7 +2648,7 @@ msgstr "" "`+1` だけが残ります。また、ブール演算子を含まないラムダはそれ自体では何のコス" "トも生じません。" -#: src/metrics.md:446 +#: src/metrics.md:499 msgid "" "Campbell gives a boolean sequence a fundamental increment and no nesting " "increment, so this is an addition to the specification rather than an " @@ -2325,11 +2661,11 @@ msgstr "" "ビューし、意図的に維持しました。Python のブール演算子のコストは、同じコードに" "対する他言語のスコアとは比較できません。" -#: src/metrics.md:452 +#: src/metrics.md:505 msgid "Cyclomatic Complexity (CC)" msgstr "循環的複雑度(CC)" -#: src/metrics.md:454 +#: src/metrics.md:507 #, fuzzy msgid "" "Cyclomatic Complexity is the original software complexity metric. Thomas J. " @@ -2342,7 +2678,7 @@ msgstr "" "Transactions on Software Engineering, SE-2(4), 308–320 ページ)で導入しまし" "た。" -#: src/metrics.md:459 +#: src/metrics.md:512 msgid "" "McCabe's idea was to apply graph theory to the _control-flow graph_ of a " "function. If you draw every basic block as a node and every jump between " @@ -2352,7 +2688,7 @@ msgstr "" "た。各基本ブロックをノード、ブロック間の各ジャンプをエッジとして描くと、その" "グラフのサイクロマティック数は次のようになります。" -#: src/metrics.md:467 +#: src/metrics.md:520 #, fuzzy msgid "" "where `E` is the number of edges, `N` the number of nodes, and `P` the " @@ -2364,7 +2700,7 @@ msgstr "" "`M` が関数を通る**線形独立パス**の数、言い換えれば、すべての分岐を少なくとも " "1 回カバーするのに必要な最小のテストケース数と正確に一致することです。" -#: src/metrics.md:474 +#: src/metrics.md:527 #, fuzzy msgid "" "big-code-analysis does not build a control-flow graph. Instead it uses the " @@ -2375,38 +2711,38 @@ msgstr "" "ん。代わりに、McCabe が 1976 年の論文で構造化プログラムについて証明した、等価" "ではるかに安価な定式化を使います。" -#: src/metrics.md:478 +#: src/metrics.md:531 msgid "_Cyclomatic Complexity = 1 + (number of decision points)_" msgstr "_循環的複雑度 = 1 + (判断点の数)_" -#: src/metrics.md:480 +#: src/metrics.md:533 msgid "A \"decision point\" is any node where control can branch:" msgstr "「判断点」とは、制御が分岐しうるあらゆるノードのことです。" -#: src/metrics.md:482 +#: src/metrics.md:535 msgid "`if`, `else if`, ternary `?:`" msgstr "`if`、`else if`、三項演算子 `?:`" -#: src/metrics.md:483 +#: src/metrics.md:536 msgid "`case` / `when` arms in `switch` / `match` / `select`" msgstr "`switch` / `match` / `select` 内の `case` / `when` アーム" -#: src/metrics.md:484 +#: src/metrics.md:537 msgid "`while`, `do … while`, every variant of `for`" msgstr "`while`、`do … while`、あらゆる種類の `for`" -#: src/metrics.md:485 +#: src/metrics.md:538 msgid "exception-handler `catch` clauses" msgstr "例外ハンドラの `catch` 節" -#: src/metrics.md:486 +#: src/metrics.md:539 msgid "" "short-circuit boolean operators `&&` and `||`, including their word " "spellings (`and` / `or` in C++, Python, Ruby, Lua, Perl, PHP, Elixir and " "iRules)" msgstr "" -#: src/metrics.md:490 +#: src/metrics.md:543 msgid "" "A `&&` or `||` counts only where it applies the operator. C++ also spells " "the token in rvalue references (`int&& x`), the ref-qualifier (`void f() " @@ -2419,7 +2755,7 @@ msgid "" "`concept C = A && B`." msgstr "" -#: src/metrics.md:501 +#: src/metrics.md:554 msgid "" "The per-language `Cyclomatic` trait, in `src/metrics/cyclomatic.rs`, asks " "each tree-sitter node \"are you a decision?\" and increments the counter. " @@ -2431,11 +2767,66 @@ msgstr "" "このメトリクスは関数ごととファイルごとにロールアップされます。メソッド本体を" "またぐクラス単位の集約は、後述の [WMC](#wmc) が別途提供します。" -#: src/metrics.md:507 +#: src/metrics.md:560 +#, fuzzy +msgid "Aggregate population" +msgstr "集約レポート" + +#: src/metrics.md:562 +msgid "" +"Every space carries its own `value`, a subtree `sum`, and a per-function " +"`average`, `min` and `max`. The three per-function fields read **one " +"population**: the spaces of kind `function` in the subtree, named functions, " +"methods, and every closure form that opens a space of its own (a Rust `|x| …" +"`, a JavaScript arrow function, a Java anonymous-class method, a Kotlin " +"property accessor or `init` block, a `static {}` initializer). `average` is " +"the mean of their `value`s, `min` and `max` their extremes, so `min <= " +"average <= max` holds on every space. A subtree with no function space " +"reports `average 0.0`, `min 0`, `max 0`." +msgstr "" + +#: src/metrics.md:573 +msgid "Two things are deliberately _not_ in that population:" +msgstr "" + +#: src/metrics.md:575 +msgid "" +"**Containers and the file unit.** Each still contributes its own `value` — " +"base 1 for cyclomatic, its module-level decisions for all three — to `sum`, " +"which is what [MI](#maintainability-index-mi) and [WMC](#wmc) read, but not " +"to the per-function fields. Before #1284 the numerator and the extrema " +"folded every space while the divisor counted functions only, so a file " +"holding one branch-free function reported cyclomatic `average 2.0` against " +"`min 1, max 1`, and the unit's own `0` pinned file-level cognitive `min` at " +"`0` whatever the functions scored." +msgstr "" + +#: src/metrics.md:584 +msgid "" +"**Closures that open no space.** A Python `lambda` is counted by [NOM](#nom) " +"but has no space of its own: its decisions are part of the enclosing " +"function's `value`, so that function is the one population member they " +"belong to. Before #1284 cognitive and NExits divided by `nom`'s total " +"instead, and a function holding one lambda could report `average 7.0` " +"against `min 14, max 14`." +msgstr "" + +#: src/metrics.md:591 +msgid "" +"The same three fields on `cognitive` and `nexits` follow this rule; `sum` on " +"all three keeps its all-spaces meaning. [NArgs](#nargs-aggregates) does not " +"follow it: its extrema fold every space and its averages divide by the " +"function and closure counts of [NOM](#nom), so `closure_args_average` can " +"fall below `closure_args_min` (#1809). The remaining metrics' `*_average` / " +"`*_min` / `*_max` fields are per-space averages over every space in the " +"subtree, as their sections say." +msgstr "" + +#: src/metrics.md:600 msgid "Modified cyclomatic" msgstr "修正循環的複雑度" -#: src/metrics.md:509 +#: src/metrics.md:602 #, fuzzy msgid "" "big-code-analysis also reports a **modified** variant that collapses all " @@ -2458,7 +2849,7 @@ msgstr "" "m` モードを踏襲したもので、多くの読者はそこで初めて目にしているはずです。)両" "方の数値は並べて出力されます。どちらか一方を選び、一貫して使ってください。" -#: src/metrics.md:520 +#: src/metrics.md:613 msgid "" "Only alternatives collapse. A sequence of tests is still one decision per " "test in both variants. Elixir's `with` is the case where the two meet: each " @@ -2471,7 +2862,7 @@ msgid "" "as its `if let` twin does. Before #1542 it scored nothing." msgstr "" -#: src/metrics.md:531 +#: src/metrics.md:624 msgid "" "Elixir's `receive` is a `case` over the mailbox, and modified scores its " "clauses once, as it does a `case`'s. Like a `case` it has one free arm: its " @@ -2483,11 +2874,11 @@ msgid "" "holding only an `after` is a timed wait and scores nothing at all (#1581)." msgstr "" -#: src/metrics.md:541 +#: src/metrics.md:634 msgid "Counting Rust's `?` operator" msgstr "Rust の `?` 演算子のカウント" -#: src/metrics.md:543 +#: src/metrics.md:636 #, fuzzy msgid "" "By default Rust's `?` operator (the `try_expression` grammar node) adds `+1` " @@ -2504,12 +2895,12 @@ msgstr "" "しているだけの、線形だが失敗しうるコードに過剰なペナルティを与えることがあり" "ます。次の方法でオプトアウトし、`?` を線形なエラー伝播として扱えます。" -#: src/metrics.md:551 +#: src/metrics.md:644 msgid "Library: `MetricsOptions::default().with_count_cyclomatic_try(false)`." msgstr "" "ライブラリ: `MetricsOptions::default().with_count_cyclomatic_try(false)`。" -#: src/metrics.md:552 +#: src/metrics.md:645 msgid "" "CLI: `--cyclomatic-count-try=false` (or the deprecated `--no-cyclomatic-try` " "alias), or `cyclomatic_count_try = false` in `bca.toml` (the CLI value " @@ -2519,7 +2910,7 @@ msgstr "" "イリアス)、あるいは `bca.toml` の `cyclomatic_count_try = false`(CLI の値は" "どちらの方向でもこのキーを上書きします)。" -#: src/metrics.md:555 +#: src/metrics.md:648 #, fuzzy msgid "" "A repo gate: set `cyclomatic_count_try = false` in the auto-discovered `bca." @@ -2533,7 +2924,7 @@ msgstr "" "の値を変化させるため、同じ変更の中で `.bca-baseline.toml` を再生成してくださ" "い。" -#: src/metrics.md:561 +#: src/metrics.md:654 #, fuzzy msgid "" "The default is unchanged (`?` keeps counting), so published metric values " @@ -2544,7 +2935,7 @@ msgstr "" "クス値は保たれます。このトグルは Rust 専用です。他の言語は `try_expression` " "を出力しません。" -#: src/metrics.md:567 +#: src/metrics.md:660 msgid "" "McCabe's original recommendation, repeated in the 1976 paper and preserved " "by [NIST's _Structured Testing_ report](https://www.nist.gov/publications/" @@ -2560,12 +2951,12 @@ msgstr "" "ことです。これを超えると、分岐カバレッジに必要なテストケース数が不快なほど増" "大します。" -#: src/metrics.md:574 +#: src/metrics.md:667 #, fuzzy msgid "Cyclomatic complexity is used for three things:" msgstr "_循環的複雑度 = 1 + (判断点の数)_" -#: src/metrics.md:576 +#: src/metrics.md:669 #, fuzzy msgid "" "**Defect prediction.** Complexity correlates, imperfectly, with the " @@ -2575,13 +2966,13 @@ msgstr "" "**欠陥予測。** 複雑度は — 完全ではないものの — 関数がバグを含む _確率_ とよく" "相関し、ほとんどの静的解析ツールは CC の高い関数をリスクありとフラグします。" -#: src/metrics.md:579 +#: src/metrics.md:672 msgid "" "**Test planning.** CC measures the size of a basis-path test set, not the " "minimum test count for branch coverage." msgstr "" -#: src/metrics.md:581 +#: src/metrics.md:674 msgid "" "**Refactor triage.** Cyclomatic Complexity is the headline \"complexity\" " "number in almost every code-quality dashboard, often as a tie-breaker " @@ -2591,7 +2982,7 @@ msgstr "" "シュボードで筆頭に挙げられる「複雑度」の数値であり、長さが同程度に見える 2 つ" "の関数の優先順位を決めるタイブレーカーとしてもよく使われます。" -#: src/metrics.md:586 +#: src/metrics.md:679 #, fuzzy msgid "" "The metric's known blind spot is that it treats every decision as equal " @@ -2606,11 +2997,11 @@ msgstr "" "く異なるにもかかわらず、どちらもおよそ 30 というスコアになります。認知的複雑" "度(前述)は、まさにこの点を解決するために設計されました。" -#: src/metrics.md:592 src/commands/check.md:79 src/python/metrics.md:115 +#: src/metrics.md:685 src/commands/check.md:79 src/python/metrics.md:121 msgid "Halstead" msgstr "Halstead" -#: src/metrics.md:594 +#: src/metrics.md:687 #, fuzzy msgid "" "The **Halstead suite** is the oldest size-and-effort metric family on this " @@ -2632,11 +3023,11 @@ msgstr "" "のと同じ意味で、定量的・経験的な _ソフトウェアの科学_ を打ち立てようとしたの" "です。" -#: src/metrics.md:605 +#: src/metrics.md:698 msgid "The four base counts" msgstr "4 つの基本カウント" -#: src/metrics.md:607 +#: src/metrics.md:700 msgid "" "Halstead reduces a program to its tokens, then partitions them into two " "categories:" @@ -2644,7 +3035,7 @@ msgstr "" "Halstead はプログラムをトークンに還元し、それらを 2 つのカテゴリに分割しま" "す。" -#: src/metrics.md:610 +#: src/metrics.md:703 #, fuzzy msgid "" "**Operators**, anything that _does_ something: keywords (`if`, `return`, " @@ -2655,77 +3046,77 @@ msgstr "" "`while`)、算術・論理演算子、代入、関数呼び出しの構文、制御フローを担う句読記" "号です。" -#: src/metrics.md:613 +#: src/metrics.md:706 #, fuzzy msgid "**Operands**, anything that _is_ something: identifiers and literals." msgstr "**被演算子(operand)** — 何かで _ある_ もの。識別子とリテラルです。" -#: src/metrics.md:616 +#: src/metrics.md:709 msgid "From these you derive four base counts:" msgstr "これらから 4 つの基本カウントを導出します。" -#: src/metrics.md:618 src/python/metrics.md:110 +#: src/metrics.md:711 src/python/metrics.md:116 msgid "JSON key" msgstr "JSON キー" -#: src/metrics.md:618 +#: src/metrics.md:711 msgid "Symbol" msgstr "記号" -#: src/metrics.md:618 src/commands/index.md:266 src/commands/vcs.md:51 -#: src/commands/vcs.md:211 src/commands/check.md:125 src/python/traversal.md:81 +#: src/metrics.md:711 src/commands/index.md:266 src/commands/vcs.md:51 +#: src/commands/vcs.md:212 src/commands/check.md:125 src/python/traversal.md:81 msgid "Meaning" msgstr "意味" -#: src/metrics.md:620 +#: src/metrics.md:713 msgid "`unique_operators`" msgstr "`unique_operators`" -#: src/metrics.md:620 +#: src/metrics.md:713 msgid "n1" msgstr "n1" -#: src/metrics.md:620 +#: src/metrics.md:713 msgid "number of **distinct** operators" msgstr "**相異なる**演算子の数" -#: src/metrics.md:621 +#: src/metrics.md:714 msgid "`unique_operands`" msgstr "`unique_operands`" -#: src/metrics.md:621 +#: src/metrics.md:714 msgid "n2" msgstr "n2" -#: src/metrics.md:621 +#: src/metrics.md:714 msgid "number of **distinct** operands" msgstr "**相異なる**被演算子の数" -#: src/metrics.md:622 +#: src/metrics.md:715 msgid "`total_operators`" msgstr "`total_operators`" -#: src/metrics.md:622 +#: src/metrics.md:715 msgid "N1" msgstr "N1" -#: src/metrics.md:622 +#: src/metrics.md:715 msgid "**total** count of operator occurrences" msgstr "演算子の出現の**合計**数" -#: src/metrics.md:623 +#: src/metrics.md:716 msgid "`total_operands`" msgstr "`total_operands`" -#: src/metrics.md:623 +#: src/metrics.md:716 msgid "N2" msgstr "N2" -#: src/metrics.md:623 +#: src/metrics.md:716 msgid "**total** count of operand occurrences" msgstr "被演算子の出現の**合計**数" -#: src/metrics.md:625 +#: src/metrics.md:718 msgid "" "The serialized output uses the descriptive **JSON key** column; the derived-" "metric formulas below use Halstead's classic `n1`/`N1`/`n2`/`N2` notation " @@ -2735,7 +3126,7 @@ msgstr "" "導出メトリクスの公式では、同じ 4 つのカウントに対して Halstead の古典的な " "`n1`/`N1`/`n2`/`N2` 表記を使用します。" -#: src/metrics.md:629 +#: src/metrics.md:722 #, fuzzy msgid "" "big-code-analysis records these four numbers in `src/metrics/halstead.rs` " @@ -2753,14 +3144,14 @@ msgstr "" "句読記号を意図的に除外しており、そのため Halstead の合計は Tokens のカウント" "と _同じにはなりません_。" -#: src/metrics.md:639 +#: src/metrics.md:732 msgid "" "The following rules define which syntax contributes to Halstead's " "vocabulary. Context matters because grammars reuse punctuation for " "operators, literal delimiters and other syntax:" msgstr "" -#: src/metrics.md:643 +#: src/metrics.md:736 msgid "" "**A literal's own delimiters are not operators.** A JavaScript regex, a " "Groovy slashy string, a C++ raw string, a Tcl braced word and a Perl or Ruby " @@ -2782,7 +3173,7 @@ msgid "" "operator." msgstr "" -#: src/metrics.md:664 +#: src/metrics.md:757 msgid "" "Recognising the command is only half of it, because most of those signatures " "mix the two roles. A braced word in a slot the command's documented syntax " @@ -2802,7 +3193,7 @@ msgid "" "in it is read, and every brace stays a block." msgstr "" -#: src/metrics.md:684 +#: src/metrics.md:777 msgid "" "This decides the _operator_ only. The words inside a braced argument are " "counted either way, because an unrecognised command is as likely to have " @@ -2816,7 +3207,7 @@ msgid "" "this reaches top-level script fragments, not functions." msgstr "" -#: src/metrics.md:696 +#: src/metrics.md:789 msgid "" "The consequence for the operand column is an asymmetry, and it is the " "contract rather than an open defect: a braced value scores one operand where " @@ -2833,7 +3224,7 @@ msgid "" "where there are two." msgstr "" -#: src/metrics.md:710 +#: src/metrics.md:803 msgid "" "**A string-interpolation opener is not an operator.** `\"{$x}\"` in PHP, " "`\"#{x}\"` in Ruby and Elixir, `\"${x}\"` in Kotlin and Groovy, `$\"{x}\"` " @@ -2851,7 +3242,7 @@ msgid "" "format-spec text and counts nothing." msgstr "" -#: src/metrics.md:725 +#: src/metrics.md:818 msgid "" "**A delimiter around _syntax_ is an operator, whatever it delimits.** The " "rule above is about a literal's own punctuation, and it stops there. " @@ -2869,7 +3260,7 @@ msgid "" "their Halstead scores rose with it." msgstr "" -#: src/metrics.md:741 +#: src/metrics.md:834 msgid "" "**A declaration keyword is an operator.** Python's `class` is billed like " "`def` since #1550, as Ruby, Kotlin, C# and PHP bill their `class`. Java, " @@ -2879,15 +3270,16 @@ msgid "" "`@protocol`. The `class` tail of Java's `C.class` is an operand, not this " "keyword (see the class literal below). Groovy's `var` bills as its `def` " "does since #1704, once per local declaration however many declarators follow " -"it. A `var` used as a name stays an operand (`def var = 3`, `[var: 1]`), or " -"bills nothing where the grammar cannot parse the statement (`var = 4`), and " -"the `var` of a field (`var field = 1`) or of `final var`, which the grammar " -"reads as a type name, still bills as a type-name operand (#1706). Kotlin's " -"`interface` followed in #1556. \\#1557 added C++'s `namespace`, `template`, " -"`typename`, `typedef` and `using` (C and Objective-C bill `typedef` too), so " -"`template ` and `template ` each bill their keyword and " -"score alike. It also added TypeScript's `type`, `namespace`, `module`, " -"`declare` and `global`. #1561 made TypeScript's type-level operator keywords " +"it, and so does the `var` of a field (`var field = 1`), which the grammar " +"reads as a type name (#1706), or of a parameter, a closure parameter, a " +"resource, a `catch` parameter or a `final var` local. A `var` used as a name " +"stays an operand (`def var = 3`, `[var: 1]`), or bills nothing where the " +"grammar cannot parse the statement (`var = 4`). Kotlin's `interface` " +"followed in #1556. \\#1557 added C++'s `namespace`, `template`, `typename`, " +"`typedef` and `using` (C and Objective-C bill `typedef` too), so `template " +"` and `template ` each bill their keyword and score " +"alike. It also added TypeScript's `type`, `namespace`, `module`, `declare` " +"and `global`. #1561 made TypeScript's type-level operator keywords " "operators, as their value-level siblings `as`, `typeof` and `extends` " "already were: `satisfies`, `keyof`, `infer`, and the `is` and `asserts` of a " "type predicate. #1564 made Kotlin's `typealias`, `init`, `where`, `by`, " @@ -2897,7 +3289,7 @@ msgid "" "(`val by = 1`, `x.get(i)`) stay operands." msgstr "" -#: src/metrics.md:769 +#: src/metrics.md:863 msgid "" "**A declaration modifier is an operator, keyed by its keyword and never its " "wrapper node.** C#, Kotlin, Java, Groovy, TypeScript and TSX, C, C++, Mozcpp " @@ -2911,7 +3303,7 @@ msgid "" "The exceptions:" msgstr "" -#: src/metrics.md:780 +#: src/metrics.md:874 msgid "" "The same word used as a name stays an operand (`val open = 1`, `let readonly " "= 1`, `obj.static`, `var sealed = 1`, `int override = 1;`). Where Kotlin's " @@ -2919,7 +3311,7 @@ msgid "" "`val suspend = 1`, a parameter named `vararg`), the word bills nothing." msgstr "" -#: src/metrics.md:785 +#: src/metrics.md:879 msgid "" "The `static` of `import static` and `requires static` bills nothing, as " "`import` does not: Java and Groovy bill no directive keyword (`package`, " @@ -2929,24 +3321,24 @@ msgid "" "directive rule, and \\#1600 kept both rather than move one." msgstr "" -#: src/metrics.md:792 +#: src/metrics.md:886 msgid "" "C++'s `auto` is a placeholder type and stays unbilled. Attributes, the MS " "calling conventions, the Gecko `MOZ_*` macros and the Apple SDK macros " "(`NS_INLINE`, `FOUNDATION_EXPORT`, `IBOutlet`) bill nothing." msgstr "" -#: src/metrics.md:797 +#: src/metrics.md:891 msgid "The words each language bills:" msgstr "" -#: src/metrics.md:799 +#: src/metrics.md:893 msgid "" "Kotlin: the `enum` of `enum class`, `data`, `sealed`, the visibility " "keywords, `open`, `override`, `suspend`, `reified`, `out` and the rest." msgstr "" -#: src/metrics.md:802 +#: src/metrics.md:896 msgid "" "TypeScript and TSX: the member modifiers `public`, `private`, `protected`, " "`override`, `readonly`, `abstract`, `accessor` and `static`. JavaScript and " @@ -2956,7 +3348,7 @@ msgid "" "and `get`." msgstr "" -#: src/metrics.md:808 +#: src/metrics.md:902 msgid "" "Java and Groovy: the visibility keywords, `static`, `native`, `strictfp`, " "`volatile`, `sealed` and `non-sealed`, where before \\#1565 they billed only " @@ -2964,7 +3356,7 @@ msgid "" "`permits` clause keyword beside `extends` and `implements`." msgstr "" -#: src/metrics.md:813 +#: src/metrics.md:907 msgid "" "C, C++ and Mozcpp: every storage class, function specifier and type " "qualifier: `static`, `extern`, `register`, `inline`, `thread_local`, " @@ -2976,7 +3368,7 @@ msgid "" "`extern \"C\"` bills `extern` and keeps `\"C\"` an operand." msgstr "" -#: src/metrics.md:822 +#: src/metrics.md:916 msgid "" "Objective-C: C's list, plus the `@public`, `@private`, `@protected` and " "`@package` ivar labels, the `@optional` and `@required` protocol sections, " @@ -2988,7 +3380,7 @@ msgid "" "`getter=` or `setter=` value stays an operand." msgstr "" -#: src/metrics.md:831 +#: src/metrics.md:925 msgid "" "**A type name is an operand.** #1557 made every TypeScript type name an " "operand (`x: Foo`, `interface I`, `Map`), as C#, Rust and the C family " @@ -3005,7 +3397,7 @@ msgid "" "`boolean_type`, so both languages report it alike." msgstr "" -#: src/metrics.md:845 +#: src/metrics.md:939 msgid "" "**A class literal bills its parts.** Since #1566 a Java class literal bills " "its parts rather than one operand spelled by its whole text, since [JLS " @@ -3017,7 +3409,7 @@ msgid "" "the `void` of `void.class` stay operators, as Java bills them everywhere." msgstr "" -#: src/metrics.md:855 +#: src/metrics.md:949 msgid "" "**Angle brackets that enclose types are one bracket pair.** The `<` and `>` " "around type arguments and type parameters count as one `<>` operator, billed " @@ -3053,7 +3445,7 @@ msgid "" "corpora it fell in 87% of the files that moved, and MI rose in most of them." msgstr "" -#: src/metrics.md:892 +#: src/metrics.md:986 msgid "" "**An alternative spelling is an operator of its own.** C++ spells `&&` " "equally as `and`, `!=` as `not_eq` and so on through all eleven [alternative " @@ -3064,7 +3456,7 @@ msgid "" "separately, so the metric matches what it reports (#1522)." msgstr "" -#: src/metrics.md:900 +#: src/metrics.md:994 msgid "" "**A self-reference is an operand.** `this`, `self`, `$this`, `super` and " "`base` name the receiver of a member access, so `this.x` counts the way `p." @@ -3075,7 +3467,7 @@ msgid "" "wildcard bound `? super T` in Java and Groovy (#1380)." msgstr "" -#: src/metrics.md:908 +#: src/metrics.md:1002 msgid "" "**A keyword's role follows its text, not its node kind.** C#'s grammar " "parses the bare `this`, `ref`, `out`, `in`, `scoped` and `readonly` of a " @@ -3088,7 +3480,7 @@ msgid "" "not to `unique_operators` (#1418, #1482)." msgstr "" -#: src/metrics.md:918 +#: src/metrics.md:1012 msgid "" "**Perl's `__END__` and `__DATA__` end the program.** Neither marker nor the " "data section after it is an operator or an operand, so two files that differ " @@ -3101,7 +3493,7 @@ msgid "" "and the opaque data leaf are still leaves, so `tokens` still counts them." msgstr "" -#: src/metrics.md:928 +#: src/metrics.md:1022 msgid "" "**JSX element text is an operand.** In JavaScript, Mozjs and TSX, the `hi` " "of `

hi

` counts the way a string's contents do. It is keyed on its " @@ -3113,7 +3505,7 @@ msgid "" "that string's one operand (#1483)." msgstr "" -#: src/metrics.md:937 +#: src/metrics.md:1031 msgid "" "**An overloaded operator's name is an operator.** The `+` of `operator +` " "was always one, and the names a grammar spells as whole tokens now agree: " @@ -3126,7 +3518,7 @@ msgid "" "`co_yield` are operators as `return` is (#1547)." msgstr "" -#: src/metrics.md:946 +#: src/metrics.md:1040 msgid "" "**Only written tokens count.** When tree-sitter cannot parse a construct, " "its error recovery may insert zero-width tokens the source does not contain: " @@ -3138,7 +3530,7 @@ msgid "" "operator." msgstr "" -#: src/metrics.md:954 +#: src/metrics.md:1048 msgid "" "**A named operator is one operand.** Elixir names an operator in a capture " "(`&==/2`, `&and/2`) and as the function of a remote call (`Kernel.||(a, " @@ -3154,11 +3546,11 @@ msgid "" "the rule above makes it." msgstr "" -#: src/metrics.md:968 +#: src/metrics.md:1062 msgid "Derived metrics" msgstr "導出メトリクス" -#: src/metrics.md:970 +#: src/metrics.md:1064 #, fuzzy msgid "" "Halstead then derives a set of formulas. big-code-analysis reports all of " @@ -3170,7 +3562,7 @@ msgstr "" "すべてに加えて、元のスイートに含まれるあまり一般的でない 3 つの導出値" "(`estimated_program_length`、`purity_ratio`、`level`)も報告します。" -#: src/metrics.md:988 +#: src/metrics.md:1082 #, fuzzy msgid "" "The numeric constants come from Halstead's empirical fits against a " @@ -3184,7 +3576,7 @@ msgstr "" "「Stroud 数」は別系統で、心理学に由来します。Halstead は、人間の頭脳が 1 秒あ" "たり約 18 回の基本的な弁別を行うという John Stroud の推定を借用しました。" -#: src/metrics.md:996 +#: src/metrics.md:1090 #, fuzzy msgid "" "Halstead's _original_ intent was to predict three things about a program " @@ -3204,11 +3596,11 @@ msgstr "" "Revisited_](https://docs.lib.purdue.edu/cgi/viewcontent.cgi?" "article=1302&context=cstech) で詳細に批判されています。" -#: src/metrics.md:1005 +#: src/metrics.md:1099 msgid "In modern practice the Halstead numbers are used for three things:" msgstr "現代の実践では、Halstead の数値は 3 つの用途に使われます。" -#: src/metrics.md:1007 +#: src/metrics.md:1101 #, fuzzy msgid "" "As inputs into composite metrics, most importantly the Maintainability Index " @@ -3217,7 +3609,7 @@ msgstr "" "複合メトリクスへの入力として。最も重要なのは、Halstead の _ボリューム_ に依存" "する保守容易性指数(次節)です。" -#: src/metrics.md:1010 +#: src/metrics.md:1104 msgid "" "As a **language-independent size proxy**: volume in bits scales smoothly " "across languages in a way that LOC does not." @@ -3225,7 +3617,7 @@ msgstr "" "**言語に依存しないサイズの代理指標**として。ビット単位のボリュームは、LOC で" "は実現できない形で言語をまたいで滑らかにスケールします。" -#: src/metrics.md:1012 +#: src/metrics.md:1106 msgid "" "For **comparative effort budgeting**: when two refactoring candidates have " "similar cyclomatic complexity, the one with the higher Halstead difficulty " @@ -3235,11 +3627,11 @@ msgstr "" "程度の場合、Halstead の difficulty が高いほうがリグレッションを持ち込む可能性" "が高くなります。" -#: src/metrics.md:1017 +#: src/metrics.md:1111 msgid "Lines of Code" msgstr "コード行数" -#: src/metrics.md:1019 +#: src/metrics.md:1113 #, fuzzy msgid "" "This section covers the LOC variants: SLOC, PLOC, LLOC, CLOC, BLANK, and " @@ -3264,19 +3656,19 @@ msgstr "" "wikipedia.org/wiki/Source_lines_of_code) の項目は、この物理行対論理行の区別を" "読みやすくまとめています。" -#: src/metrics.md:1031 +#: src/metrics.md:1125 msgid "Variant" msgstr "バリアント" -#: src/metrics.md:1031 +#: src/metrics.md:1125 msgid "Counts" msgstr "数える対象" -#: src/metrics.md:1033 +#: src/metrics.md:1127 msgid "**SLOC**" msgstr "**SLOC**" -#: src/metrics.md:1033 +#: src/metrics.md:1127 #, fuzzy msgid "" "Source Lines Of Code: every line in the file, comments, blanks, and code " @@ -3284,31 +3676,31 @@ msgid "" msgstr "" "Source Lines Of Code — コメント・空行・コードを問わずファイル内のすべての行" -#: src/metrics.md:1034 +#: src/metrics.md:1128 msgid "**PLOC**" msgstr "**PLOC**" -#: src/metrics.md:1034 +#: src/metrics.md:1128 #, fuzzy msgid "Physical Lines Of Code: non-blank, non-comment-only lines" msgstr "Physical Lines Of Code — 空行でもコメントのみの行でもない行" -#: src/metrics.md:1035 +#: src/metrics.md:1129 msgid "**LLOC**" msgstr "**LLOC**" -#: src/metrics.md:1035 +#: src/metrics.md:1129 #, fuzzy msgid "" "Logical Lines Of Code: statement-bearing lines (definitions, assignments, " "declarations)" msgstr "Logical Lines Of Code — 文を含む行(定義、代入、宣言)" -#: src/metrics.md:1036 +#: src/metrics.md:1130 msgid "**CLOC**" msgstr "**CLOC**" -#: src/metrics.md:1036 +#: src/metrics.md:1130 #, fuzzy msgid "" "Comment Lines Of Code: lines that contain a comment (with or without code on " @@ -3317,28 +3709,28 @@ msgstr "" "Comment Lines Of Code — コメントを含む行(同じ行にコードがあってもなくても数" "える)" -#: src/metrics.md:1037 +#: src/metrics.md:1131 msgid "**BLANK**" msgstr "**BLANK**" -#: src/metrics.md:1037 +#: src/metrics.md:1131 #, fuzzy msgid "Blank lines: whitespace-only lines" msgstr "空行 — 空白文字のみの行" -#: src/metrics.md:1038 +#: src/metrics.md:1132 #, fuzzy msgid "**DLOC**" msgstr "**SLOC**" -#: src/metrics.md:1038 +#: src/metrics.md:1132 msgid "" "Documentation Lines Of Code: rows the language treats as documentation (a " "doc comment, a Python docstring, a [POD](https://perldoc.perl.org/perlpod) " "block); always a subset of CLOC" msgstr "" -#: src/metrics.md:1042 +#: src/metrics.md:1136 #, fuzzy msgid "" "big-code-analysis derives every count from a single pass over the tree-" @@ -3356,7 +3748,42 @@ msgstr "" "レイトが、LLOC で「文」として数えるノード種別を規定します。何が文として数えら" "れるかは言語ごとに定義されるため、ここが微妙な部分です。" -#: src/metrics.md:1051 +#: src/metrics.md:1145 +msgid "" +"One kind of row has no node to identify it. In Bash, Tcl, iRules, the C " +"family (C, C++, Mozcpp, Objective-C), Ruby and Elixir the lexer splices a " +"line-continuation `\\` and its newline away, so a row holding only that `\\` " +"is invisible in the tree. Such rows are found by reading the bytes between " +"nodes. Each one counts as PLOC, the code it continues. The exception is a " +"row that continues a Tcl or iRules comment (`# note \\`), which counts as " +"CLOC; one that continues a C-family `//` comment is part of that comment's " +"own node and counts as CLOC with it, and one that continues a row holding " +"only C-family block comments (`/* c */ \\`) counts as what the rest of that " +"line makes it. A row that continues nothing starts a line and counts as what " +"that line becomes: CLOC when the line holds only comment text, blank when " +"the row it joins is empty, PLOC otherwise, as for `/* c */ int z = 1;`. " +"Python's grammar keeps the `\\` as a node, and the same rule applies to it: " +"a Python `#` comment never continues, so `# c \\` followed by a bare row " +"joins the row after it, and a `\\` that ends a bare-string statement counts " +"nothing, the string's rows being CLOC already, as is a bare row that " +"continues it — unless code precedes the string on that logical line, or the " +"run leads into another statement (`; x = 1`), where the row is code " +"([\\#1819](https://github.com/dekobon/big-code-analysis/issues/1819)); a " +"bare row before any string literal stays blank, because the grammar's " +"scanner drops that `\\` ([\\#1825](https://github.com/dekobon/big-code-" +"analysis/issues/1825)). A bare row inside a literal is part of the literal, " +"which should make it PLOC, but a C-family character literal, a Ruby `%w[]`, " +"regex, quoted symbol or command, and an Elixir string, sigil or quoted atom " +"still leave it blank ([\\#1816](https://github.com/dekobon/big-code-analysis/" +"issues/1816)). Where CRLF line endings reach the parser unchanged, through " +"the library's own `analyze` or Python's `Ast.parse`, the Tcl and iRules " +"grammars lex the bare row as a word, so there it counts as PLOC even after a " +"comment ([\\#1802](https://github.com/dekobon/big-code-analysis/" +"issues/1802)). `bca`, the web server and the Python bindings' `analyze`, " +"`analyze_source` and `Ast.from_path` convert line endings to LF first." +msgstr "" + +#: src/metrics.md:1181 msgid "" "Documentation rows are comment rows that are also reported on their own as " "DLOC (`loc.dloc`), so CLOC can be read with or without them. Each language's " @@ -3364,18 +3791,17 @@ msgid "" "single rule for all:" msgstr "" -#: src/metrics.md:1056 +#: src/metrics.md:1186 msgid "" "Where the grammar marks it, the mark decides: a Rust `///`, `//!`, `/** */` " -"or `/*! */` comment (tree-sitter's `doc_comment` child; `////` and `/**/` " -"carry none), a Groovy `groovydoc_comment` (but not the empty `/**/` that " -"grammar also marks), a Perl POD block (but not one that is nothing but " -"`=begin comment` and `=for comment` regions, Perl's idiom for commenting " -"code out; POD after such a region's end documents, and makes the block " -"documentation)." +"or `/*! */` comment (tree-sitter's doc marker child; `////` and `/**/` carry " +"none), a Groovy `groovydoc_comment` (but not the empty `/**/` that grammar " +"also marks), a Perl POD block (but not one that is nothing but `=begin " +"comment` and `=for comment` regions, Perl's idiom for commenting code out; " +"POD after such a region's end documents, and makes the block documentation)." msgstr "" -#: src/metrics.md:1063 +#: src/metrics.md:1193 msgid "" "Where the grammar emits one comment kind for every form, the opening marker " "decides, as the language's documentation tool reads it: [Doxygen](https://" @@ -3394,7 +3820,7 @@ msgid "" "than Doxygen's lexer." msgstr "" -#: src/metrics.md:1080 +#: src/metrics.md:1210 msgid "" "A doc comment counts only where its tool reads it. A Rust, Java, Kotlin, " "Groovy, C# or PHP doc comment inside a function or closure body, inside a " @@ -3420,7 +3846,7 @@ msgid "" "where every other non-blank row of the data section counts as PLOC." msgstr "" -#: src/metrics.md:1105 +#: src/metrics.md:1235 msgid "" "In Rust, Java, Kotlin and Groovy, a doc comment also has to be attached: it " "counts only when the declaration after it is one its tool documents. " @@ -3443,13 +3869,13 @@ msgid "" "it sits in." msgstr "" -#: src/metrics.md:1126 +#: src/metrics.md:1256 msgid "" "C#, PHP, JavaScript and TypeScript bind doc comments the same way. Each " "language still follows its own tool:" msgstr "" -#: src/metrics.md:1128 +#: src/metrics.md:1258 msgid "" "C#: Roslyn keeps the nearest run of doc comments that only blank rows " "separate, reading past plain comments and directives such as `#region` to " @@ -3459,7 +3885,7 @@ msgid "" "or an accessor such as `get;`." msgstr "" -#: src/metrics.md:1134 +#: src/metrics.md:1264 msgid "" "PHP: [phpDocumentor](https://www.phpdoc.org/) gives a class, function, " "method, property, constant or enum case the last DocBlock before it. A " @@ -3470,7 +3896,7 @@ msgid "" "before the first such element." msgstr "" -#: src/metrics.md:1143 +#: src/metrics.md:1273 msgid "" "JavaScript: [JSDoc](https://jsdoc.app/) gives a declaration or an assignment " "the nearest block comment before it, reading past `//` lines, so a plain `/* " @@ -3480,7 +3906,7 @@ msgid "" "symbol wherever it sits. `@license` does not make a block stand alone." msgstr "" -#: src/metrics.md:1150 +#: src/metrics.md:1280 msgid "" "TypeScript: tsc keeps the last `/**` before a declaration, reading past " "every plain comment, and documents no assignment statement. A doc comment " @@ -3491,13 +3917,13 @@ msgid "" "typedoc.org/) reads it." msgstr "" -#: src/metrics.md:1158 +#: src/metrics.md:1288 msgid "" "In a JavaScript or TypeScript function body every doc comment still counts, " "since JSDoc documents inner symbols." msgstr "" -#: src/metrics.md:1160 +#: src/metrics.md:1290 msgid "" "C, C++ and Objective-C follow [Doxygen](https://www.doxygen.nl/), which " "keeps every doc block it meets and gives them all to the next entry. A doc " @@ -3519,7 +3945,7 @@ msgid "" "description." msgstr "" -#: src/metrics.md:1180 +#: src/metrics.md:1310 msgid "" "In Python, every bare string statement (a string whose value is discarded) " "is a comment row, but only one where Python reads documentation is DLOC, " @@ -3550,7 +3976,7 @@ msgid "" "in bytes`). A plain `#` line breaks a `#:` block." msgstr "" -#: src/metrics.md:1212 +#: src/metrics.md:1342 msgid "" "Go, Ruby and Lua have no marker to read, so a comment is documentation by " "where it sits, decided once per _run_: the chain of comment siblings on " @@ -3558,7 +3984,7 @@ msgid "" "never joins one, and a blank row ends one):" msgstr "" -#: src/metrics.md:1217 +#: src/metrics.md:1347 msgid "" "Go: a run directly above a declaration is [go/doc](https://pkg.go.dev/go/" "doc)'s lead comment, where a declaration is the package clause, a `func` or " @@ -3569,7 +3995,7 @@ msgid "" "documentation, and is not counted." msgstr "" -#: src/metrics.md:1225 +#: src/metrics.md:1355 msgid "" "Ruby: a run directly above a `def`, `def self.`, `class`, `module`, `class " "<< Const`, a constant or class-variable assignment (`MAX = 10`, `Foo::BAR = " @@ -3594,7 +4020,7 @@ msgid "" "in a namespace body but never in a method's." msgstr "" -#: src/metrics.md:1249 +#: src/metrics.md:1379 msgid "" "Lua: a run that opens with an [LDoc](https://lunarmodules.github.io/ldoc/) " "`---` row (a row of dashes alone opens too; `--- x ---` is LDoc's end marker " @@ -3622,18 +4048,18 @@ msgid "" "instead (LuaLS's `---@type` on a local), as PHP's in-body `@var` does." msgstr "" -#: src/metrics.md:1277 +#: src/metrics.md:1407 msgid "" "Nothing else counts: an Elixir `@doc` heredoc is an assignment the compiler " "stores and is code, and Bash, Tcl and iRules have no documentation syntax." msgstr "" -#: src/metrics.md:1281 +#: src/metrics.md:1411 #, fuzzy msgid "The counts satisfy a few useful identities:" msgstr "5 つのカウントは、いくつかの有用な恒等式を満たします。" -#: src/metrics.md:1291 +#: src/metrics.md:1421 msgid "" "**SLOC** is what most people mean colloquially by \"lines of code\". It is " "the canonical size proxy, but is sensitive to formatting and not portable " @@ -3643,7 +4069,7 @@ msgstr "" "なサイズの代理指標ですが、フォーマットの影響を受けやすく、言語の慣習をまたい" "だ移植性はありません。" -#: src/metrics.md:1294 +#: src/metrics.md:1424 #, fuzzy msgid "" "**PLOC** strips away the visual noise. It is the measure to gate file length " @@ -3652,7 +4078,7 @@ msgstr "" "**PLOC** は視覚的なノイズを取り除いたものです。後述の保守容易性指数の公式の内" "部で使われるサイズ指標です。" -#: src/metrics.md:1297 +#: src/metrics.md:1427 msgid "" "**LLOC** is the most reliable _statement_ count. It is the right measure if " "you are budgeting test cases per statement, or comparing the density of a " @@ -3661,7 +4087,7 @@ msgstr "" "**LLOC** は最も信頼できる _文_ の数です。文ごとのテストケースを見積もる場合" "や、Python ファイルと Java ファイルの密度を比較する場合に適した指標です。" -#: src/metrics.md:1300 +#: src/metrics.md:1430 #, fuzzy msgid "" "**CLOC**, combined with PLOC, gives you a _comment density_: `CLOC / PLOC` " @@ -3672,7 +4098,7 @@ msgstr "" "PLOC` は、ファイルのどれだけがドキュメントでどれだけが実装かを示す、大まかな" "がら有用な代理指標です。" -#: src/metrics.md:1303 +#: src/metrics.md:1433 #, fuzzy msgid "" "**BLANK** is mostly diagnostic: a file with a very low BLANK proportion is " @@ -3681,14 +4107,14 @@ msgstr "" "**BLANK** は主に診断用です。BLANK の割合が非常に低いファイルは、読みにくいこ" "とが多いためです。" -#: src/metrics.md:1305 +#: src/metrics.md:1435 msgid "" "**DLOC** is the slice of CLOC that is documentation: doc comments, " "docstrings, POD. `CLOC − DLOC` is the count of working comments, the " "numerator of the Maintainability Index's SEI comment share." msgstr "" -#: src/metrics.md:1309 +#: src/metrics.md:1439 #, fuzzy msgid "" "LOC variants are used well beyond raw size. They are the most common input " @@ -3709,11 +4135,11 @@ msgstr "" "ディングスタイルの 10 倍の違いが LOC の 2 倍の違いを生み得ること — こそが、こ" "の章にこれほど多くの他のメトリクスがある理由です。" -#: src/metrics.md:1320 +#: src/metrics.md:1450 msgid "Maintainability Index (MI)" msgstr "保守容易性指数(MI)" -#: src/metrics.md:1322 +#: src/metrics.md:1452 #, fuzzy msgid "" "The **Maintainability Index** is a composite metric that rolls several of " @@ -3744,7 +4170,7 @@ msgstr "" "組み合わせは、Halstead ボリューム、循環的複雑度、コード行数、コメント密度を使" "うものでした。" -#: src/metrics.md:1338 +#: src/metrics.md:1468 #, fuzzy msgid "" "big-code-analysis reports the three formulas that have stuck in practice. " @@ -3756,7 +4182,7 @@ msgstr "" "キーでネストされます(ドット区切りのしきい値名は `mi.original`、`mi.sei`、" "`mi.visual_studio`)。" -#: src/metrics.md:1351 +#: src/metrics.md:1481 msgid "" "`mi.original` is the Coleman–Oman formula. It can be negative for " "pathological files." @@ -3764,7 +4190,7 @@ msgstr "" "`mi.original` は Coleman–Oman の公式です。病的なファイルでは負になることがあ" "ります。" -#: src/metrics.md:1353 +#: src/metrics.md:1483 #, fuzzy msgid "" "`mi.sei` is the Software Engineering Institute's refinement, which adds a " @@ -3783,7 +4209,7 @@ msgstr "" "(`[0, 1]` の比率ではありません)、コードはこのパーセント値をそのまま SEI 項" "に与えます(`src/metrics/mi.rs` と issue #241 を参照)。" -#: src/metrics.md:1361 +#: src/metrics.md:1491 #, fuzzy msgid "" "`mi.visual_studio` is the linear rescaling Microsoft chose for [Visual " @@ -3796,7 +4222,7 @@ msgstr "" "で、スコアは `[0, 100]` にクランプされ、信号機方式で開発者に表示されます。緑" "は 20 以上、黄は 10 以上、赤はそれ未満です。" -#: src/metrics.md:1366 +#: src/metrics.md:1496 msgid "" "The size term is `PLOC`, the rows that carry code (#1607). Comment, " "documentation and blank rows never enter it, so a `// TODO`, a commented-out " @@ -3807,7 +4233,7 @@ msgid "" "stays counted." msgstr "" -#: src/metrics.md:1374 +#: src/metrics.md:1504 msgid "" "Documentation also leaves both sides of `CM` in every language (#1597), so a " "function's `mi.sei` is the same with and without its `///` block, its " @@ -3818,7 +4244,7 @@ msgid "" "is unmoved." msgstr "" -#: src/metrics.md:1382 +#: src/metrics.md:1512 msgid "" "Two details differ from some published statements of the SEI formula. Its " "`ln` matches `mi.original`'s; releases before #1607 took `log2` of the " @@ -3827,12 +4253,12 @@ msgid "" "several times across ordinary comment densities." msgstr "" -#: src/metrics.md:1388 +#: src/metrics.md:1518 #, fuzzy msgid "Charging documentation" msgstr "コードドキュメント" -#: src/metrics.md:1390 +#: src/metrics.md:1520 msgid "" "With `mi_charges_docs` on, `mi.sei` counts documentation as comment: it " "takes its comment share as `CLOC / SLOC`, the inputs that releases without " @@ -3844,13 +4270,13 @@ msgid "" "It changes no other metric: `loc.dloc` is reported either way." msgstr "" -#: src/metrics.md:1400 +#: src/metrics.md:1530 #, fuzzy msgid "Library: `MetricsOptions::default().with_mi_charges_docs(true)`." msgstr "" "ライブラリ: `MetricsOptions::default().with_count_cyclomatic_try(false)`。" -#: src/metrics.md:1401 +#: src/metrics.md:1531 #, fuzzy msgid "" "CLI: `--mi-charges-docs` (or `--mi-charges-docs=false` to say the default " @@ -3861,19 +4287,19 @@ msgstr "" "イリアス)、あるいは `bca.toml` の `cyclomatic_count_try = false`(CLI の値は" "どちらの方向でもこのキーを上書きします)。" -#: src/metrics.md:1404 +#: src/metrics.md:1534 msgid "" "Python: `mi_charges_docs=True` on `analyze`, `analyze_source`, " "`analyze_batch`, `analyze_paths` and `Ast.metrics`." msgstr "" -#: src/metrics.md:1406 +#: src/metrics.md:1536 msgid "" "The REST server has no request field for it; an embedder sets " "`WebMetricsCfg::with_mi_charges_docs`." msgstr "" -#: src/metrics.md:1409 +#: src/metrics.md:1539 msgid "" "The LOC inputs it reads are the current ones, so a Python file whose " "docstring is an implicit concatenation (`\"\"\"doc\"\"\" \"more\"`) or whose " @@ -3881,7 +4307,7 @@ msgid "" "comment share from a release that classified those rows the other way." msgstr "" -#: src/metrics.md:1415 +#: src/metrics.md:1545 msgid "" "A baseline records which mode wrote it, and `bca check --baseline` warns " "when it reads `mi.*` entries under the other mode. Only `mi.sei` entries can " @@ -3894,7 +4320,7 @@ msgid "" "names the mode in force." msgstr "" -#: src/metrics.md:1426 +#: src/metrics.md:1556 msgid "" "A baseline also records the MI formula revision that computed its values " "(`mi_formula` in `[provenance]`; revision 2 since #1607, and an unstamped " @@ -3904,7 +4330,7 @@ msgid "" "baseline`." msgstr "" -#: src/metrics.md:1433 +#: src/metrics.md:1563 #, fuzzy msgid "" "Arie van Deursen's blog post [_Think Twice Before Using the Maintainability " @@ -3917,7 +4343,7 @@ msgstr "" "com/2014/08/29/think-twice-before-using-the-maintainability-index/) にまとめ" "られています。" -#: src/metrics.md:1440 +#: src/metrics.md:1570 #, fuzzy msgid "" "The implementation is purely arithmetic: `src/metrics/mi.rs` consumes the " @@ -3937,7 +4363,7 @@ msgstr "" "未定義です。big-code-analysis は、SLOC がゼロまたは Halstead ボリュームがゼロ" "のファイルに対して `0.0` を返します。" -#: src/metrics.md:1455 +#: src/metrics.md:1585 #, fuzzy msgid "" "MI was _originally_ designed as a portfolio-level score: \"how much " @@ -3950,7 +4376,7 @@ msgstr "" "なシステムではリリースをまたいでかなり安定しており、システムが「レガシー」の" "象限に入る前に目に見えて低下する傾向があります。" -#: src/metrics.md:1460 +#: src/metrics.md:1590 #, fuzzy msgid "" "The common use is the **Visual Studio traffic-light rendering**: Visual " @@ -3968,11 +4394,11 @@ msgstr "" "サーモスタットではなく煙探知機として扱ってください。急激な低下は有用なシグナ" "ルですが、絶対値はノイズが多いのです。" -#: src/metrics.md:1467 +#: src/metrics.md:1597 msgid "NArgs" msgstr "NArgs" -#: src/metrics.md:1469 +#: src/metrics.md:1599 #, fuzzy msgid "" "**NArgs** counts the number of arguments declared by a function, method, or " @@ -3993,7 +4419,7 @@ msgstr "" "P200000009044/9780136083252)(2008 年)で目立つ形で再度述べられました。同書" "は 3 引数を緩やかな上限として提案しています。" -#: src/metrics.md:1478 +#: src/metrics.md:1608 #, fuzzy msgid "" "big-code-analysis splits the count by callable kind: every aggregate is " @@ -4018,11 +4444,11 @@ msgstr "" "フォルト引数、可変長引数、キーワード専用引数、分割代入されたパラメータを言語" "ごとに一貫して処理します。" -#: src/metrics.md:1492 +#: src/metrics.md:1622 msgid "Macro-obscured C-family declarators" msgstr "" -#: src/metrics.md:1494 +#: src/metrics.md:1624 msgid "" "C, C++, Mozcpp and Objective-C are parsed without running the preprocessor, " "so a function-like macro standing where the declared name belongs is still " @@ -4030,7 +4456,7 @@ msgid "" "javase/21/docs/specs/jni/) shim:" msgstr "" -#: src/metrics.md:1505 +#: src/metrics.md:1635 msgid "" "Read as written, `RUN_STATS_METHOD(allocate)` is the declarator and `(JNIEnv " "*env, jclass clazz)` belongs to the return type: one argument. big-code-" @@ -4043,7 +4469,7 @@ msgid "" "unaffected, as is C++ `operator()`." msgstr "" -#: src/metrics.md:1516 +#: src/metrics.md:1646 msgid "" "The space is named for the **macro**, not the function. There is no other " "candidate: the real symbol is assembled by `##` token pasting and never " @@ -4053,11 +4479,11 @@ msgid "" "overload set." msgstr "" -#: src/metrics.md:1523 +#: src/metrics.md:1653 msgid "What the threshold gate measures" msgstr "しきい値ゲートが測定するもの" -#: src/metrics.md:1525 +#: src/metrics.md:1655 msgid "" "`bca check --threshold nargs=N` gates each callable on **its own** parameter " "list, which is what every comparable tool measures: [RuboCop `Metrics/" @@ -4071,7 +4497,7 @@ msgid "" "html) all count one callable at a time." msgstr "" -#: src/metrics.md:1536 +#: src/metrics.md:1666 #, fuzzy msgid "" "This is _not_ the serialized `total`. The `function_args` and `closure_args` " @@ -4091,7 +4517,7 @@ msgstr "" "示唆する対処であるパラメータ削減は、違反を解消できる対処ではありませんでし" "た。" -#: src/metrics.md:1545 +#: src/metrics.md:1675 msgid "" "The number the gate does read is serialized as `value`, added in [\\#1236]" "(https://github.com/dekobon/big-code-analysis/issues/1236) so a JSON-" @@ -4100,7 +4526,7 @@ msgid "" "did not." msgstr "" -#: src/metrics.md:1551 +#: src/metrics.md:1681 #, fuzzy msgid "" "Nothing escapes the narrower rule. In the twelve grammars whose closures " @@ -4118,13 +4544,13 @@ msgstr "" "の引数は外側の関数にしか帰属できません。その場合、違反者行は内訳を表示しま" "す。" -#: src/metrics.md:1563 +#: src/metrics.md:1693 msgid "" "The split identifies how many arguments come from the enclosing signature " "and how many come from lambdas." msgstr "" -#: src/metrics.md:1566 +#: src/metrics.md:1696 msgid "" "Both lists are read from the per-language role tables rather than maintained " "by hand: a language is in the first when every kind its `Closure` row owns " @@ -4134,11 +4560,251 @@ msgid "" "Bash, C, Tcl and iRules have no closure at all)." msgstr "" -#: src/metrics.md:1573 +#: src/metrics.md:1703 +msgid "Primary constructors" +msgstr "" + +#: src/metrics.md:1705 +msgid "" +"A Kotlin primary constructor and a C# 12 primary constructor — a positional " +"`record` included — have no body, only a parameter list in the class header:" +msgstr "" + +#: src/metrics.md:1718 +msgid "" +"Each opens a function space of its own, named after its class and spanning " +"the list, so it is gated like any other callable: the row above reads `D::D: " +"nargs = 6`. [detekt's `LongParameterList`](https://detekt.dev/docs/rules/" +"complexity/#longparameterlist) gates constructors the same way, under a " +"threshold of its own and a data-class opt-out that is on by default; `bca` " +"has neither, so the `data class` above is reported. Before [\\#1828](https://" +"github.com/dekobon/big-code-analysis/issues/1828) the list belonged to no " +"space and counted nowhere, so a six-parameter data class passed `--threshold " +"nargs=5`. The space also counts as one callable in [NOM](#nom), [NPM](#npm) " +"and [WMC](#wmc) — a written `class G()` declares a zero-parameter " +"constructor and counts too — and its superclass call stays with the class, " +"as [Where a constructor call lands](#abc-constructor-attribution) explains. " +"A default spelled as a lambda (`class L(val f: (Int) -> Int = { it })`) adds " +"that lambda's parameters to the constructor's `closure_args`, exactly as a " +"function's spaceless lambdas add to its own, so the row's split shows them." +msgstr "" + +#: src/metrics.md:1737 +msgid "" +"The space is the list and nothing more, so a [suppression marker](commands/" +"suppression.md) has to sit _inside_ it — a marker on the line above binds to " +"no function, as for any other callable:" +msgstr "" + +#: src/metrics.md:1742 +msgid "" +"```kotlin\n" +"data class Row(\n" +" // bca: suppress(nargs) — a column set, not a signature\n" +" val a: Int, val b: Int, val c: Int, val d: Int, val e: Int, val f: Int,\n" +")\n" +"```" +msgstr "" + +#: src/metrics.md:1749 +msgid "" +"A parameterless `class G()` opens a space with no code in it, so its `mi.*` " +"read the `0.0` placeholder that [Maintainability Index](#maintainability-" +"index-mi) describes and `bca check` and `bca report` skip." +msgstr "" + +#: src/metrics.md:1754 +msgid "" +"Two things a reader of the rows will meet. A classic constructor beside a " +"primary one shares its name — C#'s `H::H` twice, one per spelling — and `bca " +"check --baseline` tells two same-named rows apart by line, so a class " +"written on one line leaves them indistinguishable to the baseline, as two " +"same-line overloads already were. And a Kotlin _secondary_ constructor still " +"reads `` in every listing, since its node carries no name; only " +"the primary is named after the class." +msgstr "" + +#: src/metrics.md:1763 +#, fuzzy +msgid "Record headers" +msgstr "header" + +#: src/metrics.md:1765 +msgid "" +"A Java or Groovy `record` declares its components in its header and, unless " +"the body writes one, gets its canonical constructor from the compiler:" +msgstr "" + +#: src/metrics.md:1777 +msgid "" +"The components are the constructor's parameters, and since [\\#1842](https://" +"github.com/dekobon/big-code-analysis/issues/1842) the header opens a " +"function space of its own, named after the record and spanning the list — " +"the row above reads `R::R: nargs = 6` — exactly as a C# positional record's " +"does. The space counts as one callable in [NOM](#nom), [NPM](#npm) and [WMC]" +"(#wmc), with the record's own access (a `public record`'s constructor is " +"public, and so is a record's that is a member of an interface, where member " +"types are implicitly public per [JLS 9.5](https://docs.oracle.com/javase/" +"specs/jls/se21/html/jls-9.html#jls-9.5); a bare one's is package-private, " +"per [JLS 8.10.4](https://docs.oracle.com/javase/specs/jls/se21/html/jls-8." +"html#jls-8.10.4). Groovy follows the reading NPM gives every Groovy member, " +"not the compiler's, which makes each such constructor public: the header is " +"public on the record's own `public` in a class, and in an interface, a trait " +"or an annotation type unless the record is `private` or `protected`, as " +"every member there is ([NPM](#npm-interface-members))); a component-less " +"`record E() {}` opens a zero-parameter space with no code in it, whose `mi." +"*` read the `0.0` placeholder as `class G()`'s do. The suppression marker " +"binds inside the parentheses, as for a primary constructor." +msgstr "" + +#: src/metrics.md:1798 +msgid "" +"The components are counted **once**, on whichever node declares the " +"canonical constructor:" +msgstr "" + +#: src/metrics.md:1801 +msgid "the record's body writes" +msgstr "" + +#: src/metrics.md:1801 +msgid "the components belong to" +msgstr "" + +#: src/metrics.md:1803 +msgid "nothing, or only non-canonical constructors" +msgstr "" + +#: src/metrics.md:1803 +#, fuzzy +msgid "the header's space" +msgstr "ゲート対象のスペース" + +#: src/metrics.md:1804 +msgid "a compact constructor `R { … }`" +msgstr "" + +#: src/metrics.md:1804 +msgid "the compact constructor's space" +msgstr "" + +#: src/metrics.md:1805 +msgid "a normal canonical constructor `R(int a, int b) { … }`" +msgstr "" + +#: src/metrics.md:1805 +msgid "that constructor's space" +msgstr "" + +#: src/metrics.md:1807 +msgid "" +"A non-canonical constructor (`R(int a) { this(a, 0); }`) is a callable of " +"its own with its own `nargs`, and does not close the header. The normal " +"canonical constructor is recognised by its name, which must be the record's, " +"and by its parameter _types_, not its arity or its parameter names: `bca` " +"compares each parameter's declared type with the component's as spelled by " +"its tokens — comments and whitespace aside, so `List` and " +"`List` agree — and has no symbol table, so `List` beside a `java." +"util.List` component, or `List` beside a `List<@Nullable String>` " +"one (a type-use annotation is a token of the type), is one type to the " +"compiler and two spellings here: the constructor is read as non-canonical " +"and the header opens beside it. In Groovy `def` and `var` declare no type, " +"so a `def a` component agrees with a `def a` or an untyped `a` parameter. A " +"record and an alternative constructor written on one line carry two `R::R` " +"rows at one `start_line`, which `bca check --baseline` cannot tell apart, as " +"two same-line overloads already were. The previous reading, under [\\#1160]" +"(https://github.com/dekobon/big-code-analysis/issues/1160), kept a record " +"with no written constructor at 0 and counted only a compact constructor; " +"#1842 revisits it, since the component list is declared code whether or not " +"the constructor is." +msgstr "" + +#: src/metrics.md:1829 +msgid "Three grammar limitations, all Groovy's; Java has none of them." +msgstr "" + +#: src/metrics.md:1831 +msgid "" +"**A compact constructor does not parse** ([tree-sitter-groovy#72](https://" +"github.com/dekobon/tree-sitter-groovy/issues/72)). In `record R(int a) { R " +"{ assert a > 0 } }` the bare `R` is an error node and the `{ … }` after it " +"is read as an initializer block of the record. The record writes no " +"constructor that `bca` can see, so its header opens and reports the right " +"count, but the compact body is not a function of its own: its code is " +"charged to the record's class space. The members after it stay in the " +"record. Spelled with a modifier, `public R { … }`, nothing errors: the name " +"is read as a field, so [NPA](#npa) also counts one public attribute the " +"record does not have." +msgstr "" + +#: src/metrics.md:1842 +msgid "" +"**A variable-arity component** (`String... xs`) parses with its `...` " +"outside the component's type, so it never matches a written canonical " +"constructor's `String... xs` parameter, and the header opens beside that " +"constructor." +msgstr "" + +#: src/metrics.md:1846 +msgid "" +"**An untyped component list does not parse.** The grammar requires a type on " +"each component, so `record R(a, b)` recovers as one component (`a` read as " +"the type, `b` as the name, the comma in an error node) and the header " +"reports `nargs` 1 for two components. A written canonical constructor `R(a, " +"b)` has two untyped parameters, which the one-component header never " +"matches, so the header opens beside it. `bca` does not infer the count over " +"the error node." +msgstr "" + +#: src/metrics.md:1854 +msgid "Averages, minimums and maximums" +msgstr "" + +#: src/metrics.md:1856 +msgid "" +"NArgs does not follow the [aggregate population](#aggregate-population) rule " +"of cyclomatic, cognitive and NExits. Its extrema and its averages count " +"different things:" +msgstr "" + +#: src/metrics.md:1861 +msgid "" +"`function_args_min` / `function_args_max` and `closure_args_min` / " +"`closure_args_max` fold each space's own count on that channel, over every " +"space in the subtree. A space that declares no parameters on a channel folds " +"a 0 into that channel's minimum. The file unit and containers declare none, " +"so their `function_args_min` is always 0." +msgstr "" + +#: src/metrics.md:1866 +msgid "" +"`function_args_average` and `closure_args_average` divide the channel's " +"argument total by the number of functions or closures [NOM](#nom) counts. " +"`average` divides the combined total by their sum." +msgstr "" + +#: src/metrics.md:1871 +msgid "" +"The two disagree in the languages whose lambdas open no space, the second " +"list under [What the threshold gate measures](#nargs-gate). There a lambda's " +"parameters add to the enclosing function's own `closure_args`, one member of " +"the extrema, while NOM counts the lambda as one closure of the divisor. A " +"function holding several such lambdas can report a `closure_args_average` " +"below its `closure_args_min`:" +msgstr "" + +#: src/metrics.md:1886 +msgid "" +"`pick` reports `closure_args_min 4`, `closure_args_max 4` and " +"`closure_args_average 1.0`: four parameters over four closures, all held by " +"one space." +msgstr "" + +#: src/metrics.md:1890 msgid "Languages where it reads 0" msgstr "0 と表示される言語" -#: src/metrics.md:1575 +#: src/metrics.md:1892 #, fuzzy msgid "" "A metric that silently reports 0 reads as \"no offenders\" rather than \"not " @@ -4147,7 +4813,7 @@ msgstr "" "黙って 0 を報告するメトリクスは「測定されていない」ではなく「違反者なし」と読" "めてしまうため、カウントが不活性な箇所を知っておく価値があります。" -#: src/metrics.md:1578 +#: src/metrics.md:1895 #, fuzzy msgid "" "**Bash**: correct and permanent. The shell has no formal parameter list; " @@ -4158,7 +4824,7 @@ msgstr "" "なく、引数は `$1`、`$2` などとして届きます。すべての関数が 0 と表示される唯一" "の言語です。" -#: src/metrics.md:1581 +#: src/metrics.md:1898 #, fuzzy msgid "" "**Perl subs without a signature**: correct. Signatures (`sub add($x, $y)`) " @@ -4169,7 +4835,7 @@ msgstr "" "add($x, $y)`)はカウントされます。`@_` から引数を読み取るサブルーチンは、数え" "るべき形式パラメータを宣言していません。" -#: src/metrics.md:1584 +#: src/metrics.md:1901 #, fuzzy msgid "" "**Perl anonymous subs**: a gap, and an upstream one. The grammar parses an " @@ -4181,7 +4847,17 @@ msgstr "" "`my $f = sub ($x) {…}` はシグネチャを持っているにもかかわらず 0 と表示されま" "す。" -#: src/metrics.md:1588 +#: src/metrics.md:1904 +msgid "" +"**Groovy compact constructors**: a gap, and an upstream one ([tree-sitter-" +"groovy#72](https://github.com/dekobon/tree-sitter-groovy/issues/72)). The " +"grammar does not parse `record R(int a) { R { … } }`: the count is still " +"right, on the header (see [Record headers](#nargs-record-headers)), but the " +"compact body is read as an initializer block of the record, not as a " +"function of its own." +msgstr "" + +#: src/metrics.md:1912 msgid "" "A `nargs` limit is therefore inert on a Bash codebase and sparse on Perl " "written before `use v5.36`. Gate it per language rather than repository-" @@ -4192,7 +4868,7 @@ msgstr "" "言語ごとにゲートしてください。[しきい値の選択](recipes/thresholds." "md#language-gaps)を参照してください。" -#: src/metrics.md:1595 +#: src/metrics.md:1919 #, fuzzy msgid "" "A function with many arguments is hard to call correctly and harder to test " @@ -4206,7 +4882,7 @@ msgstr "" "グの助言は _パラメータオブジェクトの導入_ パターンです。関数が 4 つを超える関" "連した引数を取る場合、それらをレコード / 構造体 / データクラスにまとめます。" -#: src/metrics.md:1601 +#: src/metrics.md:1925 #, fuzzy msgid "" "The common use is as a **review-blocking lint rule**: most linters (Pylint's " @@ -4224,11 +4900,11 @@ msgstr "" "が時間とともにじわじわ増えている公開 API は、「あともう 1 つだけパラメータ" "を」という機能フラグを積み重ねてきた API であることが多いのです。" -#: src/metrics.md:1609 +#: src/metrics.md:1933 msgid "NExits" msgstr "NExits" -#: src/metrics.md:1611 +#: src/metrics.md:1935 #, fuzzy msgid "" "**NExits** counts the number of distinct exit points from a function: every " @@ -4244,7 +4920,7 @@ msgstr "" "早期リターンです。関数末尾の暗黙的なフォールスルーのリターンは**数えません" "**。明示的な出口のみが対象です(issue #243 を参照)。" -#: src/metrics.md:1619 +#: src/metrics.md:1943 #, fuzzy msgid "" "The metric goes back to the [structured-programming](https://en.wikipedia." @@ -4265,13 +4941,15 @@ msgstr "" "ださい。同書は、ネストを減らせる場合の _早期リターン_ を、明確さを高めるパ" "ターンとして明示的に推奨しています。" -#: src/metrics.md:1629 +#: src/metrics.md:1953 +#, fuzzy msgid "" "big-code-analysis walks each function's syntax tree, identifies the language-" "specific exit nodes (see the per-language `Exit` trait in `src/metrics/" "nexits.rs`), and reports per-function counts plus file-level `sum`, " -"`average`, `min`, and `max`. The serialised field name is `nexits`, matching " -"the prose acronym used here." +"`average`, `min`, and `max`; the last three read the function-space " +"[population](#aggregate-population) cyclomatic's do. The serialised field " +"name is `nexits`, matching the prose acronym used here." msgstr "" "big-code-analysis は各関数の構文木を走査し、言語固有の出口ノードを特定し" "(`src/metrics/nexits.rs` の言語ごとの `Exit` トレイトを参照)、関数ごとのカ" @@ -4279,7 +4957,7 @@ msgstr "" "シリアライズされたフィールド名は `nexits` で、本文で使っている略語表記と一致" "します。" -#: src/metrics.md:1637 +#: src/metrics.md:1963 #, fuzzy msgid "" "Strict SESE coding standards ([DO-178C](https://en.wikipedia.org/wiki/" @@ -4298,7 +4976,7 @@ msgstr "" "候です。ほとんどの場合、その関数がガード節で事前条件を処理し、その後フラット" "な本体で処理を進めていることを意味するからです。" -#: src/metrics.md:1645 +#: src/metrics.md:1971 #, fuzzy msgid "" "A very high NExits, say above 8, is the warning sign. It usually means the " @@ -4309,11 +4987,11 @@ msgstr "" "の関数は複数の小さな関数に分割されるべきであり、それぞれの「成功する分岐」が" "独自のヘルパーになるべきだったことを意味します。" -#: src/metrics.md:1649 +#: src/metrics.md:1975 msgid "NOM" msgstr "NOM" -#: src/metrics.md:1651 +#: src/metrics.md:1977 #, fuzzy msgid "" "**NOM** stands for _Number Of Methods_ and counts every function, method, " @@ -4331,7 +5009,7 @@ msgstr "" "Hall、ISBN 0-13-179292-X)で最初期に導入したメトリクスの 1 つであり、同書では" "主要なクラスサイズ指標として扱われています。" -#: src/metrics.md:1660 +#: src/metrics.md:1986 msgid "" "big-code-analysis reports the count split by callable kind in `src/metrics/" "nom.rs`. The serialised fields are `functions`, `closures`, " @@ -4345,7 +5023,7 @@ msgstr "" "するスペース全体での平均)、および種類ごとの `functions_min`、" "`functions_max`、`closures_min`、`closures_max` です。" -#: src/metrics.md:1666 +#: src/metrics.md:1992 msgid "" "The split lets you ask different questions of the same code: a Rust crate " "with many closures and few functions is typical of iterator-heavy code; a " @@ -4356,7 +5034,7 @@ msgstr "" "関数が少ない Rust クレートはイテレータ中心のコードに典型的であり、関数が多く" "クロージャが少ない Python モジュールはスクリプト風のコードに典型的です。" -#: src/metrics.md:1671 +#: src/metrics.md:1997 #, fuzzy msgid "" "Some constructs that carry executable code are deliberately counted by " @@ -4381,7 +5059,40 @@ msgstr "" "まいます。したがって、プロパティアクセサだけからなる Kotlin ファイルは、その" "複雑度を報告しつつ `nom.functions == 0` を報告します(#1184)。" -#: src/metrics.md:1685 +#: src/metrics.md:2009 +msgid "" +"A constructor is counted as a function wherever its parameters are written, " +"the bodiless kind included: a Kotlin primary constructor, a C# 12 primary " +"constructor or positional record, and a Java or Groovy record's header where " +"the body writes no canonical constructor each count one, as the classic " +"spelling does (see [Primary constructors](#nargs-primary-constructors) and " +"[Record headers](#nargs-record-headers)). A compiler-generated constructor " +"with no written parameter list — a class with no constructor at all — counts " +"nothing." +msgstr "" + +#: src/metrics.md:2019 +msgid "" +"An annotation type's elements count in Groovy and not in Java. Both " +"compilers make an element an abstract method, but the two grammars parse it " +"differently. Java's gives the element a node kind of its own, which opens no " +"function space. Groovy's parses it as a bodiless method, as it does an " +"interface's abstract method. So `@interface Top { int v(); String name(); }` " +"reports `nom.functions` 2, an interface WMC of 2 and a cyclomatic sum of 4 " +"in Groovy, and 0, 0 and 2 in Java. The Groovy values match what a plain " +"`interface` with the same two methods reports in either language. In both " +"languages NPM counts the two elements as public methods. The Groovy grammar " +"also fails to parse two valid spellings: a modifier before `@interface` " +"([tree-sitter-groovy#92](https://github.com/dekobon/tree-sitter-groovy/" +"issues/92)) and an element's `default` value ([tree-sitter-groovy#101]" +"(https://github.com/dekobon/tree-sitter-groovy/issues/101)). The modifier " +"leaves an error node and the counts the annotation type reports without it. " +"A `default` value is read as an error node or as a field named `default`, " +"depending on the value: it can add an attribute to NPA, and one written " +"before another element can drop that element from NOM, NPM and WMC." +msgstr "" + +#: src/metrics.md:2042 #, fuzzy msgid "" "NOM is the input to several other metrics: WMC sums _cyclomatic_ complexity " @@ -4402,11 +5113,11 @@ msgstr "" "catalog/extractClass.html) に記述されている「コラボレーターの抽出」リファクタ" "リングの有力候補です。" -#: src/metrics.md:1695 +#: src/metrics.md:2052 msgid "NPA" msgstr "NPA" -#: src/metrics.md:1697 +#: src/metrics.md:2054 #, fuzzy msgid "" "**NPA** counts the **number of public attributes** (also called fields, " @@ -4426,7 +5137,7 @@ msgstr "" "が提案した MOOD(「Metrics for Object-Oriented Design」)スイートに取り込まれ" "ました。" -#: src/metrics.md:1705 +#: src/metrics.md:2062 #, fuzzy msgid "" "big-code-analysis splits the count by definition-site kind: _classes_ " @@ -4452,11 +5163,11 @@ msgstr "" "C# の `public`、Rust の `pub`、Python の「先頭にアンダースコアを付けない」慣" "習など)、そして何を「メソッド」ではなく「属性」と見なすかを決定します。" -#: src/metrics.md:1718 +#: src/metrics.md:2075 msgid "Which spaces carry NPA, NPM and WMC" msgstr "" -#: src/metrics.md:1720 +#: src/metrics.md:2077 msgid "" "NPA and NPM are emitted on **container spaces** (`class`, `struct`, `trait`, " "`impl`, `namespace`, `interface`) and on the whole-file `unit` root, which " @@ -4475,7 +5186,7 @@ msgid "" "input, for every language." msgstr "" -#: src/metrics.md:1737 +#: src/metrics.md:2094 msgid "" "That rule governs the _block_, not the numbers behind it: the counts roll up " "through every enclosing space regardless. So a type declared inside a " @@ -4483,7 +5194,7 @@ msgid "" "root when there is none." msgstr "" -#: src/metrics.md:1742 +#: src/metrics.md:2099 msgid "" "Four things read differently. A Go file's NPA and NPM live on the `unit` " "root and nowhere else, because Go is the one language that emits them " @@ -4493,7 +5204,7 @@ msgid "" "question does not arise.)" msgstr "" -#: src/metrics.md:1749 +#: src/metrics.md:2106 msgid "" "Neither WMC narrowing moves NPA or NPM, which is why the rule above still " "holds as stated for those two. The first is language-level: **Go emits no " @@ -4509,14 +5220,14 @@ msgid "" "class _inside_ the namespace carries all three, and so does the file root." msgstr "" -#: src/metrics.md:1763 +#: src/metrics.md:2120 msgid "" "Finally, the CSV projection is a fixed-column format: it writes the `npa." "*` / `npm.*` columns on **every** row regardless of space kind, carrying the " "real accessor values rather than eliding them." msgstr "" -#: src/metrics.md:1767 +#: src/metrics.md:2124 msgid "" "Thresholds are narrower still: `bca check` gates `npa` / `npm` on container " "spaces only, never the file root (see [Threshold scope](commands/check." @@ -4525,7 +5236,7 @@ msgid "" "root, **no `npa` or `npm` threshold can fire on Go source**." msgstr "" -#: src/metrics.md:1776 +#: src/metrics.md:2133 #, fuzzy msgid "" "NPA is a _direct_ measure of encapsulation. Every public attribute is a " @@ -4546,7 +5257,7 @@ msgstr "" "す — は、NPA をゼロまたはその近くに保ち、代わりに公開メソッドを通じて状態を公" "開することです。" -#: src/metrics.md:1787 +#: src/metrics.md:2144 #, fuzzy msgid "" "The common use is **API-stability auditing**: a public library class whose " @@ -4557,11 +5268,11 @@ msgstr "" "イブラリのクラスは、公開メソッドの表面よりも速いペースで破壊的変更の負債を蓄" "積します。" -#: src/metrics.md:1791 +#: src/metrics.md:2148 msgid "NPM" msgstr "NPM" -#: src/metrics.md:1793 +#: src/metrics.md:2150 msgid "" "**NPM** counts the **number of public methods** declared by a class or " "interface. It is the method-side companion to NPA and was again codified by " @@ -4571,7 +5282,7 @@ msgstr "" "ます。NPA のメソッド側の対になるもので、こちらも Lorenz と Kidd(1994 年)に" "よって体系化されました。" -#: src/metrics.md:1797 +#: src/metrics.md:2154 #, fuzzy msgid "" "As with NPA, big-code-analysis splits NPM by definition-site kind (classes " @@ -4597,7 +5308,7 @@ msgstr "" "ド、コンストラクタ、演算子オーバーロードを言語に応じて適切にまとめて扱いま" "す。" -#: src/metrics.md:1810 +#: src/metrics.md:2167 msgid "" "NPM is also one of the inputs into [Mark Hitz and Behzad Montazeri's _Class " "Interface Size_ metric](https://link.springer.com/" @@ -4609,7 +5320,61 @@ msgstr "" "Chidamber と Kemerer の _Response For a Class_(RFC)への入力の 1 つでもあり" "ます。" -#: src/metrics.md:1817 +#: src/metrics.md:2172 +#, fuzzy +msgid "Interface members" +msgstr "内部の文法" + +#: src/metrics.md:2174 +msgid "" +"An interface member is public by default, so NPM counts it unless it narrows " +"its own access:" +msgstr "" + +#: src/metrics.md:2177 +msgid "Not public in an interface" +msgstr "" + +#: src/metrics.md:2179 +msgid "" +"a `private` method ([JLS 9.4](https://docs.oracle.com/javase/specs/jls/se21/" +"html/jls-9.html#jls-9.4))" +msgstr "" + +#: src/metrics.md:2180 +msgid "" +"a `private` function, the one narrowing the compiler accepts there " +"(`protected` and `internal`, which it rejects, read the same)" +msgstr "" + +#: src/metrics.md:2181 +msgid "" +"a `private` member of an interface, [trait](https://groovy-lang.org/" +"objectorientation.html#_private_methods) or annotation type, and a " +"`protected` one (groovyc accepts that on a nested type only, a member record " +"among them)" +msgstr "" + +#: src/metrics.md:2182 +msgid "" +"a member marked `private`, `protected` or `internal`, alone or paired; the " +"static constructor; an explicit implementation of another interface's member " +"(`void IA.M() { }`); a `partial` method that does not say `public`" +msgstr "" + +#: src/metrics.md:2184 +msgid "" +"C# allows these modifiers on an interface member since [C# 8](https://learn." +"microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/" +"default-interface-methods). An [`internal`](https://learn.microsoft.com/en-" +"us/dotnet/csharp/language-reference/keywords/internal) member is reachable " +"only from its own assembly, so it is not public here, and the same rule " +"reads an accessor: `public int X { get; internal set; }` has one public " +"method. NPA reads the same rules for Kotlin interface properties, Groovy " +"interface and trait fields, and C# interface fields." +msgstr "" + +#: src/metrics.md:2195 #, fuzzy msgid "" "NPM is the **public interface size**. A class with NPM in the dozens is a " @@ -4628,7 +5393,7 @@ msgstr "" "く当てはまります。そこでは契約こそが、クライアントが依存の拠り所とする形その" "ものだからです。" -#: src/metrics.md:1826 +#: src/metrics.md:2204 #, fuzzy msgid "" "The common use is as a **public-API change tracker** for libraries: " @@ -4640,11 +5405,11 @@ msgstr "" "ケージレベルで NPM を監視すると、NPA が内部フィールドの偶発的な露出を捉えるの" "と同じように、ライブラリの表面積の偶発的な拡大を捉えられます。" -#: src/metrics.md:1831 +#: src/metrics.md:2209 msgid "Tokens" msgstr "Tokens" -#: src/metrics.md:1833 +#: src/metrics.md:2211 #, fuzzy msgid "" "**Tokens** is a per-function and per-file count of the _tree-sitter leaf " @@ -4663,7 +5428,7 @@ msgstr "" "ンツールでよく知られており、多くの読者がトークンカウントメトリクスを最初に目" "にするのはそこでしょう。)" -#: src/metrics.md:1841 +#: src/metrics.md:2219 #, fuzzy msgid "" "The implementation lives in `src/metrics/tokens.rs`. Because Tokens counts " @@ -4685,7 +5450,7 @@ msgstr "" "省略可能な波括弧の追加、セミコロンが省略可能な言語でのセミコロンの挿入・削除 " "— はカウントを変化させます。" -#: src/metrics.md:1854 +#: src/metrics.md:2232 #, fuzzy msgid "" "Tokens is less sensitive to formatting than LOC. It is the right size " @@ -4698,7 +5463,7 @@ msgstr "" "スを正規化する際に使うべきサイズ指標です。`bugs per KSLOC` はフォーマットの影" "響を受けますが、`bugs per 1000 tokens` ははるかに受けにくいのです。" -#: src/metrics.md:1860 +#: src/metrics.md:2238 #, fuzzy msgid "" "The common use is as the **defect-density denominator of choice** in cross-" @@ -4713,11 +5478,11 @@ msgstr "" "れます。このため Tokens は、多くの言語にまたがって学習する機械学習ベースの" "コード品質モデルに特に有用です。" -#: src/metrics.md:1867 +#: src/metrics.md:2245 msgid "WMC" msgstr "WMC" -#: src/metrics.md:1869 +#: src/metrics.md:2247 #, fuzzy msgid "" "**WMC** (_Weighted Methods per Class_) is the first metric in the [Chidamber " @@ -4739,7 +5504,7 @@ msgstr "" "(NOM、NPA、NPM)を実装しており、継承ベース・結合ベースのものは今後の課題とし" "て追跡されています。" -#: src/metrics.md:1878 +#: src/metrics.md:2256 #, fuzzy msgid "" "WMC is the **sum of the cyclomatic complexity of every method defined in a " @@ -4755,7 +5520,7 @@ msgstr "" "と書いています。しかし、その後の経験的な追試文献はほぼ例外なく循環的複雑度を" "重みとして採用しており、big-code-analysis もそれを使用します。" -#: src/metrics.md:1888 +#: src/metrics.md:2266 #, fuzzy msgid "" "For each class or interface found by the per-language parser, big-code-" @@ -4778,7 +5543,7 @@ msgstr "" "する report サブコマンドを使ってください([Commands → Report](./commands/" "report.md) を参照)。" -#: src/metrics.md:1900 +#: src/metrics.md:2278 msgid "" "Chidamber and Kemerer offered three hypotheses about WMC, all of which have " "been validated repeatedly since:" @@ -4786,7 +5551,7 @@ msgstr "" "Chidamber と Kemerer は WMC について 3 つの仮説を提示し、そのすべてがその後繰" "り返し検証されてきました。" -#: src/metrics.md:1903 +#: src/metrics.md:2281 msgid "" "**Higher WMC predicts higher maintenance effort.** A class whose methods are " "individually complex will resist comprehension." @@ -4794,7 +5559,7 @@ msgstr "" "**WMC が高いほど保守工数の増加を予測します。** 個々のメソッドが複雑なクラス" "は、理解しにくくなります。" -#: src/metrics.md:1905 +#: src/metrics.md:2283 msgid "" "**Higher WMC reduces reuse.** Classes that do many complicated things are " "hard to drop into a new context." @@ -4802,7 +5567,7 @@ msgstr "" "**WMC が高いほど再利用が減ります。** 多くの複雑なことを行うクラスは、新しいコ" "ンテキストに投入しにくいのです。" -#: src/metrics.md:1907 +#: src/metrics.md:2285 msgid "" "**Higher WMC suggests broader application-specific behaviour.** Such classes " "tend to be \"main loop\"-style coordinators rather than reusable building " @@ -4812,7 +5577,7 @@ msgstr "" "ようなクラスは、再利用可能な部品ではなく「メインループ」型のコーディネーター" "になりがちです。" -#: src/metrics.md:1911 +#: src/metrics.md:2289 #, fuzzy msgid "" "The common use is **God-class detection**: combined with NOM, WMC is one of " @@ -4829,12 +5594,12 @@ msgstr "" "割してください)。NOM と WMC の _両方_ が高いクラスが、古典的な God クラスで" "す。" -#: src/metrics.md:1921 src/metrics-vcs.md:559 src/python/quick-start.md:95 +#: src/metrics.md:2299 src/metrics-vcs.md:565 src/python/quick-start.md:95 #: src/python/traversal.md:137 msgid "Where to go next" msgstr "次のステップ" -#: src/metrics.md:1923 +#: src/metrics.md:2301 msgid "" "The [Supported Languages](./languages.md) chapter lists every supported " "language and grammar. Metric coverage varies by language because some metric " @@ -4844,7 +5609,7 @@ msgstr "" "います。一部のメトリクス定義(`NPA`、`NPM`、`WMC`)はクラスを持つ言語でしか意" "味をなさないため、メトリクスの対応範囲は言語によって異なります。" -#: src/metrics.md:1927 +#: src/metrics.md:2305 #, fuzzy msgid "" "The [Supported Change-history (VCS) Metrics](./metrics-vcs.md) chapter " @@ -4856,7 +5621,7 @@ msgstr "" "ではなくバージョン管理履歴から導出される補完的なファミリー — コミット頻度、" "チャーン、所有権、複合的なリスクスコアとホットスポットスコア — を扱います。" -#: src/metrics.md:1931 +#: src/metrics.md:2309 msgid "" "The [Commands → Metrics](./commands/metrics.md) page documents how to invoke " "`bca metrics` to produce the JSON / YAML / TOML / CBOR output for any of " @@ -4866,7 +5631,7 @@ msgstr "" "JSON / YAML / TOML / CBOR 出力を生成するための `bca metrics` の呼び出し方を説" "明しています。" -#: src/metrics.md:1934 +#: src/metrics.md:2312 msgid "" "The [Recipes](./recipes/quality-reports.md) chapter shows end-to-end " "examples of producing quality reports from these metrics, including " @@ -5169,7 +5934,10 @@ msgid "" "(first-parent only by default; `--full-history` follows all parent links in " "the commit graph) and attributes it to every file it modifies. Merge commits " "are excluded unless `--include-merges` is passed, and renames are followed " -"by default so a file's history survives a move. The walk counts _distinct " +"by default so a file's history survives a move — paired the way git pairs " +"them, under the repository's `diff.renameLimit` (read through the same " +"trusted-section filter git applies to a repository owned by someone else, so " +"a repository-local value there is ignored). The walk counts _distinct " "commits_ per file per window, not diffs or hunks, so a commit that touches a " "file once and a commit that touches it in three hunks both count as one." msgstr "" @@ -5182,7 +5950,7 @@ msgstr "" "所だけ触れるコミットも 3 つのハンクで触れるコミットも、どちらも 1 とカウント" "されます。" -#: src/metrics-vcs.md:96 +#: src/metrics-vcs.md:100 #, fuzzy msgid "" "Commit frequency is a rate, so it is only meaningful relative to a baseline: " @@ -5199,11 +5967,11 @@ msgstr "" "(#code-churn)と組み合わせれば両者を見分けられます。少数のコミットでの大量の" "チャーンと、多数のコミットでの少量のチャーンとでは事情が異なるからです。" -#: src/metrics-vcs.md:103 +#: src/metrics-vcs.md:107 msgid "Code churn" msgstr "コードチャーン" -#: src/metrics-vcs.md:105 +#: src/metrics-vcs.md:109 msgid "" "**Code churn** is the volume of change: the sum of added and deleted lines " "touching a file, recorded per window as `churn_long` and `churn_recent`." @@ -5211,7 +5979,7 @@ msgstr "" "**コードチャーン**は変更の量です。ファイルに触れた追加行数と削除行数の合計" "で、ウィンドウごとに `churn_long` と `churn_recent` として記録されます。" -#: src/metrics-vcs.md:109 +#: src/metrics-vcs.md:113 msgid "" "Churn's defect-prediction pedigree is Nachiappan Nagappan and Thomas Ball's " "2005 ICSE paper [_Use of Relative Code Churn Measures to Predict System " @@ -5235,7 +6003,7 @@ msgstr "" "るのではなく、複合スコアがそれをサイズや新しさと組み合わせられるようにしてい" "ます。" -#: src/metrics-vcs.md:123 +#: src/metrics-vcs.md:127 #, fuzzy msgid "" "For every in-window commit touching a file, the walk adds that diff's added-" @@ -5249,7 +6017,7 @@ msgstr "" "ウントされます。チャーンが測るのは _活動量_ であって、正味の増加量ではありま" "せん。" -#: src/metrics-vcs.md:131 +#: src/metrics-vcs.md:135 #, fuzzy msgid "" "Churn is the natural numerator for a density ratio. Churn per commit " @@ -5264,11 +6032,11 @@ msgstr "" "べて高いファイルは、履歴から予測されるよりも速く変化しています。これがまさに" "後述の[バースト](#burst)シグナルです。" -#: src/metrics-vcs.md:138 +#: src/metrics-vcs.md:142 msgid "Burst" msgstr "バースト" -#: src/metrics-vcs.md:140 +#: src/metrics-vcs.md:144 msgid "" "**Burst** is the share of a file's activity concentrated in the recent " "window: `commits_recent / commits_long`, reported as a ratio in `[0, 1]`. A " @@ -5280,7 +6048,7 @@ msgstr "" "い値はファイルのコミットのほぼすべてが直近のものであることを、`0` に近い値は" "ファイルが昔は活発だったがその後静かになったことを意味します。" -#: src/metrics-vcs.md:146 +#: src/metrics-vcs.md:150 #, fuzzy msgid "" "The signal follows from the recency principle that runs through the change-" @@ -5297,7 +6065,7 @@ msgstr "" "に前倒しで集中している_ ファイルは活発な変動のさなかにあり、活発な変動こそ欠" "陥が入り込む局面です。" -#: src/metrics-vcs.md:156 +#: src/metrics-vcs.md:160 msgid "" "Burst is a tie-breaker, not a standalone alarm. A high burst on a file with " "little total history is a young, fast-moving file; a high burst on a file " @@ -5311,11 +6079,11 @@ msgstr "" "場合こちらの方が興味深いケースです。[経過日数](#age-and-last-modified)と合わ" "せて読むことで両者を見分けられます。" -#: src/metrics-vcs.md:162 +#: src/metrics-vcs.md:166 msgid "Authorship and ownership" msgstr "作者数と所有権" -#: src/metrics-vcs.md:164 +#: src/metrics-vcs.md:168 msgid "" "Two related signals describe _who_ changes a file. **Author counts** " "(`authors_long`, `authors_recent`) count the distinct people who touched it " @@ -5329,7 +6097,7 @@ msgstr "" "は、最も活発な単一の作者に帰属する編集の割合です。低いシェアは所有権が分散し" "ていることを、高いシェアは一人が支配的であることを意味します。" -#: src/metrics-vcs.md:171 +#: src/metrics-vcs.md:175 #, fuzzy msgid "" "Both trace to empirical work on ownership and security. Christian Bird and " @@ -5358,7 +6126,7 @@ msgstr "" "の開発者が触れたファイルは脆弱性を抱える可能性がおよそ 16 倍高いと報告してい" "ます。" -#: src/metrics-vcs.md:186 +#: src/metrics-vcs.md:190 #, fuzzy msgid "" "Author identities are canonicalised through the repository [`.mailmap`]" @@ -5377,7 +6145,7 @@ msgstr "" "す。`ownership_top_share` は、ウィンドウ内でのそのファイルの総編集数に対する" "トップ作者の編集数の割合です。" -#: src/metrics-vcs.md:197 +#: src/metrics-vcs.md:201 #, fuzzy msgid "" "A rising author count on a long-lived file is a knowledge-diffusion signal: " @@ -5398,11 +6166,11 @@ msgstr "" "ルな加点を行います。1 つのファイル内ではなくファイルの _集合_ をまたぐ知識の" "集中については、[バスファクター](#bus-factor)を参照してください。" -#: src/metrics-vcs.md:207 +#: src/metrics-vcs.md:211 msgid "Fix, security, and revert commits" msgstr "修正・セキュリティ・リバートコミット" -#: src/metrics-vcs.md:209 +#: src/metrics-vcs.md:213 msgid "" "big-code-analysis classifies each long-window commit touching a file by the " "intent of its message and keeps three counts: `bug_fix_commits` (messages " @@ -5416,7 +6184,7 @@ msgstr "" "`security`、`vuln`、`exploit`、`sanitize` などに一致するメッセージ)、" "`revert_commits`(リバートまたはロールバックである件名)です。" -#: src/metrics-vcs.md:216 +#: src/metrics-vcs.md:220 #, fuzzy msgid "" "Reading a commit's purpose from its message is the technique introduced by " @@ -5438,7 +6206,7 @@ msgstr "" "を得なかった変更、つまりそこで何かがうまくいかなかったという局所的な自認を刻" "印します。" -#: src/metrics-vcs.md:228 +#: src/metrics-vcs.md:232 #, fuzzy msgid "" "Classification is keyword-based on the commit subject and body (see `src/vcs/" @@ -5453,7 +6221,7 @@ msgstr "" "ち軽量なメッセージ分類の半分であって、完全なアルゴリズムではありません。カウ" "ントは長期ウィンドウについてのみ保持されます。" -#: src/metrics-vcs.md:237 +#: src/metrics-vcs.md:241 #, fuzzy msgid "" "A high `bug_fix_commits` count is a file that keeps needing repair. The " @@ -5474,11 +6242,11 @@ msgstr "" "依存します。簡素なメッセージやテンプレート化されたメッセージのリポジトリでは" "過小カウントになります。" -#: src/metrics-vcs.md:248 +#: src/metrics-vcs.md:252 msgid "Age and last-modified" msgstr "経過日数と最終更新" -#: src/metrics-vcs.md:250 +#: src/metrics-vcs.md:254 msgid "" "Two timing signals bound a file's history. `age_days` is the number of days " "since the file's _first_ in-window commit (capped at the long window); " @@ -5490,7 +6258,7 @@ msgstr "" "る)、`last_modified_days` は _最新の_ ウィンドウ内コミットからの経過日数で" "す。" -#: src/metrics-vcs.md:255 +#: src/metrics-vcs.md:259 #, fuzzy msgid "" "These anchor the recency reasoning the rest of the family depends on. A " @@ -5507,7 +6275,7 @@ msgstr "" "す。小さい `last_modified_days` は最近編集されたファイルを示しますが、この性" "質はウィンドウがすでに重み付けしています。" -#: src/metrics-vcs.md:265 +#: src/metrics-vcs.md:269 msgid "" "`age_days` is most useful as the new-file trigger it feeds into the [risk " "score](#composite-risk-score): a file first seen inside the recent window " @@ -5524,11 +6292,11 @@ msgstr "" "取りです。何か月も触れられていない高リスクファイルと、今日編集されているファ" "イルとでは、保守上の位置付けが異なります。" -#: src/metrics-vcs.md:273 +#: src/metrics-vcs.md:277 msgid "Change entropy" msgstr "変更エントロピー" -#: src/metrics-vcs.md:275 +#: src/metrics-vcs.md:279 msgid "" "**Change entropy** measures how _scattered_ the commits touching a file are. " "It is reported per window as `change_entropy_long` and " @@ -5538,7 +6306,7 @@ msgstr "" "かを測ります。ウィンドウごとに `change_entropy_long` と " "`change_entropy_recent` として、ビット単位で報告されます。" -#: src/metrics-vcs.md:279 +#: src/metrics-vcs.md:283 #, fuzzy msgid "" "The metric is Ahmed Hassan's _History Complexity Metric_ from the 2009 ICSE " @@ -5568,7 +6336,7 @@ msgstr "" "ファイルレベルの変更エントロピーが欠陥数と最大 0.54 の Pearson 相関を示すこと" "が測定されています([共変更エントロピー](#co-change-entropy)を参照)。" -#: src/metrics-vcs.md:297 +#: src/metrics-vcs.md:301 #, fuzzy msgid "" "For each commit, big-code-analysis computes the Shannon entropy `H` of its " @@ -5587,7 +6355,7 @@ msgstr "" "高い変更エントロピーを蓄積し、常に焦点の定まったコミットでのみ変更されるファ" "イルは低いままです。" -#: src/metrics-vcs.md:308 +#: src/metrics-vcs.md:312 msgid "" "Change entropy distinguishes a file that changes _as part of large, " "sprawling edits_ from one that changes in self-contained commits, even when " @@ -5603,11 +6371,11 @@ msgstr "" "ウのリスク項に加算的に入り、チャーンやコミット数の言い換えではなく補完として" "働きます。" -#: src/metrics-vcs.md:315 +#: src/metrics-vcs.md:319 msgid "Co-change entropy" msgstr "共変更エントロピー" -#: src/metrics-vcs.md:317 +#: src/metrics-vcs.md:321 #, fuzzy msgid "" "**Co-change entropy** measures how wide a file's change _blast radius_ is: " @@ -5619,7 +6387,7 @@ msgstr "" "ンドウごとに `cochange_entropy_long` と `cochange_entropy_recent` として、" "ビット単位で報告されます。" -#: src/metrics-vcs.md:322 +#: src/metrics-vcs.md:326 #, fuzzy msgid "" "The signal comes from the 2025 study [_Co-Change Graph Entropy: A New " @@ -5644,7 +6412,7 @@ msgstr "" "に共変更エントロピーを加えることで、従来のシグナル集合に対して 82.5% のケース" "で AUROC が改善したと報告されています。" -#: src/metrics-vcs.md:337 +#: src/metrics-vcs.md:341 #, fuzzy msgid "" "The walk records, per commit, which in-scope files changed together and " @@ -5664,7 +6432,7 @@ msgstr "" "そのウィンドウにファイルの共変更相手が存在しないことを意味し、これは欠測では" "なく実際の測定値です。" -#: src/metrics-vcs.md:348 +#: src/metrics-vcs.md:352 #, fuzzy msgid "" "Where change entropy asks \"how scattered are the commits that touch this " @@ -5681,11 +6449,11 @@ msgstr "" "は互いを補完するよう設計されており、[リスクスコア](#composite-risk-score) " "`v2` は両方の直近ウィンドウ項を加算します。" -#: src/metrics-vcs.md:356 src/commands/vcs.md:158 +#: src/metrics-vcs.md:360 src/commands/vcs.md:159 msgid "Composite risk score" msgstr "複合リスクスコア" -#: src/metrics-vcs.md:358 +#: src/metrics-vcs.md:362 msgid "" "The **risk score** rolls every signal above into a single per-file number, " "`risk_score`. It is the headline output of `bca vcs` and the field its " @@ -5699,11 +6467,11 @@ msgstr "" "単一の `risk_score_version`(現在は `2`)で一緒にバージョン付けされるため、下" "流の消費者は変更を検出できます。" -#: src/metrics-vcs.md:364 +#: src/metrics-vcs.md:368 msgid "The weighted formula (default)" msgstr "重み付き式(デフォルト)" -#: src/metrics-vcs.md:366 +#: src/metrics-vcs.md:370 #, fuzzy msgid "" "The default formula is a log-scaled weighted sum with categorical " @@ -5716,7 +6484,7 @@ msgstr "" "110 と 120 の差よりも大きく効きます。これは変更活動が実際に飽和していく様子に" "合致します。" -#: src/metrics-vcs.md:385 +#: src/metrics-vcs.md:389 msgid "" "where `dilution = 1 - ownership_top_share`, the `dev_bonus` is `0.35` for " "nine or more long-window authors and `0.15` for six or more, and the " @@ -5739,7 +6507,7 @@ msgstr "" "ントロピー項は加算的に入ります(Hassan、arXiv 2504.18511)。完全な導出は " "`src/vcs/score.rs` にあります。" -#: src/metrics-vcs.md:397 +#: src/metrics-vcs.md:401 #, fuzzy msgid "" "The size term `ln(1 + sloc)² / 100` is a real contributor, not the tie-" @@ -5755,11 +6523,11 @@ msgstr "" "ります。大きなファイルと欠陥の相関は弱いに過ぎませんが、2 乗対数スケーリング" "により、サイズは支配的になることなく第一級の加算シグナルであり続けます。" -#: src/metrics-vcs.md:404 +#: src/metrics-vcs.md:408 msgid "The percentile formula" msgstr "パーセンタイル式" -#: src/metrics-vcs.md:406 +#: src/metrics-vcs.md:410 #, fuzzy msgid "" "`--risk-formula percentile` is the alternative: each signal is re-ranked to " @@ -5776,7 +6544,7 @@ msgstr "" "_相対的_ トリガーを推奨しています。代償として、スコアは単一の実行のファイル集" "合内でしか意味を持ちません。" -#: src/metrics-vcs.md:416 +#: src/metrics-vcs.md:420 #, fuzzy msgid "" "The score is **ordinal**. Sort a repository's files by it and look at the " @@ -5795,24 +6563,26 @@ msgstr "" "は各履歴時点でウォークを再アンカーするため、系列は当時のファイルの実際の姿を" "反映します。" -#: src/metrics-vcs.md:424 +#: src/metrics-vcs.md:428 msgid "Hotspot score" msgstr "ホットスポットスコア" -#: src/metrics-vcs.md:426 +#: src/metrics-vcs.md:430 +#, fuzzy msgid "" "The **hotspot score** is the product of a file's complexity and its recent " "churn: `hotspot_score = cyclomatic_sum × churn_recent`. It is an `Option`, " -"present only when an AST complexity figure is computed alongside the history " -"(for example `bca metrics --metrics cyclomatic --vcs`), because it needs " -"both halves." +"present only when `cyclomatic` is among the computed metrics, because it " +"needs both halves. A [per-function block](./commands/vcs.md#per-function-" +"attribution) uses the space's own cyclomatic instead of the subtree sum, so " +"a nested function's complexity is not counted again in every enclosing space." msgstr "" "**ホットスポットスコア**は、ファイルの複雑度と直近チャーンの積です" "(`hotspot_score = cyclomatic_sum × churn_recent`)。これは `Option` であり、" "両方の半分を必要とするため、履歴と併せて AST 複雑度の数値が計算されている場合" "(たとえば `bca metrics --metrics cyclomatic --vcs`)にのみ存在します。" -#: src/metrics-vcs.md:432 +#: src/metrics-vcs.md:438 #, fuzzy msgid "" "The metric is the central idea of Adam Tornhill's 2015 book [_Your Code as a " @@ -5836,7 +6606,7 @@ msgstr "" "活動の大半を占めるのが典型だと観察しており、ホットスポットスコアはその一部を" "見つけるために作られています。" -#: src/metrics-vcs.md:446 +#: src/metrics-vcs.md:452 msgid "" "Like the risk score, the hotspot product is ordinal: rank files by it, do " "not read the magnitude. The CLI uses the file-level cyclomatic sum as the " @@ -5853,11 +6623,11 @@ msgstr "" "かつ誰かの画面ですでに開かれている今こそ最も安上がりにリファクタリングできる" "ファイルです。" -#: src/metrics-vcs.md:454 +#: src/metrics-vcs.md:460 msgid "Bus factor" msgstr "バスファクター" -#: src/metrics-vcs.md:456 +#: src/metrics-vcs.md:462 msgid "" "Where `ownership_top_share` measures knowledge concentration _within_ a " "single file, the **bus factor** (also called the _truck factor_) measures it " @@ -5876,7 +6646,7 @@ msgstr "" "れを、リポジトリ全体、各トップレベルディレクトリ、およびその直下のサブディレ" "クトリを対象とする `vcs_aggregate` オブジェクトとして出力します。" -#: src/metrics-vcs.md:466 +#: src/metrics-vcs.md:472 msgid "" "The estimation method is Guilherme Avelino, Leonardo Passos, Andre Hora, and " "Marco Tulio Valente's 2016 ICPC paper [_A Novel Approach for Estimating " @@ -5890,7 +6660,7 @@ msgstr "" "に対する作者性は、彼らの _Degree-of-Authorship_ ヒューリスティックでスコア付" "けされます。" -#: src/metrics-vcs.md:476 +#: src/metrics-vcs.md:482 msgid "" "where `FA` is first authorship (`1` if developer `d` created file `f`), `DL` " "is `d`'s number of deliveries (changes) to `f`, and `AC` is the changes made " @@ -5902,7 +6672,7 @@ msgstr "" "変更数です。開発者は、ファイルの最大値で正規化した DoA が `0.75`(論文のしき" "い値)を超えるとき、そのファイルの**作者**とみなされます。" -#: src/metrics-vcs.md:484 +#: src/metrics-vcs.md:490 msgid "" "The truck factor is a greedy removal (see `src/vcs/bus_factor.rs`): " "repeatedly drop the developer who authors the most still-covered files, " @@ -5919,7 +6689,7 @@ msgstr "" "は 1 回のウォークでスコープ内の全ファイルをカバーするため、`by_directory` の" "各エントリは各ディレクトリ配下の全ファイルを再帰的に対象として計算されます。" -#: src/metrics-vcs.md:494 +#: src/metrics-vcs.md:500 #, fuzzy msgid "" "A bus factor of `1` means losing one person orphans the set, which is " @@ -5938,11 +6708,11 @@ msgstr "" "の作成を意味しません。知識が危険なほど集中しているディレクトリを見つけ、それ" "に応じてレビューを分散させるために使ってください。" -#: src/metrics-vcs.md:503 +#: src/metrics-vcs.md:509 msgid "Just-in-time commit score" msgstr "ジャストインタイムコミットスコア" -#: src/metrics-vcs.md:505 +#: src/metrics-vcs.md:511 #, fuzzy msgid "" "Everything above ranks _files_ at a point in time. The **just-in-time (JIT) " @@ -5958,7 +6728,7 @@ msgstr "" "し、グループごとの `contributions` 内訳を伴う順序尺度の `risk_score` として報" "告されます。" -#: src/metrics-vcs.md:511 +#: src/metrics-vcs.md:517 msgid "" "The feature groups and their signs are taken from the just-in-time defect-" "prediction literature, beginning with Yasutaka Kamei and colleagues' 2013 " @@ -5980,7 +6750,7 @@ msgstr "" "く静的なルールベースのスコアラーを実装しているため、プロジェクトが古びても何" "もドリフトしません。" -#: src/metrics-vcs.md:525 +#: src/metrics-vcs.md:531 msgid "" "Five feature groups move the score, each scored against the commit's first " "parent (see `src/vcs/jit.rs`):" @@ -5988,47 +6758,47 @@ msgstr "" "5 つの特徴量グループがスコアを動かします。各グループはコミットの第一親に対し" "て評価されます(`src/vcs/jit.rs` を参照)。" -#: src/metrics-vcs.md:528 src/commands/vcs.md:386 +#: src/metrics-vcs.md:534 src/commands/vcs.md:413 msgid "Group" msgstr "グループ" -#: src/metrics-vcs.md:528 src/commands/vcs.md:386 +#: src/metrics-vcs.md:534 src/commands/vcs.md:413 msgid "Features" msgstr "特徴量" -#: src/metrics-vcs.md:528 src/commands/vcs.md:386 +#: src/metrics-vcs.md:534 src/commands/vcs.md:413 msgid "Direction" msgstr "方向" -#: src/metrics-vcs.md:530 src/commands/vcs.md:388 +#: src/metrics-vcs.md:536 src/commands/vcs.md:415 msgid "**Size**" msgstr "**サイズ**" -#: src/metrics-vcs.md:530 src/commands/vcs.md:388 +#: src/metrics-vcs.md:536 src/commands/vcs.md:415 msgid "lines added / deleted, files touched, diff hunks" msgstr "追加 / 削除行数、変更ファイル数、diff ハンク数" -#: src/metrics-vcs.md:530 src/commands/vcs.md:388 +#: src/metrics-vcs.md:536 src/commands/vcs.md:415 msgid "larger ⇒ riskier" msgstr "大きいほど ⇒ 高リスク" -#: src/metrics-vcs.md:531 src/commands/vcs.md:389 +#: src/metrics-vcs.md:537 src/commands/vcs.md:416 msgid "**Diffusion**" msgstr "**拡散度**" -#: src/metrics-vcs.md:531 +#: src/metrics-vcs.md:537 msgid "distinct subsystems and directories, within-commit change entropy" msgstr "個別のサブシステム数とディレクトリ数、コミット内変更エントロピー" -#: src/metrics-vcs.md:531 src/commands/vcs.md:389 +#: src/metrics-vcs.md:537 src/commands/vcs.md:416 msgid "more scattered ⇒ riskier" msgstr "分散しているほど ⇒ 高リスク" -#: src/metrics-vcs.md:532 src/commands/vcs.md:390 +#: src/metrics-vcs.md:538 src/commands/vcs.md:417 msgid "**History**" msgstr "**履歴**" -#: src/metrics-vcs.md:532 +#: src/metrics-vcs.md:538 #, fuzzy msgid "" "the touched files' priors (prior changes, distinct authors, fix counts, and " @@ -6037,35 +6807,35 @@ msgstr "" "触れたファイルの事前値(過去の変更回数、個別作者数、修正回数、およびそれらの" "複合リスク)をコミット _前_ に測定したもの" -#: src/metrics-vcs.md:532 +#: src/metrics-vcs.md:538 msgid "turbulent history ⇒ riskier" msgstr "波乱の履歴 ⇒ 高リスク" -#: src/metrics-vcs.md:533 src/commands/vcs.md:391 +#: src/metrics-vcs.md:539 src/commands/vcs.md:418 msgid "**Experience**" msgstr "**経験**" -#: src/metrics-vcs.md:533 +#: src/metrics-vcs.md:539 msgid "the author's prior commit count (long and recent)" msgstr "作者のそれまでのコミット数(長期・直近)" -#: src/metrics-vcs.md:533 src/commands/vcs.md:391 +#: src/metrics-vcs.md:539 src/commands/vcs.md:418 msgid "more experience ⇒ **less** risky (this group subtracts)" msgstr "経験が多いほど ⇒ リスクは**低下**(このグループは減算)" -#: src/metrics-vcs.md:534 src/commands/vcs.md:392 +#: src/metrics-vcs.md:540 src/commands/vcs.md:419 msgid "**Purpose**" msgstr "**目的**" -#: src/metrics-vcs.md:534 src/commands/vcs.md:392 +#: src/metrics-vcs.md:540 src/commands/vcs.md:419 msgid "fix / security-fix / revert classification of the message" msgstr "メッセージの修正 / セキュリティ修正 / リバート分類" -#: src/metrics-vcs.md:534 src/commands/vcs.md:392 +#: src/metrics-vcs.md:540 src/commands/vcs.md:419 msgid "fixes add, reverts dampen" msgstr "修正は加算、リバートは減衰" -#: src/metrics-vcs.md:536 +#: src/metrics-vcs.md:542 msgid "" "The `contributions` block reports each group's signed contribution, so a " "consumer can see _why_ a commit ranked where it did. A merge commit is " @@ -6085,7 +6855,7 @@ msgstr "" "のはサイズと拡散度のグループだけなので、その経路は意図的に部分的な " "`partial_risk_score` を出力します。" -#: src/metrics-vcs.md:548 +#: src/metrics-vcs.md:554 #, fuzzy msgid "" "Like the file-level score, the JIT score is **ordinal**: rank commits by it, " @@ -6105,7 +6875,7 @@ msgstr "" "たちの履歴に照らして調整してください。式に対するいかなる変更も、ファイルレベ" "ルの `risk_score_version` とは独立した `jit_score_version` を上げます。" -#: src/metrics-vcs.md:561 +#: src/metrics-vcs.md:567 msgid "" "The [Commands → Change-history (VCS) metrics](./commands/vcs.md) page " "documents how to invoke `bca vcs`, configure the windows, choose an output " @@ -6115,7 +6885,7 @@ msgstr "" "vcs` の呼び出し方、ウィンドウの設定、出力形式の選択、永続的な履歴キャッシュの" "使い方を説明しています。" -#: src/metrics-vcs.md:564 +#: src/metrics-vcs.md:570 #, fuzzy msgid "" "The [Supported Code Metrics](./metrics.md) chapter covers the AST-derived " @@ -6126,7 +6896,7 @@ msgstr "" "する AST 由来のメトリクスを扱います。特に[ホットスポットスコア](#hotspot-" "score)は 2 つのファミリーを組み合わせたものです。" -#: src/metrics-vcs.md:568 +#: src/metrics-vcs.md:574 msgid "" "The [Python Bindings → Change-history (VCS) metrics](./python/vcs.md) page " "shows the same family through the `big_code_analysis.vcs` module." @@ -6335,13 +7105,13 @@ msgstr "# 旧\n" #: src/migration.md:51 src/migration.md:60 src/commands/report.md:102 #: src/recipes/quality-reports.md:41 src/recipes/quality-reports.md:66 -#: src/recipes/quality-reports.md:76 src/recipes/quality-reports.md:124 +#: src/recipes/quality-reports.md:76 src/recipes/quality-reports.md:125 #: src/recipes/ast-queries.md:21 msgid "\"$PWD\"" msgstr "\"$PWD\"" #: src/migration.md:55 src/migration.md:63 src/commands/report.md:105 -#: src/recipes/quality-reports.md:44 src/recipes/quality-reports.md:125 +#: src/recipes/quality-reports.md:44 src/recipes/quality-reports.md:126 msgid "\"$PWD/\"" msgstr "\"$PWD/\"" @@ -6473,6 +7243,21 @@ msgstr "" "旧形式の呼び出しを実行すると、CLI は clap 自身のエラーの前に、認識した旧フラ" "グとその新しい対応フラグを示すヒントを表示します。例:" +#: src/migration.md:153 +msgid "" +"```text\n" +"$ bca --metrics -O markdown\n" +"note: the CLI was restructured into subcommands. See the migration guide for " +"the full mapping:\n" +" https://dekobon.github.io/big-code-analysis/migration.html\n" +" --metrics -> bca metrics\n" +" -O markdown -> bca report markdown|html [--top N] [--strip-prefix P]\n" +" Run `bca --help` for the new command list.\n" +"\n" +"error: unexpected argument '--metrics' found\n" +"```" +msgstr "" + #: src/commands/index.md:3 msgid "" "`bca` is the command-line tool. Each subcommand performs one analysis and " @@ -6793,7 +7578,7 @@ msgstr "" "このスキップは `bca metrics`、`bca report`、およびしきい値エンジンに一律に適" "用されます。" -#: src/commands/index.md:149 src/commands/vcs.md:209 src/commands/report.md:41 +#: src/commands/index.md:149 src/commands/vcs.md:210 src/commands/report.md:41 msgid "Flags" msgstr "フラグ" @@ -7058,7 +7843,7 @@ msgstr "" "す。文字どおり `-` という名前のファイルを渡すには `./-` と書きます。" #: src/commands/index.md:261 src/commands/check.md:123 -#: src/recipes/local-gates.md:380 +#: src/recipes/local-gates.md:391 msgid "Exit codes" msgstr "終了コード" @@ -7076,7 +7861,7 @@ msgid "Code" msgstr "コード" #: src/commands/index.md:268 src/commands/check.md:127 -#: src/commands/check.md:156 src/recipes/ci.md:960 src/recipes/ci.md:982 +#: src/commands/check.md:156 src/recipes/ci.md:969 src/recipes/ci.md:991 msgid "`0`" msgstr "`0`" @@ -7102,8 +7887,8 @@ msgstr "" "ではありません。" #: src/commands/index.md:270 src/commands/check.md:128 -#: src/commands/check.md:158 src/recipes/ci.md:961 src/recipes/ci.md:962 -#: src/recipes/ci.md:981 src/recipes/ci.md:983 +#: src/commands/check.md:158 src/recipes/ci.md:970 src/recipes/ci.md:971 +#: src/recipes/ci.md:990 src/recipes/ci.md:992 msgid "`2`" msgstr "`2`" @@ -7740,6 +8525,17 @@ msgid "`#![cfg(test)]` on `mod` items (inner attribute form)" msgstr "`mod` アイテムに付く `#![cfg(test)]`(内部属性形式)" #: src/commands/metrics.md:184 +msgid "" +"A pruned item takes its whole attribute run with it: every `#[…]` row above " +"it, any `//` or `/* */` comment among those rows (rustc reads a comment as " +"no token, so the attribute still applies), and the `///` doc comments above " +"or among them (rustc reads each as a `#[doc]` attribute of the same item). A " +"plain comment _above_ the first attribute is not part of the run and stays, " +"as does a `//!` inner doc comment, which documents the enclosing file or " +"module rather than the item below it." +msgstr "" + +#: src/commands/metrics.md:193 #, fuzzy msgid "" "Languages without a `Checker::should_skip_subtree` override ignore the flag; " @@ -7751,7 +8547,7 @@ msgstr "" "はオフのままなので、オプトインしないユーザーの既存のメトリクス値はバイト単位" "で同一に保たれます。" -#: src/commands/metrics.md:189 +#: src/commands/metrics.md:198 #, fuzzy msgid "" "To opt a whole project in without repeating the flag, set `exclude_tests = " @@ -7770,7 +8566,7 @@ msgstr "" "が、ユニットレベルの `loc.sloc` はファイル全体の範囲のまま残ります。ユニット " "SLOC はトラバーサルの累積ではなくファイルルートのスパンだからです。" -#: src/commands/metrics.md:196 +#: src/commands/metrics.md:205 msgid "" "Pruning lowers the node-counted metrics (cyclomatic, cognitive, Halstead, " "`nom`, `nargs`, and the rest), and `loc.sloc` drops with them. Unlike node-" @@ -7780,11 +8576,11 @@ msgid "" "never falls below the `ploc` and `cloc` that survive the prune." msgstr "" -#: src/commands/metrics.md:204 +#: src/commands/metrics.md:213 msgid "Aggregated report" msgstr "集約レポート" -#: src/commands/metrics.md:206 +#: src/commands/metrics.md:215 #, fuzzy msgid "" "For a human-readable quality report, use [`bca report markdown`](report.md). " @@ -7795,11 +8591,11 @@ msgstr "" "を使用してください。このコマンドは解析したすべてのファイルにわたってメトリク" "スを集約し、言語ごとのホットスポットテーブルを生成します。" -#: src/commands/metrics.md:210 +#: src/commands/metrics.md:219 msgid "Listing available metrics" msgstr "利用可能なメトリクスの一覧" -#: src/commands/metrics.md:212 +#: src/commands/metrics.md:221 msgid "" "Tooling that drives the CLI can discover the metric catalog at runtime " "instead of hard-coding it:" @@ -7807,7 +8603,7 @@ msgstr "" "CLI を駆動するツールは、メトリクスのカタログをハードコードする代わりに実行時" "に検出できます。" -#: src/commands/metrics.md:219 +#: src/commands/metrics.md:228 msgid "" "prints metric names one per line. Pass `descriptions` for a one-line summary " "of each metric:" @@ -7971,11 +8767,11 @@ msgstr "レンダリングされたレポートページ" #, fuzzy msgid "" "`--format html` produces a self-contained, sortable page styled like `bca " -"report html` (click any column header to re-sort); `--format markdown` " -"produces the same ranked table as [GitHub-Flavored Markdown](https://github." -"github.com/gfm/). Both render every signal column, the same data the " -"structured formats carry. The column set is defined once and shared by both " -"renderers, so they cannot drift." +"report html` (click any column header's label, or Tab to it and press Enter, " +"to re-sort); `--format markdown` produces the same ranked table as [GitHub-" +"Flavored Markdown](https://github.github.com/gfm/). Both render every signal " +"column, the same data the structured formats carry. The column set is " +"defined once and shared by both renderers, so they cannot drift." msgstr "" "`--format html` は、`bca report html` とまったく同じスタイルの、自己完結型で" "ソート可能なページを生成します(任意の列ヘッダーをクリックすると並べ替えられ" @@ -7985,7 +8781,7 @@ msgstr "" "セットは一度だけ定義され両方のレンダラーで共有されるため、両者が乖離すること" "はありません。" -#: src/commands/vcs.md:86 +#: src/commands/vcs.md:87 msgid "" "To fold the ranking into the aggregated quality report instead of a " "standalone page, pass [`bca report --vcs`](report.md), which appends a " @@ -7995,89 +8791,89 @@ msgstr "" "[`bca report --vcs`](report.md) を渡します。これは `report markdown` / " "`report html` に「Change-history risk」セクションを追加します。" -#: src/commands/vcs.md:90 +#: src/commands/vcs.md:91 msgid "Signals" msgstr "シグナル" -#: src/commands/vcs.md:92 src/library/walking-funcspace.md:14 +#: src/commands/vcs.md:93 src/library/walking-funcspace.md:14 msgid "Field" msgstr "フィールド" -#: src/commands/vcs.md:92 src/library/walking-funcspace.md:14 +#: src/commands/vcs.md:93 src/library/walking-funcspace.md:14 msgid "Type" msgstr "型" -#: src/commands/vcs.md:92 src/commands/report.md:43 +#: src/commands/vcs.md:93 src/commands/report.md:43 msgid "Description" msgstr "説明" -#: src/commands/vcs.md:94 +#: src/commands/vcs.md:95 msgid "`commits_long` / `commits_recent`" msgstr "`commits_long` / `commits_recent`" -#: src/commands/vcs.md:94 src/commands/vcs.md:96 src/commands/vcs.md:99 -#: src/commands/vcs.md:100 src/commands/vcs.md:101 src/commands/vcs.md:102 -#: src/commands/vcs.md:103 src/commands/vcs.md:108 +#: src/commands/vcs.md:95 src/commands/vcs.md:97 src/commands/vcs.md:100 +#: src/commands/vcs.md:101 src/commands/vcs.md:102 src/commands/vcs.md:103 +#: src/commands/vcs.md:104 src/commands/vcs.md:109 msgid "u32" msgstr "u32" -#: src/commands/vcs.md:94 +#: src/commands/vcs.md:95 msgid "Distinct commits touching the file in each window" msgstr "各ウィンドウでファイルに触れた個別コミット数" -#: src/commands/vcs.md:95 +#: src/commands/vcs.md:96 msgid "`churn_long` / `churn_recent`" msgstr "`churn_long` / `churn_recent`" -#: src/commands/vcs.md:95 +#: src/commands/vcs.md:96 msgid "u64" msgstr "u64" -#: src/commands/vcs.md:95 +#: src/commands/vcs.md:96 msgid "Σ(added + deleted) lines in each window" msgstr "各ウィンドウにおける Σ(added + deleted) 行数" -#: src/commands/vcs.md:96 +#: src/commands/vcs.md:97 msgid "`authors_long` / `authors_recent`" msgstr "`authors_long` / `authors_recent`" -#: src/commands/vcs.md:96 +#: src/commands/vcs.md:97 msgid "Distinct canonical author identities in each window" msgstr "各ウィンドウにおける正規化済み作者 ID の個別数" -#: src/commands/vcs.md:97 +#: src/commands/vcs.md:98 msgid "`ownership_top_share`" msgstr "`ownership_top_share`" -#: src/commands/vcs.md:97 src/commands/vcs.md:98 +#: src/commands/vcs.md:98 src/commands/vcs.md:99 msgid "f64 ∈ \\[0,1\\]" msgstr "f64 ∈ \\[0,1\\]" -#: src/commands/vcs.md:97 +#: src/commands/vcs.md:98 msgid "Share of edits attributable to the top author (lower = more diluted)" msgstr "トップ作者に帰属する編集の割合(低いほど所有権の希薄化が進んでいる)" -#: src/commands/vcs.md:98 +#: src/commands/vcs.md:99 msgid "`burst`" msgstr "`burst`" -#: src/commands/vcs.md:98 +#: src/commands/vcs.md:99 msgid "`commits_recent / commits_long`" msgstr "`commits_recent / commits_long`" -#: src/commands/vcs.md:99 +#: src/commands/vcs.md:100 msgid "`bug_fix_commits`" msgstr "`bug_fix_commits`" -#: src/commands/vcs.md:99 +#: src/commands/vcs.md:100 msgid "Long-window commits whose message matches a bug-fix keyword" msgstr "メッセージがバグ修正キーワードに一致する長期ウィンドウのコミット数" -#: src/commands/vcs.md:100 +#: src/commands/vcs.md:101 msgid "`security_fix_commits`" msgstr "`security_fix_commits`" -#: src/commands/vcs.md:100 +#: src/commands/vcs.md:101 msgid "" "Long-window commits matching security keywords (`CVE-####`, `security`, " "`vuln`, `exploit`, `sanitize`, …)" @@ -8085,84 +8881,85 @@ msgstr "" "セキュリティキーワード(`CVE-####`、`security`、`vuln`、`exploit`、" "`sanitize` など)に一致する長期ウィンドウのコミット数" -#: src/commands/vcs.md:101 +#: src/commands/vcs.md:102 msgid "`revert_commits`" msgstr "`revert_commits`" -#: src/commands/vcs.md:101 +#: src/commands/vcs.md:102 msgid "Long-window commits whose subject is a revert / rollback" msgstr "件名がリバート / ロールバックである長期ウィンドウのコミット数" -#: src/commands/vcs.md:102 +#: src/commands/vcs.md:103 msgid "`age_days`" msgstr "`age_days`" -#: src/commands/vcs.md:102 +#: src/commands/vcs.md:103 msgid "" "Days since the file's first in-window commit (capped at the long window)" msgstr "" "ファイルのウィンドウ内で最初のコミットからの経過日数(長期ウィンドウが上限)" -#: src/commands/vcs.md:103 +#: src/commands/vcs.md:104 msgid "`last_modified_days`" msgstr "`last_modified_days`" -#: src/commands/vcs.md:103 +#: src/commands/vcs.md:104 msgid "Days since the file's most recent in-window commit" msgstr "ファイルのウィンドウ内で最も新しいコミットからの経過日数" -#: src/commands/vcs.md:104 +#: src/commands/vcs.md:105 msgid "`change_entropy_long` / `change_entropy_recent`" msgstr "`change_entropy_long` / `change_entropy_recent`" -#: src/commands/vcs.md:104 src/commands/vcs.md:105 src/commands/vcs.md:106 +#: src/commands/vcs.md:105 src/commands/vcs.md:106 src/commands/vcs.md:107 msgid "f64" msgstr "f64" -#: src/commands/vcs.md:104 +#: src/commands/vcs.md:105 msgid "Change entropy in bits per window (see below)" msgstr "ウィンドウごとの変更エントロピー(ビット単位、下記参照)" -#: src/commands/vcs.md:105 +#: src/commands/vcs.md:106 msgid "`cochange_entropy_long` / `cochange_entropy_recent`" msgstr "`cochange_entropy_long` / `cochange_entropy_recent`" -#: src/commands/vcs.md:105 +#: src/commands/vcs.md:106 msgid "Co-change graph entropy in bits per window (see below)" msgstr "ウィンドウごとの共変更グラフエントロピー(ビット単位、下記参照)" -#: src/commands/vcs.md:106 +#: src/commands/vcs.md:107 msgid "`risk_score`" msgstr "`risk_score`" -#: src/commands/vcs.md:106 +#: src/commands/vcs.md:107 #, fuzzy msgid "Composite, formula-versioned (see below); **ordinal, not cardinal**" msgstr "" "複合スコア。式はバージョン管理されます(下記参照)— **順序尺度であり、基数尺" "度ではない**" -#: src/commands/vcs.md:107 +#: src/commands/vcs.md:108 msgid "`hotspot_score`" msgstr "`hotspot_score`" -#: src/commands/vcs.md:107 +#: src/commands/vcs.md:108 msgid "f64?" msgstr "f64?" -#: src/commands/vcs.md:107 +#: src/commands/vcs.md:108 +#, fuzzy msgid "" -"`complexity × churn_recent`; present only when AST metrics are computed " -"alongside" +"`complexity × churn_recent`; present only when `cyclomatic` is among the " +"computed metrics" msgstr "" "`complexity × churn_recent`。AST メトリクスが同時に計算される場合のみ存在しま" "す" -#: src/commands/vcs.md:108 +#: src/commands/vcs.md:109 msgid "`risk_score_version` / `vcs_schema_version`" msgstr "`risk_score_version` / `vcs_schema_version`" -#: src/commands/vcs.md:108 +#: src/commands/vcs.md:109 #, fuzzy msgid "" "Forward-compatibility version stamps. Carried **once on the report " @@ -8173,7 +8970,7 @@ msgstr "" "`recent_window_days` と並んで**レポートのエンベロープに 1 回だけ**付与され、" "ファイルごとの `vcs` ブロック内では繰り返されません(issue #635)" -#: src/commands/vcs.md:110 +#: src/commands/vcs.md:111 #, fuzzy msgid "" "Author identities are canonicalised through the repository [`.mailmap`]" @@ -8194,11 +8991,11 @@ msgstr "" "未追跡ファイルにはレコードがまったく存在しません(ウィンドウ内の活動がゼロの" "追跡ファイルとは区別されます)。" -#: src/commands/vcs.md:122 +#: src/commands/vcs.md:123 msgid "Change & co-change entropy" msgstr "変更エントロピーと共変更エントロピー" -#: src/commands/vcs.md:124 +#: src/commands/vcs.md:125 msgid "" "Two process-entropy signals (added in `risk_score_version` 2) capture _how_ " "a file changes, not just how much:" @@ -8206,7 +9003,7 @@ msgstr "" "2 つのプロセスエントロピーシグナル(`risk_score_version` 2 で追加)は、ファイ" "ルの変更量だけでなく、「どのように」変更されるかを捉えます。" -#: src/commands/vcs.md:127 +#: src/commands/vcs.md:128 #, fuzzy msgid "" "**Change entropy** (Hassan, 2009, [_Predicting Faults Using the Complexity " @@ -8232,7 +9029,7 @@ msgstr "" "2504.18511)では、8 つの Apache プロジェクトにおいてファイルレベルの変更エン" "トロピーと欠陥数との Pearson 相関が最大 0.54 と測定されました。" -#: src/commands/vcs.md:141 +#: src/commands/vcs.md:142 #, fuzzy msgid "" "**Co-change graph entropy** ([arXiv 2504.18511](https://arxiv.org/" @@ -8252,7 +9049,7 @@ msgstr "" "は高くなります。変更エントロピーと組み合わせることで、8 つの Apache プロジェ" "クトにおいて v1 シグナルセットに対し 82.5% のケースで AUROC を改善しました。" -#: src/commands/vcs.md:152 +#: src/commands/vcs.md:153 #, fuzzy msgid "" "Both are reported per window. A `0.0` is **computed**, not missing: the file " @@ -8268,7 +9065,7 @@ msgstr "" "共変更グラフからは除外されますが、O(width) の変更エントロピーには引き続き寄与" "します。" -#: src/commands/vcs.md:160 +#: src/commands/vcs.md:161 msgid "" "The default **weighted** formula is a log-scaled weighted sum with " "categorical multiplicative bumps:" @@ -8276,7 +9073,7 @@ msgstr "" "デフォルトの**加重(weighted)** 式は、カテゴリ別の乗法的ボーナスを伴う、対数" "スケールの加重和です。" -#: src/commands/vcs.md:163 +#: src/commands/vcs.md:164 msgid "" "```text\n" "recency_churn = ln(1 + churn_recent)\n" @@ -8334,7 +9131,7 @@ msgstr "" "risk_score = base * (1 + dev_bonus + new_file_bonus)\n" "```" -#: src/commands/vcs.md:188 +#: src/commands/vcs.md:189 msgid "" "The term weights are grounded in the literature: recent churn and commit " "frequency carry the highest weight (Nagappan & Ball relative churn; just-in-" @@ -8357,7 +9154,7 @@ msgstr "" "トロピーおよび共変更エントロピーの項は加算的に入ります(Hassan 2009、arXiv " "2504.18511)。完全な導出は `src/vcs/score.rs` にあります。" -#: src/commands/vcs.md:199 +#: src/commands/vcs.md:200 #, fuzzy msgid "" "The score is **ordinal**: only relative ranks have meaning. A single " @@ -8370,7 +9167,7 @@ msgstr "" "和「または」 `--risk-formula percentile` ブレンドのどちらを変更してもバージョ" "ンが上がります。直近のエントロピー 2 項は両方の式に加わっています。" -#: src/commands/vcs.md:204 +#: src/commands/vcs.md:205 #, fuzzy msgid "" "`--risk-formula percentile` is an alternative: each signal is re-ranked to " @@ -8382,26 +9179,26 @@ msgstr "" "センタイルに再ランク付けし、その平均を取ります — 文献は、プロジェクト横断の頑" "健性のために、固定しきい値よりも相対的なトリガーを推奨しています。" -#: src/commands/vcs.md:211 src/commands/report.md:43 src/commands/check.md:385 +#: src/commands/vcs.md:212 src/commands/report.md:43 src/commands/check.md:385 #: src/commands/web-server.md:60 src/recipes/ci.md:535 msgid "Flag" msgstr "フラグ" -#: src/commands/vcs.md:211 src/commands/report.md:43 +#: src/commands/vcs.md:212 src/commands/report.md:43 #: src/commands/web-server.md:60 src/commands/web-server.md:96 #: src/recipes/ci.md:535 msgid "Default" msgstr "デフォルト" -#: src/commands/vcs.md:213 +#: src/commands/vcs.md:214 msgid "`--long-window `" msgstr "`--long-window `" -#: src/commands/vcs.md:213 +#: src/commands/vcs.md:214 msgid "`12mo`" msgstr "`12mo`" -#: src/commands/vcs.md:213 +#: src/commands/vcs.md:214 msgid "" "Long window (`12mo`, `2y`, `8w`, `365d`, [ISO 8601](https://www.iso.org/" "iso-8601-date-and-time-format.html) `P1Y`)" @@ -8409,106 +9206,106 @@ msgstr "" "長期ウィンドウ(`12mo`、`2y`、`8w`、`365d`、[ISO 8601](https://www.iso.org/" "iso-8601-date-and-time-format.html) の `P1Y`)" -#: src/commands/vcs.md:214 +#: src/commands/vcs.md:215 msgid "`--recent-window `" msgstr "`--recent-window `" -#: src/commands/vcs.md:214 +#: src/commands/vcs.md:215 msgid "`90d`" msgstr "`90d`" -#: src/commands/vcs.md:214 +#: src/commands/vcs.md:215 msgid "Recent window" msgstr "直近ウィンドウ" -#: src/commands/vcs.md:215 +#: src/commands/vcs.md:216 msgid "`--top `" msgstr "`--top `" -#: src/commands/vcs.md:215 +#: src/commands/vcs.md:216 msgid "`50`" msgstr "`50`" -#: src/commands/vcs.md:215 +#: src/commands/vcs.md:216 msgid "Show only the top N (`0` = all)" msgstr "上位 N 件のみ表示(`0` = すべて)" -#: src/commands/vcs.md:216 +#: src/commands/vcs.md:217 msgid "`--file-types `" msgstr "`--file-types `" -#: src/commands/vcs.md:216 src/library/walking-funcspace.md:21 +#: src/commands/vcs.md:217 src/library/walking-funcspace.md:21 msgid "`metrics`" msgstr "`metrics`" -#: src/commands/vcs.md:216 +#: src/commands/vcs.md:217 msgid "Files to rank: `metrics`, `all`, or an extension list (`rs,py`)" msgstr "" "ランク付け対象のファイル: `metrics`、`all`、または拡張子リスト(`rs,py`)" -#: src/commands/vcs.md:217 +#: src/commands/vcs.md:218 msgid "`--ref `" msgstr "`--ref `" -#: src/commands/vcs.md:217 +#: src/commands/vcs.md:218 msgid "`HEAD`" msgstr "`HEAD`" -#: src/commands/vcs.md:217 +#: src/commands/vcs.md:218 msgid "Revision to analyse" msgstr "解析対象のリビジョン" -#: src/commands/vcs.md:218 +#: src/commands/vcs.md:219 msgid "`--full-history`" msgstr "`--full-history`" -#: src/commands/vcs.md:218 src/commands/vcs.md:219 src/commands/vcs.md:220 -#: src/commands/vcs.md:224 src/commands/vcs.md:226 src/commands/vcs.md:227 -#: src/commands/vcs.md:228 src/commands/web-server.md:66 +#: src/commands/vcs.md:219 src/commands/vcs.md:220 src/commands/vcs.md:221 +#: src/commands/vcs.md:225 src/commands/vcs.md:227 src/commands/vcs.md:228 +#: src/commands/vcs.md:229 src/commands/web-server.md:66 msgid "off" msgstr "オフ" -#: src/commands/vcs.md:218 +#: src/commands/vcs.md:219 msgid "Walk the full DAG (default: first-parent only)" msgstr "DAG 全体を走査(デフォルト: first-parent のみ)" -#: src/commands/vcs.md:219 +#: src/commands/vcs.md:220 msgid "`--include-merges`" msgstr "`--include-merges`" -#: src/commands/vcs.md:219 +#: src/commands/vcs.md:220 msgid "Include merge commits" msgstr "マージコミットを含める" -#: src/commands/vcs.md:220 +#: src/commands/vcs.md:221 msgid "`--no-follow-renames`" msgstr "`--no-follow-renames`" -#: src/commands/vcs.md:220 +#: src/commands/vcs.md:221 msgid "Stop following renames (default: follow)" msgstr "リネームの追跡を止める(デフォルト: 追跡する)" -#: src/commands/vcs.md:221 +#: src/commands/vcs.md:222 msgid "`--no-exclude-bots` / `--bot-pattern `" msgstr "`--no-exclude-bots` / `--bot-pattern `" -#: src/commands/vcs.md:221 +#: src/commands/vcs.md:222 msgid "exclude" msgstr "除外" -#: src/commands/vcs.md:221 +#: src/commands/vcs.md:222 msgid "Bot-author filtering" msgstr "ボット作者のフィルタリング" -#: src/commands/vcs.md:222 +#: src/commands/vcs.md:223 msgid "`--as-of `" msgstr "`--as-of `" -#: src/commands/vcs.md:222 +#: src/commands/vcs.md:223 msgid "wall clock" msgstr "現在時刻" -#: src/commands/vcs.md:222 +#: src/commands/vcs.md:223 #, fuzzy msgid "" "Reference \"now\" ([RFC 3339](https://www.rfc-editor.org/rfc/rfc3339) / " @@ -8517,38 +9314,38 @@ msgstr "" "再現可能なスナップショットのための基準「now」(RFC 3339 / `@unix` / git 日付" "形式)" -#: src/commands/vcs.md:223 +#: src/commands/vcs.md:224 msgid "`--risk-formula {weighted\\|percentile}`" msgstr "`--risk-formula {weighted\\|percentile}`" -#: src/commands/vcs.md:223 +#: src/commands/vcs.md:224 msgid "`weighted`" msgstr "`weighted`" -#: src/commands/vcs.md:223 +#: src/commands/vcs.md:224 msgid "Composite formula" msgstr "複合スコアの式" -#: src/commands/vcs.md:224 +#: src/commands/vcs.md:225 msgid "`--emit-author-details`" msgstr "`--emit-author-details`" -#: src/commands/vcs.md:224 +#: src/commands/vcs.md:225 #, fuzzy msgid "" "Emit [SHA-256](https://doi.org/10.6028/NIST.FIPS.180-4)\\-hashed canonical " "author IDs" msgstr "SHA-256 でハッシュ化した正規作者 ID を出力" -#: src/commands/vcs.md:225 +#: src/commands/vcs.md:226 msgid "`--author-hash-key `" msgstr "`--author-hash-key `" -#: src/commands/vcs.md:225 +#: src/commands/vcs.md:226 msgid "unset" msgstr "未設定" -#: src/commands/vcs.md:225 +#: src/commands/vcs.md:226 #, fuzzy msgid "" "Harden the emitted author digests into a keyed [HMAC](https://www.rfc-editor." @@ -8558,47 +9355,47 @@ msgstr "" "出力される作者ダイジェストを鍵付き HMAC に強化する([作者詳細のプライバシー]" "(#author-detail-privacy)を参照)。`--emit-author-details` が必要" -#: src/commands/vcs.md:226 +#: src/commands/vcs.md:227 msgid "`--include-deleted`" msgstr "`--include-deleted`" -#: src/commands/vcs.md:226 +#: src/commands/vcs.md:227 msgid "Also rank files deleted at the target ref" msgstr "対象 ref で削除済みのファイルもランク付けする" -#: src/commands/vcs.md:227 +#: src/commands/vcs.md:228 msgid "`--no-cache`" msgstr "`--no-cache`" -#: src/commands/vcs.md:227 +#: src/commands/vcs.md:228 msgid "Skip the persistent history cache (always walk fresh)" msgstr "永続履歴キャッシュをスキップする(常に新規に走査)" -#: src/commands/vcs.md:228 +#: src/commands/vcs.md:229 msgid "`--clear-cache`" msgstr "`--clear-cache`" -#: src/commands/vcs.md:228 +#: src/commands/vcs.md:229 msgid "Wipe this repo's cached history before running" msgstr "実行前にこのリポジトリのキャッシュ済み履歴を消去する" -#: src/commands/vcs.md:229 +#: src/commands/vcs.md:230 msgid "`--cache-dir `" msgstr "`--cache-dir `" -#: src/commands/vcs.md:229 +#: src/commands/vcs.md:230 msgid "platform cache" msgstr "プラットフォーム標準のキャッシュ" -#: src/commands/vcs.md:229 +#: src/commands/vcs.md:230 msgid "Override the cache directory" msgstr "キャッシュディレクトリを上書きする" -#: src/commands/vcs.md:231 src/python/vcs.md:205 +#: src/commands/vcs.md:232 src/python/vcs.md:205 msgid "Caching" msgstr "キャッシュ" -#: src/commands/vcs.md:233 +#: src/commands/vcs.md:234 #, fuzzy msgid "" "On large, active repositories, walking the long-window history dominates " @@ -8612,11 +9409,11 @@ msgstr "" "済みの `HEAD` SHA とリポジトリの同一性をキーとして、各走査の**永続キャッシュ" "**を保持します。" -#: src/commands/vcs.md:238 +#: src/commands/vcs.md:239 msgid "On an **unchanged tree** the prior result is replayed, no history walk." msgstr "**変更のないツリー**では前回の結果が再生され、履歴走査は行われません。" -#: src/commands/vcs.md:239 +#: src/commands/vcs.md:240 msgid "" "When **`HEAD` has advanced** the walk visits only the new commits and " "splices them onto the cached history." @@ -8624,7 +9421,7 @@ msgstr "" "**`HEAD` が前進した**場合、走査は新しいコミットのみを訪れ、それをキャッシュ済" "み履歴に継ぎ足します。" -#: src/commands/vcs.md:241 +#: src/commands/vcs.md:242 msgid "" "A **force-push** (the cached head is no longer an ancestor of the new one) " "falls back to a full walk." @@ -8632,33 +9429,41 @@ msgstr "" "**フォースプッシュ**(キャッシュされた head が新しい head の祖先でなくなった" "状態)では、完全走査にフォールバックします。" -#: src/commands/vcs.md:244 -#, fuzzy +#: src/commands/vcs.md:245 msgid "" "The cache is a pure optimization: a hit is **bit-identical** to a fresh " "walk, and the time windows are recomputed against the _current_ moment on " "every run rather than frozen when the entry was written. An entry is " "ignored, and the history recomputed, whenever the schema, the score-formula " -"version, the _walk-affecting_ options, or the repository's effective `." -"mailmap` differ; in particular **changing a window forces a fresh walk**. " -"One walk input is not covered: the git diff configuration (`diff.algorithm`, " -"diff drivers) decides the recorded churn, so after changing it run once with " -"`--clear-cache`. Finalization-only knobs such as `--risk-formula`, `--emit-" -"author-details`, `--author-hash-key`, and `--include-deleted` are applied on " -"replay, so they reuse the same cached walk; a cached walk even re-finalizes " -"under a _different_ author-hash key without re-walking." -msgstr "" -"このキャッシュは純粋な最適化です。キャッシュヒットは新規の走査と**ビット単位" -"で同一**であり、時間ウィンドウは実行のたびに「現在」時刻に対して再計算される" -"ため、キャッシュされた結果が古くなることはありません。スキーマ、スコア式の" -"バージョン、または「走査に影響する」オプションが異なる場合、エントリは無視さ" -"れ履歴が再計算されます。特に、**ウィンドウを変更すると新規の走査が強制されま" -"す**。(`--risk-formula`、`--emit-author-details`、`--author-hash-key`、`--" -"include-deleted` のような最終化のみのノブは再生時に適用されるため、同じキャッ" -"シュ済み走査を再利用します — キャッシュ済み走査は、「異なる」作者ハッシュ鍵の" -"下でも再走査なしで再最終化されます。)" - -#: src/commands/vcs.md:258 +"version, the _walk-affecting_ options, the repository's effective `." +"mailmap`, or the git diff configuration that decides how gix diffs (`diff." +"algorithm`, `core.bigFileThreshold`, and a `diff.` section's " +"`algorithm`, `binary`, and whether it sets a `textconv`; a driver's " +"`command` never runs here and does not count), the `diff` attribute bindings " +"that route a path to a diff driver or mark it `-diff` (the `.gitattributes` " +"files in the index — committed or staged, never an unstaged edit, which the " +"walk does not read either — and the full content of `.git/info/attributes`, " +"`core.attributesFile` or its XDG default, and the system attributes file, so " +"a reorder of two overlapping rules counts as much as an edit, as does a " +"`core.ignoreCase` flip; each file is read once per run and both the walk and " +"the entry's stamp come from that one read), or the shallow boundary of a " +"shallow clone (a `git fetch --deepen` or `--unshallow` leaves `HEAD` where " +"it was but reaches commits the entry never saw), or the effective `diff." +"renameLimit` the rename pass ran under (read through the same trusted-" +"section filter gix applies to a repository owned by someone else; with `--no-" +"follow-renames` it is not read at all) differ; in particular **changing a " +"window forces a fresh walk**. A bca release that adds a term retires every " +"existing entry, so the first `bca vcs` after such an upgrade re-walks the " +"whole long window once. Nothing deletes an entry that no longer matches, " +"since a run with other options may still use it; `--clear-cache` removes the " +"repository's entries, retired ones included. Finalization-only knobs such as " +"`--risk-formula`, `--emit-author-details`, `--author-hash-key`, and `--" +"include-deleted` are applied on replay, so they reuse the same cached walk; " +"a cached walk even re-finalizes under a _different_ author-hash key without " +"re-walking." +msgstr "" + +#: src/commands/vcs.md:279 #, fuzzy msgid "" "By default the cache lives under [`$XDG_CACHE_HOME`](https://specifications." @@ -8679,23 +9484,23 @@ msgstr "" "同じキャッシュは `bca metrics --vcs` と `bca report --vcs` も透過的に高速化し" "ます。" -#: src/commands/vcs.md:268 +#: src/commands/vcs.md:289 msgid "# First run primes the cache; the second replays it.\n" msgstr "# 最初の実行がキャッシュを準備し、2 回目はそれを再生します。\n" -#: src/commands/vcs.md:270 +#: src/commands/vcs.md:291 msgid "# reuses prior work\n" msgstr "# 前回の作業を再利用\n" -#: src/commands/vcs.md:272 +#: src/commands/vcs.md:293 msgid "# ignore the cache for this run\n" msgstr "# この実行ではキャッシュを無視\n" -#: src/commands/vcs.md:273 +#: src/commands/vcs.md:294 msgid "# rebuild from scratch\n" msgstr "# ゼロから再構築\n" -#: src/commands/vcs.md:277 +#: src/commands/vcs.md:298 msgid "" "The REST (`POST /v1/vcs`) and Python ([`vcs.rank`](../python/vcs.md)) " "surfaces expose the same behaviour through optional `no_cache` / `cache_dir` " @@ -8705,7 +9510,7 @@ msgstr "" "フェースは、省略可能な `no_cache` / `cache_dir` パラメータを通じて同じ挙動を" "提供します。" -#: src/commands/vcs.md:281 +#: src/commands/vcs.md:302 #, fuzzy msgid "" "The cache is specific to the file ranking. The `trend` and `commit` " @@ -8722,11 +9527,11 @@ msgstr "" "エンドポイントは `no_cache` / `cache_dir` フィールドを黙って無視するのではな" "く拒否します(issue #961)。" -#: src/commands/vcs.md:288 +#: src/commands/vcs.md:309 msgid "In `bca metrics`" msgstr "`bca metrics` での利用" -#: src/commands/vcs.md:290 +#: src/commands/vcs.md:311 msgid "" "Pass `bca metrics --vcs` to attach a `vcs` block (plus a `hotspot_score` " "computed from the file's cyclomatic sum) to each file's `metrics`:" @@ -8734,7 +9539,7 @@ msgstr "" "`bca metrics --vcs` を渡すと、各ファイルの `metrics` に `vcs` ブロック(およ" "びファイルの cyclomatic 合計から計算される `hotspot_score`)が付加されます:" -#: src/commands/vcs.md:293 +#: src/commands/vcs.md:314 msgid "" "```console\n" "$ bca metrics --vcs --paths src/parser.rs --format json\n" @@ -8752,7 +9557,7 @@ msgstr "" " \"risk_score\": 3.7, \"hotspot_score\": 7596.0, ... } } }\n" "```" -#: src/commands/vcs.md:301 +#: src/commands/vcs.md:322 msgid "" "`bca metrics --vcs` uses the default windows and weighted formula; for " "window / formula tuning use `bca vcs`." @@ -8760,11 +9565,11 @@ msgstr "" "`bca metrics --vcs` はデフォルトのウィンドウと重み付き計算式を使用します。" "ウィンドウや計算式を調整したい場合は `bca vcs` を使用してください。" -#: src/commands/vcs.md:304 +#: src/commands/vcs.md:325 msgid "Per-function attribution" msgstr "関数単位の帰属" -#: src/commands/vcs.md:306 +#: src/commands/vcs.md:327 #, fuzzy msgid "" "`bca metrics --vcs-per-function` (which implies `--vcs`) additionally " @@ -8779,7 +9584,7 @@ msgstr "" "ンに振り分けるため、リスクの高いファイルの中のリスクの高い「関数」をランク付" "けできます:" -#: src/commands/vcs.md:313 +#: src/commands/vcs.md:334 msgid "" "```console\n" "$ bca metrics --vcs-per-function --paths src/parser.rs --format json\n" @@ -8805,7 +9610,7 @@ msgstr "" "144.0 } } } ] }\n" "```" -#: src/commands/vcs.md:323 +#: src/commands/vcs.md:344 msgid "" "The per-function block is a **current-blame snapshot** and is _not_ directly " "comparable to the file-level block: its `churn` counts surviving lines whose " @@ -8822,7 +9627,16 @@ msgstr "" "関数のカウントはゼロと報告されます。最終変更が長期ウィンドウより前の行は、関" "数のサイズには寄与しますが、ウィンドウ付きのどのカウントにも寄与しません。" -#: src/commands/vcs.md:331 +#: src/commands/vcs.md:352 +msgid "" +"Each nested space's `hotspot_score` multiplies its _own_ cyclomatic " +"(`cyclomatic.value`) by its `churn_recent`, not its subtree `cyclomatic." +"sum`, so a nested function's complexity is not counted again at every " +"enclosing level; the file-level block keeps the subtree sum. The Python " +"bindings' `vcs_per_function=True` reports the same scores." +msgstr "" + +#: src/commands/vcs.md:358 #, fuzzy msgid "" "**Limitations.** Blame follows file renames (so edits under a former path " @@ -8842,11 +9656,11 @@ msgstr "" "数単位のブロックは単に省略され、ファイルレベルのブロック(と AST メトリクス)" "は引き続き出力されます。" -#: src/commands/vcs.md:340 +#: src/commands/vcs.md:367 msgid "Just-in-time (commit-level) scoring" msgstr "ジャストインタイム(コミットレベル)スコアリング" -#: src/commands/vcs.md:342 +#: src/commands/vcs.md:369 #, fuzzy msgid "" "Where everything above ranks _files_ at a ref, `bca vcs commit ` " @@ -8878,7 +9692,7 @@ msgstr "" "Inducing Changes a Moving Target?_](https://doi.org/10.1109/TSE.2017.2693980)" "(IEEE TSE 2018)です。" -#: src/commands/vcs.md:357 +#: src/commands/vcs.md:384 msgid "" "```console\n" "$ bca vcs commit HEAD --pretty\n" @@ -8942,15 +9756,15 @@ msgstr "" "}\n" "```" -#: src/commands/vcs.md:384 +#: src/commands/vcs.md:411 msgid "The five feature groups, and how each moves the score:" msgstr "5 つの特徴量グループと、それぞれがスコアをどう動かすか:" -#: src/commands/vcs.md:389 +#: src/commands/vcs.md:416 msgid "distinct subsystems & directories, within-commit change entropy" msgstr "個別のサブシステム数とディレクトリ数、コミット内の変更エントロピー" -#: src/commands/vcs.md:390 +#: src/commands/vcs.md:417 #, fuzzy msgid "" "the touched files' priors (prior changes, distinct authors, bug- and " @@ -8961,15 +9775,15 @@ msgstr "" "ティ修正の回数、および複合 [`risk_score`](#composite-risk-score) — をコミット" "「以前」の履歴から測定" -#: src/commands/vcs.md:390 +#: src/commands/vcs.md:417 msgid "turbulent file history ⇒ riskier" msgstr "荒れたファイル履歴 ⇒ よりリスキー" -#: src/commands/vcs.md:391 +#: src/commands/vcs.md:418 msgid "the author's prior commit count (long & recent)" msgstr "作者の過去のコミット数(長期・直近)" -#: src/commands/vcs.md:394 +#: src/commands/vcs.md:421 msgid "" "The `contributions` block reports each group's signed contribution to the " "ordinal `risk_score`, so a consumer can see _why_ a commit ranked where it " @@ -8987,7 +9801,7 @@ msgstr "" "されると `jit_score_version` が上がります(ファイルレベルの " "`risk_score_version` とは別です)。" -#: src/commands/vcs.md:401 +#: src/commands/vcs.md:428 #, fuzzy msgid "" "The commit is scored against its **first parent**. A **merge** commit is " @@ -9002,7 +9816,7 @@ msgstr "" "なります — その場合スコアはサイズと作者の経験に依存します。これはファイル履歴" "のない変更に対して文献が定めるとおりの挙動です。" -#: src/commands/vcs.md:407 +#: src/commands/vcs.md:434 msgid "" "The window / `--ref` / bot / merge / rename flags are shared with the parent " "`bca vcs` command; the commit-only flags are the positional `` " @@ -9014,12 +9828,12 @@ msgstr "" "フォルト `HEAD`)、`--format json|yaml|toml|cbor`(デフォルト `json`)、`--" "output`、`--pretty`、および次のとおりです:" -#: src/commands/vcs.md:413 +#: src/commands/vcs.md:440 msgid "# CI gate: exit 2 when the commit scores at or above the threshold.\n" msgstr "" "# CI ゲート:コミットのスコアがしきい値以上のとき exit 2 で終了する。\n" -#: src/commands/vcs.md:417 +#: src/commands/vcs.md:444 msgid "" "`--fail-above` uses exit code `2` (the same \"metric gate\" convention as " "`bca check`; exit `1` stays reserved for tool errors). Because the score is " @@ -9031,11 +9845,11 @@ msgstr "" "コアは順序尺度なので、しきい値は絶対値として扱うのではなく、リポジトリ自身の" "コミットスコア分布に対して調整してください。" -#: src/commands/vcs.md:422 +#: src/commands/vcs.md:449 msgid "Scoring an arbitrary diff (`--diff`)" msgstr "任意の diff のスコアリング(`--diff`)" -#: src/commands/vcs.md:424 +#: src/commands/vcs.md:451 #, fuzzy msgid "" "`bca vcs commit --diff ` scores a `git diff` instead of a commit (use " @@ -9048,7 +9862,7 @@ msgstr "" "ミットされておらず diff としてのみ存在する pre-commit フックやコードレビュー" "ボットで便利です。" -#: src/commands/vcs.md:433 +#: src/commands/vcs.md:460 #, fuzzy msgid "" "The input must be a **git-style** unified diff carrying `diff --git` file " @@ -9065,7 +9879,7 @@ msgstr "" "クヘッダーを持つ `git diff --cc`)は不正な diff として拒否されます — 代わりに" "通常の 2-way `git diff` をパイプしてください。" -#: src/commands/vcs.md:440 +#: src/commands/vcs.md:467 #, fuzzy msgid "" "A bare diff carries **no author, parent, or file history**, so only the " @@ -9076,7 +9890,7 @@ msgstr "" "**size**と**diffusion** のグループだけです。したがって出力は意図的に「部分的" "な」レポートであり、コミットレポートとは異なる形をしています:" -#: src/commands/vcs.md:445 +#: src/commands/vcs.md:472 msgid "" "```console\n" "$ git diff | bca vcs commit --diff - --pretty\n" @@ -9108,7 +9922,7 @@ msgstr "" "}\n" "```" -#: src/commands/vcs.md:459 +#: src/commands/vcs.md:486 #, fuzzy msgid "" "The `source` field is a permanent `\"diff\"` marker, and the history / " @@ -9126,7 +9940,7 @@ msgstr "" "リスク」と取り違えることはありません。同じ理由で、スコアのフィールド名は " "`risk_score` ではなく `partial_risk_score` です。" -#: src/commands/vcs.md:467 +#: src/commands/vcs.md:494 #, fuzzy msgid "" "**A diff-only score is not comparable to a commit score.** The partial score " @@ -9146,7 +9960,7 @@ msgstr "" "モードで機能します(diff モードのしきい値は自身の diff スコア分布に対して調整" "してください)。" -#: src/commands/vcs.md:477 +#: src/commands/vcs.md:504 msgid "" "The parser understands git's default C-style path quoting (`core." "quotePath=true`), so a diff touching a file with a non-ASCII or spaced name " @@ -9159,15 +9973,15 @@ msgstr "" "量では引用付きの生文字列ではなく、デコードされたパスの下にグループ化されま" "す。" -#: src/commands/vcs.md:482 +#: src/commands/vcs.md:509 msgid "REST and Python parity" msgstr "REST と Python のパリティ" -#: src/commands/vcs.md:484 +#: src/commands/vcs.md:511 msgid "The JIT score is also available off the CLI:" msgstr "JIT スコアは CLI 以外からも利用できます:" -#: src/commands/vcs.md:486 +#: src/commands/vcs.md:513 msgid "" "**REST:** `POST /v1/vcs/jit` with `{ \"id\", \"repo_path\", \"commit\" }` " "returns the commit `JitReport` JSON, or `{ \"id\", \"diff\" }` returns the " @@ -9178,7 +9992,7 @@ msgstr "" "な diff レポートが返ります。[REST API の利用](../recipes/rest-api.md)を参照し" "てください。" -#: src/commands/vcs.md:489 +#: src/commands/vcs.md:516 msgid "" "**Python:** `vcs.commit(repo_path, commit=...)` returns the commit report as " "a `dict`, and `vcs.score_diff(diff)` the partial diff report. See [Change-" @@ -9188,17 +10002,17 @@ msgstr "" "として返し、`vcs.score_diff(diff)` は部分的な diff レポートを返します。[変更" "履歴(VCS)メトリクス](../python/vcs.md)を参照してください。" -#: src/commands/vcs.md:493 +#: src/commands/vcs.md:520 msgid "" "ML-based JIT models and server-side hook integration remain out of scope." msgstr "" "ML ベースの JIT モデルとサーバーサイドフック統合は、引き続きスコープ外です。" -#: src/commands/vcs.md:495 +#: src/commands/vcs.md:522 msgid "Historical trend (over time)" msgstr "履歴トレンド(時系列)" -#: src/commands/vcs.md:497 +#: src/commands/vcs.md:524 #, fuzzy msgid "" "A single `bca vcs` run answers \"what is risky now\". `bca vcs trend` " @@ -9211,7 +10025,7 @@ msgstr "" "とで、_「良くなっているのか悪くなっているのか」_ — 技術的負債プログラムにとっ" "て行動につながる問い — に答えます。" -#: src/commands/vcs.md:502 +#: src/commands/vcs.md:529 msgid "" "```console\n" "$ bca vcs --top 20 trend --points 12 --span 24mo --pretty\n" @@ -9265,7 +10079,7 @@ msgstr "" "}\n" "```" -#: src/commands/vcs.md:526 +#: src/commands/vcs.md:553 msgid "" "`--points N` evenly-spaced samples (inclusive of both endpoints) cover `--" "span DURATION`, ending at `--as-of` (or wall-clock now). `as_of_points` " @@ -9283,7 +10097,7 @@ msgstr "" "がったファイル(`improved`)と最も上がったファイル(`regressed`)をランク付け" "します。`--top-deltas` で各リストを切り詰められます。" -#: src/commands/vcs.md:534 +#: src/commands/vcs.md:561 #, fuzzy msgid "" "Each point **re-anchors at the mainline tip that existed at or before that " @@ -9298,7 +10112,7 @@ msgstr "" "す(現在のメトリクスが過去に漏れ出すことはありません)。系列に残されるファイ" "ルは、最新サンプルの時点でリスクが最も高い `--top` 件です。" -#: src/commands/vcs.md:540 +#: src/commands/vcs.md:567 msgid "" "Flags reused from the parent `bca vcs` command: the window (`--long-" "window` / `--recent-window`), `--ref`, `--file-types`, bot / merge / rename " @@ -9316,7 +10130,7 @@ msgstr "" "い履歴でも時点ごとの履歴走査が扱いきれる範囲に収まるよう、2–120 に制限されて" "います。" -#: src/commands/vcs.md:548 +#: src/commands/vcs.md:575 msgid "" "**Rename caveat.** Renames are followed _within_ each sample's walk, but a " "file renamed _between_ two samples appears as two separate path series (its " @@ -9328,11 +10142,11 @@ msgstr "" "く、2 つの別々のパス系列(旧名、次に新名)として現れます。サンプル間のリネー" "ムの縫合は後回しのフォローアップです。" -#: src/commands/vcs.md:553 +#: src/commands/vcs.md:580 msgid "Bus factor (directory & repo level)" msgstr "バスファクター(ディレクトリ・リポジトリレベル)" -#: src/commands/vcs.md:555 +#: src/commands/vcs.md:582 #, fuzzy msgid "" "Where the per-file `ownership_top_share` measures concentration _within_ a " @@ -9349,7 +10163,7 @@ msgstr "" "付けされた `files` と並ぶトップレベルの `vcs_aggregate` オブジェクトとして出" "力します:" -#: src/commands/vcs.md:563 +#: src/commands/vcs.md:590 msgid "" "```jsonc\n" "{\n" @@ -9389,7 +10203,7 @@ msgstr "" "}\n" "```" -#: src/commands/vcs.md:580 +#: src/commands/vcs.md:607 #, fuzzy msgid "" "Each developer's authorship of each file is scored with the Avelino _Degree-" @@ -9401,7 +10215,7 @@ msgstr "" "ヒューリスティック(Avelino, Passos, Hora & Valente, _A Novel Approach for " "Estimating Truck Factors_, ICPC 2016)でスコアリングされます:" -#: src/commands/vcs.md:589 +#: src/commands/vcs.md:616 msgid "" "where `FA` is first authorship (`1` if `d` created `f`), `DL` is `d`'s " "deliveries (changes) to `f`, and `AC` is the changes made by _other_ " @@ -9423,11 +10237,11 @@ msgstr "" "ルディレクトリとその直下のサブディレクトリをカバーし、それぞれ再帰的に配下の" "すべてのファイルに対して計算されます。" -#: src/commands/vcs.md:600 +#: src/commands/vcs.md:627 msgid "Caveats, by construction:" msgstr "構造上の注意点:" -#: src/commands/vcs.md:602 +#: src/commands/vcs.md:629 #, fuzzy msgid "" "With the default threshold, a repository whose files all share one sole " @@ -9440,7 +10254,7 @@ msgstr "" "らです。これはヒューリスティックが意図どおりに働いているのであってバグではあ" "りません。この数値は保証ではなく計画のためのシグナルとして扱ってください。" -#: src/commands/vcs.md:607 +#: src/commands/vcs.md:634 msgid "" "Bot identities are filtered (like the per-file signals), and files with no " "in-window activity carry no authorship and are excluded from the denominator." @@ -9448,7 +10262,7 @@ msgstr "" "ボットのアイデンティティは(ファイルごとのシグナルと同様に)フィルタリングさ" "れ、ウィンドウ内に活動のないファイルは作者性を持たず、分母から除外されます。" -#: src/commands/vcs.md:610 +#: src/commands/vcs.md:637 msgid "" "\"First authorship\" means the earliest commit _observed within the long " "window_, not necessarily a file's true creation." @@ -9456,7 +10270,7 @@ msgstr "" "「最初の作者性」は「長期ウィンドウ内で観測された」最古のコミットを意味し、必" "ずしもファイルの真の作成を意味しません。" -#: src/commands/vcs.md:613 +#: src/commands/vcs.md:640 #, fuzzy msgid "" "The aggregate reflects the **whole repository within the file-type scope**: " @@ -9476,7 +10290,7 @@ msgstr "" "注目したい場合は、走査をフィルタリングするのではなく `by_directory` の該当エ" "ントリを読んでください。" -#: src/commands/vcs.md:621 +#: src/commands/vcs.md:648 #, fuzzy msgid "" "`--emit-author-details` adds a `key_author_ids` list to each group: the " @@ -9493,11 +10307,11 @@ msgstr "" "ドポイントに対してのみ計算されます。ファイルごとの `bca metrics --vcs` 注入パ" "スはこのコストを払いません。" -#: src/commands/vcs.md:628 +#: src/commands/vcs.md:655 msgid "Author-detail privacy" msgstr "作者詳細のプライバシー" -#: src/commands/vcs.md:630 +#: src/commands/vcs.md:657 #, fuzzy msgid "" "The `key_author_ids` digests are a **stable pseudonym, not anonymization**. " @@ -9518,7 +10332,7 @@ msgstr "" "ジェストが誰のものかを割り出せます。これは Gravatar のメールハッシュ化を破っ" "たのと同じ弱点です。" -#: src/commands/vcs.md:640 +#: src/commands/vcs.md:667 msgid "" "Treat published `key_author_ids` (and the per-file `author_ids`) as " "pseudonymization that avoids emitting plaintext emails, **not** as a " @@ -9530,11 +10344,11 @@ msgstr "" "識別されないことの保証としては**扱わないで**ください。その保証が必要なら、ダ" "イジェストを公開しないでください。" -#: src/commands/vcs.md:645 +#: src/commands/vcs.md:672 msgid "Hardened mode: `--author-hash-key`" msgstr "強化モード:`--author-hash-key`" -#: src/commands/vcs.md:647 +#: src/commands/vcs.md:674 #, fuzzy msgid "" "For stronger resistance, pass a secret key with `--author-hash-key ` " @@ -9554,7 +10368,7 @@ msgstr "" "鍵が必要です。高エントロピーの鍵を選び、秘密に保ってください。鍵を知った者は" "誰でも列挙をやり直せます。" -#: src/commands/vcs.md:657 +#: src/commands/vcs.md:684 msgid "" "The key is **stable**: the same key yields the same digests across every " "report and across a persistent-cache replay, so cross-report correlation and " @@ -9567,7 +10381,7 @@ msgstr "" "成するため、履歴を共有する 2 つのチームは、鍵を共有しない限り作者を相互にひも" "付けることはできません。" -#: src/commands/vcs.md:663 +#: src/commands/vcs.md:690 #, fuzzy msgid "" "Prefer the `BCA_AUTHOR_HASH_KEY` environment variable over the flag: a key " @@ -9579,11 +10393,11 @@ msgstr "" "ンに置かれた鍵はプロセスリスト(`ps`)経由で他のローカルユーザーから見え、" "シェル履歴にも保存されます。両方が設定されている場合はフラグが優先されます:" -#: src/commands/vcs.md:669 +#: src/commands/vcs.md:696 msgid "\"$(cat ~/.config/bca/author-key)\"" msgstr "\"$(cat ~/.config/bca/author-key)\"" -#: src/commands/vcs.md:673 +#: src/commands/vcs.md:700 msgid "" "What the key does **not** cover: the on-disk history cache (issue #334) " "deliberately stores the _unkeyed_ inner SHA-256 digest, because the key is " @@ -9603,11 +10417,11 @@ msgstr "" "は REST エンドポイント(`author_hash_key`)と Python(`vcs." "Options(author_hash_key=…)`)でも利用できます。" -#: src/commands/vcs.md:682 +#: src/commands/vcs.md:709 msgid "Dogfooding in this repo" msgstr "このリポジトリでのドッグフーディング" -#: src/commands/vcs.md:684 +#: src/commands/vcs.md:711 #, fuzzy msgid "" "This project runs `bca vcs` on its own source. `make vcs` prints the ranked " @@ -9637,11 +10451,11 @@ msgstr "" "ランキングが [`reports/vcs-report.json`](https://dekobon.github.io/big-code-" "analysis/reports/vcs-report.json) として公開されます。" -#: src/commands/vcs.md:698 +#: src/commands/vcs.md:725 msgid "REST and Python" msgstr "REST と Python" -#: src/commands/vcs.md:700 +#: src/commands/vcs.md:727 msgid "" "**REST:** `POST /v1/vcs` with a JSON body `{ \"id\": \"...\", \"repo_path\": " "\"/path/to/repo\", ... }` returns the ranked report, and `POST /v1/vcs/" @@ -9654,7 +10468,7 @@ msgstr "" "`top_deltas`)は履歴の時系列を返します。[REST API の利用](../recipes/rest-" "api.md)を参照してください。" -#: src/commands/vcs.md:704 +#: src/commands/vcs.md:731 msgid "" "**Python:** [`big_code_analysis.vcs.rank(repo_path, …)`](../python/vcs.md) " "returns the ranked report as a dict, `vcs.trend(repo_path, points=…, span=…, " @@ -9666,7 +10480,7 @@ msgstr "" "span=…, …)` は時系列を返します。また `analyze(path, vcs=True)` は単一ファイル" "のメトリクスに `vcs` ブロックを付加します。" -#: src/commands/vcs.md:709 +#: src/commands/vcs.md:736 msgid "" "Both `POST /v1/vcs` and `vcs.rank()` (through `vcs.Options`) accept an " "optional `file_types` (`\"metrics\"` / `\"all\"` / `\"rs,py\"`) to scope " @@ -9677,7 +10491,7 @@ msgstr "" "`\"all\"` / `\"rs,py\"`)を受け付けます。これは CLI の `--file-types` に対応" "します。" -#: src/commands/vcs.md:713 +#: src/commands/vcs.md:740 msgid "" "Both include the `vcs_aggregate` bus factor in the result and accept a " "`bus_factor_threshold` (in `(0, 1)`) to tune the coverage fraction." @@ -10091,15 +10905,18 @@ msgstr "" #, fuzzy msgid "" "Both formats carry a **Legend** that defines every metric column " -"abbreviation (`CC`, `MI`, `ABC`, `WMC`, and so on) plus the global-header " -"stats (`PLOC`, `Comments`, `Comment ratio`). It is a `## Legend` section in " -"Markdown (its own outline entry, not nested under the last language) and an " -"expanded (`
`) block in HTML, so it survives print, mobile, and " -"screen readers as well as a hover tooltip. Each entry links to its chapter " -"in the [Supported Metrics](../metrics.md) reference, so a one-line " -"definition can hand the reader the full explanation. The definitions come " -"from the same shared column specs the tooltips use, so the two formats " -"cannot drift." +"abbreviation (`CC`, `MI`, `ABC`, `WMC`, and so on), the global-header stats " +"(`PLOC`, `Comments`, `Comment ratio`), and the Per-language overview's " +"columns (`Files`, `Functions`, `Avg MI`, `Avg CC`, `Avg Cognitive`) — `Avg " +"MI` in particular, since it is the unclamped, SLOC-weighted average and can " +"read negative where the per-file `MI` column saturates at 0. It is a `## " +"Legend` section in Markdown (its own outline entry, not nested under the " +"last language) and an expanded (`
`) block in HTML, so it " +"survives print, mobile, and screen readers as well as a hover tooltip. Each " +"entry links to its chapter in the [Supported Metrics](../metrics.md) " +"reference, so a one-line definition can hand the reader the full " +"explanation. The definitions come from the same shared column specs the " +"tooltips use, so the two formats cannot drift." msgstr "" "どちらのフォーマットにも、すべてのメトリクス列の略語(`CC`、`MI`、`ABC`、" "`WMC`、…)とグローバルヘッダーの統計(`PLOC`、`Comments`、`Comment ratio`)を" @@ -10111,19 +10928,21 @@ msgstr "" "定義から完全な説明へ読者を案内できます。定義はツールチップが使うのと同じ共有" "列仕様に由来するため、2 つのフォーマットが乖離することはありません。" -#: src/commands/report.md:197 +#: src/commands/report.md:201 #, fuzzy msgid "" -"Both formats close with a **provenance footer** stating the `bca` version, " -"generation date, the seed paths scanned, the per-table `--top` value, and " -"whether suppression markers were honored, so a detached artifact (a PR " -"comment, a Pages deployment, a file on a ticket) records what it was " -"generated from. The date honors [`SOURCE_DATE_EPOCH`](https://reproducible-" -"builds.org/docs/source-date-epoch/) for reproducible builds. The HTML report " -"additionally carries a `` tag and wraps every table " -"in a horizontal-scroll container so wide tables stay reachable on mobile and " -"narrow windows, and its table of contents nests each language's hotspot " -"subsections under a collapsible entry." +"Both formats close with a **provenance footer** stating the `bca` version — " +"followed, for a `bca` built from a source checkout, by the first twelve " +"digits of its build-inputs digest in parentheses, the same digest `bca --" +"version` prints in full — the generation date, the seed paths scanned, the " +"per-table `--top` value, and whether suppression markers were honored, so a " +"detached artifact (a PR comment, a Pages deployment, a file on a ticket) " +"records what it was generated from. The date honors [`SOURCE_DATE_EPOCH`]" +"(https://reproducible-builds.org/docs/source-date-epoch/) for reproducible " +"builds. The HTML report additionally carries a `` " +"tag and wraps every table in a horizontal-scroll container so wide tables " +"stay reachable on mobile and narrow windows, and its table of contents nests " +"each language's hotspot subsections under a collapsible entry." msgstr "" "どちらのフォーマットも、`bca` のバージョン、生成日、走査したシードパス、テー" "ブルごとの `--top` 値、抑制マーカーを尊重したかどうかを記した**来歴フッター**" @@ -10135,7 +10954,7 @@ msgstr "" "閲覧可能なままです。また目次では、各言語のホットスポットのサブセクションが折" "りたたみ可能なエントリの下に入れ子になります。" -#: src/commands/report.md:209 +#: src/commands/report.md:216 #, fuzzy msgid "" "Source suppression markers apply per metric to both report hotspot tables " @@ -10155,7 +10974,7 @@ msgstr "" "自体が 1 つの違反集合の 3 つのレンダリングなので、構造上一致します。レポート" "も同じメトリクス単位の抑制判断を尊重します。" -#: src/commands/report.md:220 +#: src/commands/report.md:227 #, fuzzy msgid "" "The single deliberate exception is the **Actionable Summary**, a whole-" @@ -10177,11 +10996,11 @@ msgstr "" "記には「(excluding suppressed functions)」が追加され、Actionable Summary はそ" "のカウントが抑制を無視した生の値に基づくことを明示します。" -#: src/commands/report.md:230 +#: src/commands/report.md:237 msgid "HTML format" msgstr "HTML フォーマット" -#: src/commands/report.md:232 +#: src/commands/report.md:239 #, fuzzy msgid "" "`bca report html` emits a single self-contained HTML page covering the same " @@ -10197,32 +11016,33 @@ msgstr "" "フォントなし、テンプレートエンジンなし)。ページはオフラインでも同一にレンダ" "リングされます。" -#: src/commands/report.md:238 +#: src/commands/report.md:245 #, fuzzy msgid "Write it to a file and open it in any browser:" msgstr "ファイルに書き出して任意のブラウザで開きます:" -#: src/commands/report.md:245 +#: src/commands/report.md:252 msgid "" -"Click any column header to sort that table ascending, click again to toggle " +"Every column header is a native button: click its label — or Tab to it and " +"press Enter or Space — to sort that table ascending, and again to toggle " "descending. Each table sorts independently. Empty cells (where a metric was " -"not measured) sort as if they were positive infinity, which keeps \"no " -"data\" rows out of the visible top of a hotspot." +"not measured) sort last in both directions, so \"no data\" rows never " +"surface at the top of a hotspot. The header follows the WAI-ARIA sortable-" +"table pattern — the label is the `