Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
# Changelog

## Unreleased

### Added

- `OXC.Lint.type_aware_rules/1` resolves the type-aware rules that `OXC.Lint.run/2` submits to tsgolint, so callers can batch files by their effective rules.

### Fixed

- Type-aware linting with `OXC.Lint.run/2` selects the type-aware rules of `all` and category filters, such as `"correctness" => :deny`, from the enabled plugins, instead of passing the category names to tsgolint as rules.
- Apply `all` first, then categories, then single rules, so a single rule's setting always overrides its category whatever the order of the `:rules` map.

## 0.18.0 - 2026-09-29

### Breaking changes
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,10 @@ The `:tsgolint` option can be a native `tsgolint` executable or the npm shim
from `oxlint-tsgolint`. `type_check: true` also reports TypeScript syntactic and
semantic diagnostics.

Categories select type-aware rules too. For example, `rules: %{"correctness" => :deny}`
runs the category's type-aware rules from the enabled `:plugins`, and single rule
settings override their category.

#### Custom Elixir Rules

Write project-specific lint rules in Elixir using the same AST from `OXC.parse/2`:
Expand Down
42 changes: 40 additions & 2 deletions lib/oxc/lint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,16 @@ defmodule OXC.Lint do
tsgolint: "tsgolint",
rules: %{"typescript/no-floating-promises" => :deny})

Categories select type-aware rules too, from the enabled `:plugins`, so
`rules: %{"correctness" => :deny}` runs `typescript/no-floating-promises`.

## Options

* `:rules` — map of rule names to severity (`:deny`, `:warn`, `:allow`).
Rule names follow oxlint conventions: `"eqeqeq"`, `"react/no-danger"`,
`"typescript/no-explicit-any"`, etc.
`"typescript/no-explicit-any"`, etc. Categories such as `"correctness"`
and `"all"` select every rule in them. `"all"` applies first, then
categories, then single rules, so a single rule overrides its category.

* `:plugins` — oxlint plugin names to enable, such as `["react", "jsx-a11y"]`,
accepting the same names and aliases as an oxlint config file.
Expand Down Expand Up @@ -87,7 +92,9 @@ defmodule OXC.Lint do
@spec run(iodata(), String.t(), [option()]) :: {:ok, [diagnostic()]} | {:error, [diagnostic()]}
def run(files, opts) when is_list(files) and is_list(opts) do
if Keyword.get(opts, :type_aware, false) do
OXC.Lint.TypeAware.run(files, opts)
with {:ok, rules} <- type_aware_rules(opts) do
OXC.Lint.TypeAware.run(files, Keyword.put(opts, :rules, rules))
end
else
{:error,
OXC.Diagnostic.from_raw(
Expand Down Expand Up @@ -121,6 +128,37 @@ defmodule OXC.Lint do
end
end

@doc """
Resolve the type-aware rules that `run/2` submits to tsgolint for these options.

`all` and category filters in `:rules` select type-aware rules from the enabled
`:plugins` through oxlint's rule registry. Rules named `typescript/*` keep their
options and override their categories. Other rules are syntax rules and are left out.

{:ok, %{"typescript/no-floating-promises" => :deny}} =
OXC.Lint.type_aware_rules(rules: %{"typescript/no-floating-promises" => :deny})
"""
@spec type_aware_rules(keyword()) ::
{:ok, %{String.t() => severity() | {severity(), term()}}} | {:error, [diagnostic()]}
def type_aware_rules(opts) do
rules = Keyword.get(opts, :rules, %{})
severities = Enum.map(rules, fn {name, config} -> {name, rule_severity(config)} end)

case OXC.Lint.Native.type_aware_rules(Keyword.get(opts, :plugins, []), severities) do
{:ok, selected} ->
named =
Map.filter(rules, fn {name, _config} -> String.starts_with?(name, "typescript/") end)

{:ok, Map.merge(Map.new(selected), named)}

{:error, message} ->
{:error, OXC.Diagnostic.from_raw([message], nil, nil)}
end
end

defp rule_severity({severity, _options}), do: severity
defp rule_severity(severity), do: severity

@doc """
Like `run/3` but raises on errors.
"""
Expand Down
4 changes: 4 additions & 0 deletions lib/oxc/lint/native/generated_stubs.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ defmodule OXC.Lint.Native.GeneratedStubs do
def lint(_source_term, _filename, _input) do
:erlang.nif_error(:nif_not_loaded)
end

def type_aware_rules(_plugins, _rules) do
:erlang.nif_error(:nif_not_loaded)
end
end
end
end
1 change: 1 addition & 0 deletions lib/oxc/lint/type_aware.ex
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ defmodule OXC.Lint.TypeAware do
@type option ::
{:type_aware, true}
| {:rules, %{String.t() => OXC.Lint.severity() | {OXC.Lint.severity(), term()}}}
| {:plugins, [OXC.Lint.plugin()]}
| {:tsgolint, String.t()}
| {:type_check, boolean()}
| {:report_syntactic, boolean()}
Expand Down
7 changes: 7 additions & 0 deletions native/oxc_lint_nif/src/generated_nifs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,10 @@ fn lint<'a>(
) -> NifResult<Term<'a>> {
lint_impl(env, source_term, filename, input)
}
#[rustler::nif(schedule = "DirtyCpu")]
fn type_aware_rules(
plugins: Vec<String>,
rules: Vec<(String, RuleSeverity)>,
) -> NifResult<Result<Vec<(String, RuleSeverity)>, String>> {
type_aware_rules_impl(plugins, rules)
}
73 changes: 65 additions & 8 deletions native/oxc_lint_nif/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,24 @@ fn allow_warn_deny(severity: RuleSeverity) -> AllowWarnDeny {
}
}

fn rule_severity(severity: AllowWarnDeny) -> RuleSeverity {
match severity {
AllowWarnDeny::Allow => RuleSeverity::Allow,
AllowWarnDeny::Warn => RuleSeverity::Warn,
AllowWarnDeny::Deny => RuleSeverity::Deny,
}
}

/// Filters apply `all` first, then categories, then single rules, so the most
/// specific setting wins whatever order the rules arrive in.
fn filter_rank(filter: &LintFilter) -> u8 {
match filter.kind() {
LintFilterKind::All => 0,
LintFilterKind::Category(_) => 1,
LintFilterKind::Generic(_) | LintFilterKind::Rule(_, _) => 2,
}
}

fn global_access(access: GlobalAccess) -> &'static str {
match access {
GlobalAccess::Readonly => "readonly",
Expand Down Expand Up @@ -119,14 +137,18 @@ fn build_lint_config(
.map_err(|e| format!("Failed to configure lint globals: {e}"))?
.with_builtin_plugins(lint_plugins);

for (rule_name, severity) in rules {
let severity = allow_warn_deny(*severity);
let filter_kind = LintFilterKind::parse(std::borrow::Cow::Owned(rule_name.clone()))
.map_err(|e| format!("Invalid rule filter '{rule_name}': {e}"))?;
let filter = LintFilter::new(severity, filter_kind)
.map_err(|e| format!("Invalid lint filter '{rule_name}': {e}"))?;
builder = builder.with_filters([&filter]);
}
let mut filters = rules
.iter()
.map(|(rule_name, severity)| {
let kind = LintFilterKind::parse(std::borrow::Cow::Owned(rule_name.clone()))
.map_err(|e| format!("Invalid rule filter '{rule_name}': {e}"))?;
LintFilter::new(allow_warn_deny(*severity), kind)
.map_err(|e| format!("Invalid lint filter '{rule_name}': {e}"))
})
.collect::<Result<Vec<_>, String>>()?;

filters.sort_by_key(filter_rank);
builder = builder.with_filters(&filters);

let config = builder
.build(&mut external_plugin_store)
Expand All @@ -144,6 +166,41 @@ fn build_lint_config(
})
}

/// The type-aware (tsgolint) rules that `all` and category filters in `rules`
/// select from `plugins`, with their severities, resolved through oxlint's rule
/// registry. Without such filters no rules are selected, so callers that name
/// rules individually run only those.
fn type_aware_rules_impl(
plugins: Vec<String>,
rules: Vec<(String, RuleSeverity)>,
) -> NifResult<Result<Vec<(String, RuleSeverity)>, String>> {
let selects_categories = rules.iter().any(|(name, _)| {
matches!(
LintFilterKind::parse(std::borrow::Cow::Owned(name.clone())),
Ok(LintFilterKind::All | LintFilterKind::Category(_))
)
});

if !selects_categories {
return Ok(Ok(Vec::new()));
}

Ok(build_lint_config(&plugins, &rules, &[], &[]).map(|config| {
config
.config_store
.rules()
.iter()
.filter(|(rule, _)| rule.is_tsgolint_rule())
.map(|(rule, severity)| {
(
format!("{}/{}", rule.plugin_name(), rule.name()),
rule_severity(*severity),
)
})
.collect()
}))
}

fn format_rule_enum_name(rule: &oxc_linter::rules::RuleEnum) -> String {
let name = rule.name();
let plugin = rule.plugin_name();
Expand Down
2 changes: 1 addition & 1 deletion rustq.exs
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ generate :fmt_native_stubs, "lib/oxc/format/native/generated_stubs.ex" do
end

lint_source = "native/oxc_lint_nif/src/lib.rs"
lint_nifs = [lint: []]
lint_nifs = [lint: [], type_aware_rules: []]

rust :lint_nifs, "native/oxc_lint_nif/src/generated_nifs.rs" do
Nif.wrappers_from_source(lint_source, lint_nifs, schedule: :dirty_cpu)
Expand Down
87 changes: 87 additions & 0 deletions test/oxc_lint_test.exs
Original file line number Diff line number Diff line change
@@ -1,6 +1,84 @@
defmodule OXC.LintTest do
use ExUnit.Case, async: true

describe "run/2 with type-aware categories" do
test "expands categories and preserves diagnostic severity" do
{rules, diagnostic} = selected_type_aware_rules(%{"correctness" => :deny})
assert "no-floating-promises" in rules
refute "correctness" in rules
refute "consistent-type-imports" in rules
assert diagnostic.severity == :error
end

test "individual settings override categories and categories override all" do
{rules, diagnostic} =
selected_type_aware_rules(%{
"all" => :deny,
"correctness" => :allow,
"typescript/no-floating-promises" => :warn,
"typescript/no-unsafe-assignment" => :allow
})

assert "no-floating-promises" in rules
refute "await-thenable" in rules
refute "no-unsafe-assignment" in rules
assert diagnostic.severity == :warning
end

test "passes rules unknown to oxlint through to tsgolint" do
{rules, _diagnostic} =
selected_type_aware_rules(%{"correctness" => :deny, "typescript/newer-rule" => :warn})

assert "newer-rule" in rules
assert "no-floating-promises" in rules
end

test "type_aware_rules/1 resolves categories and keeps named rule options" do
assert {:ok, rules} =
OXC.Lint.type_aware_rules(
plugins: ["typescript"],
rules: %{
"correctness" => :warn,
"eqeqeq" => :deny,
"typescript/no-floating-promises" => {:deny, %{"ignoreVoid" => true}}
}
)

assert rules["typescript/no-floating-promises"] == {:deny, %{"ignoreVoid" => true}}
assert rules["typescript/await-thenable"] == :warn
refute Map.has_key?(rules, "eqeqeq")
refute Map.has_key?(rules, "correctness")
assert OXC.Lint.type_aware_rules(rules: rules) == {:ok, rules}
end

test "does not select rules from disabled plugins" do
{rules, _diagnostic} = selected_type_aware_rules(%{"correctness" => :deny}, ["unicorn"])
assert rules == []
end
end

defp selected_type_aware_rules(rules, plugins \\ ["typescript"]) do
directory =
Path.join(System.tmp_dir!(), "oxc-categories-#{System.unique_integer([:positive])}")

File.mkdir_p!(directory)
on_exit(fn -> File.rm_rf!(directory) end)
executable = fake_tsgolint(directory)
file = Path.join(directory, "app.ts")
File.write!(file, "Promise.resolve(1)")

assert {:ok, [diagnostic]} =
OXC.Lint.run([file],
type_aware: true,
tsgolint: executable,
plugins: plugins,
rules: rules
)

payload = directory |> Path.join("payload.json") |> File.read!() |> Jason.decode!()
{Enum.map(hd(payload["configs"])["rules"], & &1["name"]), diagnostic}
end

describe "run/3 with built-in rules" do
test "detects eqeqeq violation with configured severity" do
{:ok, diags} = OXC.Lint.run("x == y", "test.js", rules: %{"eqeqeq" => :deny})
Expand All @@ -9,6 +87,15 @@ defmodule OXC.LintTest do
assert diag.severity == :error
end

test "explicit syntax-rule exceptions take precedence over categories" do
assert {:ok, diagnostics} =
OXC.Lint.run("export const x = 1;", "test.js",
rules: %{"style" => :deny, "eslint/id-length" => :allow}
)

refute Enum.any?(diagnostics, &(&1.rule =~ "id-length"))
end

test "detects no-debugger" do
{:ok, diags} = OXC.Lint.run("debugger;", "test.js", rules: %{"no-debugger" => :deny})
diag = Enum.find(diags, &(&1.rule =~ "no-debugger"))
Expand Down
Loading