diff --git a/docs/rule-packs.md b/docs/rule-packs.md index 750b067..0a4aa0c 100644 --- a/docs/rule-packs.md +++ b/docs/rule-packs.md @@ -149,3 +149,87 @@ Run `amber-lsp context [--root DIR]` to print the context blocks for detected pack modes. It prints nothing when no mode is detected. Exit status is 0 for successful context inspection; invalid command arguments or an unreadable project return nonzero. + +## Library lint command + +The command-only library rules run through `amber-lsp check`. They use a +separate list from `RuleRegistry`, so the editor keeps its existing diagnostic +set. + +```text +amber-lsp check [--since REF] [--all] [--carried-in PATH]... [--format text|json|github] [--advisory] [--root DIR] [PATH...] +``` + +The default paths are `src` and `spec`; directories are scanned recursively +for `*.cr` files. `--root` selects the project root. `--since REF` compares the +working tree with `git merge-base REF HEAD` and keeps findings on added lines. +`--all` reports all file-level findings. Changed-method collars run with +`--since`, where the changed line overlaps the method body. + +The command loads rule enablement and severity from `.amber-lsp.yml`. It accepts +the existing `rules` mapping and `exclude_patterns`. A carried-in path is +scanned even when an exclusion covers it; within that path, the command keeps +the four carry-in-safe rules: `library/swallowed-rescue`, +`library/unchecked-cast`, `library/unsynchronized-class-variable`, and +`library/disabled-certificate-verification`. + +```yaml +rules: + library/typed-raise: + enabled: false + library/vague-internal-name: + severity: information +exclude_patterns: + - src/generated/**/*.cr +``` + +Findings use the rule's configured severity. `warning` and `error` are +classified as blocking; `information` and `hint` are advisory. The `--advisory` +option returns exit status 0 while keeping every finding and its classification +in the output. Without it, blocking findings return 1. Successful checks return +0; invalid arguments and failed git commands return 2. + +`--format text` prints `PATH:LINE:COLUMN [classification] rule: message` and +the final blocking/advisory counts. `--format json` prints a JSON object with +`issues` (`path`, `line`, `column`, `classification`, `rule`, and `message`), +`blocking_count`, and `advisory_count`. `--format github` prints one GitHub +warning annotation per finding followed by the same counts line. + +### Rule list + +| Rule | Reports | Default classification | +|---|---|---| +| `library/typed-raise` | Receiverless `raise` calls with string literals or interpolations. | Blocking | +| `library/environment-read` | Calls through the `ENV` path. | Blocking | +| `library/stdlib-reopen` | Top-level definitions reopening configured core types. | Blocking | +| `library/log-setup` | `Log.setup`, `Log.setup_from_env`, and global `Log` setup calls. | Blocking | +| `library/process-output` | Receiverless `puts`, `print`, `printf`, `p`, and `pp` calls. | Blocking | +| `library/swallowed-rescue` | Untyped or `Exception` rescue clauses that swallow failures or replace them without preserving the cause. | Blocking | +| `library/unchecked-cast` | `.as(T)` casts to named types. | Blocking | +| `library/unsynchronized-class-variable` | Collection-valued class variables in files without `Mutex` or `Atomic`. | Blocking | +| `library/disabled-certificate-verification` | Paths ending in `VerifyMode::NONE`. | Blocking | +| `library/public-return-type` | Documented public methods without explicit return types, with lifecycle and `:nodoc:` exemptions. | Blocking | +| `library/vague-internal-name` | Vague local names, block parameters, and private method parameters. | Advisory | +| `library/collared-spec` | Method behavior describes without a golden case and both boundary contexts. | Blocking | +| `library/public-method-has-spec` | Public methods with arguments and no matching `describe` selector. | Blocking | +| `library/spec-without-assertion` | `it` blocks without a recognized assertion call. | Blocking | +| `library/changed-method-collar` | Changed behavior methods whose public entry point lacks collared coverage. | Blocking | + +### Collared specs and private callers + +A method behavior describe has a direct golden `it` or ordinary `context`, a +context beginning `at the boundary`, and a context beginning +`just past the boundary` with an expected-failure assertion. The expected +failure calls include `expect_raises`, `should_not`, `be_nil`, `be_false`, and +`be_empty`. A valid `# collar: none, ` comment immediately above the +describe or changed method records a deliberate exemption. + +For changed private or protected methods, `library/changed-method-collar` +builds a call index from every `src/**/*.cr` file. Reopened types merge by +fully qualified name. A no-receiver or `self` call connects methods on the +same type. The rule walks private and protected callers until it reaches public +methods that belong to the documented public type. At least one reachable +public caller needs a matching collared describe. A public `initialize` uses +the `describe ".new"` selector. If no public caller exists in the type, the +finding names that condition and directs the collar to the nearest public entry +point. diff --git a/spec/amber_lsp/library_lint/check_command_spec.cr b/spec/amber_lsp/library_lint/check_command_spec.cr new file mode 100644 index 0000000..c94639a --- /dev/null +++ b/spec/amber_lsp/library_lint/check_command_spec.cr @@ -0,0 +1,535 @@ +require "./spec_helper" + +private def build_private_method_source(changed_expression : String) : String + String.build do |source_builder| + source_builder << "module " + source_builder << "Sam" + source_builder << "ple\n class " + source_builder << "Wid" + source_builder << "get\n" + source_builder << " def process(value : String) : String\n" + source_builder << " self.decode(value)\n" + source_builder << " end\n\n" + source_builder << " private def decode(value : String) : String\n" + source_builder << " if value.empty?\n \"\"\n else\n " + source_builder << changed_expression + source_builder << "\n end\n end\n end\nend" + end +end + +private def build_two_level_private_method_source(changed_expression : String) : String + String.build do |source_builder| + source_builder << "module " + source_builder << "Sam" + source_builder << "ple\n class " + source_builder << "Wid" + source_builder << "get\n" + source_builder << " def process(value : String) : String\n" + source_builder << " decode(value)\n" + source_builder << " end\n\n" + source_builder << " private def decode(value : String) : String\n" + source_builder << " normalize(value)\n end\n\n" + source_builder << " private def normalize(value : String) : String\n" + source_builder << " if value.empty?\n \"\"\n else\n " + source_builder << changed_expression + source_builder << "\n end\n end\n end\nend" + end +end + +private def build_protected_method_source(changed_expression : String) : String + String.build do |source_builder| + source_builder << "module " + source_builder << "Sam" + source_builder << "ple\n class " + source_builder << "Wid" + source_builder << "get\n" + source_builder << " protected def calculate(value : Int32) : Int32\n" + source_builder << " if value > 0\n value\n else\n " + source_builder << changed_expression + source_builder << "\n end\n end\n end\nend" + end +end + +private def build_public_initialize_source(changed_value : String) : String + String.build do |source_builder| + source_builder << "module " + source_builder << "Sam" + source_builder << "ple\n class " + source_builder << "Wid" + source_builder << "get\n" + source_builder << " def initialize(value : String) : Nil\n" + source_builder << " if value.empty?\n @value = \"\"\n else\n @value = " + source_builder << changed_value + source_builder << "\n end\n end\n end\nend" + end +end + +private def build_private_initialize_source(changed_expression : String) : String + String.build do |source_builder| + source_builder << "module " + source_builder << "Sam" + source_builder << "ple\n class " + source_builder << "Wid" + source_builder << "get\n" + source_builder << " def initialize(value : String) : Nil\n" + source_builder << " @value = decode(value)\n end\n\n" + source_builder << " private def decode(value : String) : String\n" + source_builder << " if value.empty?\n \"\"\n else\n " + source_builder << changed_expression + source_builder << "\n end\n end\n end\nend" + end +end + +private def build_collared_process_spec : String + <<-CRYSTAL + describe "#process" do + context "at the boundary: last accepted value" do + it "accepts the value" do + process("value").should eq("value") + end + end + context "just past the boundary: first rejected value" do + it "rejects the value" do + expect_raises(ArgumentError) { raise ArgumentError.new("outside") } + end + end + it "handles a typical value" do + process("typical").should eq("typical") + end + end + CRYSTAL +end + +private def build_collared_new_spec : String + <<-CRYSTAL + describe ".new" do + context "at the boundary: empty value" do + it "accepts the value" do + Widget.new("").should be_a(Widget) + end + end + context "just past the boundary: invalid value" do + it "rejects the value" do + expect_raises(ArgumentError) { raise ArgumentError.new("outside") } + end + end + it "builds a typical value" do + Widget.new("value").should be_a(Widget) + end + end + CRYSTAL +end + +describe "amber-lsp check" do + context "golden: a private method reaches a collared public caller" do + it "passes" do + source_before = build_private_method_source("value") + source_after = build_private_method_source("value.strip") + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => build_collared_process_spec, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "at the boundary: a private method is two callers below the public API" do + it "passes when the public caller has collars" do + source_before = build_two_level_private_method_source("value") + source_after = build_two_level_private_method_source("value.strip") + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => build_collared_process_spec, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + + it "reports the private def when its public caller has no collars" do + source_before = build_private_method_source("value") + source_after = build_private_method_source("value.strip") + spec_source = "describe \"#process\" do\n it \"handles a value\" do\n process(\"value\").should eq(\"value\")\n end\nend" + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => spec_source, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(1) + error_output.should be_empty + output.should contain("src/widget.cr:7:") + output.should contain("public callers #process") + output.should contain("at the boundary") + end + end + + context "just past the boundary: an added line follows the private method end" do + it "leaves the private method outside the changed range" do + source_before = build_private_method_source("value") + source_after = source_before.sub( + " end\n end\nend", + " end\n # changed after the method\n end\nend", + ) + base_files = {"src/widget.cr" => source_before} + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should_not contain("library/changed-method-collar") + end + end + + context "just past the boundary: a protected method has no public caller in its type" do + it "reports the protected def and nearest public entry point requirement" do + source_before = build_protected_method_source("value") + source_after = build_protected_method_source("value + 1") + base_files = {"src/widget.cr" => source_before} + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(1) + error_output.should be_empty + output.should contain("src/widget.cr:3:") + output.should contain("no public caller in this type") + output.should contain("nearest public entry point needs") + end + end + + context "when a changed method is marked :nodoc:" do + it "treats it as internal and reports it when no public caller exists in its type" do + source_before = build_protected_method_source("value").sub("protected def", "# :nodoc:\n def") + source_after = build_protected_method_source("value + 1").sub("protected def", "# :nodoc:\n def") + base_files = {"src/widget.cr" => source_before} + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(1) + error_output.should be_empty + output.should contain("no public caller in this type") + end + end + + context "when types reopen across source files" do + it "connects the changed private method to a collared public caller" do + type_prefix = "module " + "Sam" + "ple\n class " + "Wid" + "get\n" + public_source = type_prefix + " def process(value : String) : String\n decode(value)\n end\n end\nend" + private_before = type_prefix + " private def decode(value : String) : String\n if value.empty?\n \"\"\n else\n value\n end\n end\n end\nend" + private_after = private_before.sub("value\n", "value.strip\n") + base_files = { + "src/public_api.cr" => public_source, + "src/private_code.cr" => private_before, + "spec/widget_spec.cr" => build_collared_process_spec, + } + changed_files = {"src/private_code.cr" => private_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "at the boundary: public initialize uses the .new selector" do + it "passes a changed initialize with a collared new describe" do + source_before = build_public_initialize_source("value") + source_after = build_public_initialize_source("value.strip") + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => build_collared_new_spec, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + + it "uses .new when initialize calls a changed private method" do + source_before = build_private_initialize_source("value") + source_after = build_private_initialize_source("value.strip") + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => build_collared_new_spec, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "just past the boundary: an internal method has a reasoned exemption" do + it "passes without a public caller" do + source_builder = String.build do |source_buffer| + source_buffer << "module " + source_buffer << "Sam" + source_buffer << "ple\n class " + source_buffer << "Wid" + source_buffer << "get\n" + source_buffer << " # collar: none, generated internal parser has no public input boundary\n" + source_buffer << " private def decode(value : String) : String\n" + source_buffer << " if value.empty?\n " + source_buffer << 34.chr + source_buffer << 34.chr + source_buffer << "\n else\n value\n end\n end\n end\nend" + end + source_after = source_builder.sub("value\n", "value.strip\n") + base_files = {"src/widget.cr" => source_builder} + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "when a changed path is carried in" do + it "keeps that path outside the changed-method collar step" do + source_before = build_private_method_source("value") + source_after = build_private_method_source("value.strip") + base_files = {"src/vendored/widget.cr" => source_before} + changed_files = {"src/vendored/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes( + base_files, + changed_files, + ["--carried-in", "src/vendored"], + ) + + exit_code.should eq(0) + error_output.should be_empty + output.should_not contain("library/changed-method-collar") + end + end + + context "when an exclusion covers a carried-in path" do + it "scans the path when it is named as carried in" do + source_before = "def fetch : Nil\n 1\nend" + source_after = "def fetch : Nil\n begin\n work\n rescue\n recover\n end\nend" + base_files = {"src/vendored/example.cr" => source_before} + changed_files = {"src/vendored/example.cr" => source_after} + config_source = "exclude_patterns:\n - src/vendored/**/*.cr\n" + + excluded_status, excluded_output, excluded_error = run_library_lint_with_git_changes( + base_files, + changed_files, + [] of String, + config_source, + ) + carried_status, carried_output, carried_error = run_library_lint_with_git_changes( + base_files, + changed_files, + ["--carried-in", "src/vendored"], + config_source, + ) + + excluded_status.should eq(0) + excluded_error.should be_empty + excluded_output.should_not contain("library/swallowed-rescue") + carried_status.should eq(1) + carried_error.should be_empty + carried_output.should contain("library/swallowed-rescue") + end + end + + context "when advisory mode is selected" do + it "exits successfully while retaining blocking findings" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, output, error_output = run_library_lint_for_files(files, ["--all", "--advisory"]) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("[blocking] library/process-output") + output.should contain("1 issue (1 blocking, 0 advisory)") + end + end + + context "when invalid arguments are combined with advisory mode" do + it "returns invalid argument status" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, _output, error_output = run_library_lint_for_files(files, ["--advisory"]) + + exit_code.should eq(2) + error_output.should contain("Provide --since REF or --all") + end + end + + context "when JSON output is requested" do + it "emits one JSON document with finding fields and counts" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, output, error_output = run_library_lint_for_files(files, ["--all", "--format", "json"]) + report = AmberLSP::LibraryLint::Report.from_json(output) + + exit_code.should eq(1) + error_output.should be_empty + output.lines.size.should eq(1) + report.list_of_issues.first.path.should eq("src/console.cr") + report.list_of_issues.first.rule.should eq("library/process-output") + report.blocking_count.should eq(1) + report.advisory_count.should eq(0) + end + end + + context "when GitHub output is requested" do + it "prints warning annotations and a final count line" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, output, error_output = run_library_lint_for_files(files, ["--all", "--format", "github"]) + + exit_code.should eq(1) + error_output.should be_empty + output.should contain("::warning file=src/console.cr,line=1,col=1,title=library/process-output::") + output.lines.last.should eq("1 issue (1 blocking, 0 advisory)") + end + end + + context "when a rule is disabled in .amber-lsp.yml" do + it "suppresses that rule in the check command" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + configuration = "rules:\n library/process-output:\n enabled: false\n" + exit_code, output, error_output = run_library_lint_for_files(files, ["--all"], configuration) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "when a rule severity is changed in .amber-lsp.yml" do + it "classifies information findings as advisory" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + configuration = "rules:\n library/process-output:\n severity: information\n" + exit_code, output, error_output = run_library_lint_for_files(files, ["--all"], configuration) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("[advisory] library/process-output") + output.should contain("1 issue (0 blocking, 1 advisory)") + end + end + + context "when both --all and --since are passed" do + it "returns invalid argument status" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, _output, error_output = run_library_lint_for_files(files, ["--all", "--since", "HEAD"]) + + exit_code.should eq(2) + error_output.should contain("--all and --since cannot be combined") + end + end + + context "when a git reference cannot be resolved" do + it "returns failed command status" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, _output, error_output = run_library_lint_for_files(files, ["--since", "missing-reference"]) + + exit_code.should eq(2) + error_output.should contain("git merge-base failed") + end + end + + context "when check help is requested" do + it "prints the command usage" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, output, error_output = run_library_lint_for_files(files, ["--help"]) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("--carried-in PATH") + output.should contain("--format text|json|github") + end + end +end + +describe AmberLSP::LibraryLint::Report do + describe "#exit_code" do + it "returns success for blocking findings in advisory mode" do + issue = AmberLSP::LibraryLint::Issue.new( + "src/file.cr", + 1, + 1, + "blocking", + "library/typed-raise", + "Use a named error", + ) + report = AmberLSP::LibraryLint::Report.new([issue]) + + report.exit_code(true).should eq(0) + report.blocking_count.should eq(1) + end + + it "returns failure for blocking findings by default" do + issue = AmberLSP::LibraryLint::Issue.new( + "src/file.cr", + 1, + 1, + "blocking", + "library/typed-raise", + "Use a named error", + ) + report = AmberLSP::LibraryLint::Report.new([issue]) + + report.exit_code(false).should eq(1) + end + end +end +describe "changed-line and advisory selection" do + context "when a finding is on a line that was not added" do + it "filters the existing finding from --since output" do + base_files = {"src/console.cr" => "puts \"existing\"\nvalue = 1\n"} + changed_files = {"src/console.cr" => "puts \"existing\"\nvalue = 2\n"} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "when the only finding is a vague internal name" do + it "classifies the finding as advisory and exits successfully" do + files = {"src/internal.cr" => "def calculate : Int32\n tmp = 1\n tmp\nend"} + exit_code, output, error_output = run_library_lint_for_files(files, ["--all"]) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("[advisory] library/vague-internal-name") + output.should contain("1 issue (0 blocking, 1 advisory)") + end + end + + context "when the requested output format is invalid" do + it "returns invalid argument status" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, _output, error_output = run_library_lint_for_files(files, ["--all", "--format", "yaml"]) + + exit_code.should eq(2) + error_output.should contain("--format supports text, json, or github") + end + end + + context "when check help is requested" do + it "prints the command usage" do + files = {"src/console.cr" => "puts \"diagnostic\"\n"} + exit_code, output, error_output = run_library_lint_for_files(files, ["--help"]) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("--carried-in PATH") + output.should contain("--format text|json|github") + end + end +end diff --git a/spec/amber_lsp/library_lint/check_scope_and_changed_lines_spec.cr b/spec/amber_lsp/library_lint/check_scope_and_changed_lines_spec.cr new file mode 100644 index 0000000..6b02974 --- /dev/null +++ b/spec/amber_lsp/library_lint/check_scope_and_changed_lines_spec.cr @@ -0,0 +1,273 @@ +require "./spec_helper" + +private RAISE_SOURCE = %(def failing_call\n raise "failure"\nend\n) + +private def build_owner_spec(owner_declaration : String) : String + <<-SPEC + describe #{owner_declaration} do + describe "#process" do + it "returns a positive value" do + Widget.new.process(1).should eq(1) + end + + context "at the boundary" do + it "accepts zero" do + Widget.new.process(0).should eq(0) + end + end + + context "just past the boundary" do + it "rejects a negative value" do + expect_raises(ArgumentError) { Widget.new.process(-1) } + end + end + end + end + SPEC +end + +private def build_widget_source(changed_expression : String) : String + "module Sample\n class Widget\n def process(value : Int32) : Int32\n if value > 0\n #{changed_expression}\n else\n 0\n end\n end\n end\nend\n" +end + +private def build_longer_namespace_widget_source(changed_expression : String) : String + "module Other\n module Sample\n class Widget\n def process(value : Int32) : Int32\n if value > 0\n #{changed_expression}\n else\n 0\n end\n end\n end\n end\nend\n" +end + +private def run_collar_check(owner_declaration : String) : String + run_collar_check_with_spec(build_owner_spec(owner_declaration)) +end + +private def run_collar_check_with_spec(spec_source : String) : String + _exit_code, output, _error_output = run_library_lint_with_git_changes( + {"src/widget.cr" => build_widget_source("value"), "spec/widget_spec.cr" => spec_source}, + {"src/widget.cr" => build_widget_source("value + 1")}, + ) + output +end + +# Commits *relative_path*, appends a string raise, and checks from *root_directory*. +private def run_changed_line_check( + relative_path : String, + root_directory : String = ".", + list_of_git_settings : Array(Tuple(String, String)) = [] of Tuple(String, String), +) : Tuple(Int32, String, String) + result : Tuple(Int32, String, String) = {0, "", ""} + with_tempdir do |repository_path| + write_library_lint_fixture_files(repository_path, {relative_path => "def stable_call\n 1\nend\n"}) + Dir.mkdir_p(File.join(repository_path, root_directory, "src")) + run_library_lint_git_command(repository_path, ["init", "-q"]) + run_library_lint_git_command(repository_path, ["config", "user.name", "Spec Runner"]) + run_library_lint_git_command(repository_path, ["config", "user.email", "spec@example.invalid"]) + list_of_git_settings.each do |setting_name, setting_value| + run_library_lint_git_command(repository_path, ["config", setting_name, setting_value]) + end + run_library_lint_git_command(repository_path, ["add", "-A"]) + run_library_lint_git_command(repository_path, ["commit", "-q", "-m", "base fixture"]) + File.open(File.join(repository_path, relative_path), "a", &.print(RAISE_SOURCE)) + + output = IO::Memory.new + error_output = IO::Memory.new + project_root = File.expand_path(root_directory, repository_path) + exit_code = AmberLSP::LibraryLint::RunLibraryLintCheck.new( + ["--since", "HEAD", "--root", project_root], + output, + error_output, + ).perform + result = {exit_code, output.to_s, error_output.to_s} + end + result +end + +describe AmberLSP::LibraryLint::CheckLibraryProjectFiles do + describe "#perform" do + it "applies a source rule to a nested source file" do + _exit_code, output, _error_output = run_library_lint_for_files({"src/nested/sample.cr" => RAISE_SOURCE}, ["--all"]) + output.should contain("library/typed-raise") + end + + context "at the boundary: the file sits directly under src" do + it "applies the source rule" do + _exit_code, output, _error_output = run_library_lint_for_files({"src/sample.cr" => RAISE_SOURCE}, ["--all"]) + output.should contain("library/typed-raise") + end + end + + context "just past the boundary: the file sits under spec" do + it "leaves the source rule out" do + _exit_code, output, _error_output = run_library_lint_for_files({"spec/sample_spec.cr" => RAISE_SOURCE}, ["--all"]) + output.should_not contain("library/typed-raise") + end + + it "leaves the source rule out when a spec path contains src" do + _exit_code, output, _error_output = run_library_lint_for_files({"spec/src/sample_spec.cr" => RAISE_SOURCE}, ["--all"]) + output.should_not contain("library/typed-raise") + end + + it "keeps carry-in-safe rules on a carried-in spec path" do + rescue_source = %(def quiet_call\n work\nrescue\n nil\nend\n) + _exit_code, output, _error_output = run_library_lint_for_files( + {"spec/upstream/sample_spec.cr" => rescue_source}, + ["--all", "--carried-in", "spec/upstream"], + ) + output.should contain("library/swallowed-rescue") + end + end + end +end + +describe AmberLSP::Rules::Library::Support::AnalyzeChangedMethodCollars do + describe "#perform" do + it "accepts a collar under the method's own type" do + run_collar_check("Sample::Widget").should_not contain("library/changed-method-collar") + end + + context "at the boundary: the describe names the type without its namespace" do + it "accepts the short name" do + run_collar_check("Widget").should_not contain("library/changed-method-collar") + end + + it "accepts an unqualified name for a deeper namespace" do + _exit_code, output, _error_output = run_library_lint_with_git_changes( + { + "src/widget.cr" => build_longer_namespace_widget_source("value"), + "spec/widget_spec.cr" => build_owner_spec("Widget"), + }, + {"src/widget.cr" => build_longer_namespace_widget_source("value + 1")}, + ) + output.should_not contain("library/changed-method-collar") + end + + it "accepts a string naming the type" do + run_collar_check(%("Sample::Widget")).should_not contain("library/changed-method-collar") + end + + it "accepts a string with a leading global scope" do + run_collar_check(%("::Sample::Widget")).should_not contain("library/changed-method-collar") + end + + it "keeps the enclosing type through a capitalized heading" do + spec_source = "describe Sample::Widget do\n#{build_owner_spec(%("Behavior"))}\nend\n" + run_collar_check_with_spec(spec_source).should_not contain("library/changed-method-collar") + end + + it "accepts a describe with no type named" do + run_collar_check(%("widget behavior")).should_not contain("library/changed-method-collar") + end + end + + context "just past the boundary: the collar belongs to another type" do + it "reports the changed method" do + run_collar_check("Other").should contain("library/changed-method-collar") + end + + it "reports a longer namespace ending in the method's type" do + run_collar_check("Other::Sample::Widget").should contain("library/changed-method-collar") + end + + it "reports a wrong owner written with a leading global scope" do + run_collar_check(%("::Other::Sample::Widget")).should contain("library/changed-method-collar") + end + + it "reports a qualified describe that is only a suffix of the method's owner" do + _exit_code, output, _error_output = run_library_lint_with_git_changes( + { + "src/widget.cr" => build_longer_namespace_widget_source("value"), + "spec/widget_spec.cr" => build_owner_spec("Sample::Widget"), + }, + {"src/widget.cr" => build_longer_namespace_widget_source("value + 1")}, + ) + output.should contain("library/changed-method-collar") + end + + it "reports a type sharing only a name suffix" do + run_collar_check("SampleWidget").should contain("library/changed-method-collar") + end + end + end +end + +describe AmberLSP::Rules::Library::Support::GitChangedLines do + describe "#perform" do + it "selects an added line at the repository top level" do + _exit_code, output, _error_output = run_changed_line_check("src/sample.cr") + output.should contain("library/typed-raise") + end + + context "at the boundary: paths git would otherwise rewrite" do + it "selects a line when the root is below the git top level" do + _exit_code, output, _error_output = run_changed_line_check("packages/core/src/sample.cr", "packages/core") + output.should contain("library/typed-raise") + end + + it "selects a line in a non-ASCII file name" do + _exit_code, output, _error_output = run_changed_line_check("src/café.cr") + output.should contain("library/typed-raise") + end + + it "selects a line in a file name with a space" do + _exit_code, output, _error_output = run_changed_line_check("src/two words.cr") + output.should contain("library/typed-raise") + end + + it "selects a line when git is configured without diff prefixes" do + _exit_code, output, _error_output = run_changed_line_check("src/sample.cr", ".", [{"diff.noprefix", "true"}]) + output.should contain("library/typed-raise") + end + end + + context "just past the boundary: the change is outside the root" do + it "reports nothing" do + exit_code, output, _error_output = run_changed_line_check("packages/other/src/sample.cr", "packages/core") + exit_code.should eq(0) + output.should contain("0 issues") + end + end + end +end + +describe AmberLSP::LibraryLint::ReadLibraryLintExclusionPatterns do + describe "#perform" do + it "excludes a file matching a listed pattern" do + _exit_code, output, _error_output = run_library_lint_for_files( + {"src/generated/sample.cr" => RAISE_SOURCE}, + ["--all"], + "exclude_patterns:\n - src/generated/**\n", + ) + output.should contain("0 issues") + end + + context "at the boundary: an empty list" do + it "excludes nothing" do + _exit_code, output, _error_output = run_library_lint_for_files( + {"src/sample.cr" => RAISE_SOURCE}, + ["--all"], + "exclude_patterns: []\n", + ) + output.should contain("library/typed-raise") + end + end + + context "just past the boundary: a value that is not a list of strings" do + it "exits 2 for a scalar" do + exit_code, _output, error_output = run_library_lint_for_files( + {"src/sample.cr" => RAISE_SOURCE}, + ["--all"], + "exclude_patterns: src/generated/**\n", + ) + exit_code.should eq(2) + error_output.should contain("exclude_patterns") + end + + it "exits 2 for a list holding a number" do + exit_code, _output, error_output = run_library_lint_for_files( + {"src/sample.cr" => RAISE_SOURCE}, + ["--all"], + "exclude_patterns:\n - 7\n", + ) + exit_code.should eq(2) + error_output.should contain("exclude_patterns") + end + end + end +end diff --git a/spec/amber_lsp/library_lint/spec_helper.cr b/spec/amber_lsp/library_lint/spec_helper.cr new file mode 100644 index 0000000..7116a59 --- /dev/null +++ b/spec/amber_lsp/library_lint/spec_helper.cr @@ -0,0 +1,75 @@ +require "../spec_helper" + +def write_library_lint_fixture_files(root_path : String, list_of_file_contents : Hash(String, String)) : Nil + list_of_file_contents.each do |relative_path, source_code| + absolute_path = File.join(root_path, relative_path) + Dir.mkdir_p(File.dirname(absolute_path)) + File.write(absolute_path, source_code) + end +end + +def run_library_lint_git_command(root_path : String, list_of_arguments : Array(String)) : Nil + output = IO::Memory.new + error_output = IO::Memory.new + status = Process.run("git", list_of_arguments, chdir: root_path, output: output, error: error_output) + return if status.success? + + raise Exception.new("git #{list_of_arguments.join(" ")} failed: #{error_output}") +end + +def run_library_lint_with_git_changes( + list_of_base_files : Hash(String, String), + list_of_changed_files : Hash(String, String), + list_of_extra_arguments : Array(String) = [] of String, + config_source : String? = nil, +) : Tuple(Int32, String, String) + result : Tuple(Int32, String, String) = {0, "", ""} + with_tempdir do |root_path| + write_library_lint_fixture_files(root_path, list_of_base_files) + if configuration_source = config_source + File.write(File.join(root_path, ".amber-lsp.yml"), configuration_source) + end + + run_library_lint_git_command(root_path, ["init", "-q"]) + run_library_lint_git_command(root_path, ["config", "user.name", "Spec Runner"]) + run_library_lint_git_command(root_path, ["config", "user.email", "spec@example.invalid"]) + run_library_lint_git_command(root_path, ["add", "-A"]) + run_library_lint_git_command(root_path, ["commit", "-m", "base fixture"]) + + write_library_lint_fixture_files(root_path, list_of_changed_files) + list_of_arguments = ["--since", "HEAD", "--root", root_path] + list_of_arguments.concat(list_of_extra_arguments) + output = IO::Memory.new + error_output = IO::Memory.new + exit_code = AmberLSP::LibraryLint::RunLibraryLintCheck.new( + list_of_arguments, + output, + error_output, + ).perform + result = {exit_code, output.to_s, error_output.to_s} + end + result +end + +def run_library_lint_for_files( + list_of_file_contents : Hash(String, String), + list_of_arguments : Array(String), + config_source : String? = nil, +) : Tuple(Int32, String, String) + result : Tuple(Int32, String, String) = {0, "", ""} + with_tempdir do |root_path| + write_library_lint_fixture_files(root_path, list_of_file_contents) + if configuration_source = config_source + File.write(File.join(root_path, ".amber-lsp.yml"), configuration_source) + end + + arguments = list_of_arguments.dup + arguments << "--root" + arguments << root_path + output = IO::Memory.new + error_output = IO::Memory.new + exit_code = AmberLSP::LibraryLint::RunLibraryLintCheck.new(arguments, output, error_output).perform + result = {exit_code, output.to_s, error_output.to_s} + end + result +end diff --git a/spec/amber_lsp/rules/library/changed_method_collar_spec.cr b/spec/amber_lsp/rules/library/changed_method_collar_spec.cr new file mode 100644 index 0000000..72da882 --- /dev/null +++ b/spec/amber_lsp/rules/library/changed_method_collar_spec.cr @@ -0,0 +1,59 @@ +require "../../library_lint/spec_helper" + +describe AmberLSP::Rules::Library::ChangedMethodCollar do + describe "check-project behavior" do + context "golden: a changed public method has all three collars" do + it "passes" do + source_before = "module Sample\n class Widget\n def process(value : Int32) : Int32\n if value > 0\n value\n else\n value\n end\n value + 1\n end\n end\nend" + source_after = source_before.sub("value + 1", "value + 2") + spec_source = <<-CRYSTAL + describe "#process" do + context "at the boundary: last accepted value" do + it "accepts the value" do + process(10).should eq(10) + end + end + context "just past the boundary: first rejected value" do + it "rejects the value" do + expect_raises(ArgumentError) { raise ArgumentError.new("outside") } + end + end + it "handles a typical value" do + process(5).should eq(5) + end + end + CRYSTAL + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => spec_source, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(0) + error_output.should be_empty + output.should contain("0 issues (0 blocking, 0 advisory)") + end + end + + context "at the boundary: a changed method body line" do + it "reports at the public def line when its describe has no collars" do + source_before = "module Sample\n class Widget\n def process(value : Int32) : Int32\n if value > 0\n value\n else\n value\n end\n value + 1\n end\n end\nend" + source_after = source_before.sub("value + 1", "value + 2") + spec_source = "describe \"#process\" do\n it \"handles a value\" do\n process(5).should eq(5)\n end\nend" + base_files = { + "src/widget.cr" => source_before, + "spec/widget_spec.cr" => spec_source, + } + changed_files = {"src/widget.cr" => source_after} + exit_code, output, error_output = run_library_lint_with_git_changes(base_files, changed_files) + + exit_code.should eq(1) + error_output.should be_empty + output.should contain("src/widget.cr:3:") + output.should contain("library/changed-method-collar") + output.should contain("Method #process is missing:") + end + end + end +end diff --git a/spec/amber_lsp/rules/library/collared_spec_spec.cr b/spec/amber_lsp/rules/library/collared_spec_spec.cr new file mode 100644 index 0000000..5c5bb0e --- /dev/null +++ b/spec/amber_lsp/rules/library/collared_spec_spec.cr @@ -0,0 +1,50 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::CollaredSpec do + describe "#check" do + context "golden: a method describe has both collars" do + it "passes a complete instance method shape" do + source_code = "describe \"#sample\" do\n context \"at the boundary: largest accepted value\" do\n it \"accepts the value\" do\n value.should eq(10)\n end\n end\n context \"just past the boundary: first rejected value\" do\n it \"rejects the value\" do\n expect_raises(ArgumentError) { raise ArgumentError.new(\"outside\") }\n end\n end\n it \"accepts a typical value\" do\n value.should eq(5)\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::CollaredSpec.new, source_code, "spec/sample_spec.cr") + issues.should be_empty + end + + it "passes a complete class method shape" do + source_code = "describe \".sample\" do\n context \"at the boundary: largest accepted value\" do\n it \"accepts the value\" do\n value.should eq(10)\n end\n end\n context \"just past the boundary: first rejected value\" do\n it \"rejects the value\" do\n expect_raises(ArgumentError) { raise ArgumentError.new(\"outside\") }\n end\n end\n it \"accepts a typical value\" do\n value.should eq(5)\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::CollaredSpec.new, source_code, "spec/sample_spec.cr") + issues.should be_empty + end + end + + context "at the boundary: a golden case and expected failure are present" do + it "reports only the missing at-the-boundary context" do + source_code = "describe \"#sample\" do\n context \"just past the boundary: first rejected value\" do\n it \"rejects the value\" do\n expect_raises(ArgumentError) { raise ArgumentError.new(\"outside\") }\n end\n end\n it \"accepts a typical value\" do\n value.should eq(5)\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::CollaredSpec.new, source_code, "spec/sample_spec.cr") + issues.map(&.message).should eq([AmberLSP::Rules::Library::Support::CollaredSpecShape::MSG_BOUNDARY_CONTEXT]) + end + end + + context "just past the boundary: a context has no expected-failure assertion" do + it "reports the missing expected-failure assertion" do + source_code = "describe \"#sample\" do\n context \"at the boundary: largest accepted value\" do\n it \"accepts the value\" do\n value.should eq(10)\n end\n end\n context \"just past the boundary: first rejected value\" do\n it \"rejects the value\" do\n value.should eq(10)\n end\n end\n it \"accepts a typical value\" do\n value.should eq(5)\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::CollaredSpec.new, source_code, "spec/sample_spec.cr") + issues.map(&.message).should eq([AmberLSP::Rules::Library::Support::CollaredSpecShape::MSG_EXPECTED_FAILURE]) + end + end + + context "when a describe has a reasoned exemption" do + it "passes" do + source_code = "# collar: none, this generated callback has no input boundary\ndescribe \"#generated_callback\" do\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::CollaredSpec.new, source_code, "spec/sample_spec.cr") + issues.should be_empty + end + end + + context "when source is not a spec file" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::CollaredSpec.new, "describe \"#sample\" do\nend", "src/sample.cr") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/disabled_certificate_verification_spec.cr b/spec/amber_lsp/rules/library/disabled_certificate_verification_spec.cr new file mode 100644 index 0000000..3118e95 --- /dev/null +++ b/spec/amber_lsp/rules/library/disabled_certificate_verification_spec.cr @@ -0,0 +1,26 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::DisabledCertificateVerification do + describe "#check" do + context "when VerifyMode::NONE is used" do + it "reports the path" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::DisabledCertificateVerification.new, + "OpenSSL::SSL::VerifyMode::NONE", + ) + issues.size.should eq(1) + issues.first.message.should eq("Keep certificate verification enabled") + end + end + + context "when another verification mode is used" do + it "passes" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::DisabledCertificateVerification.new, + "OpenSSL::SSL::VerifyMode::PEER", + ) + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/environment_read_spec.cr b/spec/amber_lsp/rules/library/environment_read_spec.cr new file mode 100644 index 0000000..b619c4f --- /dev/null +++ b/spec/amber_lsp/rules/library/environment_read_spec.cr @@ -0,0 +1,24 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::EnvironmentRead do + describe "#check" do + context "when a call uses ENV" do + it "reports a receiver call" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::EnvironmentRead.new, "ENV[\"TOKEN\"]") + issues.size.should eq(1) + end + + it "reports the global ENV path" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::EnvironmentRead.new, "::ENV[\"TOKEN\"]") + issues.size.should eq(1) + end + end + + context "when another path is used" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::EnvironmentRead.new, "Application::ENV[\"TOKEN\"]") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/library_rule_list_spec.cr b/spec/amber_lsp/rules/library/library_rule_list_spec.cr new file mode 100644 index 0000000..d53ffff --- /dev/null +++ b/spec/amber_lsp/rules/library/library_rule_list_spec.cr @@ -0,0 +1,33 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::BuildLibraryRuleList do + describe "#perform" do + it "returns all 15 check-only library rules outside RuleRegistry" do + registry_ids_before = AmberLSP::Rules::RuleRegistry.rules.map(&.id) + list_of_rules = AmberLSP::Rules::Library::BuildLibraryRuleList.new(Dir.current).perform + list_of_rule_ids = list_of_rules.map(&.id) + + list_of_rules.size.should eq(15) + list_of_rule_ids.should eq(%w[ + library/typed-raise + library/environment-read + library/stdlib-reopen + library/log-setup + library/process-output + library/swallowed-rescue + library/unchecked-cast + library/unsynchronized-class-variable + library/disabled-certificate-verification + library/public-return-type + library/vague-internal-name + library/collared-spec + library/public-method-has-spec + library/spec-without-assertion + library/changed-method-collar + ]) + list_of_rules.all? { |rule| !rule.requires_amber_project? }.should be_true + AmberLSP::Rules::RuleRegistry.rules.map(&.id).should eq(registry_ids_before) + AmberLSP::Rules::RuleRegistry.rules.any?(&.id.starts_with?("library/")).should be_false + end + end +end diff --git a/spec/amber_lsp/rules/library/log_setup_spec.cr b/spec/amber_lsp/rules/library/log_setup_spec.cr new file mode 100644 index 0000000..9db009d --- /dev/null +++ b/spec/amber_lsp/rules/library/log_setup_spec.cr @@ -0,0 +1,29 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::LogSetup do + describe "#check" do + context "when global Log setup is called" do + it "reports setup" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::LogSetup.new, "Log.setup do\nend") + issues.size.should eq(1) + end + + it "reports setup_from_env" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::LogSetup.new, "Log.setup_from_env") + issues.size.should eq(1) + end + + it "reports the global Log path" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::LogSetup.new, "::Log.setup") + issues.size.should eq(1) + end + end + + context "when a library logger is created" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::LogSetup.new, "Log.for(self)") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/process_output_spec.cr b/spec/amber_lsp/rules/library/process_output_spec.cr new file mode 100644 index 0000000..f1dd334 --- /dev/null +++ b/spec/amber_lsp/rules/library/process_output_spec.cr @@ -0,0 +1,21 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::ProcessOutput do + describe "#check" do + context "when a receiverless output method is called" do + it "reports each process output method" do + %w[puts print printf p pp].each do |output_method_name| + issues = library_rule_diagnostics(AmberLSP::Rules::Library::ProcessOutput.new, "#{output_method_name}(1)") + issues.size.should eq(1) + end + end + end + + context "when output is sent to a receiver" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::ProcessOutput.new, "io.puts(1)") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/public_method_has_spec_spec.cr b/spec/amber_lsp/rules/library/public_method_has_spec_spec.cr new file mode 100644 index 0000000..6f7dbfc --- /dev/null +++ b/spec/amber_lsp/rules/library/public_method_has_spec_spec.cr @@ -0,0 +1,57 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::PublicMethodHasSpec do + describe "#check" do + context "golden: both method selector forms exist" do + it "passes instance and class methods" do + with_tempdir do |project_path| + spec_directory = File.join(project_path, "spec") + Dir.mkdir_p(spec_directory) + File.write( + File.join(spec_directory, "sample_spec.cr"), + "describe \"#covered_instance_api\" do\nend\ndescribe \".covered_class_api\" do\nend", + ) + rule = AmberLSP::Rules::Library::PublicMethodHasSpec.new(project_path) + source_code = "def covered_instance_api(value : String) : String\n value\nend\ndef covered_class_api(value : String) : String\n value\nend" + issues = library_rule_diagnostics(rule, source_code) + issues.should be_empty + end + end + end + + context "at the boundary: a public method has an argument" do + it "reports the method without a selector" do + with_tempdir do |project_path| + rule = AmberLSP::Rules::Library::PublicMethodHasSpec.new(project_path) + issues = library_rule_diagnostics( + rule, + "def uncovered_library_api(value : String) : String\n value\nend", + ) + issues.size.should eq(1) + issues.first.message.should contain("uncovered_library_api") + end + end + end + + context "just past the boundary: a method has no arguments" do + it "passes" do + with_tempdir do |project_path| + rule = AmberLSP::Rules::Library::PublicMethodHasSpec.new(project_path) + issues = library_rule_diagnostics(rule, "def no_arguments : Nil\nend") + issues.should be_empty + end + end + end + + context "when lifecycle, operator, private, and nodoc methods are defined" do + it "passes those methods" do + with_tempdir do |project_path| + source_code = "class InternalAPI\n def initialize(value : String)\n end\n def +(other : InternalAPI) : InternalAPI\n self\n end\n private def private_lookup(value : String) : String\n value\n end\n # :nodoc:\n def internal_lookup(value : String) : String\n value\n end\nend" + rule = AmberLSP::Rules::Library::PublicMethodHasSpec.new(project_path) + issues = library_rule_diagnostics(rule, source_code) + issues.should be_empty + end + end + end + end +end diff --git a/spec/amber_lsp/rules/library/public_return_type_spec.cr b/spec/amber_lsp/rules/library/public_return_type_spec.cr new file mode 100644 index 0000000..2b3702a --- /dev/null +++ b/spec/amber_lsp/rules/library/public_return_type_spec.cr @@ -0,0 +1,44 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::PublicReturnType do + describe "#check" do + context "when a public method has no return type" do + it "reports the method" do + source_code = "class API\n def read\n 1\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::PublicReturnType.new, source_code) + issues.size.should eq(1) + end + end + + context "when a special method has no return type" do + it "passes initialize and finalize" do + source_code = "class API\n def initialize\n end\n def finalize\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::PublicReturnType.new, source_code) + issues.should be_empty + end + end + + context "when a method is private or protected" do + it "passes" do + source_code = "class API\n private def read\n end\n protected def write\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::PublicReturnType.new, source_code) + issues.should be_empty + end + end + + context "when a definition is under a nodoc comment" do + it "passes" do + source_code = "# :nodoc:\nmodule InternalAPI\n def read\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::PublicReturnType.new, source_code) + issues.should be_empty + end + end + + context "when a public method has an explicit return type" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::PublicReturnType.new, "def read : Int32\n 1\nend") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/spec_helper.cr b/spec/amber_lsp/rules/library/spec_helper.cr new file mode 100644 index 0000000..7baad9c --- /dev/null +++ b/spec/amber_lsp/rules/library/spec_helper.cr @@ -0,0 +1,9 @@ +require "../../spec_helper" + +def library_rule_diagnostics( + rule : AmberLSP::Rules::BaseRule, + source_code : String, + file_path : String = "src/sample.cr", +) : Array(AmberLSP::Rules::Diagnostic) + rule.check(file_path, source_code) +end diff --git a/spec/amber_lsp/rules/library/spec_without_assertion_spec.cr b/spec/amber_lsp/rules/library/spec_without_assertion_spec.cr new file mode 100644 index 0000000..90cde86 --- /dev/null +++ b/spec/amber_lsp/rules/library/spec_without_assertion_spec.cr @@ -0,0 +1,30 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::SpecWithoutAssertion do + describe "#check" do + context "golden: a supported assertion call is present" do + it "accepts direct assertion methods and the default prefixes" do + source_code = "describe \"assertions\" do\n it \"uses should\" do\n 1.should eq(1)\n end\n it \"uses should_not\" do\n 1.should_not eq(2)\n end\n it \"uses expect_raises\" do\n expect_raises(ArgumentError) { raise ArgumentError.new(\"expected\") }\n end\n it \"uses fail\" do\n fail(\"unreachable\")\n end\n it \"uses an assert prefix\" do\n assert_equal(1, 1)\n end\n it \"uses an expect prefix\" do\n expect_value(1)\n end\n it \"uses a verify prefix\" do\n verify_value(1)\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SpecWithoutAssertion.new, source_code, "spec/sample_spec.cr") + issues.should be_empty + end + end + + context "at the boundary: an example contains no assertion" do + it "reports the empty example" do + source_code = "describe \"a feature\" do\n it \"builds a response\" do\n build_response\n end\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SpecWithoutAssertion.new, source_code, "spec/sample_spec.cr") + issues.size.should eq(1) + issues.first.message.should contain("Add an assertion") + end + end + + context "just past the boundary: the source is not a spec file" do + it "passes" do + source_code = "def check_response : Nil\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SpecWithoutAssertion.new, source_code, "src/example.cr") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/stdlib_reopen_spec.cr b/spec/amber_lsp/rules/library/stdlib_reopen_spec.cr new file mode 100644 index 0000000..41e129f --- /dev/null +++ b/spec/amber_lsp/rules/library/stdlib_reopen_spec.cr @@ -0,0 +1,48 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::StdlibReopen do + describe "#check" do + context "when a core type is defined" do + it "reports a class definition" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::StdlibReopen.new, "class String\nend") + issues.size.should eq(1) + issues.first.message.should eq("Avoid reopening core type `String`") + end + + it "reports a struct definition" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::StdlibReopen.new, "struct Array\nend") + issues.size.should eq(1) + end + + it "reports a module definition" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::StdlibReopen.new, "module Enumerable\nend") + issues.size.should eq(1) + end + + it "reports a globally qualified definition inside another module" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::StdlibReopen.new, + "module Extensions\n class ::String\n end\nend", + ) + issues.size.should eq(1) + end + end + + context "when a core name is nested in an application namespace" do + it "passes" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::StdlibReopen.new, + "module WidgetApp\n class String\n end\nend", + ) + issues.should be_empty + end + end + + context "when another type is defined" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::StdlibReopen.new, "class Widget\nend") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/swallowed_rescue_spec.cr b/spec/amber_lsp/rules/library/swallowed_rescue_spec.cr new file mode 100644 index 0000000..77ed2d8 --- /dev/null +++ b/spec/amber_lsp/rules/library/swallowed_rescue_spec.cr @@ -0,0 +1,50 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::SwallowedRescue do + describe "#check" do + context "golden: broad rescues preserve or re-raise the cause" do + it "passes a replacement error with cause:" do + source_code = "begin\n work\nrescue ex : Exception\n raise Error.new(ex.message, cause: ex)\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SwallowedRescue.new, source_code) + issues.should be_empty + end + + it "passes a bare re-raise" do + source_code = "begin\n work\nrescue\n raise\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SwallowedRescue.new, source_code) + issues.should be_empty + end + + it "passes when re-raising the rescued value" do + source_code = "begin\n work\nrescue ex\n raise ex\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SwallowedRescue.new, source_code) + issues.should be_empty + end + end + + context "at the boundary: a broad rescue replaces an error" do + it "reports a replacement without cause:" do + source_code = "begin\n work\nrescue ex : Exception\n raise Error.new(ex.message)\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SwallowedRescue.new, source_code) + issues.map(&.message).should eq(["Pass cause: when converting a broad rescue into a new error"]) + end + end + + context "just past the boundary: a specific rescue converts an error" do + it "allows a typed rescue conversion" do + source_code = "begin\n work\nrescue ex : ArgumentError\n raise Error.new(ex.message)\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SwallowedRescue.new, source_code) + issues.should be_empty + end + end + + context "when a broad rescue does not raise" do + it "reports the swallowed rescue" do + source_code = "begin\n work\nrescue\n recover\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::SwallowedRescue.new, source_code) + issues.size.should eq(1) + issues.first.message.should eq("Reraise or rescue a specific error") + end + end + end +end diff --git a/spec/amber_lsp/rules/library/typed_raise_spec.cr b/spec/amber_lsp/rules/library/typed_raise_spec.cr new file mode 100644 index 0000000..2adc97d --- /dev/null +++ b/spec/amber_lsp/rules/library/typed_raise_spec.cr @@ -0,0 +1,40 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::TypedRaise do + describe "#check" do + context "when raise receives a string message" do + it "reports a string literal" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::TypedRaise.new, "raise \"failure\"") + issues.size.should eq(1) + issues.first.message.should eq("Raise a named error instead of a string message") + end + + it "reports an interpolated string message" do + source_code = String.build do |source_buffer| + source_buffer << "raise " + source_buffer << 34.chr + source_buffer << "failure: " + source_buffer << 35.chr + source_buffer << "{reason}" + source_buffer << 34.chr + end + issues = library_rule_diagnostics(AmberLSP::Rules::Library::TypedRaise.new, source_code) + issues.size.should eq(1) + end + end + + context "when raise receives an error object" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::TypedRaise.new, "raise error") + issues.should be_empty + end + end + + context "when a compile-time raise appears" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::TypedRaise.new, "{% raise \"failure\" %}") + issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/unchecked_cast_spec.cr b/spec/amber_lsp/rules/library/unchecked_cast_spec.cr new file mode 100644 index 0000000..2b08826 --- /dev/null +++ b/spec/amber_lsp/rules/library/unchecked_cast_spec.cr @@ -0,0 +1,33 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::UncheckedCast do + describe "#check" do + context "when a value is cast to a named type" do + it "reports the unchecked cast" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UncheckedCast.new, "value.as(Int32)") + issues.size.should eq(1) + end + + it "reports a generic named type cast" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UncheckedCast.new, "value.as(Array(String))") + issues.size.should eq(1) + end + end + + context "when a pointer type is used" do + it "passes" do + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UncheckedCast.new, "value.as(Void*)") + issues.should be_empty + end + end + + context "when nil or a checked cast is used" do + it "passes" do + nil_issues = library_rule_diagnostics(AmberLSP::Rules::Library::UncheckedCast.new, "nil.as(String)") + checked_issues = library_rule_diagnostics(AmberLSP::Rules::Library::UncheckedCast.new, "value.as?(String)") + nil_issues.should be_empty + checked_issues.should be_empty + end + end + end +end diff --git a/spec/amber_lsp/rules/library/unsynchronized_class_variable_spec.cr b/spec/amber_lsp/rules/library/unsynchronized_class_variable_spec.cr new file mode 100644 index 0000000..c29c14c --- /dev/null +++ b/spec/amber_lsp/rules/library/unsynchronized_class_variable_spec.cr @@ -0,0 +1,41 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::UnsynchronizedClassVariable do + describe "#check" do + context "when a collection class variable is assigned" do + it "reports an Array value" do + source_code = "class Cache\n @@items = [] of String\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UnsynchronizedClassVariable.new, source_code) + issues.size.should eq(1) + end + + it "reports a Hash value" do + source_code = "class Cache\n @@items = {} of String => String\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UnsynchronizedClassVariable.new, source_code) + issues.size.should eq(1) + end + + it "reports a Set value" do + source_code = "class Cache\n @@items = Set(String).new\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UnsynchronizedClassVariable.new, source_code) + issues.size.should eq(1) + end + end + + context "when the file uses Mutex or Atomic" do + it "passes the collection class variable" do + source_code = "class Cache\n @@items = [] of String\n LOCK = Mutex.new\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UnsynchronizedClassVariable.new, source_code) + issues.should be_empty + end + end + + context "when the class variable has a collection type declaration" do + it "reports an unguarded declaration" do + source_code = "class Cache\n @@items : Array(String)\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::UnsynchronizedClassVariable.new, source_code) + issues.size.should eq(1) + end + end + end +end diff --git a/spec/amber_lsp/rules/library/vague_internal_name_spec.cr b/spec/amber_lsp/rules/library/vague_internal_name_spec.cr new file mode 100644 index 0000000..6f3fcd6 --- /dev/null +++ b/spec/amber_lsp/rules/library/vague_internal_name_spec.cr @@ -0,0 +1,59 @@ +require "./spec_helper" + +describe AmberLSP::Rules::Library::VagueInternalName do + describe "#check" do + context "when a local uses a vague name" do + it "reports the local declaration" do + source_code = "def calculate : Int32\n tmp = 1\n tmp\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::VagueInternalName.new, source_code) + issues.size.should eq(1) + end + end + + context "when a block parameter uses a vague name" do + it "reports the block parameter" do + block_parameter_name = 120.chr + source_code = "[1].each do |#{block_parameter_name}|\n #{block_parameter_name}\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::VagueInternalName.new, source_code) + issues.size.should eq(1) + end + end + + context "when a private method parameter uses a vague name" do + it "reports the parameter" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::VagueInternalName.new, + "private def parse(val : String)\n val\nend", + ) + issues.size.should eq(1) + end + end + + context "when a name is underscored or a loop index" do + it "passes" do + source_code = "def calculate : Int32\n _tmp = 1\n i = 2\n j = 3\n k = 4\n i\nend" + issues = library_rule_diagnostics(AmberLSP::Rules::Library::VagueInternalName.new, source_code) + issues.should be_empty + end + end + + context "when a public method parameter uses a short name" do + it "passes the parameter" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::VagueInternalName.new, + "def parse(tmp : String) : String\n tmp\nend", + ) + issues.should be_empty + end + end + end +end +describe "top-level local names" do + it "reports a vague variable assigned outside a method" do + issues = library_rule_diagnostics( + AmberLSP::Rules::Library::VagueInternalName.new, + "tmp = 1", + ) + issues.size.should eq(1) + end +end diff --git a/spec/amber_lsp/spec_helper.cr b/spec/amber_lsp/spec_helper.cr index b7d488a..3faf71a 100644 --- a/spec/amber_lsp/spec_helper.cr +++ b/spec/amber_lsp/spec_helper.cr @@ -27,6 +27,8 @@ require "../../src/amber_lsp/analyzer" require "../../src/amber_lsp/analyze_file_with_coverage" require "../../src/amber_lsp/controller" require "../../src/amber_lsp/server" +require "../../src/amber_lsp/rules/library" +require "../../src/amber_lsp/library_lint" def with_tempdir(&) dir = File.join(Dir.tempdir, "amber_lsp_test_#{Random::Secure.hex(8)}") diff --git a/spec/amber_lsp/version_spec.cr b/spec/amber_lsp/version_spec.cr index e758561..6fd8a6f 100644 --- a/spec/amber_lsp/version_spec.cr +++ b/spec/amber_lsp/version_spec.cr @@ -3,7 +3,7 @@ require "./spec_helper" describe AmberLSP do describe "USAGE" do it "names every command-line mode" do - ["lookup QUERY", "hint", "--check FILE.cr", "context", "--version"].each do |mode| + ["lookup QUERY", "hint", "--check FILE.cr", "check", "context", "--version"].each do |mode| AmberLSP::USAGE.should contain("amber-lsp #{mode}") end end diff --git a/src/amber_lsp.cr b/src/amber_lsp.cr index a3155af..fe3e2b4 100644 --- a/src/amber_lsp.cr +++ b/src/amber_lsp.cr @@ -19,6 +19,7 @@ require "./amber_lsp/rules/specs/*" require "./amber_lsp/rules/sockets/*" require "./amber_lsp/rules/fsdd/*" require "./amber_lsp/rules/custom_rule" +require "./amber_lsp/rules/library" require "./amber_lsp/document_store" require "./amber_lsp/project_context" require "./amber_lsp/configuration" @@ -41,6 +42,7 @@ require "./amber_lsp/analyze_file_with_coverage" require "./amber_lsp/controller" require "./amber_lsp/server" require "./amber_lsp/check_file_for_diagnostics" +require "./amber_lsp/library_lint" require "./amber_lsp/lookup/build_layered_api_index" require "./amber_lsp/lookup/resolve_api_query" require "./amber_lsp/lookup/answer_api_query" @@ -58,6 +60,8 @@ elsif ARGV.first? == "lookup" exit AmberLSP::Lookup::RunLookupCommand.new(ARGV[1..].to_a).perform elsif ARGV.first? == "hint" exit AmberLSP::Lookup::RunHintCommand.new(ARGV[1..].to_a).perform +elsif ARGV.first? == "check" + exit AmberLSP::LibraryLint::RunLibraryLintCheck.new(ARGV[1..].to_a).perform elsif ARGV[0]? == "--check" file_path = ARGV[1]? unless file_path diff --git a/src/amber_lsp/library_lint.cr b/src/amber_lsp/library_lint.cr new file mode 100644 index 0000000..657d118 --- /dev/null +++ b/src/amber_lsp/library_lint.cr @@ -0,0 +1,14 @@ +require "./library_lint/issue" +require "./library_lint/report" +require "./library_lint/invalid_arguments" +require "./library_lint/options" +require "./library_lint/parse_library_lint_check_options" +require "./library_lint/resolve_library_lint_paths" +require "./library_lint/read_library_lint_exclusion_patterns" +require "./library_lint/path_matches_exclusion_pattern" +require "./library_lint/check_library_project_files" +require "./library_lint/print_library_lint_report" +require "./library_lint/run_library_lint_check" + +module AmberLSP::LibraryLint +end diff --git a/src/amber_lsp/library_lint/check_library_project_files.cr b/src/amber_lsp/library_lint/check_library_project_files.cr new file mode 100644 index 0000000..1205a95 --- /dev/null +++ b/src/amber_lsp/library_lint/check_library_project_files.cr @@ -0,0 +1,135 @@ +module AmberLSP::LibraryLint + # Checks selected project files with the isolated library rule list. + class CheckLibraryProjectFiles + CARRIED_IN_RULE_IDS = %w[ + library/swallowed-rescue + library/unchecked-cast + library/unsynchronized-class-variable + library/disabled-certificate-verification + ] + + # Initializes the checker with its root, paths, rules config, and git changes. + def initialize( + @root_path : String, + @list_of_relative_paths : Array(String), + @configuration : AmberLSP::Configuration, + @list_of_exclusion_patterns : Array(String), + @list_of_carried_in_prefixes : Array(String), + @changed_lines : AmberLSP::Rules::Library::Support::GitChangedLines?, + ) + end + + # Runs enabled rules and returns sorted findings. + def perform : ListOfIssues + list_of_included_paths = included_paths + list_of_rules = AmberLSP::Rules::Library::BuildLibraryRuleList.new(@root_path).perform + changed_method_rule : AmberLSP::Rules::Library::ChangedMethodCollar? = nil + list_of_issues = [] of Issue + + list_of_rules.each do |rule| + if collar_rule = rule.as?(AmberLSP::Rules::Library::ChangedMethodCollar) + changed_method_rule = collar_rule + next + end + next unless @configuration.rule_enabled?(rule.id) + + list_of_included_paths.each do |relative_path| + next unless rule_checks_path?(rule, relative_path) + + source_code = File.read(File.join(@root_path, relative_path)) + rule.check(relative_path, source_code).each do |diagnostic| + next unless changed_line_includes?(relative_path, diagnostic) + + list_of_issues << issue_from_diagnostic(relative_path, rule, diagnostic) + end + end + end + + if changed_lines = @changed_lines + if rule = changed_method_rule + if @configuration.rule_enabled?(rule.id) + list_of_diagnostics = rule.check_project( + @root_path, + list_of_included_paths, + changed_lines, + @list_of_carried_in_prefixes, + ) + list_of_diagnostics.each do |diagnostic| + list_of_issues << issue_from_diagnostic(diagnostic.source, rule, diagnostic) + end + end + end + end + + list_of_issues.sort_by! { |issue| {issue.path, issue.line, issue.column, issue.rule} } + list_of_issues + end + + private def included_paths : Array(String) + @list_of_relative_paths.reject do |relative_path| + excluded_path?(relative_path) && !carried_in_path?(relative_path) + end + end + + private def excluded_path?(relative_path : String) : Bool + @list_of_exclusion_patterns.any? do |pattern| + PathMatchesExclusionPattern.new(relative_path, pattern).perform? + end + end + + private def rule_checks_path?(rule : AmberLSP::Rules::BaseRule, relative_path : String) : Bool + return CARRIED_IN_RULE_IDS.includes?(rule.id) if carried_in_path?(relative_path) + + rule.applies_to.any? { |pattern| path_matches_rule_pattern?(relative_path, pattern) } + end + + # The registry matches `src/**` anywhere in an absolute editor path. These + # paths are root-relative, so the prefix has to sit at the start. + private def path_matches_rule_pattern?(relative_path : String, pattern : String) : Bool + return relative_path.starts_with?(pattern.rchop("**")) if pattern.ends_with?("**") + + AmberLSP::Rules::RuleRegistry.file_matches_pattern?(relative_path, pattern) + end + + private def carried_in_path?(relative_path : String) : Bool + @list_of_carried_in_prefixes.any? do |path_prefix| + path_prefix.empty? || relative_path == path_prefix || relative_path.starts_with?("#{path_prefix}/") + end + end + + private def changed_line_includes?(relative_path : String, diagnostic : AmberLSP::Rules::Diagnostic) : Bool + return true unless changed_lines = @changed_lines + + line_number = diagnostic.range.start.line + 1 + changed_lines.includes?(relative_path, line_number) + end + + private def issue_from_diagnostic( + relative_path : String, + rule : AmberLSP::Rules::BaseRule, + diagnostic : AmberLSP::Rules::Diagnostic, + ) : Issue + configured_severity = @configuration.rule_severity(rule.id, diagnostic.severity) + classification = classification_for(configured_severity) + Issue.new( + relative_path, + diagnostic.range.start.line + 1, + diagnostic.range.start.character + 1, + classification, + rule.id, + diagnostic.message, + ) + end + + private def classification_for(severity : AmberLSP::Rules::Severity) : String + case severity + when AmberLSP::Rules::Severity::Error, AmberLSP::Rules::Severity::Warning + "blocking" + when AmberLSP::Rules::Severity::Information, AmberLSP::Rules::Severity::Hint + "advisory" + else + "advisory" + end + end + end +end diff --git a/src/amber_lsp/library_lint/invalid_arguments.cr b/src/amber_lsp/library_lint/invalid_arguments.cr new file mode 100644 index 0000000..056c615 --- /dev/null +++ b/src/amber_lsp/library_lint/invalid_arguments.cr @@ -0,0 +1,5 @@ +module AmberLSP::LibraryLint + # Reports invalid command-line arguments. + class InvalidArguments < Exception + end +end diff --git a/src/amber_lsp/library_lint/issue.cr b/src/amber_lsp/library_lint/issue.cr new file mode 100644 index 0000000..4f10bec --- /dev/null +++ b/src/amber_lsp/library_lint/issue.cr @@ -0,0 +1,31 @@ +require "json" + +module AmberLSP::LibraryLint + # Holds one machine-readable library lint finding. + struct Issue + include JSON::Serializable + + getter path : String + getter line : Int32 + getter column : Int32 + getter classification : String + getter rule : String + getter message : String + + # Initializes a finding with its path, location, classification, and message. + def initialize( + @path : String, + @line : Int32, + @column : Int32, + @classification : String, + @rule : String, + @message : String, + ) + end + + # Returns whether this finding blocks the check command. + def blocking? : Bool + classification == "blocking" + end + end +end diff --git a/src/amber_lsp/library_lint/options.cr b/src/amber_lsp/library_lint/options.cr new file mode 100644 index 0000000..427dab7 --- /dev/null +++ b/src/amber_lsp/library_lint/options.cr @@ -0,0 +1,26 @@ +module AmberLSP::LibraryLint + # Holds parsed arguments for the library lint command. + struct Options + getter root_path : String + getter since_reference : String + getter format : String + getter list_of_paths : Array(String) + getter list_of_carried_in_paths : Array(String) + getter? all = false + getter? advisory = false + getter? has_explicit_paths = false + + # Initializes the command options. + def initialize( + @root_path : String, + @since_reference : String, + @format : String, + @list_of_paths : Array(String), + @list_of_carried_in_paths : Array(String), + @all : Bool, + @advisory : Bool, + @has_explicit_paths : Bool, + ) + end + end +end diff --git a/src/amber_lsp/library_lint/parse_library_lint_check_options.cr b/src/amber_lsp/library_lint/parse_library_lint_check_options.cr new file mode 100644 index 0000000..451343b --- /dev/null +++ b/src/amber_lsp/library_lint/parse_library_lint_check_options.cr @@ -0,0 +1,96 @@ +module AmberLSP::LibraryLint + # Parses and validates arguments for `amber-lsp check`. + class ParseLibraryLintCheckOptions + USAGE = "Usage: amber-lsp check [--since REF] [--all] [--carried-in PATH]... [--format text|json|github] [--advisory] [--root DIR] [PATH...]" + + # Initializes the parser with command arguments. + def initialize(@list_of_arguments : Array(String)) + @since_reference = "" + @root_path = Dir.current + @format = "text" + @list_of_paths = [] of String + @list_of_carried_in_paths = [] of String + @all = false + @advisory = false + @has_explicit_paths = false + end + + # Parses arguments and returns the validated options. + def perform : Options + argument_index = 0 + while argument_index < @list_of_arguments.size + argument_index = parse_argument(argument_index) + 1 + end + + validate_arguments + @list_of_paths = %w[src spec] if @list_of_paths.empty? + Options.new( + @root_path, + @since_reference, + @format, + @list_of_paths, + @list_of_carried_in_paths, + @all, + @advisory, + @has_explicit_paths, + ) + end + + private def parse_argument(argument_index : Int32) : Int32 + current_argument = @list_of_arguments[argument_index] + case current_argument + when "--since" + @since_reference = option_value(argument_index, "--since requires a REF") + argument_index + 1 + when "--all" + @all = true + argument_index + when "--carried-in" + @list_of_carried_in_paths << option_value(argument_index, "--carried-in requires a PATH") + argument_index + 1 + when "--format" + @format = option_value(argument_index, "--format requires text, json, or github") + unless @format.in?(%w[text json github]) + raise InvalidArguments.new("--format supports text, json, or github") + end + argument_index + 1 + when "--advisory" + @advisory = true + argument_index + when "--root" + @root_path = option_value(argument_index, "--root requires a DIR") + argument_index + 1 + else + add_path_argument(current_argument) + argument_index + end + end + + private def option_value(argument_index : Int32, error_message : String) : String + option_value = @list_of_arguments[argument_index + 1]? + if option_value.nil? || option_value.starts_with?("--") + raise InvalidArguments.new(error_message) + end + + option_value + end + + private def add_path_argument(path_argument : String) : Nil + if path_argument.starts_with?('-') + raise InvalidArguments.new("Unknown option `#{path_argument}`") + end + + @has_explicit_paths = true + @list_of_paths << path_argument + end + + private def validate_arguments : Nil + if @all && !@since_reference.empty? + raise InvalidArguments.new("--all and --since cannot be combined") + end + if !@all && @since_reference.empty? + raise InvalidArguments.new("Provide --since REF or --all") + end + end + end +end diff --git a/src/amber_lsp/library_lint/path_matches_exclusion_pattern.cr b/src/amber_lsp/library_lint/path_matches_exclusion_pattern.cr new file mode 100644 index 0000000..5cf9f2b --- /dev/null +++ b/src/amber_lsp/library_lint/path_matches_exclusion_pattern.cr @@ -0,0 +1,26 @@ +module AmberLSP::LibraryLint + # Checks whether a project-relative path matches a configured exclusion. + class PathMatchesExclusionPattern + # Initializes the matcher with *relative_path* and *pattern*. + def initialize(@relative_path : String, @pattern : String) + end + + # Returns whether *relative_path* is covered by *pattern*. + def perform? : Bool + normalized_pattern = @pattern.lchop("./") + if normalized_pattern.ends_with?("/") + directory_prefix = normalized_pattern.rstrip('/') + return @relative_path == directory_prefix || @relative_path.starts_with?("#{directory_prefix}/") + end + + return true if File.match?(normalized_pattern, @relative_path) + return @relative_path.includes?(normalized_pattern) unless has_glob?(normalized_pattern) + + false + end + + private def has_glob?(pattern : String) : Bool + pattern.includes?('*') || pattern.includes?('?') || pattern.includes?('[') + end + end +end diff --git a/src/amber_lsp/library_lint/print_library_lint_report.cr b/src/amber_lsp/library_lint/print_library_lint_report.cr new file mode 100644 index 0000000..1f0c16f --- /dev/null +++ b/src/amber_lsp/library_lint/print_library_lint_report.cr @@ -0,0 +1,45 @@ +module AmberLSP::LibraryLint + # Prints the text, JSON, or GitHub representation of a report. + class PrintLibraryLintReport + # Initializes the printer with *report*, *format*, and output stream. + def initialize( + @report : Report, + @format : String, + @output : IO, + ) + end + + # Prints all findings and the final counts line. + def perform : Nil + case @format + when "json" + @output.puts(@report.to_json) + return + when "github" + print_github_findings + else + print_text_findings + end + print_counts + end + + private def print_text_findings : Nil + @report.list_of_issues.each do |issue| + @output.puts("#{issue.path}:#{issue.line}:#{issue.column} [#{issue.classification}] #{issue.rule}: #{issue.message}") + end + end + + private def print_github_findings : Nil + @report.list_of_issues.each do |issue| + message = issue.message.gsub('\n', " ").gsub('\r', " ") + @output.puts("::warning file=#{issue.path},line=#{issue.line},col=#{issue.column},title=#{issue.rule}::#{message}") + end + end + + private def print_counts : Nil + issue_count = @report.list_of_issues.size + issue_label = issue_count == 1 ? "issue" : "issues" + @output.puts("#{issue_count} #{issue_label} (#{@report.blocking_count} blocking, #{@report.advisory_count} advisory)") + end + end +end diff --git a/src/amber_lsp/library_lint/read_library_lint_exclusion_patterns.cr b/src/amber_lsp/library_lint/read_library_lint_exclusion_patterns.cr new file mode 100644 index 0000000..665325d --- /dev/null +++ b/src/amber_lsp/library_lint/read_library_lint_exclusion_patterns.cr @@ -0,0 +1,41 @@ +require "yaml" + +module AmberLSP::LibraryLint + # Reads check-command exclusion patterns while preserving editor configuration behavior. + class ReadLibraryLintExclusionPatterns + # Initializes the reader with *root_path* and existing Amber LSP exclusions. + def initialize( + @root_path : String, + @list_of_default_exclusion_patterns : Array(String), + ) + end + + # Reads `exclude_patterns` or returns the existing `exclude` patterns. + def perform : AmberLSP::Rules::Library::Support::ListOfStrings + configuration_path = File.join(@root_path, AmberLSP::Configuration::CONFIG_FILE_NAME) + return @list_of_default_exclusion_patterns unless File.file?(configuration_path) + + yaml_document = YAML.parse(File.read(configuration_path)) + return @list_of_default_exclusion_patterns unless configuration_mapping = yaml_document.as_h? + + exclusion_node = configuration_mapping[YAML::Any.new("exclude_patterns")]? + return @list_of_default_exclusion_patterns unless exclusion_node + + read_list_of_patterns(exclusion_node) + end + + private def read_list_of_patterns( + exclusion_node : YAML::Any, + ) : AmberLSP::Rules::Library::Support::ListOfStrings + list_of_nodes = exclusion_node.as_a? + raise InvalidArguments.new("exclude_patterns in .amber-lsp.yml must be a list of strings") unless list_of_nodes + + list_of_nodes.map do |pattern_node| + pattern = pattern_node.as_s? + raise InvalidArguments.new("exclude_patterns in .amber-lsp.yml must be a list of strings") unless pattern + + pattern + end + end + end +end diff --git a/src/amber_lsp/library_lint/report.cr b/src/amber_lsp/library_lint/report.cr new file mode 100644 index 0000000..b728351 --- /dev/null +++ b/src/amber_lsp/library_lint/report.cr @@ -0,0 +1,28 @@ +require "json" + +module AmberLSP::LibraryLint + alias ListOfIssues = Array(Issue) + + # Holds sorted findings and their severity counts. + struct Report + include JSON::Serializable + + @[JSON::Field(key: "issues")] + getter list_of_issues : Array(Issue) + getter blocking_count : Int32 + getter advisory_count : Int32 + + # Initializes the report and calculates its blocking and advisory counts. + def initialize(@list_of_issues : Array(Issue)) + @blocking_count = list_of_issues.count(&.blocking?) + @advisory_count = list_of_issues.size - blocking_count + end + + # Returns the command exit status for the selected advisory mode. + def exit_code(advisory_mode : Bool) : Int32 + return 0 if advisory_mode || blocking_count.zero? + + 1 + end + end +end diff --git a/src/amber_lsp/library_lint/resolve_library_lint_paths.cr b/src/amber_lsp/library_lint/resolve_library_lint_paths.cr new file mode 100644 index 0000000..f31e05f --- /dev/null +++ b/src/amber_lsp/library_lint/resolve_library_lint_paths.cr @@ -0,0 +1,63 @@ +module AmberLSP::LibraryLint + # Resolves command paths to sorted, root-relative Crystal source paths. + class ResolveLibraryLintPaths + # Initializes the resolver with the project root and requested paths. + def initialize( + @root_path : String, + @list_of_requested_paths : Array(String), + @has_explicit_paths : Bool, + ) + end + + # Resolves all Crystal files selected by *list_of_requested_paths*. + def perform : AmberLSP::Rules::Library::Support::ListOfStrings + list_of_absolute_paths = [] of String + @list_of_requested_paths.each do |requested_path| + collect_paths_for(requested_path, list_of_absolute_paths) + end + + list_of_relative_paths = list_of_absolute_paths.map do |absolute_path| + relative_path_for(absolute_path) + end + list_of_relative_paths.uniq! + list_of_relative_paths.sort! + list_of_relative_paths + end + + private def collect_paths_for(requested_path : String, list_of_absolute_paths : Array(String)) : Nil + absolute_pattern = File.expand_path(requested_path, @root_path) + has_glob = requested_path.includes?('*') || requested_path.includes?('?') || requested_path.includes?('[') + + if has_glob + matches = Dir.glob(absolute_pattern) + raise InvalidArguments.new("Path did not match any files: #{requested_path}") if matches.empty? + matches.each { |match| collect_path_match(match, list_of_absolute_paths) } + else + collect_path_match(absolute_pattern, list_of_absolute_paths) + end + end + + private def collect_path_match(path : String, list_of_absolute_paths : Array(String)) : Nil + if File.file?(path) + unless path.ends_with?(".cr") + raise InvalidArguments.new("Path must identify Crystal files: #{path}") + end + list_of_absolute_paths << File.expand_path(path) + elsif File.directory?(path) + crystal_pattern = File.join(path, "**", "*.cr") + list_of_absolute_paths.concat(Dir.glob(crystal_pattern).map { |source_path| File.expand_path(source_path) }) + else + raise InvalidArguments.new("Path does not exist: #{path}") if @has_explicit_paths + end + end + + private def relative_path_for(absolute_path : String) : String + root_prefix = @root_path.ends_with?(File::SEPARATOR.to_s) ? @root_path : "#{@root_path}#{File::SEPARATOR}" + unless absolute_path.starts_with?(root_prefix) + raise InvalidArguments.new("Path must be inside the project root: #{absolute_path}") + end + + absolute_path[root_prefix.size..] + end + end +end diff --git a/src/amber_lsp/library_lint/run_library_lint_check.cr b/src/amber_lsp/library_lint/run_library_lint_check.cr new file mode 100644 index 0000000..ba74426 --- /dev/null +++ b/src/amber_lsp/library_lint/run_library_lint_check.cr @@ -0,0 +1,94 @@ +require "yaml" + +module AmberLSP::LibraryLint + # Runs the isolated library lint command for a project. + class RunLibraryLintCheck + # Initializes the command with arguments and output streams. + def initialize( + @list_of_arguments : Array(String), + @output : IO = STDOUT, + @error_output : IO = STDERR, + ) + end + + # Runs the check command and returns its process status. + def perform : Int32 + if @list_of_arguments.includes?("--help") || @list_of_arguments.includes?("-h") + @output.puts(ParseLibraryLintCheckOptions::USAGE) + return 0 + end + + options = ParseLibraryLintCheckOptions.new(@list_of_arguments).perform + root_path = File.expand_path(options.root_path) + unless File.directory?(root_path) + raise InvalidArguments.new("Project root does not exist: #{root_path}") + end + + configuration = AmberLSP::Configuration.load(root_path) + list_of_exclusion_patterns = ReadLibraryLintExclusionPatterns.new( + root_path, + configuration.exclude_patterns, + ).perform + list_of_relative_paths = ResolveLibraryLintPaths.new( + root_path, + options.list_of_paths, + options.has_explicit_paths?, + ).perform + list_of_carried_in_prefixes = normalize_carried_in_paths(root_path, options.list_of_carried_in_paths) + changed_lines = changed_lines_for(root_path, options) + list_of_issues = CheckLibraryProjectFiles.new( + root_path, + list_of_relative_paths, + configuration, + list_of_exclusion_patterns, + list_of_carried_in_prefixes, + changed_lines, + ).perform + report = Report.new(list_of_issues) + PrintLibraryLintReport.new(report, options.format, @output).perform + report.exit_code(options.advisory?) + rescue ex : InvalidArguments + @error_output.puts(ex.message || "Invalid check arguments") + 2 + rescue ex : AmberLSP::Rules::Library::Support::GitCommandError + @error_output.puts(ex.message || "Git command failed") + 2 + rescue ex : YAML::ParseException + @error_output.puts("amber-lsp check: invalid .amber-lsp.yml: #{ex.message}") + 2 + rescue ex : IO::Error + @error_output.puts("amber-lsp check: #{ex.message || "project files could not be read"}") + 2 + end + + private def changed_lines_for( + root_path : String, + options : Options, + ) : AmberLSP::Rules::Library::Support::GitChangedLines? + return if options.all? + + AmberLSP::Rules::Library::Support::GitChangedLines.new(root_path, options.since_reference).perform + end + + private def normalize_carried_in_paths( + root_path : String, + list_of_paths : Array(String), + ) : Array(String) + list_of_paths.map do |carried_in_path| + absolute_path = File.expand_path(carried_in_path, root_path) + unless File.file?(absolute_path) || File.directory?(absolute_path) + raise InvalidArguments.new("Carried-in path does not exist: #{carried_in_path}") + end + + next "" if absolute_path == root_path + + root_prefix = root_path.ends_with?(File::SEPARATOR.to_s) ? root_path : "#{root_path}#{File::SEPARATOR}" + unless absolute_path.starts_with?(root_prefix) + raise InvalidArguments.new("Carried-in path must be inside the project root: #{carried_in_path}") + end + + absolute_path[root_prefix.size..].rstrip('/') + end + end + end +end diff --git a/src/amber_lsp/rules/library.cr b/src/amber_lsp/rules/library.cr new file mode 100644 index 0000000..896922b --- /dev/null +++ b/src/amber_lsp/rules/library.cr @@ -0,0 +1,18 @@ +require "./library/support" +require "./library/support/*" +require "./library/typed_raise" +require "./library/environment_read" +require "./library/stdlib_reopen" +require "./library/log_setup" +require "./library/process_output" +require "./library/swallowed_rescue" +require "./library/unchecked_cast" +require "./library/unsynchronized_class_variable" +require "./library/disabled_certificate_verification" +require "./library/public_return_type" +require "./library/vague_internal_name" +require "./library/collared_spec" +require "./library/public_method_has_spec" +require "./library/spec_without_assertion" +require "./library/changed_method_collar" +require "./library/build_library_rule_list" diff --git a/src/amber_lsp/rules/library/build_library_rule_list.cr b/src/amber_lsp/rules/library/build_library_rule_list.cr new file mode 100644 index 0000000..da0ef27 --- /dev/null +++ b/src/amber_lsp/rules/library/build_library_rule_list.cr @@ -0,0 +1,30 @@ +module AmberLSP::Rules::Library + # Builds independent rule instances for one library check. + class BuildLibraryRuleList + # Initializes the list builder with *project_root*. + def initialize(@project_root : String) + end + + # Builds this command's isolated library rule instances. + # Builds this command's isolated library rule instances. + def perform : Support::ListOfLibraryRules + [ + TypedRaise.new, + EnvironmentRead.new, + StdlibReopen.new, + LogSetup.new, + ProcessOutput.new, + SwallowedRescue.new, + UncheckedCast.new, + UnsynchronizedClassVariable.new, + DisabledCertificateVerification.new, + PublicReturnType.new, + VagueInternalName.new, + CollaredSpec.new, + PublicMethodHasSpec.new(@project_root), + SpecWithoutAssertion.new, + ChangedMethodCollar.new, + ] of AmberLSP::Rules::BaseRule + end + end +end diff --git a/src/amber_lsp/rules/library/changed_method_collar.cr b/src/amber_lsp/rules/library/changed_method_collar.cr new file mode 100644 index 0000000..3238c93 --- /dev/null +++ b/src/amber_lsp/rules/library/changed_method_collar.cr @@ -0,0 +1,52 @@ +module AmberLSP::Rules::Library + # Requires collars for changed methods with behavioral branches. + class ChangedMethodCollar < AmberLSP::Rules::BaseRule + # Returns this rule's stable identifier. + def id : String + "library/changed-method-collar" + end + + # Describes the changed method collar policy. + def description : String + "Requires golden and boundary collars for changed behavioral methods" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Leaves ordinary file checks empty; collar analysis needs the project graph. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + return [] of AmberLSP::Rules::Diagnostic if content.empty? + + [] of AmberLSP::Rules::Diagnostic + end + + # :nodoc: + def check_project( + root_path : String, + list_of_target_paths : Support::ListOfStrings, + changed_lines : Support::GitChangedLines, + list_of_carried_in_prefixes : Support::ListOfStrings, + ) : Support::ListOfDiagnostics + Support::AnalyzeChangedMethodCollars.new( + root_path, + list_of_target_paths, + changed_lines, + list_of_carried_in_prefixes, + ).perform + end + end +end diff --git a/src/amber_lsp/rules/library/collared_spec.cr b/src/amber_lsp/rules/library/collared_spec.cr new file mode 100644 index 0000000..714b9ec --- /dev/null +++ b/src/amber_lsp/rules/library/collared_spec.cr @@ -0,0 +1,58 @@ +module AmberLSP::Rules::Library + # Requires golden and boundary cases for behavior describes in specs. + class CollaredSpec < AmberLSP::Rules::BaseRule + # Returns this rule's stable identifier. + def id : String + "library/collared-spec" + end + + # Describes the collared spec shape. + def description : String + "Requires golden and collared cases in method behavior specs" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects spec source files. + def applies_to : Support::ListOfStrings + ["spec/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports method behavior describes that miss a golden case or boundary collar. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless spec_file?(file_path) + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectBehaviorDescribes.new(syntax_tree).perform.each do |describe_call| + shape = Support::CollaredSpecShape.new(content, describe_call) + shape.list_of_missing_parts.each do |missing_part| + if diagnostic = Support::CreateDiagnosticForASTNode.new( + describe_call, + content, + id, + default_severity, + missing_part, + ).perform + list_of_diagnostics << diagnostic + end + end + end + list_of_diagnostics + end + + private def spec_file?(file_path : String) : Bool + file_path.starts_with?("spec/") || file_path.includes?("/spec/") + end + end +end diff --git a/src/amber_lsp/rules/library/disabled_certificate_verification.cr b/src/amber_lsp/rules/library/disabled_certificate_verification.cr new file mode 100644 index 0000000..4f17318 --- /dev/null +++ b/src/amber_lsp/rules/library/disabled_certificate_verification.cr @@ -0,0 +1,56 @@ +module AmberLSP::Rules::Library + # Reports paths that disable certificate verification. + class DisabledCertificateVerification < AmberLSP::Rules::BaseRule + MESSAGE = "Keep certificate verification enabled" + + # Returns this rule's stable identifier. + def id : String + "library/disabled-certificate-verification" + end + + # Describes the certificate verification policy. + def description : String + "Disallows disabling certificate verification" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports paths that end in `VerifyMode::NONE`. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectPathsFromCrystalAST.new(syntax_tree).perform.each do |path_node| + next unless path_node.names.size >= 2 + next unless path_node.names[-2..-1] == %w[VerifyMode NONE] + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + path_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/environment_read.cr b/src/amber_lsp/rules/library/environment_read.cr new file mode 100644 index 0000000..d84734d --- /dev/null +++ b/src/amber_lsp/rules/library/environment_read.cr @@ -0,0 +1,56 @@ +module AmberLSP::Rules::Library + # Reports direct environment access in library source. + class EnvironmentRead < AmberLSP::Rules::BaseRule + MESSAGE = "Read environment variables at the application boundary" + + # Returns this rule's stable identifier. + def id : String + "library/environment-read" + end + + # Describes the environment boundary policy. + def description : String + "Disallows environment reads inside library code" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports calls made through the global `ENV` path. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectCrystalMethodCalls.new(syntax_tree).perform.each do |call_node| + receiver_path = call_node.obj.as?(Crystal::Path) + next unless receiver_path && receiver_path.names == ["ENV"] + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + call_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/log_setup.cr b/src/amber_lsp/rules/library/log_setup.cr new file mode 100644 index 0000000..6ff3656 --- /dev/null +++ b/src/amber_lsp/rules/library/log_setup.cr @@ -0,0 +1,58 @@ +module AmberLSP::Rules::Library + # Reports global Log setup calls inside library source. + class LogSetup < AmberLSP::Rules::BaseRule + MESSAGE = "Configure global Log setup in the application" + SETUP_METHOD_NAMES = %w[setup setup_from_env] + + # Returns this rule's stable identifier. + def id : String + "library/log-setup" + end + + # Describes the global logging policy. + def description : String + "Disallows configuring global Log setup from a library" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports global `Log.setup` and `Log.setup_from_env` calls. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectCrystalMethodCalls.new(syntax_tree).perform.each do |call_node| + receiver_path = call_node.obj.as?(Crystal::Path) + next unless receiver_path && receiver_path.names == ["Log"] + next unless SETUP_METHOD_NAMES.includes?(call_node.name) + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + call_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/process_output.cr b/src/amber_lsp/rules/library/process_output.cr new file mode 100644 index 0000000..256d39d --- /dev/null +++ b/src/amber_lsp/rules/library/process_output.cr @@ -0,0 +1,56 @@ +module AmberLSP::Rules::Library + # Reports direct process output calls in library source. + class ProcessOutput < AmberLSP::Rules::BaseRule + MESSAGE = "Use library logging instead of process output" + OUTPUT_METHOD_NAMES = %w[puts print printf p pp] + + # Returns this rule's stable identifier. + def id : String + "library/process-output" + end + + # Describes the process output policy. + def description : String + "Disallows writing process output directly from a library" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports receiverless process output calls. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectCrystalMethodCalls.new(syntax_tree).perform.each do |call_node| + next unless call_node.obj.nil? && OUTPUT_METHOD_NAMES.includes?(call_node.name) + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + call_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/public_method_has_spec.cr b/src/amber_lsp/rules/library/public_method_has_spec.cr new file mode 100644 index 0000000..73e7279 --- /dev/null +++ b/src/amber_lsp/rules/library/public_method_has_spec.cr @@ -0,0 +1,98 @@ +require "set" + +module AmberLSP::Rules::Library + # Requires a spec selector for each public method with arguments. + class PublicMethodHasSpec < AmberLSP::Rules::BaseRule + MESSAGE = "Add a `describe \"#%s\"` or `describe \".%s\"` spec" + + @list_of_method_spec_selectors : Set(String)? = nil + + # Initializes the rule with the project root used to index specs. + def initialize(@project_root : String) + end + + # Returns this rule's stable identifier. + def id : String + "library/public-method-has-spec" + end + + # Describes the public method spec policy. + def description : String + "Requires a method describe selector for public methods with arguments" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports public methods with arguments that have no method selector in specs. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.starts_with?("src/") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_method_spec_selectors = method_spec_selectors + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectPublicMethods.new(syntax_tree, content).perform.each do |method_node| + next if method_node.name == "initialize" + next if operator_method_name?(method_node.name) + next unless method_takes_arguments?(method_node) + next if method_spec_exists?(method_node.name, list_of_method_spec_selectors) + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + method_node, + content, + id, + default_severity, + MESSAGE % {method_node.name, method_node.name}, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + + private def method_takes_arguments?(method_node : Crystal::Def) : Bool + !method_node.args.empty? || !method_node.block_arg.nil? + end + + private def method_spec_exists?(method_name : String, list_of_selectors : Set(String)) : Bool + list_of_selectors.includes?("##{method_name}") || list_of_selectors.includes?(".#{method_name}") + end + + private def operator_method_name?(method_name : String) : Bool + method_name != "->" && method_name.each_char.none?(&.alphanumeric?) + end + + private def method_spec_selectors : Set(String) + if list_of_selectors = @list_of_method_spec_selectors + return list_of_selectors + end + + list_of_selectors = Set(String).new + spec_pattern = File.join(@project_root, "spec", "**", "*_spec.cr") + Dir.glob(spec_pattern).each do |spec_path| + source_code = File.read(spec_path) + syntax_tree = Support::ParseCrystalSource.new(source_code).perform + next unless syntax_tree + + selectors = Support::CollectMethodDescribeSelectors.new(syntax_tree).perform + selectors.each { |selector| list_of_selectors << selector } + end + @list_of_method_spec_selectors = list_of_selectors + list_of_selectors + end + end +end diff --git a/src/amber_lsp/rules/library/public_return_type.cr b/src/amber_lsp/rules/library/public_return_type.cr new file mode 100644 index 0000000..8be172e --- /dev/null +++ b/src/amber_lsp/rules/library/public_return_type.cr @@ -0,0 +1,58 @@ +module AmberLSP::Rules::Library + # Reports documented public methods without an explicit return type. + class PublicReturnType < AmberLSP::Rules::BaseRule + MESSAGE = "Add an explicit return type to this public definition" + LIFECYCLE_METHOD_NAMES = %w[initialize finalize] + + # Returns this rule's stable identifier. + def id : String + "library/public-return-type" + end + + # Describes the public return type policy. + def description : String + "Requires explicit return types on documented public methods" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports public methods that omit a return type annotation. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + method_nodes = Support::CollectPublicMethods.new(syntax_tree, content).perform + method_nodes.each do |method_node| + next if LIFECYCLE_METHOD_NAMES.includes?(method_node.name) + next if method_node.return_type + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + method_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/spec_without_assertion.cr b/src/amber_lsp/rules/library/spec_without_assertion.cr new file mode 100644 index 0000000..b935cf1 --- /dev/null +++ b/src/amber_lsp/rules/library/spec_without_assertion.cr @@ -0,0 +1,62 @@ +module AmberLSP::Rules::Library + # Reports spec examples that contain no recognized assertion call. + class SpecWithoutAssertion < AmberLSP::Rules::BaseRule + ASSERTION_PREFIXES = %w[assert_ expect_ verify_] + MESSAGE = "Add an assertion to this `it` block" + + # Returns this rule's stable identifier. + def id : String + "library/spec-without-assertion" + end + + # Describes the spec assertion policy. + def description : String + "Requires a recognized assertion in each spec example" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects spec source files. + def applies_to : Support::ListOfStrings + ["spec/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports `it` blocks without a recognized assertion call. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless spec_file?(file_path) + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectCrystalMethodCalls.new(syntax_tree).perform.each do |call_node| + next unless call_node.name == "it" + next unless block_node = call_node.block + next if Support::DetectSpecAssertion.new(block_node.body, ASSERTION_PREFIXES).perform? + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + call_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + + private def spec_file?(file_path : String) : Bool + file_path.starts_with?("spec/") || file_path.includes?("/spec/") + end + end +end diff --git a/src/amber_lsp/rules/library/stdlib_reopen.cr b/src/amber_lsp/rules/library/stdlib_reopen.cr new file mode 100644 index 0000000..32222f3 --- /dev/null +++ b/src/amber_lsp/rules/library/stdlib_reopen.cr @@ -0,0 +1,55 @@ +module AmberLSP::Rules::Library + # Reports direct reopenings of standard library types. + class StdlibReopen < AmberLSP::Rules::BaseRule + CORE_TYPE_NAMES = %w[String Array Hash Object Nil Symbol Int32 Int64 Float64 Time Enumerable Number] + MESSAGE = "Avoid reopening core type `%s`" + + # Returns this rule's stable identifier. + def id : String + "library/stdlib-reopen" + end + + # Describes the core type reopening policy. + def description : String + "Disallows reopening configured core types" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports top-level class or module definitions that reopen core types. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + reopens = Support::CollectCoreTypeReopens.new(syntax_tree, CORE_TYPE_NAMES).perform + reopens.each do |node, type_name| + if diagnostic = Support::CreateDiagnosticForASTNode.new( + node, + content, + id, + default_severity, + MESSAGE % type_name, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/support.cr b/src/amber_lsp/rules/library/support.cr new file mode 100644 index 0000000..c29c814 --- /dev/null +++ b/src/amber_lsp/rules/library/support.cr @@ -0,0 +1,19 @@ +# :nodoc: +require "compiler/crystal/syntax" +require "set" + +module AmberLSP::Rules::Library::Support + alias ListOfDiagnostics = Array(AmberLSP::Rules::Diagnostic) + alias ListOfPublicMethods = Array(Crystal::Def) + alias ListOfVagueNameFindings = Array(Tuple(Crystal::ASTNode, String)) + alias ListOfCoreTypeReopens = Array(Tuple(Crystal::ASTNode, String)) + alias ListOfRescueClauses = Array(Crystal::Rescue) + alias ListOfTypeCasts = Array(Crystal::Cast) + alias ListOfCrystalPaths = Array(Crystal::Path) + alias ListOfCrystalCalls = Array(Crystal::Call) + alias ListOfASTNodes = Array(Crystal::ASTNode) + alias ListOfStrings = Array(String) + alias ListOfLibraryRules = Array(AmberLSP::Rules::BaseRule) + alias ListOfBehaviorDescribes = Array(BehaviorDescribe) + alias SetOfMethodDescribeSelectors = Set(String) +end diff --git a/src/amber_lsp/rules/library/support/analyze_changed_method_collars.cr b/src/amber_lsp/rules/library/support/analyze_changed_method_collars.cr new file mode 100644 index 0000000..ecc8867 --- /dev/null +++ b/src/amber_lsp/rules/library/support/analyze_changed_method_collars.cr @@ -0,0 +1,194 @@ +require "set" + +module AmberLSP::Rules::Library::Support + # Checks changed methods against collars on their public callers. + class AnalyzeChangedMethodCollars + RULE_ID = "library/changed-method-collar" + + NO_PUBLIC_CALLER_MESSAGE = "The nearest public entry point needs a describe with a direct golden `it` or `context` case, an `at the boundary` context, and a `just past the boundary` context with an expected-failure assertion." + + # Initializes the analysis with project paths, changed lines, and carry-in prefixes. + def initialize( + @root_path : String, + @list_of_target_paths : ListOfStrings, + @changed_lines : GitChangedLines, + @list_of_carried_in_prefixes : ListOfStrings, + ) + @list_of_target_paths_as_set = @list_of_target_paths.to_set + end + + # Checks changed behavior methods against matching public caller specs. + def perform : ListOfDiagnostics + list_of_method_definitions = index_all_source_methods + call_graph = ChangedMethodCallGraph.new(list_of_method_definitions) + list_of_behavior_describes = ReadBehaviorDescribes.new(@root_path).perform + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + + list_of_method_definitions.each do |method_definition| + next unless changed_behavior_method?(method_definition) + next if carried_in_path?(method_definition.relative_path) + + message = message_for_changed_method(method_definition, call_graph, list_of_behavior_describes) + next unless message + + if diagnostic = CreateDiagnosticForASTNode.new( + method_definition.method_node, + method_definition.source_code, + RULE_ID, + AmberLSP::Rules::Severity::Warning, + message, + method_definition.relative_path, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + + private def index_all_source_methods : ListOfMethodDefinitions + list_of_method_definitions = [] of MethodDefinition + source_pattern = File.join(@root_path, "src", "**", "*.cr") + + Dir.glob(source_pattern).sort.each do |absolute_path| + relative_path = Path[absolute_path].relative_to(Path[@root_path]).to_s + source_code = File.read(absolute_path) + syntax_tree = ParseCrystalSource.new(source_code).perform + next unless syntax_tree + + method_definitions = IndexMethodsFromSource.new( + syntax_tree, + relative_path, + source_code, + @changed_lines, + ).perform + list_of_method_definitions.concat(method_definitions) + end + list_of_method_definitions + end + + private def changed_behavior_method?(method_definition : MethodDefinition) : Bool + return false unless @list_of_target_paths_as_set.includes?(method_definition.relative_path) + return false unless method_definition.changed_behavior_method? + + method_definition.visibility.public? || method_definition.private_or_protected? + end + + private def message_for_changed_method( + method_definition : MethodDefinition, + call_graph : ChangedMethodCallGraph, + list_of_behavior_describes : ListOfBehaviorDescribes, + ) : String? + if line_number = method_definition.method_node.location.try(&.line_number) + exemption_reason = ReadSourceAnnotations.new(method_definition.source_code).collar_exemption_reason_at(line_number) + return if exemption_reason && !exemption_reason.empty? + end + + return message_for_public_method(method_definition, list_of_behavior_describes) if method_definition.public_caller? + + message_for_private_or_protected_method(method_definition, call_graph, list_of_behavior_describes) + end + + private def message_for_public_method( + method_definition : MethodDefinition, + list_of_behavior_describes : ListOfBehaviorDescribes, + ) : String? + list_of_matching_describes = matching_describes(method_definition, list_of_behavior_describes) + return "Method #{method_definition.selector} has no matching describe" if list_of_matching_describes.empty? + return if any_describe_has_collar?(list_of_matching_describes) + + closest_shape = closest_shape(list_of_matching_describes) + "Method #{method_definition.selector} is missing: #{closest_shape.list_of_missing_parts.join("; ")}" + end + + private def message_for_private_or_protected_method( + method_definition : MethodDefinition, + call_graph : ChangedMethodCallGraph, + list_of_behavior_describes : ListOfBehaviorDescribes, + ) : String? + list_of_public_callers = public_callers_for(method_definition, call_graph) + return "Changed method #{method_definition.selector} has no public caller in this type; #{NO_PUBLIC_CALLER_MESSAGE}" if list_of_public_callers.empty? + + return if list_of_public_callers.any? do |caller_definition| + any_describe_has_collar?(matching_describes(caller_definition, list_of_behavior_describes)) + end + + list_of_caller_names = [] of String + list_of_caller_details = [] of String + list_of_public_callers.each do |caller_definition| + selector = caller_definition.selector + list_of_caller_names << selector unless list_of_caller_names.includes?(selector) + list_of_matching_describes = matching_describes(caller_definition, list_of_behavior_describes) + if list_of_matching_describes.empty? + missing_parts = [ + "Add a matching describe for #{selector}", + CollaredSpecShape::MSG_GOLDEN_CASE, + CollaredSpecShape::MSG_BOUNDARY_CONTEXT, + CollaredSpecShape::MSG_PAST_BOUNDARY_CONTEXT, + CollaredSpecShape::MSG_EXPECTED_FAILURE, + ] + list_of_caller_details << "#{selector}: #{missing_parts.join("; ")}" + else + shape = closest_shape(list_of_matching_describes) + list_of_caller_details << "#{selector}: #{shape.list_of_missing_parts.join("; ")}" + end + end + + "Changed method #{method_definition.selector} is called by public callers #{list_of_caller_names.join(", ")}; missing collar parts: #{list_of_caller_details.join("; ")}" + end + + private def public_callers_for( + method_definition : MethodDefinition, + call_graph : ChangedMethodCallGraph, + ) : ListOfMethodDefinitions + list_of_public_callers = [] of MethodDefinition + list_of_pending_methods = [method_definition] + list_of_visited_definitions = Set(String).new + + until list_of_pending_methods.empty? + current_method = list_of_pending_methods.pop + next if list_of_visited_definitions.includes?(current_method.definition_identity) + + list_of_visited_definitions << current_method.definition_identity + call_graph.callers_for(current_method).each do |caller_definition| + next unless caller_definition.owner_type_name == method_definition.owner_type_name + + if caller_definition.public_caller? + unless list_of_public_callers.any? { |public_caller| public_caller.definition_identity == caller_definition.definition_identity } + list_of_public_callers << caller_definition + end + elsif caller_definition.has_public_type? + list_of_pending_methods << caller_definition + end + end + end + + list_of_public_callers + end + + private def matching_describes( + method_definition : MethodDefinition, + list_of_behavior_describes : ListOfBehaviorDescribes, + ) : ListOfBehaviorDescribes + list_of_behavior_describes.select do |behavior_describe| + behavior_describe.selector == method_definition.selector && + behavior_describe.covers_owner?(method_definition.owner_type_name) + end + end + + private def any_describe_has_collar?(list_of_describes : ListOfBehaviorDescribes) : Bool + list_of_describes.any?(&.shape.satisfied?) + end + + private def closest_shape(list_of_describes : ListOfBehaviorDescribes) : CollaredSpecShape + shapes = list_of_describes.map(&.shape) + shapes.min_by(&.list_of_missing_parts.size) + end + + private def carried_in_path?(relative_path : String) : Bool + @list_of_carried_in_prefixes.any? do |path_prefix| + normalized_prefix = path_prefix.lchop("./").rstrip('/') + normalized_prefix.empty? || relative_path == normalized_prefix || relative_path.starts_with?("#{normalized_prefix}/") + end + end + end +end diff --git a/src/amber_lsp/rules/library/support/behavior_describe.cr b/src/amber_lsp/rules/library/support/behavior_describe.cr new file mode 100644 index 0000000..0ad41a1 --- /dev/null +++ b/src/amber_lsp/rules/library/support/behavior_describe.cr @@ -0,0 +1,39 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Holds one parsed method behavior describe and its source. + struct BehaviorDescribe + getter selector : String + getter source_code : String + getter node : Crystal::Call + getter owner_type_name : String? + + # Initializes the describe record with its selector, source, and AST node. + def initialize( + @selector : String, + @source_code : String, + @node : Crystal::Call, + @owner_type_name : String? = nil, + ) + end + + # Returns whether this describe can cover a method on *method_owner_type_name*. + # + # A describe with no enclosing type could cover any owner. An unqualified + # name such as `Widget` covers `Sample::Widget`; a qualified name covers only + # the type it names. + def covers_owner?(method_owner_type_name : String) : Bool + return true unless describe_owner = @owner_type_name + + return describe_owner == method_owner_type_name if describe_owner.includes?("::") + + describe_owner == method_owner_type_name || + method_owner_type_name.ends_with?("::#{describe_owner}") + end + + # Builds the collar shape for this describe. + def shape : CollaredSpecShape + CollaredSpecShape.new(@source_code, @node) + end + end +end diff --git a/src/amber_lsp/rules/library/support/changed_method_call_graph.cr b/src/amber_lsp/rules/library/support/changed_method_call_graph.cr new file mode 100644 index 0000000..37e009a --- /dev/null +++ b/src/amber_lsp/rules/library/support/changed_method_call_graph.cr @@ -0,0 +1,68 @@ +require "set" + +module AmberLSP::Rules::Library::Support + # Indexes calls between methods declared on the same reopened type. + class ChangedMethodCallGraph + # Initializes the graph from method definitions collected across source files. + def initialize(@list_of_method_definitions : ListOfMethodDefinitions) + @list_of_method_definitions_by_key = Hash(String, ListOfMethodDefinitions).new + @list_of_callers_by_method_key = Hash(String, ListOfMethodDefinitions).new + @list_of_caller_identities_by_method_key = Hash(String, Set(String)).new + index_method_definitions + index_method_callers + end + + # Returns methods of the same type that call *method_definition*. + def callers_for(method_definition : MethodDefinition) : ListOfMethodDefinitions + @list_of_callers_by_method_key[method_definition.method_key]?.try(&.dup) || [] of MethodDefinition + end + + private def index_method_definitions : Nil + @list_of_method_definitions.each do |method_definition| + method_key = method_definition.method_key + list_of_definitions = @list_of_method_definitions_by_key[method_key]? + unless list_of_definitions + list_of_definitions = [] of MethodDefinition + @list_of_method_definitions_by_key[method_key] = list_of_definitions + end + list_of_definitions << method_definition + end + end + + private def index_method_callers : Nil + @list_of_method_definitions.each do |caller_definition| + caller_definition.list_of_called_method_names.each do |called_method_name| + method_key = method_key_for(caller_definition, called_method_name) + callee_definitions = @list_of_method_definitions_by_key[method_key]? + next unless callee_definitions + + callee_definitions.each do |callee_definition| + add_caller(callee_definition.method_key, caller_definition) + end + end + end + end + + private def method_key_for(method_definition : MethodDefinition, method_name : String) : String + method_kind = method_definition.class_method? ? "class" : "instance" + "#{method_definition.owner_type_name}::#{method_kind}::#{method_name}" + end + + private def add_caller(method_key : String, caller_definition : MethodDefinition) : Nil + list_of_identities = @list_of_caller_identities_by_method_key[method_key]? + unless list_of_identities + list_of_identities = Set(String).new + @list_of_caller_identities_by_method_key[method_key] = list_of_identities + end + return if list_of_identities.includes?(caller_definition.definition_identity) + + list_of_identities << caller_definition.definition_identity + list_of_callers = @list_of_callers_by_method_key[method_key]? + unless list_of_callers + list_of_callers = [] of MethodDefinition + @list_of_callers_by_method_key[method_key] = list_of_callers + end + list_of_callers << caller_definition + end + end +end diff --git a/src/amber_lsp/rules/library/support/check_method_for_behavior.cr b/src/amber_lsp/rules/library/support/check_method_for_behavior.cr new file mode 100644 index 0000000..3b67750 --- /dev/null +++ b/src/amber_lsp/rules/library/support/check_method_for_behavior.cr @@ -0,0 +1,39 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Checks whether a method body contains branching or error-handling behavior. + class CheckMethodForBehavior < Crystal::Visitor + getter? found = false + + # Initializes the checker with *method_body*. + def initialize(@method_body : Crystal::ASTNode) + end + + # Returns whether *method_body* contains a behavior branch. + def perform? : Bool + @method_body.accept(self) + found? + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::If | Crystal::Unless | Crystal::Case | Crystal::While | Crystal::Until | Crystal::Rescue | Crystal::ExceptionHandler | Crystal::And | Crystal::Or) : Bool + @found = true + false + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + if node.obj.nil? && node.name == "raise" + @found = true + return false + end + + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collared_spec_shape.cr b/src/amber_lsp/rules/library/support/collared_spec_shape.cr new file mode 100644 index 0000000..d3b4166 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collared_spec_shape.cr @@ -0,0 +1,114 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Checks the direct golden and boundary cases in a method describe. + class CollaredSpecShape + MSG_BOUNDARY_CONTEXT = "Add a context starting with `at the boundary`" + MSG_PAST_BOUNDARY_CONTEXT = "Add a context starting with `just past the boundary`" + MSG_GOLDEN_CASE = "Add a direct golden `it` or `context` case" + MSG_EXPECTED_FAILURE = "Add an expected-failure assertion to the just-past-the-boundary context" + MSG_EXEMPTION_REASON = "Add a reason after `# collar: none,`" + + getter list_of_missing_parts = [] of String + getter? has_valid_exemption = false + + # Initializes the shape checker with *source_code* and *describe_call*. + def initialize(@source_code : String, @describe_call : Crystal::Call) + if exemption_reason = collar_exemption_reason + if exemption_reason.empty? + list_of_missing_parts << MSG_EXEMPTION_REASON + else + @has_valid_exemption = true + return + end + end + + check_shape + end + + # Returns whether the describe has both collars and a golden case. + def satisfied? : Bool + has_valid_exemption? || list_of_missing_parts.empty? + end + + private def collar_exemption_reason : String? + return unless location = @describe_call.location + + line_index = location.line_number - 2 + return if line_index < 0 + return unless source_line = @source_code.lines[line_index]? + + comment_parts = source_line.strip.split(',', 2) + return unless comment_parts.size == 2 + return unless comment_parts[0].strip == "# collar: none" + + comment_parts[1].strip + end + + private def check_shape : Nil + list_of_child_calls = direct_block_calls + past_boundary_call = list_of_child_calls.find { |child_call| past_boundary_context?(child_call) } + + if !list_of_child_calls.any? { |child_call| boundary_context?(child_call) } + list_of_missing_parts << MSG_BOUNDARY_CONTEXT + end + list_of_missing_parts << MSG_PAST_BOUNDARY_CONTEXT unless past_boundary_call + list_of_missing_parts << MSG_GOLDEN_CASE unless golden_case_exists?(list_of_child_calls) + if past_boundary_call && !expected_failure_assertion_exists?(past_boundary_call) + list_of_missing_parts << MSG_EXPECTED_FAILURE + end + end + + private def direct_block_calls : Array(Crystal::Call) + list_of_calls = [] of Crystal::Call + return list_of_calls unless block_node = @describe_call.block + + body = block_node.body + if expression_list = body.as?(Crystal::Expressions) + expression_list.expressions.each do |expression| + if expression.is_a?(Crystal::Call) + list_of_calls << expression + end + end + elsif body.is_a?(Crystal::Call) + list_of_calls << body + end + list_of_calls + end + + private def context_description(node : Crystal::Call) : String? + return unless node.name == "context" + return unless description_node = node.args.first?.try(&.as?(Crystal::StringLiteral)) + + description_node.value + end + + private def boundary_context?(node : Crystal::Call) : Bool + context_description(node).try(&.starts_with?("at the boundary")) || false + end + + private def past_boundary_context?(node : Crystal::Call) : Bool + context_description(node).try(&.starts_with?("just past the boundary")) || false + end + + private def expected_failure_assertion_exists?(context_call : Crystal::Call) : Bool + return false unless block_node = context_call.block + + DetectExpectedFailureAssertion.new(block_node.body).perform? + end + + private def golden_case_exists?(list_of_child_calls : Array(Crystal::Call)) : Bool + list_of_child_calls.any? do |child_call| + child_call.name == "it" || golden_context?(child_call) + end + end + + private def golden_context?(node : Crystal::Call) : Bool + return false unless node.name == "context" + return true unless description = context_description(node) + + !description.starts_with?("at the boundary") && + !description.starts_with?("just past the boundary") + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_behavior_describes.cr b/src/amber_lsp/rules/library/support/collect_behavior_describes.cr new file mode 100644 index 0000000..a24960f --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_behavior_describes.cr @@ -0,0 +1,64 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects behavior describe calls from a Crystal syntax tree. + class CollectBehaviorDescribes < Crystal::Visitor + # Requires `::` because a one-word string such as "Behavior" is usually a + # heading, and a heading must leave the enclosing type in place. + NAMESPACED_TYPE_NAME_PATTERN = /\A(?:::[A-Z]\w*(?:::[A-Z]\w*)*|[A-Z]\w*(?:::[A-Z]\w*)+)\z/ + + getter list_of_describes = [] of Crystal::Call + @list_of_enclosing_type_names = [] of String + @owner_type_name_by_node_id = {} of UInt64 => String + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects method behavior describes from *root_node*. + def perform : ListOfCrystalCalls + @root_node.accept(self) + list_of_describes + end + + # Returns the type named by the describe enclosing *describe_call*, if any. + def owner_type_name_for(describe_call : Crystal::Call) : String? + @owner_type_name_by_node_id[describe_call.object_id]? + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + if ReadBehaviorSelector.new(node).perform + list_of_describes << node + if enclosing_type_name = @list_of_enclosing_type_names.last? + @owner_type_name_by_node_id[node.object_id] = enclosing_type_name + end + end + if described_type_name = described_type_name_for(node) + @list_of_enclosing_type_names << described_type_name + end + true + end + + # :nodoc: + def end_visit(node : Crystal::Call) : Nil + @list_of_enclosing_type_names.pop if described_type_name_for(node) + end + + private def described_type_name_for(node : Crystal::Call) : String? + return unless node.name == "describe" + return unless described_node = node.args.first? + + if described_node.is_a?(Crystal::Path) + described_node.names.join("::") + elsif described_node.is_a?(Crystal::StringLiteral) && described_node.value.matches?(NAMESPACED_TYPE_NAME_PATTERN) + described_node.value.lchop("::") + end + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_calls_within_method_body.cr b/src/amber_lsp/rules/library/support/collect_calls_within_method_body.cr new file mode 100644 index 0000000..2e21654 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_calls_within_method_body.cr @@ -0,0 +1,42 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects receiverless and `self` calls from one method body. + class CollectCallsWithinMethodBody < Crystal::Visitor + getter list_of_called_method_names = [] of String + + # Initializes the collector with *method_body*. + def initialize(@method_body : Crystal::ASTNode) + end + + # Collects eligible call names from *method_body*. + def perform : ListOfStrings + @method_body.accept(self) + list_of_called_method_names.uniq + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # Leaves nested type and method bodies outside the caller's edges. + def visit(node : Crystal::Def | Crystal::ClassDef | Crystal::ModuleDef | Crystal::EnumDef) : Bool + false + end + + # Collects a receiverless call or a call whose receiver is `self`. + def visit(node : Crystal::Call) : Bool + if node.obj.nil? || self_receiver?(node.obj) + list_of_called_method_names << node.name + end + true + end + + private def self_receiver?(receiver : Crystal::ASTNode?) : Bool + return false unless receiver_node = receiver.as?(Crystal::Var) + + receiver_node.name == "self" + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_core_type_reopens.cr b/src/amber_lsp/rules/library/support/collect_core_type_reopens.cr new file mode 100644 index 0000000..d7b1cf4 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_core_type_reopens.cr @@ -0,0 +1,56 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects top-level reopenings of configured core classes and modules. + class CollectCoreTypeReopens < Crystal::Visitor + getter list_of_reopens = [] of Tuple(Crystal::ASTNode, String) + + # Initializes the collector with *root_node* and core type names. + def initialize(@root_node : Crystal::ASTNode, @list_of_core_type_names : Array(String)) + @list_of_enclosing_type_names = [] of String + end + + # Collects core type reopenings from *root_node*. + def perform : ListOfCoreTypeReopens + @root_node.accept(self) + list_of_reopens + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # Collects class definitions that reopen a configured core type. + def visit(node : Crystal::ClassDef) : Bool + collect_reopening(node, node.name) + @list_of_enclosing_type_names << node.name.names.join("::") + true + end + + # Collects module definitions that reopen a configured core type. + def visit(node : Crystal::ModuleDef) : Bool + collect_reopening(node, node.name) + @list_of_enclosing_type_names << node.name.names.join("::") + true + end + + # Leaves the enclosing class scope after visiting its body. + def end_visit(node : Crystal::ClassDef) : Nil + @list_of_enclosing_type_names.pop + end + + # Leaves the enclosing module scope after visiting its body. + def end_visit(node : Crystal::ModuleDef) : Nil + @list_of_enclosing_type_names.pop + end + + private def collect_reopening(node : Crystal::ASTNode, name_path : Crystal::Path) : Nil + full_name = name_path.names.join("::") + return unless @list_of_core_type_names.includes?(full_name) + return if name_path.names.size == 1 && !name_path.global? && !@list_of_enclosing_type_names.empty? + + list_of_reopens << {node, full_name} + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_crystal_method_calls.cr b/src/amber_lsp/rules/library/support/collect_crystal_method_calls.cr new file mode 100644 index 0000000..724a060 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_crystal_method_calls.cr @@ -0,0 +1,29 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects method calls in a Crystal syntax tree. + class CollectCrystalMethodCalls < Crystal::Visitor + getter list_of_calls = [] of Crystal::Call + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects method calls from *root_node* and its descendants. + def perform : ListOfCrystalCalls + @root_node.accept(self) + list_of_calls + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + list_of_calls << node + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_method_describe_selectors.cr b/src/amber_lsp/rules/library/support/collect_method_describe_selectors.cr new file mode 100644 index 0000000..3be80ce --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_method_describe_selectors.cr @@ -0,0 +1,32 @@ +require "compiler/crystal/syntax" +require "set" + +module AmberLSP::Rules::Library::Support + # Collects instance and class method selectors from spec syntax trees. + class CollectMethodDescribeSelectors < Crystal::Visitor + getter list_of_selectors = Set(String).new + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects method selectors from *root_node* and its descendants. + def perform : SetOfMethodDescribeSelectors + @root_node.accept(self) + list_of_selectors + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + if selector = ReadBehaviorSelector.new(node).perform + list_of_selectors << selector + end + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_paths_from_crystal_ast.cr b/src/amber_lsp/rules/library/support/collect_paths_from_crystal_ast.cr new file mode 100644 index 0000000..f0644ef --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_paths_from_crystal_ast.cr @@ -0,0 +1,29 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects path constants from a Crystal AST. + class CollectPathsFromCrystalAST < Crystal::Visitor + getter list_of_paths = [] of Crystal::Path + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects paths from *root_node* and its descendants. + def perform : ListOfCrystalPaths + @root_node.accept(self) + list_of_paths + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Path) : Bool + list_of_paths << node + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_public_methods.cr b/src/amber_lsp/rules/library/support/collect_public_methods.cr new file mode 100644 index 0000000..cd0e271 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_public_methods.cr @@ -0,0 +1,67 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects documented public method definitions from a Crystal AST. + class CollectPublicMethods < Crystal::Visitor + getter list_of_methods = [] of Crystal::Def + + # Initializes the collector with *root_node* and its source text. + def initialize(@root_node : Crystal::ASTNode, @content : String) + @source_annotations = ReadSourceAnnotations.new(@content) + @list_of_type_visibility = [] of Bool + @list_of_type_nodoc = [] of Bool + end + + # Collects documented public methods from *root_node*. + def perform : ListOfPublicMethods + @root_node.accept(self) + list_of_methods + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # Applies explicit visibility to a declaration before visiting it. + def visit(node : Crystal::VisibilityModifier) : Bool + expression = node.exp + if expression.is_a?(Crystal::Def) || expression.is_a?(Crystal::ClassDef) || + expression.is_a?(Crystal::ModuleDef) || expression.is_a?(Crystal::EnumDef) + expression.visibility = node.modifier + end + true + end + + # Tracks visibility and nodoc comments for nested types. + def visit(node : Crystal::ClassDef | Crystal::ModuleDef | Crystal::EnumDef) : Bool + @list_of_type_visibility << node.visibility.public? + has_nodoc = node.location.try { |location| @source_annotations.has_nodoc_comment_at?(location.line_number) } || false + @list_of_type_nodoc << has_nodoc + true + end + + # :nodoc: + def end_visit(node : Crystal::ClassDef | Crystal::ModuleDef | Crystal::EnumDef) : Nil + @list_of_type_visibility.pop + @list_of_type_nodoc.pop + end + + # Collects methods that remain public through every containing type. + def visit(method_node : Crystal::Def) : Bool + if public_method?(method_node) + list_of_methods << method_node + end + true + end + + private def public_method?(method_node : Crystal::Def) : Bool + return false unless method_node.visibility.public? + return false unless @list_of_type_visibility.all? { |is_public| is_public } + return false if @list_of_type_nodoc.any? { |has_nodoc| has_nodoc } + return false unless location = method_node.location + + !@source_annotations.has_nodoc_comment_at?(location.line_number) + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_receiverless_raise_calls.cr b/src/amber_lsp/rules/library/support/collect_receiverless_raise_calls.cr new file mode 100644 index 0000000..8784267 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_receiverless_raise_calls.cr @@ -0,0 +1,29 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects receiverless raise calls from a Crystal AST. + class CollectReceiverlessRaiseCalls < Crystal::Visitor + getter list_of_raise_calls = [] of Crystal::Call + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects receiverless raise calls from *root_node* and its descendants. + def perform : ListOfCrystalCalls + @root_node.accept(self) + list_of_raise_calls + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + list_of_raise_calls << node if node.obj.nil? && node.name == "raise" + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_rescue_clauses.cr b/src/amber_lsp/rules/library/support/collect_rescue_clauses.cr new file mode 100644 index 0000000..b6f707f --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_rescue_clauses.cr @@ -0,0 +1,29 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects rescue clauses from a Crystal syntax tree. + class CollectRescueClauses < Crystal::Visitor + getter list_of_rescue_clauses = [] of Crystal::Rescue + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects rescue clauses from *root_node* and its descendants. + def perform : ListOfRescueClauses + @root_node.accept(self) + list_of_rescue_clauses + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Rescue) : Bool + list_of_rescue_clauses << node + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_type_casts.cr b/src/amber_lsp/rules/library/support/collect_type_casts.cr new file mode 100644 index 0000000..a11a38f --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_type_casts.cr @@ -0,0 +1,29 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects unchecked cast nodes from a Crystal syntax tree. + class CollectTypeCasts < Crystal::Visitor + getter list_of_type_casts = [] of Crystal::Cast + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects casts from *root_node* and its descendants. + def perform : ListOfTypeCasts + @root_node.accept(self) + list_of_type_casts + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Cast) : Bool + list_of_type_casts << node + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_typed_raise_calls.cr b/src/amber_lsp/rules/library/support/collect_typed_raise_calls.cr new file mode 100644 index 0000000..57d55a2 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_typed_raise_calls.cr @@ -0,0 +1,34 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Collects receiverless raises with string messages outside compile-time macros. + class CollectTypedRaiseCalls < Crystal::Visitor + getter list_of_raise_calls = [] of Crystal::Call + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects eligible receiverless raise calls from *root_node*. + def perform : ListOfCrystalCalls + @root_node.accept(self) + list_of_raise_calls + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # Skips macro expressions because they run during compilation. + def visit(node : Crystal::MacroExpression) : Bool + false + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + list_of_raise_calls << node if node.obj.nil? && node.name == "raise" + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/collect_vague_internal_names.cr b/src/amber_lsp/rules/library/support/collect_vague_internal_names.cr new file mode 100644 index 0000000..85fb058 --- /dev/null +++ b/src/amber_lsp/rules/library/support/collect_vague_internal_names.cr @@ -0,0 +1,126 @@ +require "compiler/crystal/syntax" +require "set" + +module AmberLSP::Rules::Library::Support + # Collects vague local names, block parameters, and private method parameters. + class CollectVagueInternalNames < Crystal::Visitor + VAGUE_NAMES = %w[tmp temp val vals res ret retval obj arr ary lst str num idx info data item items stuff thing things m x y z] + + getter list_of_findings = [] of Tuple(Crystal::ASTNode, String) + + # Initializes the collector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + @list_of_argument_names_by_scope = [] of Set(String) + @list_of_local_names_by_scope = [] of Set(String) + start_scope + end + + # Collects vague names from *root_node*. + def perform : ListOfVagueNameFindings + @root_node.accept(self) + list_of_findings + end + + # Applies explicit visibility before visiting a method definition. + def visit(node : Crystal::VisibilityModifier) : Bool + expression = node.exp + if expression.is_a?(Crystal::Def) + expression.visibility = node.modifier + end + true + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # Starts the local and argument scopes for a method definition. + def visit(node : Crystal::Def) : Bool + start_scope + node.args.each do |argument_node| + add_argument_name(argument_node.name) + if node.visibility.private? || node.name == "->" + record_vague_name(argument_node, argument_node.name) + end + end + if block_argument = node.block_arg + add_argument_name(block_argument.name) + if node.visibility.private? + record_vague_name(block_argument, block_argument.name) + end + end + true + end + + # Ends the local and argument scopes for a method definition. + def end_visit(node : Crystal::Def) : Nil + finish_scope + end + + # Starts a local scope and checks its block parameters. + def visit(node : Crystal::Block) : Bool + start_scope + node.args.each do |argument_node| + add_argument_name(argument_node.name) + record_vague_name(argument_node, argument_node.name) + end + true + end + + # Ends the local scope for a block. + def end_visit(node : Crystal::Block) : Nil + finish_scope + end + + # Collects a vague local assignment target once per scope. + def visit(node : Crystal::Assign) : Bool + if local_variable = node.target.as?(Crystal::Var) + record_local_variable(local_variable) + end + true + end + + private def start_scope : Nil + @list_of_argument_names_by_scope << Set(String).new + @list_of_local_names_by_scope << Set(String).new + end + + private def finish_scope : Nil + @list_of_argument_names_by_scope.pop + @list_of_local_names_by_scope.pop + end + + private def add_argument_name(argument_name : String) : Nil + if argument_names = @list_of_argument_names_by_scope.last? + argument_names << argument_name + end + end + + private def record_local_variable(local_variable : Crystal::Var) : Nil + local_name = local_variable.name + return unless vague_name?(local_name) + + argument_names = @list_of_argument_names_by_scope.last? + return if argument_names && argument_names.includes?(local_name) + return unless local_names = @list_of_local_names_by_scope.last? + return if local_names.includes?(local_name) + + local_names << local_name + list_of_findings << {local_variable, local_name} + end + + private def record_vague_name(node : Crystal::ASTNode, name : String) : Nil + return unless vague_name?(name) + + list_of_findings << {node, name} + end + + private def vague_name?(name : String) : Bool + return false if name.starts_with?("_") + return true if VAGUE_NAMES.includes?(name) + + name.size == 1 && !name.in?(%w[i j k]) + end + end +end diff --git a/src/amber_lsp/rules/library/support/create_diagnostic_for_ast_node.cr b/src/amber_lsp/rules/library/support/create_diagnostic_for_ast_node.cr new file mode 100644 index 0000000..e753051 --- /dev/null +++ b/src/amber_lsp/rules/library/support/create_diagnostic_for_ast_node.cr @@ -0,0 +1,34 @@ +module AmberLSP::Rules::Library::Support + # Creates a diagnostic at a Crystal AST node's source location. + class CreateDiagnosticForASTNode + # Initializes the diagnostic builder with its AST node and message details. + def initialize( + @node : Crystal::ASTNode, + @content : String, + @rule_id : String, + @severity : AmberLSP::Rules::Severity, + @message : String, + @source : String = "amber-lsp", + ) + end + + # Creates a diagnostic or returns nil when the node has no source location. + def perform : AmberLSP::Rules::Diagnostic? + return unless location = @node.location + + line_index = location.line_number - 1 + start_character = location.column_number - 1 + end_character = start_character + 1 + if source_line = @content.lines[line_index]? + line_length = source_line.size.to_i32 + end_character = line_length if end_character > line_length + end + + range = AmberLSP::Rules::TextRange.new( + AmberLSP::Rules::Position.new(line_index.to_i32, start_character.to_i32), + AmberLSP::Rules::Position.new(line_index.to_i32, end_character.to_i32), + ) + AmberLSP::Rules::Diagnostic.new(range, @severity, @rule_id, @message, @source) + end + end +end diff --git a/src/amber_lsp/rules/library/support/detect_cause_argument.cr b/src/amber_lsp/rules/library/support/detect_cause_argument.cr new file mode 100644 index 0000000..8c13f30 --- /dev/null +++ b/src/amber_lsp/rules/library/support/detect_cause_argument.cr @@ -0,0 +1,33 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Detects a named cause argument in a Crystal AST. + class DetectCauseArgument < Crystal::Visitor + getter? found_cause_argument = false + + # Initializes the detector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Returns whether *root_node* contains a `cause:` argument. + def perform? : Bool + @root_node.accept(self) + found_cause_argument? + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::NamedArgument) : Bool + if node.name == "cause" + @found_cause_argument = true + return false + end + + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/detect_expected_failure_assertion.cr b/src/amber_lsp/rules/library/support/detect_expected_failure_assertion.cr new file mode 100644 index 0000000..ebd7ccd --- /dev/null +++ b/src/amber_lsp/rules/library/support/detect_expected_failure_assertion.cr @@ -0,0 +1,35 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Detects expected-failure assertions in a just-past-the-boundary context. + class DetectExpectedFailureAssertion < Crystal::Visitor + EXPECTED_FAILURE_CALLS = %w[expect_raises should_not be_nil be_false be_empty] + + getter? found = false + + # Initializes the detector with *context_body*. + def initialize(@context_body : Crystal::ASTNode) + end + + # Returns whether *context_body* contains an expected-failure assertion. + def perform? : Bool + @context_body.accept(self) + found? + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + if EXPECTED_FAILURE_CALLS.includes?(node.name) + @found = true + return false + end + + true + end + end +end diff --git a/src/amber_lsp/rules/library/support/detect_spec_assertion.cr b/src/amber_lsp/rules/library/support/detect_spec_assertion.cr new file mode 100644 index 0000000..8ab6c19 --- /dev/null +++ b/src/amber_lsp/rules/library/support/detect_spec_assertion.cr @@ -0,0 +1,43 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Detects supported assertions in a spec example. + class DetectSpecAssertion < Crystal::Visitor + ASSERTION_METHOD_NAMES = %w[should should_not expect_raises fail] + + getter? found = false + + # Initializes the detector with *example_body* and assertion prefixes. + def initialize(@example_body : Crystal::ASTNode, @list_of_assertion_prefixes : Array(String)) + end + + # Returns whether *example_body* contains a supported assertion. + def perform? : Bool + @example_body.accept(self) + found? + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Call) : Bool + if assertion_call?(node.name) + @found = true + return false + end + + true + end + + private def assertion_call?(call_name : String) : Bool + return true if ASSERTION_METHOD_NAMES.includes?(call_name) + + @list_of_assertion_prefixes.any? do |prefix| + !prefix.empty? && call_name.starts_with?(prefix) + end + end + end +end diff --git a/src/amber_lsp/rules/library/support/detect_unsynchronized_class_variable_collections.cr b/src/amber_lsp/rules/library/support/detect_unsynchronized_class_variable_collections.cr new file mode 100644 index 0000000..257f250 --- /dev/null +++ b/src/amber_lsp/rules/library/support/detect_unsynchronized_class_variable_collections.cr @@ -0,0 +1,62 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Detects collection-valued class variables without file-level synchronization. + class DetectUnsynchronizedClassVariableCollections < Crystal::Visitor + getter list_of_findings = [] of Crystal::ASTNode + getter? has_synchronization_primitive = false + + # Initializes the detector with *root_node*. + def initialize(@root_node : Crystal::ASTNode) + end + + # Collects collection-valued class variables and synchronization markers. + def perform : DetectUnsynchronizedClassVariableCollections + @root_node.accept(self) + self + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # :nodoc: + def visit(node : Crystal::Path) : Bool + last_name = node.names.last? + @has_synchronization_primitive = true if last_name.try(&.in?(%w[Mutex Atomic])) + true + end + + # :nodoc: + def visit(node : Crystal::Assign) : Bool + if node.target.is_a?(Crystal::ClassVar) && collection_value?(node.value) + list_of_findings << node + end + true + end + + # :nodoc: + def visit(node : Crystal::TypeDeclaration) : Bool + if node.var.is_a?(Crystal::ClassVar) && collection_type?(node.declared_type) + list_of_findings << node + end + true + end + + private def collection_value?(node : Crystal::ASTNode) : Bool + return true if node.is_a?(Crystal::ArrayLiteral) || node.is_a?(Crystal::HashLiteral) + return false unless call_node = node.as?(Crystal::Call) + + collection_type?(call_node.obj) || (call_node.obj.nil? && call_node.name.in?(%w[Array Hash Set])) + end + + private def collection_type?(node : Crystal::ASTNode?) : Bool + return false unless node + return node.names.last?.try(&.in?(%w[Array Hash Set])) || false if node.is_a?(Crystal::Path) + return collection_type?(node.name) if node.is_a?(Crystal::Generic) + + false + end + end +end diff --git a/src/amber_lsp/rules/library/support/git_changed_lines.cr b/src/amber_lsp/rules/library/support/git_changed_lines.cr new file mode 100644 index 0000000..f35c21f --- /dev/null +++ b/src/amber_lsp/rules/library/support/git_changed_lines.cr @@ -0,0 +1,100 @@ +require "set" + +module AmberLSP::Rules::Library::Support + # Holds lines added relative to a git merge base. + class GitChangedLines + HUNK_PATTERN = /^@@ -[0-9]+(?:,[0-9]+)? \+([0-9]+)(?:,([0-9]+))? @@/ + + @added_lines_by_path : Hash(String, Set(Int32)) + + # Initializes the line set with *root_path* and *reference*. + def initialize(@root_path : String, @reference : String) + @added_lines_by_path = Hash(String, Set(Int32)).new + end + + # Reads working-tree additions since the merge base of *reference* and HEAD. + def perform : GitChangedLines + merge_base = run_git("merge-base", [@reference, "HEAD"]).strip + # --relative keeps paths root-relative when the root is below the git top + # level, and the explicit prefixes hold up against a user's diff settings. + diff_text = run_git( + "diff", + ["--relative", "--src-prefix=a/", "--dst-prefix=b/", "--no-ext-diff", "--unified=0", "--no-color", merge_base], + ) + parse_added_lines(diff_text) + self + end + + # Returns whether *line_number* was added in *relative_path*. + def includes?(relative_path : String, line_number : Int32) : Bool + normalized_path = relative_path.lchop("./") + @added_lines_by_path[normalized_path]?.try(&.includes?(line_number)) || false + end + + # Returns paths with at least one added line. + def changed_paths : Support::ListOfStrings + @added_lines_by_path.keys + end + + # Returns whether an added line overlaps the inclusive method line range. + def includes_any?(relative_path : String, first_line : Int32, last_line : Int32) : Bool + return false if first_line > last_line + + normalized_path = relative_path.lchop("./") + return false unless line_numbers = @added_lines_by_path[normalized_path]? + + line_numbers.any? do |line_number| + line_number >= first_line && line_number <= last_line + end + end + + private def run_git(command_name : String, command_arguments : Array(String)) : String + output_buffer = IO::Memory.new + error_buffer = IO::Memory.new + status = Process.run( + "git", + ["-c", "core.quotePath=false", command_name] + command_arguments, + chdir: @root_path, + output: output_buffer, + error: error_buffer, + ) + return output_buffer.to_s if status.success? + + details = error_buffer.to_s.strip + details = output_buffer.to_s.strip if details.empty? + message = details.empty? ? "git #{command_name} failed" : "git #{command_name} failed: #{details}" + raise GitCommandError.new(message) + rescue ex : IO::Error + raise GitCommandError.new("git #{command_name} could not run: #{ex.message}") + end + + private def parse_added_lines(diff_text : String) : Nil + current_path : String? = nil + diff_text.each_line do |diff_line| + if diff_line.starts_with?("+++ b/") + # Git ends the header with a tab when the path contains a space. + current_path = diff_line.lchop("+++ b/").rstrip('\t') + current_path = nil if current_path == "/dev/null" + next + end + + next unless current_path + next unless hunk_match = HUNK_PATTERN.match(diff_line) + + first_added_line = hunk_match[1].to_i + added_line_count = hunk_match[2]?.try(&.to_i) || 1 + next if added_line_count == 0 + + path_line_numbers = @added_lines_by_path[current_path]? + unless path_line_numbers + path_line_numbers = Set(Int32).new + @added_lines_by_path[current_path] = path_line_numbers + end + + (first_added_line...first_added_line + added_line_count).each do |line_number| + path_line_numbers << line_number + end + end + end + end +end diff --git a/src/amber_lsp/rules/library/support/git_command_error.cr b/src/amber_lsp/rules/library/support/git_command_error.cr new file mode 100644 index 0000000..04807b3 --- /dev/null +++ b/src/amber_lsp/rules/library/support/git_command_error.cr @@ -0,0 +1,5 @@ +module AmberLSP::Rules::Library::Support + # Reports a failed git command used by the library check. + class GitCommandError < Exception + end +end diff --git a/src/amber_lsp/rules/library/support/index_methods_from_source.cr b/src/amber_lsp/rules/library/support/index_methods_from_source.cr new file mode 100644 index 0000000..87e1e1e --- /dev/null +++ b/src/amber_lsp/rules/library/support/index_methods_from_source.cr @@ -0,0 +1,111 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Indexes method definitions, visibility, behavior, and calls from one source file. + class IndexMethodsFromSource < Crystal::Visitor + getter list_of_method_definitions = [] of MethodDefinition + + # Initializes the indexer with source, path, and changed-line information. + def initialize( + @root_node : Crystal::ASTNode, + @relative_path : String, + @source_code : String, + @changed_lines : GitChangedLines, + ) + @source_annotations = ReadSourceAnnotations.new(@source_code) + @list_of_enclosing_type_names = [] of String + @list_of_type_visibility = [] of Bool + @list_of_type_nodoc = [] of Bool + end + + # Collects method definitions from *root_node*. + def perform : ListOfMethodDefinitions + @root_node.accept(self) + list_of_method_definitions + end + + # :nodoc: + def visit(node : Crystal::ASTNode) : Bool + true + end + + # Applies explicit visibility before visiting its declaration. + def visit(node : Crystal::VisibilityModifier) : Bool + expression = node.exp + if expression.is_a?(Crystal::Def) || expression.is_a?(Crystal::ClassDef) || + expression.is_a?(Crystal::ModuleDef) || expression.is_a?(Crystal::EnumDef) + expression.visibility = node.modifier + end + true + end + + # Tracks class and module names, visibility, and nodoc state. + def visit(node : Crystal::ClassDef | Crystal::ModuleDef | Crystal::EnumDef) : Bool + @list_of_enclosing_type_names << full_type_name(node.name) + @list_of_type_visibility << node.visibility.public? + has_nodoc = node.location.try { |location| @source_annotations.has_nodoc_comment_at?(location.line_number) } || false + @list_of_type_nodoc << has_nodoc + true + end + + # Leaves the current type after its definitions are indexed. + def end_visit(node : Crystal::ClassDef | Crystal::ModuleDef | Crystal::EnumDef) : Nil + @list_of_enclosing_type_names.pop + @list_of_type_visibility.pop + @list_of_type_nodoc.pop + end + + # Indexes a method and its receiverless or self calls. + def visit(method_node : Crystal::Def) : Bool + list_of_method_definitions << method_definition_for(method_node) + true + end + + private def method_definition_for(method_node : Crystal::Def) : MethodDefinition + location = method_node.location + end_location = method_node.end_location + method_changed = if location && end_location + @changed_lines.includes_any?( + @relative_path, + location.line_number, + end_location.line_number, + ) + else + false + end + has_nodoc_method = location.try { |method_location| @source_annotations.has_nodoc_comment_at?(method_location.line_number) } || false + owner_type_name = @list_of_enclosing_type_names.last? || "Object" + has_public_type = @list_of_type_visibility.all? { |has_public_visibility| has_public_visibility } + has_nodoc_type = @list_of_type_nodoc.any? { |type_has_nodoc| type_has_nodoc } + list_of_called_method_names = CollectCallsWithinMethodBody.new(method_node.body).perform + method_has_behavior = CheckMethodForBehavior.new(method_node.body).perform? + + MethodDefinition.new( + owner_type_name, + method_node.name, + method_node.visibility, + @relative_path, + @source_code, + method_node, + list_of_called_method_names, + !method_node.receiver.nil?, + method_changed, + method_has_behavior, + has_public_type, + has_nodoc_type, + has_nodoc_method, + ) + end + + private def full_type_name(name_path : Crystal::Path) : String + path_name = name_path.names.join("::") + return path_name if name_path.global? + return path_name if @list_of_enclosing_type_names.empty? + + enclosing_type_name = @list_of_enclosing_type_names.last + return path_name if path_name.starts_with?("#{enclosing_type_name}::") + + "#{enclosing_type_name}::#{path_name}" + end + end +end diff --git a/src/amber_lsp/rules/library/support/method_definition.cr b/src/amber_lsp/rules/library/support/method_definition.cr new file mode 100644 index 0000000..dea41d3 --- /dev/null +++ b/src/amber_lsp/rules/library/support/method_definition.cr @@ -0,0 +1,76 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Holds one method, its owner type, visibility, source, and local calls. + struct MethodDefinition + getter owner_type_name : String + getter method_name : String + getter visibility : Crystal::Visibility + getter relative_path : String + getter source_code : String + getter method_node : Crystal::Def + getter list_of_called_method_names : ListOfStrings + getter? class_method = false + getter? changed = false + getter? has_behavior = false + getter? has_public_type = false + getter? has_nodoc_type = false + getter? has_nodoc_method = false + + # Initializes the method record with its parsed declaration and context. + def initialize( + @owner_type_name : String, + @method_name : String, + @visibility : Crystal::Visibility, + @relative_path : String, + @source_code : String, + @method_node : Crystal::Def, + @list_of_called_method_names : ListOfStrings, + @class_method : Bool, + @changed : Bool, + @has_behavior : Bool, + @has_public_type : Bool, + @has_nodoc_type : Bool, + @has_nodoc_method : Bool, + ) + end + + # Returns the describe selector for this method. + def selector : String + return ".new" if method_name == "initialize" + return ".#{method_name}" if class_method? + + "##{method_name}" + end + + # Returns the key used to merge reopened type methods in the call graph. + def method_key : String + method_kind = class_method? ? "class" : "instance" + "#{owner_type_name}::#{method_kind}::#{method_name}" + end + + # Returns a source-unique identity for this declaration. + def definition_identity : String + line_number = method_node.location.try(&.line_number) || 0 + "#{relative_path}:#{line_number}:#{method_key}" + end + + # Returns whether this is a public method callers can expose in specs. + def public_caller? : Bool + has_public_type? && !has_nodoc_type? && visibility.public? && !has_nodoc_method? + end + + # Returns whether this is a private or protected implementation method. + def private_or_protected? : Bool + visibility.private? || visibility.protected? + end + + # Returns whether this changed behavior needs collars. A `:nodoc:` method is internal, + # like a private one, so it is reached through its public callers. + def changed_behavior_method? : Bool + changed? && has_behavior? && has_public_type? + end + end + + alias ListOfMethodDefinitions = Array(MethodDefinition) +end diff --git a/src/amber_lsp/rules/library/support/parse_crystal_source.cr b/src/amber_lsp/rules/library/support/parse_crystal_source.cr new file mode 100644 index 0000000..270ecb0 --- /dev/null +++ b/src/amber_lsp/rules/library/support/parse_crystal_source.cr @@ -0,0 +1,16 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Parses Crystal source and returns nil when its syntax is incomplete. + class ParseCrystalSource + def initialize(@content : String) + end + + # Parses *content* as a Crystal syntax tree. + def perform : Crystal::ASTNode? + Crystal::Parser.new(@content).parse + rescue Crystal::SyntaxException + nil + end + end +end diff --git a/src/amber_lsp/rules/library/support/read_behavior_describes.cr b/src/amber_lsp/rules/library/support/read_behavior_describes.cr new file mode 100644 index 0000000..94bb433 --- /dev/null +++ b/src/amber_lsp/rules/library/support/read_behavior_describes.cr @@ -0,0 +1,36 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Reads all method behavior describes under a project's spec directory. + class ReadBehaviorDescribes + # Initializes the reader with *root_path*. + def initialize(@root_path : String) + end + + # Reads parsed behavior describes from every spec source file. + def perform : ListOfBehaviorDescribes + list_of_describes = [] of BehaviorDescribe + spec_pattern = File.join(@root_path, "spec", "**", "*_spec.cr") + + Dir.glob(spec_pattern).each do |spec_path| + source_code = File.read(spec_path) + syntax_tree = ParseCrystalSource.new(source_code).perform + next unless syntax_tree + + describe_collector = CollectBehaviorDescribes.new(syntax_tree) + describe_collector.perform.each do |describe_call| + if selector = ReadBehaviorSelector.new(describe_call).perform + list_of_describes << BehaviorDescribe.new( + selector, + source_code, + describe_call, + describe_collector.owner_type_name_for(describe_call), + ) + end + end + end + + list_of_describes + end + end +end diff --git a/src/amber_lsp/rules/library/support/read_behavior_selector.cr b/src/amber_lsp/rules/library/support/read_behavior_selector.cr new file mode 100644 index 0000000..5cb1c60 --- /dev/null +++ b/src/amber_lsp/rules/library/support/read_behavior_selector.cr @@ -0,0 +1,21 @@ +require "compiler/crystal/syntax" + +module AmberLSP::Rules::Library::Support + # Reads an instance or class method selector from a describe call. + class ReadBehaviorSelector + # Initializes the selector reader with *describe_call*. + def initialize(@describe_call : Crystal::Call) + end + + # Returns the behavior selector or nil for other describes. + def perform : String? + return unless @describe_call.name == "describe" + return unless description_node = @describe_call.args.first?.try(&.as?(Crystal::StringLiteral)) + + description = description_node.value + return unless description.starts_with?("#") || description.starts_with?(".") + + description + end + end +end diff --git a/src/amber_lsp/rules/library/support/read_source_annotations.cr b/src/amber_lsp/rules/library/support/read_source_annotations.cr new file mode 100644 index 0000000..0fa162b --- /dev/null +++ b/src/amber_lsp/rules/library/support/read_source_annotations.cr @@ -0,0 +1,34 @@ +module AmberLSP::Rules::Library::Support + # Reads line comments that mark source declarations as internal or exempt. + class ReadSourceAnnotations + # Initializes the reader with *content*. + def initialize(@content : String) + end + + # Returns whether a declaration at *line_number* has a preceding nodoc comment. + def has_nodoc_comment_at?(line_number : Int32) : Bool + line_index = line_number - 2 + while line_index >= 0 + source_line = @content.lines[line_index]?.try(&.strip) + return false unless source_line && source_line.starts_with?("#") + return true if source_line.includes?(":nodoc:") + + line_index -= 1 + end + false + end + + # Returns a collar exemption reason immediately above *line_number*. + def collar_exemption_reason_at(line_number : Int32) : String? + line_index = line_number - 2 + return if line_index < 0 + return unless source_line = @content.lines[line_index]? + + comment_parts = source_line.strip.split(',', 2) + return unless comment_parts.size == 2 + return unless comment_parts[0].strip == "# collar: none" + + comment_parts[1].strip + end + end +end diff --git a/src/amber_lsp/rules/library/swallowed_rescue.cr b/src/amber_lsp/rules/library/swallowed_rescue.cr new file mode 100644 index 0000000..ef3655e --- /dev/null +++ b/src/amber_lsp/rules/library/swallowed_rescue.cr @@ -0,0 +1,98 @@ +module AmberLSP::Rules::Library + # Reports broad rescue clauses that swallow errors or discard their cause. + class SwallowedRescue < AmberLSP::Rules::BaseRule + MESSAGE = "Reraise or rescue a specific error" + CAUSE_MESSAGE = "Pass cause: when converting a broad rescue into a new error" + + # Returns this rule's stable identifier. + def id : String + "library/swallowed-rescue" + end + + # Describes the broad rescue policy. + def description : String + "Disallows swallowing broad rescue failures or dropping their cause" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports untyped or `Exception` rescues that do not preserve the failure. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectRescueClauses.new(syntax_tree).perform.each do |rescue_clause| + next unless broad_rescue?(rescue_clause) + + list_of_raise_calls = Support::CollectReceiverlessRaiseCalls.new(rescue_clause.body).perform + message = message_for_rescue(rescue_clause, list_of_raise_calls) + next unless message + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + rescue_clause, + content, + id, + default_severity, + message, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + + private def broad_rescue?(rescue_clause : Crystal::Rescue) : Bool + return true unless rescue_types = rescue_clause.types + return true if rescue_types.empty? + + rescue_types.any? do |rescue_type| + rescue_type.is_a?(Crystal::Path) && rescue_type.names == ["Exception"] + end + end + + private def message_for_rescue( + rescue_clause : Crystal::Rescue, + list_of_raise_calls : Support::ListOfCrystalCalls, + ) : String? + return MESSAGE if list_of_raise_calls.empty? + return if list_of_raise_calls.all? { |raise_call| cause_preserved?(raise_call, rescue_clause.name) } + + CAUSE_MESSAGE + end + + private def cause_preserved?(raise_call : Crystal::Call, rescue_name : String?) : Bool + return true if bare_raise?(raise_call) + return true if re_raises_rescued_value?(raise_call, rescue_name) + + Support::DetectCauseArgument.new(raise_call).perform? + end + + private def bare_raise?(raise_call : Crystal::Call) : Bool + raise_call.args.empty? && raise_call.named_args.try(&.empty?) != false + end + + private def re_raises_rescued_value?(raise_call : Crystal::Call, rescue_name : String?) : Bool + return false unless rescue_name + return false unless raised_value = raise_call.args.first? + return false unless variable = raised_value.as?(Crystal::Var) + + variable.name == rescue_name + end + end +end diff --git a/src/amber_lsp/rules/library/typed_raise.cr b/src/amber_lsp/rules/library/typed_raise.cr new file mode 100644 index 0000000..f933282 --- /dev/null +++ b/src/amber_lsp/rules/library/typed_raise.cr @@ -0,0 +1,56 @@ +module AmberLSP::Rules::Library + # Reports raised strings so libraries can use named error types. + class TypedRaise < AmberLSP::Rules::BaseRule + MESSAGE = "Raise a named error instead of a string message" + + # Returns this rule's stable identifier. + def id : String + "library/typed-raise" + end + + # Describes the raised-string policy. + def description : String + "Disallows raising string messages instead of named errors" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports receiverless raises whose first argument is a string. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectTypedRaiseCalls.new(syntax_tree).perform.each do |raise_call| + first_argument = raise_call.args.first? + next unless first_argument.is_a?(Crystal::StringLiteral) || first_argument.is_a?(Crystal::StringInterpolation) + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + raise_call, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/unchecked_cast.cr b/src/amber_lsp/rules/library/unchecked_cast.cr new file mode 100644 index 0000000..f003c92 --- /dev/null +++ b/src/amber_lsp/rules/library/unchecked_cast.cr @@ -0,0 +1,63 @@ +module AmberLSP::Rules::Library + # Reports unchecked casts to named types. + class UncheckedCast < AmberLSP::Rules::BaseRule + MESSAGE = "Use a checked cast or narrow the value before casting" + + # Returns this rule's stable identifier. + def id : String + "library/unchecked-cast" + end + + # Describes the unchecked cast policy. + def description : String + "Disallows unchecked casts to named types" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports `.as(T)` casts to named types. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectTypeCasts.new(syntax_tree).perform.each do |cast_node| + next if cast_node.obj.is_a?(Crystal::NilLiteral) + next unless named_type?(cast_node.to) + + if diagnostic = Support::CreateDiagnosticForASTNode.new( + cast_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + + private def named_type?(type_node : Crystal::ASTNode) : Bool + return true if type_node.is_a?(Crystal::Path) + return false unless generic_node = type_node.as?(Crystal::Generic) + + generic_node.suffix != Crystal::Generic::Suffix::Asterisk && generic_node.name.is_a?(Crystal::Path) + end + end +end diff --git a/src/amber_lsp/rules/library/unsynchronized_class_variable.cr b/src/amber_lsp/rules/library/unsynchronized_class_variable.cr new file mode 100644 index 0000000..ef7dc67 --- /dev/null +++ b/src/amber_lsp/rules/library/unsynchronized_class_variable.cr @@ -0,0 +1,56 @@ +module AmberLSP::Rules::Library + # Reports mutable collection class variables without synchronization primitives. + class UnsynchronizedClassVariable < AmberLSP::Rules::BaseRule + MESSAGE = "Guard mutable class variable collections with Mutex or Atomic" + + # Returns this rule's stable identifier. + def id : String + "library/unsynchronized-class-variable" + end + + # Describes the shared collection policy. + def description : String + "Disallows unsynchronized collection-valued class variables" + end + + # Returns the default blocking severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Warning + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports collection class variables when the file has no synchronization marker. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + scan_result = Support::DetectUnsynchronizedClassVariableCollections.new(syntax_tree).perform + return [] of AmberLSP::Rules::Diagnostic if scan_result.has_synchronization_primitive? + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + scan_result.list_of_findings.each do |finding_node| + if diagnostic = Support::CreateDiagnosticForASTNode.new( + finding_node, + content, + id, + default_severity, + MESSAGE, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/rules/library/vague_internal_name.cr b/src/amber_lsp/rules/library/vague_internal_name.cr new file mode 100644 index 0000000..7e9dd93 --- /dev/null +++ b/src/amber_lsp/rules/library/vague_internal_name.cr @@ -0,0 +1,53 @@ +module AmberLSP::Rules::Library + # Reports vague local names, block parameters, and private method parameters. + class VagueInternalName < AmberLSP::Rules::BaseRule + MESSAGE = "Use a descriptive internal name instead of `%s`" + + # Returns this rule's stable identifier. + def id : String + "library/vague-internal-name" + end + + # Describes the internal naming policy. + def description : String + "Suggests descriptive names for internal variables and parameters" + end + + # Returns the default advisory severity. + def default_severity : AmberLSP::Rules::Severity + AmberLSP::Rules::Severity::Information + end + + # Selects library source files. + def applies_to : Support::ListOfStrings + ["src/**"] + end + + # Keeps the rule out of editor diagnostics for Amber applications. + def requires_amber_project? : Bool + false + end + + # Reports vague internal variable and parameter names. + def check(file_path : String, content : String) : Support::ListOfDiagnostics + return [] of AmberLSP::Rules::Diagnostic unless file_path.ends_with?(".cr") + + syntax_tree = Support::ParseCrystalSource.new(content).perform + return [] of AmberLSP::Rules::Diagnostic unless syntax_tree + + list_of_diagnostics = [] of AmberLSP::Rules::Diagnostic + Support::CollectVagueInternalNames.new(syntax_tree).perform.each do |node, variable_name| + if diagnostic = Support::CreateDiagnosticForASTNode.new( + node, + content, + id, + default_severity, + MESSAGE % variable_name, + ).perform + list_of_diagnostics << diagnostic + end + end + list_of_diagnostics + end + end +end diff --git a/src/amber_lsp/version.cr b/src/amber_lsp/version.cr index 2ad3153..3ab356e 100644 --- a/src/amber_lsp/version.cr +++ b/src/amber_lsp/version.cr @@ -16,10 +16,11 @@ module AmberLSP amber-lsp lookup QUERY look up a Crystal API: Type.method, Type#method, or Type amber-lsp hint read compiler output on stdin and print matching API card hints amber-lsp --check FILE.cr check one file with the Amber V2 rules + amber-lsp check [--since REF] [--all] [--carried-in PATH]... [--format text|json|github] [--advisory] [--root DIR] [PATH...] amber-lsp context [--root DIR] print the library rule packs detected for this project amber-lsp --version print the build: version, amber_cli release, commit - Add --help after lookup, hint, or context for its options. + Add --help after lookup, hint, check, or context for its options. Guide: https://github.com/amberframework/amber_cli/blob/main/docs/guides/ai-assistants.md TEXT