From 7fb3202cdabe8a6c53f8b46375b860b874c6ea3e Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:59:04 +0200 Subject: [PATCH 1/3] feat(locali): warn of a retired rule in a config A linting configuration written for an earlier release may still name a rule this linter has since retired in ignoreDiagnostics. That line was refused as LOC0020, an error, failing every run, while a project pinned to the earlier release could not drop the line until it moved to the new one. Locali's own CI, linting Forma with the build under test, sat in exactly that gap whenever a rule was retired. Such a line is now LOC0021, a warning that it leaves nothing out, so the configuration keeps passing across the release and the line goes when the project bumps its pin. An identifier no release ever defined is still refused as LOC0020. --- CHANGELOG.md | 7 +++++++ README.md | 2 +- docs/linting-rules.md | 15 ++++++++------ .../Configuration/LintingConfiguration.cs | 10 +++++++++- .../Diagnostics/LintingCodes.cs | 7 +++++-- .../LintingConfigurationTests.cs | 20 +++++++++++++++++++ .../Diagnostics/LintingCodesTests.cs | 10 ++++++++++ 7 files changed, 61 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7e731a2..23df959 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,13 @@ Each release of Locali, newest first. An entry is dated when its release is cut, and reads *Unreleased* until then. The releases before `1.0.0-preview.11` are recorded by their [tags](https://github.com/FormaUI/Locali/tags) alone. +## `1.0.0-preview.23` + +*Unreleased* + +- A linting configuration naming a retired rule in `ignoreDiagnostics` is reported as LOC0021, a warning, rather than + LOC0020, so a configuration written for an earlier release keeps its run passing until the line is dropped. + ## `1.0.0-preview.22` *November 17, 2026* diff --git a/README.md b/README.md index 5b5935f..be6143b 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,7 @@ under 100, a file rule in the 100s, and a callsite rule in the 200s. | Code | Severity | Reports | |------|----------|---------| | LOC0020 | Error | The linting configuration is not readable JSON, does not follow its shape, or names a rule this linter does not define | -| LOC0021 | Warning | An entry in the linting configuration applied to no file the run reached | +| LOC0021 | Warning | An entry in the linting configuration applied to no file the run reached, or names a retired rule | | LOC0022 | Error | The runtime's `.locale.json` is not readable, names a key the runtime does not read, gives a value it would refuse, is one of two for an assembly, sits anywhere but its project's root, or sits in a locale pack | | LOC0023 | Warning | The root namespace the runtime counts a type's name from holds none of the project's types | | LOC0024 | Error | A locale pack's file has a name starting with no assembly the solution builds or references | diff --git a/docs/linting-rules.md b/docs/linting-rules.md index cbb4548..6db1e9a 100644 --- a/docs/linting-rules.md +++ b/docs/linting-rules.md @@ -117,9 +117,9 @@ hint naming an assembly the run neither builds nor references. ### LOC0020 — The linting configuration cannot be read **Reports.** A `.locali.json` or a `.locali-hints.json` that is not readable JSON or does not -follow its shape, or a `.locali.json` naming a rule this linter does not define, in either list. -A restored package's `.locali-hints.json` is reported as a warning, since the run cannot change -it. +follow its shape, or a `.locali.json` naming a rule this linter does not define and never +retired, in either list. A restored package's `.locali-hints.json` is reported as a warning, +since the run cannot change it. **Why it matters.** A typo in a rule identifier would silence nothing and say nothing; the file is refused instead. The rule over `.locali.json` itself can never be named in its own @@ -132,12 +132,15 @@ is refused instead. The rule over `.locali.json` itself can never be named in it **Reports.** A glob in `ignoreDiagnostics` or `excludeFiles` that matched no file the run reached, a `localeSources` line that is the last match for no locale file the run reached, because none matches it or a later line claims every file it matches, a hint naming an assembly -no project of the run builds or references. +no project of the run builds or references, or an `ignoreDiagnostics` line naming a rule this +linter has retired, which no run reports. **Why it matters.** A file moved out of the tree is exactly when its exceptions go stale, and an exception that names nothing sits unnoticed until it excuses the wrong file. A `localeSources` -line outlives the files it was written for the same way, or is written after a broader line -that already claims its files, and then reads as a policy nothing is held to. +line outlives the files it was written for the same way, or is written after a broader line that +already claims its files, and then reads as a policy nothing is held to. A line naming a retired +rule was written for a release that still reported it; it is a warning rather than LOC0020's +error, so a configuration keeps its run passing past that release until the line is dropped. **What fixes it.** Delete the entry, point it at the file's new place, or move the line after the broader one that overrides it. diff --git a/src/Forma.Locali.Engine/Configuration/LintingConfiguration.cs b/src/Forma.Locali.Engine/Configuration/LintingConfiguration.cs index 8986d9f..3740c9a 100644 --- a/src/Forma.Locali.Engine/Configuration/LintingConfiguration.cs +++ b/src/Forma.Locali.Engine/Configuration/LintingConfiguration.cs @@ -258,7 +258,15 @@ private static void DiagnoseFile(TrackedFile tracked, List di { foreach (var diagnostic in entry.Entries) { - if (Resolve(diagnostic.Id) is null) + // A retired rule reports nowhere, so a configuration still naming it leaves nothing out and fails no run. + if (LintingCodes.Retired.Contains(diagnostic.Id)) + { + diagnostics.Add(config.Diagnose( + diagnostic.Offset, + LintingCodes.StaleConfigurationEntry, + $"'{diagnostic.Id}' is a rule this linter has retired, so it leaves nothing out.")); + } + else if (Resolve(diagnostic.Id) is null) { diagnostics.Add(config.Diagnose( diagnostic.Offset, diff --git a/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs b/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs index 0d445af..51fea99 100644 --- a/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs +++ b/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs @@ -62,17 +62,20 @@ public static IReadOnlyList All NotRestored, ]; + /// The identifiers of the rules this linter has retired, which a linting configuration may still name and no run reports. + public static IReadOnlySet Retired { get; } = new HashSet(StringComparer.Ordinal) { "LOC0117" }; + /// The linting configuration is not readable JSON, does not follow its shape, or names a rule this linter does not define. public static LintingCode MalformedConfiguration { get; } = new( "LOC0020", LintingSeverity.Error, "The linting configuration is not readable JSON, does not follow its shape, or names a rule this linter does not define."); - /// An entry in the linting configuration applied to no file the run reached. + /// An entry in the linting configuration applied to no file the run reached, or names a rule this linter has retired. public static LintingCode StaleConfigurationEntry { get; } = new( "LOC0021", LintingSeverity.Warning, - "An entry in the linting configuration applied to no file the run reached, so it excludes, leaves out, or governs nothing."); + "An entry in the linting configuration applied to no file the run reached, or names a rule this linter has retired, so it excludes, leaves out, or governs nothing."); /// The runtime's config file is not readable JSON, names a key the runtime does not read, gives a value the runtime would refuse, is one of two for an assembly, sits anywhere but its project's root, or sits in a locale pack. public static LintingCode MalformedLocaleConfig { get; } = new( diff --git a/tests/Forma.Locali.Engine.Tests/Configuration/LintingConfigurationTests.cs b/tests/Forma.Locali.Engine.Tests/Configuration/LintingConfigurationTests.cs index 965ae86..9c18390 100644 --- a/tests/Forma.Locali.Engine.Tests/Configuration/LintingConfigurationTests.cs +++ b/tests/Forma.Locali.Engine.Tests/Configuration/LintingConfigurationTests.cs @@ -293,6 +293,26 @@ public void Should_report_a_rule_identifier_this_linter_does_not_define() () => Assert.Contains("LOC9999", diagnostic.Message, StringComparison.Ordinal)); } + [Fact] + public void Should_warn_that_a_retired_rule_leaves_nothing_out_rather_than_fail_the_run() + { + // Arrange — a configuration written for a release that still reported LOC0117. + using var directory = new TempDirectory(); + directory.Write(".locali.json", """{ "ignoreDiagnostics": { "Widget.he.json": ["LOC0117"] } }"""); + var file = directory.Write("Widget.he.json", "{}"); + var configuration = new LintingConfiguration(directory.Root); + configuration.GetIgnoredCodes(file); + + // Act + var diagnostics = configuration.GetDiagnostics(); + + // Assert + var diagnostic = Assert.Single(diagnostics); + Assert.Multiple( + () => Assert.Equal((LintingCodes.StaleConfigurationEntry, LintingSeverity.Warning), (diagnostic.Code, diagnostic.Severity)), + () => Assert.StartsWith("'LOC0117' is a rule this linter has retired", diagnostic.Message, StringComparison.Ordinal)); + } + [Fact] public void Should_report_a_configuration_file_that_is_not_readable_json() { diff --git a/tests/Forma.Locali.Engine.Tests/Diagnostics/LintingCodesTests.cs b/tests/Forma.Locali.Engine.Tests/Diagnostics/LintingCodesTests.cs index 4c95ba3..f0d5931 100644 --- a/tests/Forma.Locali.Engine.Tests/Diagnostics/LintingCodesTests.cs +++ b/tests/Forma.Locali.Engine.Tests/Diagnostics/LintingCodesTests.cs @@ -12,6 +12,16 @@ public void Should_give_every_rule_a_distinct_identifier() Assert.Equal(LintingCodes.All.Count, ids.Count()); } + [Fact] + public void Should_retire_no_identifier_a_catalogued_rule_still_reports_under() + { + // Act + var reused = LintingCodes.All.Where(code => LintingCodes.Retired.Contains(code.Id)); + + // Assert + Assert.Empty(reused); + } + [Fact] public void Should_describe_every_rule() { From d8ae8b6cc8af0752a0c0f1bb3e9ff31e18de5bfa Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:00:33 +0200 Subject: [PATCH 2/3] feat(locali)!: list unchecked lookups, not warn LOC0208, LOC0214 and LOC0215 reported Locali's own blind spots as warnings: a key written as an expression, a key a parameter takes that some call writes otherwise, and a lookup from which no path reaches a type. None of them is a defect, and what they cover is decided only while the app runs. They are retired, LOC0208 at a library's public method included. Each such lookup is now counted unchecked in the coverage and listed in the JSON report with its place, its reasons and what kept it unchecked; for a library's public method whose key its consumers write, the explanation names the key hint that lets their runs check those calls. The console summary says how many went unchecked. BREAKING CHANGE: LOC0208, LOC0214 and LOC0215 are no longer reported, a configuration still naming them gets a LOC0021 warning, and the coverage's lookup count now takes in keys written as expressions and keys taken from parameters some call writes otherwise. --- CHANGELOG.md | 6 + README.md | 47 ++--- docs/linting-rules.md | 112 +++--------- .../Diagnostics/LintingCodes.cs | 23 +-- .../Diagnostics/LookupCoverage.cs | 9 +- .../Diagnostics/UncheckedLookup.cs | 9 + src/Forma.Locali.Engine/Flow/FlowEvaluator.cs | 6 +- src/Forma.Locali.Engine/Flow/LocaleFlow.cs | 2 +- .../Linting/LintingService.cs | 73 ++------ .../Linting/LookupCoverages.cs | 161 ++++++++++++++++++ .../Projects/UnreadLocaleSourceChecker.cs | 35 ---- .../Rules/Projects/UnresolvedLocaleChecker.cs | 63 ------- .../ServiceCollectionExtensions.cs | 2 - .../Sources/ForwardedKey.cs | 6 +- .../Sources/ISourceLinter.cs | 5 +- .../Sources/SourceLintResult.cs | 5 + .../Sources/SourceLinter.cs | 30 +--- .../Reporting/ConsoleDiagnosticReporter.cs | 8 + .../Linting/LintingServiceTests.cs | 114 ++++++++++++- .../UnreadLocaleSourceCheckerTests.cs | 108 ------------ .../Projects/UnresolvedLocaleCheckerTests.cs | 154 ----------------- .../Sources/SourceLinterTests.cs | 65 ++++--- .../Sources/ProjectLinterTestFactory.cs | 2 - .../ConsoleDiagnosticReporterTests.cs | 20 ++- 24 files changed, 434 insertions(+), 631 deletions(-) create mode 100644 src/Forma.Locali.Engine/Diagnostics/UncheckedLookup.cs create mode 100644 src/Forma.Locali.Engine/Linting/LookupCoverages.cs delete mode 100644 src/Forma.Locali.Engine/Rules/Projects/UnreadLocaleSourceChecker.cs delete mode 100644 src/Forma.Locali.Engine/Rules/Projects/UnresolvedLocaleChecker.cs delete mode 100644 tests/Forma.Locali.Engine.Tests/Rules/Projects/UnreadLocaleSourceCheckerTests.cs delete mode 100644 tests/Forma.Locali.Engine.Tests/Rules/Projects/UnresolvedLocaleCheckerTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 23df959..144554d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ The releases before `1.0.0-preview.11` are recorded by their [tags](https://gith *Unreleased* +- Breaking: LOC0208, LOC0214 and LOC0215 are retired, LOC0208 at a library's public method included. A lookup the run + could not check is no diagnostic: one writing its key as an expression, one taking its key from a parameter some call + writes otherwise, and one from which no path reaches a type are counted unchecked, the console summary says how many, + and the JSON report's `coverage.uncheckedLookups` lists each with its place, its reasons, `keyNotWritten` and + `keyFromParameter` among them, and what kept it unchecked, naming for a library's public method the key hint that lets + its consumers' runs check the calls they make. `coverage.lookups` counts those two kinds of key as well. - A linting configuration naming a retired rule in `ignoreDiagnostics` is reported as LOC0021, a warning, rather than LOC0020, so a configuration written for an earlier release keeps its run passing until the line is dropped. diff --git a/README.md b/README.md index be6143b..ce0c747 100644 --- a/README.md +++ b/README.md @@ -145,16 +145,18 @@ nothing disappears without a trace: ```text Linted 658 file(s); 6 diagnostic(s). +12 of 840 lookup(s) went unchecked; pass --report to list each and why. 8 diagnostic(s) not shown: - LOC0106 (1) - - LOC0204 (1), LOC0207 (4), LOC0208 (2) + - LOC0204 (1), LOC0207 (4), LOC0209 (2) Pass --severity warning to read them. ``` The brief names each rule and how many it contributed, a line per family. Its closing line only promises what raising `--severity` will reveal: where the linting configuration accounts for -some or all of what is left out, it says so instead. +some or all of what is left out, it says so instead. A lookup the run could not check is no +diagnostic, so the line after the summary counts those, and the JSON report lists each. | Exit code | Meaning | |-----------|---------| @@ -165,15 +167,20 @@ some or all of what is left out, it says so instead. `--report` writes a JSON report carrying `fileCount`, `diagnosticCount`, `suppressedCount`, `ignoredCount` — how many of the suppressed diagnostics the linting configuration left out rather than the severity — a `diagnostics` array of `path`, `line`, `column`, `severity`, -`code`, `message`, and a `coverage` object for the lookups writing their keys in the files the -run linted: `lookups`; `fullyChecked`, `partiallyChecked` and `unchecked`, as each was held to -every type it reads with entries the run could read, to some, or to none; `evidence`, how many -checked lookups rest on the flow alone (`analysis`), on a hint the flow confirmed -(`verifiedHint`), or on a hint alone (`hint`); and `reasons`, how many lookups each reason left -short of fully checked: the kind of place a path ended, as `customFactory` or `externalCallers`, -`approximate` alternatives, `unavailableEntries` for a type whose assembly no project of the run -builds, or `notFollowed` for a lookup found without a bound compilation, or in code no instance -runs. +`code`, `message`, and a `coverage` object for the lookups the run found in the files it linted: +`lookups`, among them those writing their key as an expression and those taking it from a +parameter some call writes otherwise; `fullyChecked`, `partiallyChecked` and `unchecked`, as +each was held to every type it reads with entries the run could read, to some, or to none; +`evidence`, how many checked lookups rest on the flow alone (`analysis`), on a hint the flow +confirmed (`verifiedHint`), or on a hint alone (`hint`); `reasons`, how many lookups each reason +left short of fully checked: the kind of place a path ended, as `customFactory` or +`externalCallers`, `approximate` alternatives, `unavailableEntries` for a type whose assembly no +project of the run builds, `notFollowed` for a lookup found without a bound compilation, or in +code no instance runs, `keyNotWritten` for a key written as an expression, or `keyFromParameter` +for a key a parameter takes that some call writes otherwise; and `uncheckedLookups`, each lookup +counted unchecked with its `path`, `line`, `column`, `reasons` and an `explanation` of what kept +it unchecked, which for a library's public method whose key its consumers write names the key +hint that lets their runs check the calls they make. ## How Callsites Are Found @@ -198,12 +205,12 @@ is read through the method's paths with what it passes: a condition its constant settle, such as an empty or null test of the key or a flag it passes as `false`, is followed the one way it goes, so a call the method returns from before the lookup looks nothing up, and a condition on anything but the key leaves the lookup as reachable as one written under it. The -key is reported as an expression where a call reaching the lookup writes it otherwise; where -calls the run cannot see may write it: through a delegate, a base or an interface method, or -from outside a library, unless a key hint the method's body bears out names it; and where a -call's text may not be what the lookup reads: a condition on the key the flow cannot settle, -such as `key.StartsWith("raw:")`, stands between the call and the lookup, or the method writes -the parameter first, or reads it in a lambda, a local function or a handler. +lookup is counted unchecked, and listed in the run's report, where a call reaching it writes the +key otherwise; where calls the run cannot see may write it: through a delegate, a base or an +interface method, or from outside a library, unless a key hint the method's body bears out names +it; and where a call's text may not be what the lookup reads: a condition on the key the flow +cannot settle, such as `key.StartsWith("raw:")`, stands between the call and the lookup, or the +method writes the parameter first, or reads it in a lambda, a local function or a handler. A lookup through Microsoft's `IStringLocalizer`, written as `localizer["Checkout"]` with a literal key, is a lookup of Forma's where the run has Forma's adapter answer it: its product @@ -229,7 +236,8 @@ the walk cannot follow a value, such as a type chosen at run time, a factory the itself, or a service registered in a way the walk cannot read, the path ends and the lookup is held to no type along it; alternatives the walk cannot pair with the lookup, such as both sides of a conditional, whether locales, objects holding them, or delegates returning them, are never -held to it for certain. +held to it for certain. A lookup held to no type is counted unchecked, and the report lists it +with where its path ended. What the walk cannot read, a hint states: a member whose locale is read for the type another member of the same instance returns, as `FormaComponentBase.L` is for `LocaleSourceType`, or a @@ -302,14 +310,11 @@ under 100, a file rule in the 100s, and a callsite rule in the 200s. | LOC0205 | Warning | A project's Razor markup went unchecked | | LOC0206 | Error | A key writes text shaped like a hole the runtime cannot read | | LOC0207 | Warning | A key is not answered in a culture its type is localized in | -| LOC0208 | Warning | A lookup writes its key as an expression | | LOC0209 | Warning | A key carries holes but no words anywhere else | | LOC0210 | Warning | An expression key carries no words in any field | | LOC0211 | Error | A lookup writes its key as an interpolated string with holes | | LOC0212 | Error | A lookup writes a key shaped like a reserved entry | | LOC0213 | Error | A lookup supplies `string.Format`'s format text | -| LOC0214 | Warning | A lookup's type through a hinted member could not be read | -| LOC0215 | Warning | A lookup writing its key in a localized project reaches no type its locale is read for | | LOC0216 | Error | A project referencing packages was loaded without its restore output | ## Contributing diff --git a/docs/linting-rules.md b/docs/linting-rules.md index 6db1e9a..c1a7c49 100644 --- a/docs/linting-rules.md +++ b/docs/linting-rules.md @@ -108,11 +108,11 @@ each method of the run it passes the key on to: every lookup of the parameter th reached with the call's text as written on every path that text does not decide, in the locale the hint names, and a body that does not bear the hint out sets it aside, which LOC0029 reports. A hint the body bears out answers for the calls a library's consumers make, which their own runs -read, so the method's key is not reported as one they may write; and in a run that only -references the method, every call to it is a lookup of the key it passes, in the locale the hint -names. LOC0028 reports a hint naming what is not there, LOC0029 two hints relating one member to -different type members, or one method differently, which leaves it to neither, and LOC0021 a -hint naming an assembly the run neither builds nor references. +read, so the method's key is not counted unchecked; and in a run that only references the +method, every call to it is a lookup of the key it passes, in the locale the hint names. LOC0028 +reports a hint naming what is not there, LOC0029 two hints relating one member to different type +members, or one method differently, which leaves it to neither, and LOC0021 a hint naming an +assembly the run neither builds nor references. ### LOC0020 — The linting configuration cannot be read @@ -687,6 +687,14 @@ a constant is folded by the compiler and checked like a literal on the semantic inside a type that implements `IStringLocale` is left alone throughout, since such a type forwards the key its own caller wrote. +A lookup the run cannot check is no diagnostic, since a rule reports only what the evidence the +run established makes certain: a lookup writing its key as an expression, one taking its key +from a parameter some call writes otherwise, and one from which no path reaches a type its +locale is read for. The run counts each as unchecked, its console summary says how many there +were, and the JSON report lists each under `coverage.uncheckedLookups` with its place, its +reasons and what kept it unchecked; for a library's public method whose key its consumers write, +that names the key hint which lets their runs check the calls they make. + A call to `LocalizableText.For`, the runtime's text carried as data, is a lookup too, found on the semantic path alone: its first argument is the key, read in the entries of its type argument, and the values are what its `params` parameter gathers: @@ -705,13 +713,13 @@ is read through the method's paths with what it passes: a condition its constant settle, such as an empty or null test of the key or a flag it passes as `false`, is followed the one way it goes, so a call the method returns from before the lookup looks nothing up, and a condition on anything but the key leaves the lookup as reachable as one written under it. The -key is reported as an expression where a call reaching the lookup writes it otherwise; where -calls the run cannot see may write it: through a delegate, a base or an interface method, or -from outside a library, unless a key hint the method's body bears out names it; and where a -call's text may not be what the lookup reads: a condition on the key the flow cannot settle, -such as `key.StartsWith("raw:")`, stands between the call and the lookup, or the method writes -the parameter first, or reads it in a lambda, a local function or a handler. The values such a -call passes are left uncounted, since the method may fill the holes itself: +lookup is counted unchecked, and listed in the run's report, where a call reaching it writes the +key otherwise; where calls the run cannot see may write it: through a delegate, a base or an +interface method, or from outside a library, unless a key hint the method's body bears out names +it; and where a call's text may not be what the lookup reads: a condition on the key the flow +cannot settle, such as `key.StartsWith("raw:")`, stands between the call and the lookup, or the +method writes the parameter first, or reads it in a lambda, a local function or a handler. The +values such a call passes are left uncounted, since the method may fill the holes itself: ```csharp LocalizableText Title(string key) => LocalizableText.For(key); @@ -852,35 +860,11 @@ twice, as an instance, through a factory creating no one type, or by a call of t own handed the service collection, or declared outside the run's projects; the types the walk reaches are alternatives it cannot pair with the lookup, as both sides of a conditional, several returns, or a value a constructor or a later write may replace; the type member a hint names -returns nothing the walk can read, which LOC0214 reports; a type derived from the lookup's own -overrides the member holding the lookup, so its instances never run it; the lookup goes through -Microsoft's `IStringLocalizer` where the run does not have Forma's adapter answer it, so it -reads the localizer's own resources; a parent culture answers, since `es-419` reads `es` for -what it does not declare; or the run did not name the project's files. - -### LOC0208 — A lookup writes its key as an expression - -**Reports.** `L[column.ToString()]`: a key only the run knows. A key the lookup takes from a -parameter of its own method is reported where a call reaching the lookup writes it as an -expression, or where calls the run cannot see may write it: the method is passed as a delegate, -is virtual, implements an interface, or is a public method of a library, which its consumers -call, and no key hint its body bears out names it; or where a call's text may not be what the -lookup reads: a condition on the key the flow cannot settle stands between the call and the -lookup, where it settles a test of the text for being null, empty or blank, of its length, of -its equality with a constant, and an ordinal test of its start, its end or a part of it; or the -method writes the parameter first, or reads it in a lambda, a local function or a handler. - -**Why it matters.** No rule can judge the key and no coverage check can count it; leaving it -silent would let a run read as complete when part of it was never looked at. - -**What fixes it.** Write the key as a literal or a constant, which the compiler folds and every -rule reads. - -**Silent where.** The lookup sits inside a type that implements `IStringLocale`, which forwards -the key its own caller wrote; or the key is a parameter every call reaching the lookup writes as -text, which is checked at those calls instead, where a call writing it otherwise is one the -method never reaches the lookup for, and where the method is a library's public one a key hint -its body bears out names, whose consumers' runs read the calls they make. +returns nothing the walk can read; a type derived from the lookup's own overrides the member +holding the lookup, so its instances never run it; the lookup goes through Microsoft's +`IStringLocalizer` where the run does not have Forma's adapter answer it, so it reads the +localizer's own resources; a parent culture answers, since `es-419` reads `es` for what it does +not declare; or the run did not name the project's files. ### LOC0209 — A key with holes and no words @@ -939,52 +923,6 @@ cannot follow. Without a bound compilation, only the lookup written as the unnam `format`-named first argument is certain. A call to `LocalizableText.For` is never read as format text, since it returns text carried as data. -### LOC0214 — A lookup's type through a hinted member could not be read - -**Reports.** A lookup through a member a hint relates to a type member, where the flow reaches -no type on its own and the type member, as a type of instance reads it, has a getter that -returns no `typeof` of a type or `GetType()` of the instance that could be read, once per lookup -and type member, naming the types of instance it was left unread for: `protected override Type -LocaleSourceType => _source;`. A getter is read in source, in another project of the run's -source, or in the compiled code of the assembly the build runs, where it returns one of the two -in one straight run. - -**Why it matters.** LOC0207 holds the key to the type the getter names; where no reading tells -the type, the key goes unchecked, and leaving that silent would let a run read as complete when -part of it was never looked at. - -**What fixes it.** Return the type as `typeof(X)`, or the instance's own as `GetType()`, from -the getter; or, where the type is chosen at run time, accept the key unchecked. - -**Silent where.** The project is localized in no culture, by its own files or a pack, so no key -of it could be checked; the flow reaches the member's type without the hint; the lookup goes -through the generic `IStringLocale`, through a member no hint names, or through another -instance than the one its code runs on, which LOC0207 leaves alone. - -### LOC0215 — A lookup reaches no type - -**Reports.** A lookup writing its key, in a project localized in at least one culture, from -which no path reaches a type its locale is read for, naming where a path ended: `new -JsonStringLocaleFactory().Create(typeof(Page))["Save"]` ends at a factory the code builds -itself, whose files no rule can know. - -**Why it matters.** LOC0207 holds a key to the files of the types its lookup reads; a lookup -reaching none has its key held to nothing, and a run reading clean would claim a check it never -made. The JSON report counts every such lookup as unchecked, with the reason. - -**What fixes it.** Read the locale through `IStringLocale` or the registered factory, -injected or reached through `GetStringLocaleFactory()`; state what the code hides as a hint; or, -where the type is chosen at run time, accept the key unchecked and name the file in -`ignoreDiagnostics`. - -**Silent where.** The project is localized in no culture, by its own files or a pack, so no key -of it could be checked; a path reaches a type, even where another ends, which the JSON report -counts as partly checked; the type member a hint names tells no type, which LOC0214 reports; no -path was followed from the lookup, as one found where the compilation does not bind the -localizer contract, or in code no instance of the project runs; the key is an expression, which -LOC0208 reports; or the lookup goes through Microsoft's `IStringLocalizer` where the run does -not have Forma's adapter answer it. - ### LOC0216 — A project was not restored **Reports.** A project that references packages, loaded without the assets file restore writes, diff --git a/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs b/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs index 51fea99..c429390 100644 --- a/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs +++ b/src/Forma.Locali.Engine/Diagnostics/LintingCodes.cs @@ -51,19 +51,16 @@ public static IReadOnlyList All RazorNotAnalysed, HoleShapedText, MissingLocalization, - KeyNotAnalysed, BareHoleKey, BareExpressionKey, InterpolatedKey, ReservedShapedLookup, ReformattedLookup, - UnreadLocaleSource, - UnresolvedLocale, NotRestored, ]; /// The identifiers of the rules this linter has retired, which a linting configuration may still name and no run reports. - public static IReadOnlySet Retired { get; } = new HashSet(StringComparer.Ordinal) { "LOC0117" }; + public static IReadOnlySet Retired { get; } = new HashSet(StringComparer.Ordinal) { "LOC0117", "LOC0208", "LOC0214", "LOC0215" }; /// The linting configuration is not readable JSON, does not follow its shape, or names a rule this linter does not define. public static LintingCode MalformedConfiguration { get; } = new( @@ -317,12 +314,6 @@ public static IReadOnlyList All LintingSeverity.Warning, "A key written at a callsite has no entry in a culture its type is already localized in, so it renders in the source language."); - /// A lookup writes its key as an expression, so no rule could read it. - public static LintingCode KeyNotAnalysed { get; } = new( - "LOC0208", - LintingSeverity.Warning, - "A lookup writes its key as an expression, so what it reads went unchecked."); - /// The key carries holes but no words for anyone localizing it to read. public static LintingCode BareHoleKey { get; } = new( "LOC0209", @@ -353,18 +344,6 @@ public static IReadOnlyList All LintingSeverity.Error, "A lookup supplies string.Format's format text, which reads its own '{0}' rather than the runtime's holes, and throws once a text names one."); - /// A lookup goes through a member a hint relates to a type member whose getter tells no type that could be read. - public static LintingCode UnreadLocaleSource { get; } = new( - "LOC0214", - LintingSeverity.Warning, - "A lookup goes through a member a hint relates to a type member whose getter tells no type that could be read, so its key went unchecked."); - - /// A lookup writing its key in a localized project reaches no type its locale is read for. - public static LintingCode UnresolvedLocale { get; } = new( - "LOC0215", - LintingSeverity.Warning, - "A lookup writes its key in a localized project, but no path from it reaches the type its locale is read for, so whether a culture answers the key went unchecked."); - /// A project referencing packages was loaded without its restore output. public static LintingCode NotRestored { get; } = new( "LOC0216", diff --git a/src/Forma.Locali.Engine/Diagnostics/LookupCoverage.cs b/src/Forma.Locali.Engine/Diagnostics/LookupCoverage.cs index c968df6..677a93a 100644 --- a/src/Forma.Locali.Engine/Diagnostics/LookupCoverage.cs +++ b/src/Forma.Locali.Engine/Diagnostics/LookupCoverage.cs @@ -1,14 +1,17 @@ namespace Forma.Locali.Diagnostics; -/// How far a run checked the lookups whose keys it read: whether each was held to every type it reads, what established those types, and why the rest went unchecked. -/// How many lookups writing their key the run found in the files it linted. +/// How far a run checked the lookups it found: whether each was held to every type it reads, what established those types, and why the rest went unchecked. +/// How many lookups the run found in the files it linted: those writing their key, those writing it as an expression, and those taking it from a parameter some call writes otherwise. /// How many were held to every type they read, each with entries the run could read. /// How many were held to some of the types they read, while another path ended or its entries could not be read. -/// How many were held to no type. +/// How many were held to no type, or wrote no key a rule could read. /// What established the types the checked lookups were held to. /// How many lookups each reason left short of fully checked, by reason; a lookup short for several reasons counts under each. public sealed record LookupCoverage(int Lookups, int FullyChecked, int PartiallyChecked, int Unchecked, LookupEvidence Evidence, IReadOnlyDictionary Reasons) { /// A run that found no lookup. public static LookupCoverage None { get; } = new(0, 0, 0, 0, new LookupEvidence(0, 0, 0), new Dictionary()); + + /// Each lookup counted as unchecked, with where it sits and what kept it unchecked, ordered by file and then by position. + public IReadOnlyList UncheckedLookups { get; init; } = []; } diff --git a/src/Forma.Locali.Engine/Diagnostics/UncheckedLookup.cs b/src/Forma.Locali.Engine/Diagnostics/UncheckedLookup.cs new file mode 100644 index 0000000..cd44697 --- /dev/null +++ b/src/Forma.Locali.Engine/Diagnostics/UncheckedLookup.cs @@ -0,0 +1,9 @@ +namespace Forma.Locali.Diagnostics; + +/// A lookup the run could not check, where it sits and what kept it unchecked. +/// The file holding the lookup's key. +/// The key's line, counted from one. +/// The key's column, counted from one. +/// What kept the lookup unchecked, each named as the coverage's reasons are. +/// What kept the lookup unchecked, in a sentence. +public sealed record UncheckedLookup(string Path, int Line, int Column, IReadOnlyList Reasons, string Explanation); diff --git a/src/Forma.Locali.Engine/Flow/FlowEvaluator.cs b/src/Forma.Locali.Engine/Flow/FlowEvaluator.cs index 61afeaf..3cbebaa 100644 --- a/src/Forma.Locali.Engine/Flow/FlowEvaluator.cs +++ b/src/Forma.Locali.Engine/Flow/FlowEvaluator.cs @@ -303,8 +303,10 @@ private static bool IsDispatched(IMethodSymbol method) || method.ContainingType.AllInterfaces.SelectMany(face => face.GetMembers()).OfType() .Any(member => SymbolEqualityComparer.Default.Equals(method.ContainingType.FindImplementationForInterfaceMember(member), method)); - // A public method of a library is called by its consumers, outside the run. - private static bool IsLibraryMember(IMethodSymbol method, Compilation compilation) + /// Whether a method is a library's public one, which its consumers call outside the run. + /// The method. + /// The compilation declaring it. + internal static bool IsLibraryMember(IMethodSymbol method, Compilation compilation) => IsReachableFromOutside(method) && compilation.Options.OutputKind == OutputKind.DynamicallyLinkedLibrary; private static IOperation? Unconverted(IOperation? operation) diff --git a/src/Forma.Locali.Engine/Flow/LocaleFlow.cs b/src/Forma.Locali.Engine/Flow/LocaleFlow.cs index ee71299..25b326a 100644 --- a/src/Forma.Locali.Engine/Flow/LocaleFlow.cs +++ b/src/Forma.Locali.Engine/Flow/LocaleFlow.cs @@ -116,7 +116,7 @@ public ForwardedLookups Forward(IReadOnlyList<(LoadedProject Project, ForwardedK var calls = new List(); if (!new FlowEvaluator(_run, _memo, _analysisMemo).Forward(lookup, parameter, calls)) { - unforwarded.Add(key); + unforwarded.Add(key with { IsCalledFromOutside = parameter.ContainingSymbol is IMethodSymbol method && FlowEvaluator.IsLibraryMember(method, compilation) }); } // A call reaching several lookups is one lookup of its key, in every type they read. diff --git a/src/Forma.Locali.Engine/Linting/LintingService.cs b/src/Forma.Locali.Engine/Linting/LintingService.cs index 84a6f4c..02ba1ba 100644 --- a/src/Forma.Locali.Engine/Linting/LintingService.cs +++ b/src/Forma.Locali.Engine/Linting/LintingService.cs @@ -163,6 +163,7 @@ .. leftOut linted[index] = (project, new SourceLintResult([.. sources.Diagnostics, .. keyed.Diagnostics], [.. sources.Callsites, .. keyed.Callsites]) { ForwardedKeys = [.. sources.ForwardedKeys, .. keyed.ForwardedKeys], + UnreadKeys = [.. sources.UnreadKeys, .. keyed.UnreadKeys], }); } } @@ -170,15 +171,15 @@ .. leftOut // A type's entries are read from its own assembly's project, so every project's files are resolved before any rule reads them. var localizations = RunLocalizations.Resolve(_localeFormat.RuntimeFormat, projects.All, target.LocalizationFilesOf, packs, builtAssemblies); - // A key passed through a parameter is checked at each call writing it, in the project holding the call, and is left unread where - // a call writes it otherwise. + // A key passed through a parameter is checked at each call writing it, in the project holding the call, and is counted unchecked + // where a call writes it otherwise. var forwarded = flow.Forward([.. linted.SelectMany(entry => entry.Sources.ForwardedKeys.Select(key => (entry.Project, key)))]); IReadOnlyList Forwarded(LoadedProject project) { return [.. forwarded.ByProject.GetValueOrDefault(project.Path, []).Where(site => wanted.Contains(site.Key.Location.Path))]; } - diagnostics.AddRange(_sources.Lint([.. linted.SelectMany(entry => Forwarded(entry.Project))], [.. forwarded.Unforwarded.Where(key => wanted.Contains(key.Key.Path))])); + diagnostics.AddRange(_sources.Lint([.. linted.SelectMany(entry => Forwarded(entry.Project))])); var resolved = new List(); foreach (var (project, sources) in linted) @@ -192,69 +193,15 @@ IReadOnlyList Forwarded(LoadedProject project) diagnostics.AddRange(hints.Diagnostics); diagnostics.AddRange(flow.GetDiagnostics()); - return (diagnostics, Coverage(resolved, localizations)); - } - - // A lookup is checked against each certain type whose entries the run reads, from the project building the type's assembly; - // what kept it short of that is named for the path that ended, or for the alternatives or the entries it could not use. - private static LookupCoverage Coverage(List lookups, RunLocalizations localizations) - { - int fullyChecked = 0, partiallyChecked = 0, notChecked = 0, byAnalysis = 0, byVerifiedHint = 0, byHint = 0; - var reasons = new SortedDictionary(StringComparer.Ordinal); - - foreach (var lookup in lookups) - { - var certain = lookup.Origins.Where(origin => !origin.IsApproximate).ToArray(); - var read = certain.Where(origin => origin.Type.ContainingAssembly?.Name is { Length: > 0 } name && localizations.ForAssembly(name) is not null).ToArray(); - - var shortfalls = new SortedSet(lookup.Gaps.Select(gap => Camel(gap.Kind.ToString())), StringComparer.Ordinal); - if (certain.Length < lookup.Origins.Count) - { - shortfalls.Add("approximate"); - } - - if (read.Length < certain.Length) - { - shortfalls.Add("unavailableEntries"); - } - - // A lookup found without a bound compilation, or in code no instance runs, was never followed to a type. - if (read.Length == 0 && shortfalls.Count == 0) - { - shortfalls.Add("notFollowed"); - } + var coverage = LookupCoverages.Of( + resolved, + [.. linted.SelectMany(entry => entry.Sources.UnreadKeys)], + [.. forwarded.Unforwarded.Where(key => wanted.Contains(key.Key.Path))], + localizations); - foreach (var reason in shortfalls) - { - reasons[reason] = reasons.GetValueOrDefault(reason) + 1; - } - - if (read.Length == 0) - { - notChecked++; - continue; - } - - if (shortfalls.Count == 0) - { - fullyChecked++; - } - else - { - partiallyChecked++; - } - - byAnalysis += read.Any(origin => origin.Evidence == LocaleEvidence.Analysis) ? 1 : 0; - byVerifiedHint += read.Any(origin => origin.Evidence == LocaleEvidence.VerifiedHint) ? 1 : 0; - byHint += read.Any(origin => origin.Evidence == LocaleEvidence.Hint) ? 1 : 0; - } - - return new LookupCoverage(lookups.Count, fullyChecked, partiallyChecked, notChecked, new LookupEvidence(byAnalysis, byVerifiedHint, byHint), reasons); + return (diagnostics, coverage); } - private static string Camel(string name) - => string.Concat(char.ToLowerInvariant(name[0]).ToString(), name[1..]); - // Each project's folder and each restored package's root, once, with the assemblies the library there builds or ships. private static HintsFolder[] Libraries(IReadOnlyList projects) { diff --git a/src/Forma.Locali.Engine/Linting/LookupCoverages.cs b/src/Forma.Locali.Engine/Linting/LookupCoverages.cs new file mode 100644 index 0000000..ff87c70 --- /dev/null +++ b/src/Forma.Locali.Engine/Linting/LookupCoverages.cs @@ -0,0 +1,161 @@ +namespace Forma.Locali.Linting; + +using Forma.Locali.Diagnostics; +using Forma.Locali.Flow; +using Forma.Locali.Sources; + +using Microsoft.CodeAnalysis; + +/// Counts how far a run checked the lookups it found, and lists each one it could not check with what kept it unchecked. +internal static class LookupCoverages +{ + private const string KeyNotWritten = "keyNotWritten"; + private const string KeyFromParameter = "keyFromParameter"; + + /// The coverage of a run's lookups. + /// The lookups writing their key, each with the types the flow settled for it. + /// Where a lookup writes its key as an expression. + /// The keys taken from a parameter that some call writes otherwise, or that no call of the run writes at all. + /// The entries the run reads for each assembly. + public static LookupCoverage Of(IReadOnlyList lookups, IReadOnlyList unreadKeys, IReadOnlyList unforwarded, RunLocalizations localizations) + { + int fullyChecked = 0, partiallyChecked = 0, notChecked = 0, byAnalysis = 0, byVerifiedHint = 0, byHint = 0; + var reasons = new SortedDictionary(StringComparer.Ordinal); + var uncheckedLookups = new List(); + + void Count(IEnumerable shortfalls) + { + foreach (var reason in shortfalls) + { + reasons[reason] = reasons.GetValueOrDefault(reason) + 1; + } + } + + // A lookup is checked against each certain type whose entries the run reads, from the project building the type's assembly; + // what kept it short of that is named for the path that ended, or for the alternatives or the entries it could not use. + foreach (var lookup in lookups) + { + var certain = lookup.Origins.Where(origin => !origin.IsApproximate).ToArray(); + var read = certain.Where(origin => origin.Type.ContainingAssembly?.Name is { Length: > 0 } name && localizations.ForAssembly(name) is not null).ToArray(); + + var shortfalls = new SortedSet(lookup.Gaps.Select(gap => Camel(gap.Kind.ToString())), StringComparer.Ordinal); + if (certain.Length < lookup.Origins.Count) + { + shortfalls.Add("approximate"); + } + + if (read.Length < certain.Length) + { + shortfalls.Add("unavailableEntries"); + } + + // A lookup found without a bound compilation, or in code no instance runs, was never followed to a type. + if (read.Length == 0 && shortfalls.Count == 0) + { + shortfalls.Add("notFollowed"); + } + + Count(shortfalls); + + if (read.Length == 0) + { + notChecked++; + uncheckedLookups.Add(new UncheckedLookup( + lookup.Key.Location.Path, + lookup.Key.Location.StartLinePosition.Line + 1, + lookup.Key.Location.StartLinePosition.Character + 1 + lookup.Key.TextOffset, + [.. shortfalls], + Explain(lookup, certain))); + continue; + } + + if (shortfalls.Count == 0) + { + fullyChecked++; + } + else + { + partiallyChecked++; + } + + byAnalysis += read.Any(origin => origin.Evidence == LocaleEvidence.Analysis) ? 1 : 0; + byVerifiedHint += read.Any(origin => origin.Evidence == LocaleEvidence.VerifiedHint) ? 1 : 0; + byHint += read.Any(origin => origin.Evidence == LocaleEvidence.Hint) ? 1 : 0; + } + + foreach (var key in unreadKeys) + { + uncheckedLookups.Add(Unread(key, [KeyNotWritten], "The lookup's key is an expression rather than text, so no rule could check what it reads.")); + } + + foreach (var key in unforwarded) + { + var explanation = $"The lookup's key is the parameter '{key.Parameter}', which a call writes as an expression, passes from outside the run, or hands a method whose path to the lookup turns on the text in a way the flow cannot tell, so no rule could check what it reads."; + uncheckedLookups.Add(Unread( + key.Key, + [KeyFromParameter], + key.IsCalledFromOutside + ? $"{explanation} The method is a library's public one: a localeKeys hint its body bears out lets its consumers' runs check the calls they make." + : explanation)); + } + + var unread = unreadKeys.Count + unforwarded.Count; + Count(Enumerable.Repeat(KeyNotWritten, unreadKeys.Count)); + Count(Enumerable.Repeat(KeyFromParameter, unforwarded.Count)); + + return new LookupCoverage(lookups.Count + unread, fullyChecked, partiallyChecked, notChecked + unread, new LookupEvidence(byAnalysis, byVerifiedHint, byHint), reasons) + { + UncheckedLookups = + [ + .. uncheckedLookups + .OrderBy(entry => entry.Path, StringComparer.Ordinal) + .ThenBy(entry => entry.Line) + .ThenBy(entry => entry.Column), + ], + }; + } + + private static UncheckedLookup Unread(FileLinePositionSpan key, IReadOnlyList reasons, string explanation) + => new(key.Path, key.StartLinePosition.Line + 1, key.StartLinePosition.Character + 1, reasons, explanation); + + private static string Explain(LocalizerLookup lookup, LocaleOrigin[] certain) + { + if (lookup.Gaps.FirstOrDefault(gap => gap.Kind == LocaleGapKind.UnreadTypeMember) is { } unread) + { + return $"A hint reads the lookup's type from '{unread.Detail}', whose getter returns no typeof or GetType() that could be read, so no rule could check '{lookup.Key.Text}' there."; + } + + if (lookup.Gaps is [var gap, ..]) + { + return $"No path from the lookup reaches the type its locale is read for, ending at {Phrase(gap.Kind)}, '{gap.Detail}', so no rule could check whether a culture answers '{lookup.Key.Text}'."; + } + + if (certain.Length < lookup.Origins.Count) + { + return $"No path from the lookup reaches the type its locale is read for, ending at alternatives the flow cannot pair with the lookup, '{string.Join("', '", lookup.Origins.Select(origin => origin.Type.Name).Distinct(StringComparer.Ordinal))}', so no rule could check whether a culture answers '{lookup.Key.Text}'."; + } + + return certain.Length > 0 + ? $"The lookup reads '{string.Join("', '", certain.Select(origin => origin.Type.Name).Distinct(StringComparer.Ordinal))}', whose assembly carries no entries the run reads, so no rule could check '{lookup.Key.Text}'." + : $"No path was followed from the lookup, which was found without a bound compilation or in code no instance runs, so no rule could check '{lookup.Key.Text}'."; + } + + private static string Phrase(LocaleGapKind kind) + => kind switch + { + LocaleGapKind.CompiledCode => "compiled code", + LocaleGapKind.CustomFactory => "a factory the code builds itself", + LocaleGapKind.NamedByString => "a locale named by a string", + LocaleGapKind.Dispatch => "a call no one implementation answers that the flow can tell", + LocaleGapKind.Reflection => "a value the framework sets", + LocaleGapKind.ExternalCallers => "callers outside the run", + LocaleGapKind.Local => "a local assigned more than once", + LocaleGapKind.Write => "a member written where the flow cannot pair the write with the object read", + LocaleGapKind.Cycle => "a path returning to itself", + LocaleGapKind.Depth => "the depth the flow follows a path to", + _ => "code the flow does not read", + }; + + private static string Camel(string name) + => string.Concat(char.ToLowerInvariant(name[0]).ToString(), name[1..]); +} diff --git a/src/Forma.Locali.Engine/Rules/Projects/UnreadLocaleSourceChecker.cs b/src/Forma.Locali.Engine/Rules/Projects/UnreadLocaleSourceChecker.cs deleted file mode 100644 index d0035b2..0000000 --- a/src/Forma.Locali.Engine/Rules/Projects/UnreadLocaleSourceChecker.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace Forma.Locali.Rules.Projects; - -using Forma.Locali.Diagnostics; -using Forma.Locali.Flow; - -/// Checks that the type a lookup through a hinted member reads could be told from the type member the hint relates it to. -public sealed class UnreadLocaleSourceChecker : IProjectRuleChecker -{ - /// - public LintingCode Code - => LintingCodes.UnreadLocaleSource; - - /// - public void Check(ProjectContext context) - { - ArgumentNullException.ThrowIfNull(context); - - // A project localized in no culture, by its own files or a pack, has no key to check, so nothing went unchecked. - if (context.Localization is not { Cultures.Count: > 0 }) - { - return; - } - - foreach (var site in context.Callsites) - { - foreach (var gap in site.Gaps.Where(gap => gap.Kind == LocaleGapKind.UnreadTypeMember).Distinct()) - { - context.Report( - Code, - site, - $"A hint reads the lookup's type from '{gap.Detail}', whose getter returns no typeof or GetType() that could be read, so no rule could check '{site.Key.Text}' there."); - } - } - } -} diff --git a/src/Forma.Locali.Engine/Rules/Projects/UnresolvedLocaleChecker.cs b/src/Forma.Locali.Engine/Rules/Projects/UnresolvedLocaleChecker.cs deleted file mode 100644 index 5b6034f..0000000 --- a/src/Forma.Locali.Engine/Rules/Projects/UnresolvedLocaleChecker.cs +++ /dev/null @@ -1,63 +0,0 @@ -namespace Forma.Locali.Rules.Projects; - -using Forma.Locali.Diagnostics; -using Forma.Locali.Flow; -using Forma.Locali.Sources; - -/// Checks that a lookup writing its key in a localized project reaches a type its locale is read for, so the key can be checked. -public sealed class UnresolvedLocaleChecker : IProjectRuleChecker -{ - /// - public LintingCode Code - => LintingCodes.UnresolvedLocale; - - /// - public void Check(ProjectContext context) - { - ArgumentNullException.ThrowIfNull(context); - - // A project localized in no culture, by its own files or a pack, has no key to check, so nothing went unchecked. - if (context.Localization is not { Cultures.Count: > 0 }) - { - return; - } - - foreach (var site in context.Callsites) - { - // A lookup reaching a type is checked, one whose hinted type member tells none is LOC0214's, and one no path was followed - // from, found without a bound compilation or in code no instance runs, ended nowhere to name. - if (site.Origins.Any(origin => !origin.IsApproximate) - || site.Gaps.Any(gap => gap.Kind == LocaleGapKind.UnreadTypeMember) - || site.Gaps.Count == 0 && site.Origins.Count == 0) - { - continue; - } - - context.Report( - Code, - site, - $"No path from the lookup reaches the type its locale is read for, ending at {Ending(site)}, so no rule could check whether a culture answers '{site.Key.Text}'."); - } - } - - private static string Ending(LocalizerLookup site) - => site.Gaps is [var gap, ..] - ? $"{Phrase(gap.Kind)}, '{gap.Detail}'" - : $"alternatives the flow cannot pair with the lookup, '{string.Join("', '", site.Origins.Select(origin => origin.Type.Name).Distinct(StringComparer.Ordinal))}'"; - - private static string Phrase(LocaleGapKind kind) - => kind switch - { - LocaleGapKind.CompiledCode => "compiled code", - LocaleGapKind.CustomFactory => "a factory the code builds itself", - LocaleGapKind.NamedByString => "a locale named by a string", - LocaleGapKind.Dispatch => "a call no one implementation answers that the flow can tell", - LocaleGapKind.Reflection => "a value the framework sets", - LocaleGapKind.ExternalCallers => "callers outside the run", - LocaleGapKind.Local => "a local assigned more than once", - LocaleGapKind.Write => "a member written where the flow cannot pair the write with the object read", - LocaleGapKind.Cycle => "a path returning to itself", - LocaleGapKind.Depth => "the depth the flow follows a path to", - _ => "code the flow does not read", - }; -} diff --git a/src/Forma.Locali.Engine/ServiceCollectionExtensions.cs b/src/Forma.Locali.Engine/ServiceCollectionExtensions.cs index aa75bbb..d57028d 100644 --- a/src/Forma.Locali.Engine/ServiceCollectionExtensions.cs +++ b/src/Forma.Locali.Engine/ServiceCollectionExtensions.cs @@ -57,8 +57,6 @@ public static IServiceCollection AddLocaliEngine(this IServiceCollection service services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Forma.Locali.Engine/Sources/ForwardedKey.cs b/src/Forma.Locali.Engine/Sources/ForwardedKey.cs index c8fb0bb..4183ccf 100644 --- a/src/Forma.Locali.Engine/Sources/ForwardedKey.cs +++ b/src/Forma.Locali.Engine/Sources/ForwardedKey.cs @@ -6,4 +6,8 @@ namespace Forma.Locali.Sources; /// The lookup's node. /// Where the lookup writes the parameter as its key. /// The parameter's name. -public sealed record ForwardedKey(SyntaxNode Lookup, FileLinePositionSpan Key, string Parameter); +public sealed record ForwardedKey(SyntaxNode Lookup, FileLinePositionSpan Key, string Parameter) +{ + /// Whether the lookup's method is a library's public one, whose consumers write the key at calls outside the run. + public bool IsCalledFromOutside { get; init; } +} diff --git a/src/Forma.Locali.Engine/Sources/ISourceLinter.cs b/src/Forma.Locali.Engine/Sources/ISourceLinter.cs index e8b3b24..953f79d 100644 --- a/src/Forma.Locali.Engine/Sources/ISourceLinter.cs +++ b/src/Forma.Locali.Engine/Sources/ISourceLinter.cs @@ -15,10 +15,9 @@ SourceLintResult Lint( IReadOnlyCollection files, CancellationToken cancellationToken = default); - /// What the callsite rules report for the lookups keys passed through parameters make at the calls writing them, and for the keys no path writes as text. + /// What the callsite rules report for the lookups keys passed through parameters make at the calls writing them. /// The lookups the calls make. - /// The keys some call writes otherwise, or that no call of the run writes at all. - IReadOnlyList Lint(IReadOnlyList forwarded, IReadOnlyList unforwarded); + IReadOnlyList Lint(IReadOnlyList forwarded); /// Lints a project's calls to the methods a hint states look a parameter up as a key, which no project of the run builds, as lookups of their keys. /// The loaded project. diff --git a/src/Forma.Locali.Engine/Sources/SourceLintResult.cs b/src/Forma.Locali.Engine/Sources/SourceLintResult.cs index fc2ead0..c78712f 100644 --- a/src/Forma.Locali.Engine/Sources/SourceLintResult.cs +++ b/src/Forma.Locali.Engine/Sources/SourceLintResult.cs @@ -2,6 +2,8 @@ namespace Forma.Locali.Sources; using Forma.Locali.Diagnostics; +using Microsoft.CodeAnalysis; + /// What a project's callsites produced, and the sites themselves for the rules that read a project whole. /// Everything the callsite rules reported. /// The callsites the walk found, in the order it found them. @@ -9,4 +11,7 @@ public sealed record SourceLintResult(IReadOnlyList Diagnosti { /// The lookups taking their key from a parameter of their own method, left for the calls of that method to write, whichever files the run named. public IReadOnlyList ForwardedKeys { get; init; } = []; + + /// Where a lookup in the files the run named writes its key as an expression, which no rule reads. + public IReadOnlyList UnreadKeys { get; init; } = []; } diff --git a/src/Forma.Locali.Engine/Sources/SourceLinter.cs b/src/Forma.Locali.Engine/Sources/SourceLinter.cs index ca98bbc..3fc7b3a 100644 --- a/src/Forma.Locali.Engine/Sources/SourceLinter.cs +++ b/src/Forma.Locali.Engine/Sources/SourceLinter.cs @@ -87,40 +87,18 @@ private SourceLintResult Checked(LocalizerLookups lookups, List - public IReadOnlyList Lint(IReadOnlyList forwarded, IReadOnlyList unforwarded) + public IReadOnlyList Lint(IReadOnlyList forwarded) { ArgumentNullException.ThrowIfNull(forwarded); - ArgumentNullException.ThrowIfNull(unforwarded); - - return - [ - .. forwarded.SelectMany(Check), - .. unforwarded.Select(key => new LintingDiagnostic( - key.Key.Path, - key.Key.StartLinePosition.Line + 1, - key.Key.StartLinePosition.Character + 1, - LintingCodes.KeyNotAnalysed.DefaultSeverity, - LintingCodes.KeyNotAnalysed, - $"The lookup's key is the parameter '{key.Parameter}', which a call writes as an expression, passes from outside the run, or hands a method whose path to the lookup turns on the text in a way the flow cannot tell, so no rule could check what it reads.")), - ]; - } - // Naming the blind spot keeps a run from reading as complete coverage when part of it was unreadable. - private static LintingDiagnostic Unreadable(FileLinePositionSpan location) - => new( - location.Path, - location.StartLinePosition.Line + 1, - location.StartLinePosition.Character + 1, - LintingCodes.KeyNotAnalysed.DefaultSeverity, - LintingCodes.KeyNotAnalysed, - "The lookup's key is an expression rather than text, so no rule could check what it reads."); + return [.. forwarded.SelectMany(Check)]; + } private static LintingDiagnostic Interpolated(FileLinePositionSpan location) => new( diff --git a/src/Forma.Locali/Reporting/ConsoleDiagnosticReporter.cs b/src/Forma.Locali/Reporting/ConsoleDiagnosticReporter.cs index a87aa47..c8f3564 100644 --- a/src/Forma.Locali/Reporting/ConsoleDiagnosticReporter.cs +++ b/src/Forma.Locali/Reporting/ConsoleDiagnosticReporter.cs @@ -24,6 +24,14 @@ public async ValueTask ReportAsync(LintingResult result, CancellationToken cance await _writer.WriteLineAsync(summary.AsMemory(), cancellationToken).ConfigureAwait(false); + // A lookup the run could not check is no diagnostic, so the summary counts them and says where each is listed. + if (result.Coverage is { Unchecked: > 0 } coverage) + { + await _writer + .WriteLineAsync($"{coverage.Unchecked} of {coverage.Lookups} lookup(s) went unchecked; pass --report to list each and why.".AsMemory(), cancellationToken) + .ConfigureAwait(false); + } + if (result.Suppressed.Count == 0) { return; diff --git a/tests/Forma.Locali.Engine.Tests/Linting/LintingServiceTests.cs b/tests/Forma.Locali.Engine.Tests/Linting/LintingServiceTests.cs index 79b04dc..cd7445f 100644 --- a/tests/Forma.Locali.Engine.Tests/Linting/LintingServiceTests.cs +++ b/tests/Forma.Locali.Engine.Tests/Linting/LintingServiceTests.cs @@ -676,6 +676,109 @@ public sealed class Widget(IStringLocale locale) () => Assert.Equal(new Dictionary { ["customFactory"] = 1 }, coverage.Reasons)); } + [Fact] + public async Task Should_list_each_lookup_the_run_could_not_check_with_what_kept_it_unchecked() + { + // Arrange — a factory the code builds makes the locale, so no path reaches the type it is read for. + using var directory = new TempDirectory(); + var project = directory.Write(Path.Combine("Widgets", "Scratch.csproj"), """"""); + var source = directory.Write(Path.Combine("Widgets", "Widget.cs"), """ + using System; + + using Forma.Framework.Localization; + + namespace Scratch; + + internal sealed class Factory : IStringLocaleFactory + { + public IStringLocale Create(Type resourceSource) => throw new NotSupportedException(); + + public IStringLocale Create(string baseName, string location) => throw new NotSupportedException(); + } + + public sealed class Widget + { + public string Show() => new Factory().Create(typeof(Widget))["Tomorrow"].Value; + } + """); + directory.Write(Path.Combine("Widgets", ".locales", "Widget.he.json"), LocalizationFileFakeData.Valid); + var loader = new StubProjectLoader(new LoadedProject(project, CompilationTestFactory.ReferencedFiles("Scratch", source), false, false)); + + // Act + var result = await LintingServiceTestFactory.Create(directory.Root, LintingSeverity.Warning, loader).RunAsync(TestContext.Current.CancellationToken); + + // Assert + var entry = Assert.Single(result.Coverage.UncheckedLookups); + Assert.Multiple( + () => Assert.Empty(result.Diagnostics), + () => Assert.Equal((source, 16), (entry.Path, entry.Line)), + () => Assert.Equal(["customFactory"], entry.Reasons), + () => Assert.Contains("a factory the code builds itself", entry.Explanation, StringComparison.Ordinal)); + } + + [Fact] + public async Task Should_count_and_list_a_key_written_as_an_expression_as_unchecked() + { + // Arrange + using var directory = new TempDirectory(); + var project = directory.Write(Path.Combine("Widgets", "Scratch.csproj"), """"""); + var source = directory.Write(Path.Combine("Widgets", "Widget.cs"), """ + using Forma.Framework.Localization; + + namespace Scratch; + + public sealed class Widget(IStringLocale locale) + { + public string Show(object column) => locale[column.ToString()!].Value; + } + """); + directory.Write(Path.Combine("Widgets", ".locales", "Widget.he.json"), LocalizationFileFakeData.Valid); + var loader = new StubProjectLoader(new LoadedProject(project, CompilationTestFactory.ReferencedFiles("Scratch", source), false, false)); + + // Act + var result = await LintingServiceTestFactory.Create(directory.Root, LintingSeverity.Warning, loader).RunAsync(TestContext.Current.CancellationToken); + + // Assert + var coverage = result.Coverage; + var entry = Assert.Single(coverage.UncheckedLookups); + Assert.Multiple( + () => Assert.Empty(result.Diagnostics), + () => Assert.Equal((1, 0, 1), (coverage.Lookups, coverage.FullyChecked, coverage.Unchecked)), + () => Assert.Equal(new Dictionary { ["keyNotWritten"] = 1 }, coverage.Reasons), + () => Assert.Equal(7, entry.Line), + () => Assert.Equal(["keyNotWritten"], entry.Reasons)); + } + + [Fact] + public async Task Should_tell_how_a_hint_lets_consumers_check_a_public_library_methods_key() + { + // Arrange — the library's own run makes no call writing the key, which its consumers write outside the run. + using var directory = new TempDirectory(); + var project = directory.Write(Path.Combine("Widgets", "Scratch.csproj"), """"""); + var source = directory.Write(Path.Combine("Widgets", "Widget.cs"), """ + using Forma.Framework.Localization; + + namespace Scratch; + + public sealed class Widget(IStringLocale locale) + { + public string Label(string key) => locale[key].Value; + } + """); + directory.Write(Path.Combine("Widgets", ".locales", "Widget.he.json"), LocalizationFileFakeData.Valid); + var loader = new StubProjectLoader(new LoadedProject(project, CompilationTestFactory.ReferencedFiles("Scratch", source), false, false)); + + // Act + var result = await LintingServiceTestFactory.Create(directory.Root, LintingSeverity.Warning, loader).RunAsync(TestContext.Current.CancellationToken); + + // Assert + var entry = Assert.Single(result.Coverage.UncheckedLookups); + Assert.Multiple( + () => Assert.Empty(result.Diagnostics), + () => Assert.Equal(["keyFromParameter"], entry.Reasons), + () => Assert.Contains("a localeKeys hint its body bears out lets its consumers' runs check the calls they make", entry.Explanation, StringComparison.Ordinal)); + } + [Fact] public async Task Should_check_a_key_a_lookup_takes_from_a_parameter_at_the_calls_writing_it() { @@ -701,10 +804,15 @@ public sealed class Widget(IStringLocale locale) var result = await LintingServiceTestFactory.Create(directory.Root, LintingSeverity.Warning, loader).RunAsync(TestContext.Current.CancellationToken); // Assert + var diagnostic = Assert.Single(result.Diagnostics); + var unread = Assert.Single(result.Coverage.UncheckedLookups); Assert.Multiple( - () => Assert.Equal([LintingCodes.MissingLocalization.Id, LintingCodes.KeyNotAnalysed.Id], result.Diagnostics.Select(diagnostic => diagnostic.Code.Id).Order(StringComparer.Ordinal)), - () => Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == LintingCodes.MissingLocalization && diagnostic.Line == 9 && diagnostic.Message.StartsWith("'Tomorrow' has no entry", StringComparison.Ordinal)), - () => Assert.Contains(result.Diagnostics, diagnostic => diagnostic.Code == LintingCodes.KeyNotAnalysed && diagnostic.Line == 7 && diagnostic.Message.Contains("the parameter 'key'", StringComparison.Ordinal))); + () => Assert.Equal((LintingCodes.MissingLocalization, 9), (diagnostic.Code, diagnostic.Line)), + () => Assert.StartsWith("'Tomorrow' has no entry", diagnostic.Message, StringComparison.Ordinal), + () => Assert.Equal(7, unread.Line), + () => Assert.Equal(["keyFromParameter"], unread.Reasons), + () => Assert.Contains("the parameter 'key'", unread.Explanation, StringComparison.Ordinal), + () => Assert.DoesNotContain("localeKeys", unread.Explanation, StringComparison.Ordinal)); } [Fact] diff --git a/tests/Forma.Locali.Engine.Tests/Rules/Projects/UnreadLocaleSourceCheckerTests.cs b/tests/Forma.Locali.Engine.Tests/Rules/Projects/UnreadLocaleSourceCheckerTests.cs deleted file mode 100644 index 5df9376..0000000 --- a/tests/Forma.Locali.Engine.Tests/Rules/Projects/UnreadLocaleSourceCheckerTests.cs +++ /dev/null @@ -1,108 +0,0 @@ -namespace Forma.Locali.Tests.Rules.Projects; - -using Forma.Locali.Projects; -using Forma.Locali.Rules.Projects; - -public sealed class UnreadLocaleSourceCheckerTests -{ - private static readonly string HebrewFile = Path.Combine(".locales", "Widget.he.json"); - - [Fact] - public void Should_report_a_lookup_whose_named_property_returns_a_type_from_an_array() - { - // Arrange - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostic = Assert.Single(Check(directory, """ - private readonly Type[] _sources = [typeof(Widget)]; - - protected override Type LocalizationSourceType => _sources[0]; - """, file)); - - // Assert - Assert.Multiple( - () => Assert.Equal(LintingCodes.UnreadLocaleSource, diagnostic.Code), - () => Assert.Equal(LintingSeverity.Warning, diagnostic.Severity), - () => Assert.Equal( - "A hint reads the lookup's type from 'Widget.LocalizationSourceType for Widget', whose getter returns no typeof or GetType() that could be read, so no rule could check 'Tomorrow' there.", - diagnostic.Message)); - } - - [Fact] - public void Should_leave_a_lookup_whose_named_property_returns_a_type_through_typeof_alone() - { - // Arrange - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostics = Check(directory, "protected override Type LocalizationSourceType => typeof(Widget);", file); - - // Assert - Assert.Empty(diagnostics); - } - - [Fact] - public void Should_leave_a_lookup_whose_named_property_returns_the_instances_GetType_alone() - { - // Arrange - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostics = Check(directory, string.Empty, file); - - // Assert - Assert.Empty(diagnostics); - } - - [Fact] - public void Should_leave_a_project_with_no_locale_files_alone() - { - // Arrange — a project localizing nothing has no key to check, read through any type. - using var directory = new TempDirectory(); - - // Act - var diagnostics = Check(directory, """ - private readonly Type[] _sources = [typeof(Widget)]; - - protected override Type LocalizationSourceType => _sources[0]; - """); - - // Assert - Assert.Empty(diagnostics); - } - - private static IReadOnlyList Check(TempDirectory directory, string members, params string[] localizationFiles) - { - var compilation = CompilationTestFactory.Referenced($$""" - using System; - - using Forma.Framework.Localization; - - namespace Scratch; - - public abstract class Component - { - protected virtual Type LocalizationSourceType => GetType(); - - protected IStringLocale L => default!; - } - - public sealed class Widget : Component - { - {{members}} - - public void Show() => _ = L["Tomorrow"]; - } - """); - var project = new LoadedProject(Path.Combine(directory.Root, "Scratch.csproj"), compilation, false, false); - var sites = new SourceLinter(SourceLinterTestFactory.Finders(), SourceLinterTestFactory.Checkers()) - .Lint(project, [.. compilation.SyntaxTrees.Select(tree => tree.FilePath)], TestContext.Current.CancellationToken) - .Callsites; - - return ProjectLinterTestFactory.Check(new UnreadLocaleSourceChecker(), project, localizationFiles, new LocaleFlow([project], [LocaleFlowTestFactory.Hint("Scratch", "Scratch.Component")], []).Resolve(project, sites)); - } -} diff --git a/tests/Forma.Locali.Engine.Tests/Rules/Projects/UnresolvedLocaleCheckerTests.cs b/tests/Forma.Locali.Engine.Tests/Rules/Projects/UnresolvedLocaleCheckerTests.cs deleted file mode 100644 index b0aa00c..0000000 --- a/tests/Forma.Locali.Engine.Tests/Rules/Projects/UnresolvedLocaleCheckerTests.cs +++ /dev/null @@ -1,154 +0,0 @@ -namespace Forma.Locali.Tests.Rules.Projects; - -using Forma.Locali.Projects; -using Forma.Locali.Rules.Projects; - -public sealed class UnresolvedLocaleCheckerTests -{ - private static readonly string HebrewFile = Path.Combine("Widget", ".locales", "he.json"); - - [Fact] - public void Should_report_a_lookup_no_path_reaches_a_type_for() - { - // Arrange - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostic = Assert.Single(Check(directory, """ - internal sealed class Factory : IStringLocaleFactory - { - public IStringLocale Create(Type resourceSource) => throw new NotSupportedException(); - - public IStringLocale Create(string baseName, string location) => throw new NotSupportedException(); - } - - public sealed class Widget - { - public string Show() => new Factory().Create(typeof(Widget))["Tomorrow"].Value; - } - """, [], file)); - - // Assert - Assert.Multiple( - () => Assert.Equal(LintingCodes.UnresolvedLocale, diagnostic.Code), - () => Assert.Equal(LintingSeverity.Warning, diagnostic.Severity), - () => Assert.Equal( - "No path from the lookup reaches the type its locale is read for, ending at a factory the code builds itself, 'new Factory().Create(typeof(Widget))', so no rule could check whether a culture answers 'Tomorrow'.", - diagnostic.Message)); - } - - [Fact] - public void Should_leave_a_lookup_reaching_a_type_alone() - { - // Arrange - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostics = Check(directory, """ - public sealed class Widget(IStringLocale locale) - { - public string Show() => locale["Tomorrow"].Value; - } - """, [], file); - - // Assert - Assert.Empty(diagnostics); - } - - [Fact] - public void Should_leave_a_project_localized_in_no_culture_alone() - { - // Arrange — a project localizing nothing has no key to check, through any type. - using var directory = new TempDirectory(); - - // Act - var diagnostics = Check(directory, """ - internal sealed class Factory : IStringLocaleFactory - { - public IStringLocale Create(Type resourceSource) => throw new NotSupportedException(); - - public IStringLocale Create(string baseName, string location) => throw new NotSupportedException(); - } - - public sealed class Widget - { - public string Show() => new Factory().Create(typeof(Widget))["Tomorrow"].Value; - } - """, []); - - // Assert - Assert.Empty(diagnostics); - } - - [Fact] - public void Should_leave_a_lookup_whose_hinted_type_member_tells_no_type_to_LOC0214() - { - // Arrange - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostics = Check(directory, """ - public abstract class Component - { - protected virtual Type LocalizationSourceType => GetType(); - - protected IStringLocale L => default!; - } - - public sealed class Widget : Component - { - private readonly Type[] _sources = [typeof(Widget)]; - - protected override Type LocalizationSourceType => _sources[0]; - - public string Show() => L["Tomorrow"].Value; - } - """, [LocaleFlowTestFactory.Hint("Scratch", "Scratch.Component")], file); - - // Assert - Assert.Empty(diagnostics); - } - - [Fact] - public void Should_leave_a_lookup_no_path_was_followed_from_alone() - { - // Arrange — no instance of the project runs the abstract type's code, so no path ended anywhere to name. - using var directory = new TempDirectory(); - var file = directory.Write(HebrewFile, LocalizationFileFakeData.Valid); - - // Act - var diagnostics = Check(directory, """ - public abstract class Widget - { - protected IStringLocale L => default!; - - public string Show() => L["Tomorrow"].Value; - } - """, [], file); - - // Assert - Assert.Empty(diagnostics); - } - - private static IReadOnlyList Check(TempDirectory directory, string declarations, IReadOnlyList hints, params string[] localizationFiles) - { - var compilation = CompilationTestFactory.Referenced($$""" - using System; - - using Forma.Framework.Localization; - - namespace Scratch; - - {{declarations}} - """); - var project = new LoadedProject(Path.Combine(directory.Root, "Scratch.csproj"), compilation, false, false); - var sites = new SourceLinter(SourceLinterTestFactory.Finders(), SourceLinterTestFactory.Checkers()) - .Lint(project, [.. compilation.SyntaxTrees.Select(tree => tree.FilePath)], TestContext.Current.CancellationToken) - .Callsites; - - return ProjectLinterTestFactory.Check(new UnresolvedLocaleChecker(), project, localizationFiles, new LocaleFlow([project], hints, []).Resolve(project, sites)); - } -} diff --git a/tests/Forma.Locali.Engine.Tests/Sources/SourceLinterTests.cs b/tests/Forma.Locali.Engine.Tests/Sources/SourceLinterTests.cs index 89fc49d..3f93cd1 100644 --- a/tests/Forma.Locali.Engine.Tests/Sources/SourceLinterTests.cs +++ b/tests/Forma.Locali.Engine.Tests/Sources/SourceLinterTests.cs @@ -9,30 +9,28 @@ namespace Forma.Locali.Tests.Sources; public sealed class SourceLinterTests { [Fact] - public void Should_report_a_key_written_as_an_expression() + public void Should_count_a_key_written_as_an_expression_as_unread_without_reporting_it() { // Act - var diagnostics = Lint(""" + var result = Result(Compile(""" private string Column { get; } = "Name"; public void Show() => _ = L[Column]; - """); + """)); // Assert - var diagnostic = Assert.Single(diagnostics); - Assert.Multiple( - () => Assert.Equal(LintingCodes.KeyNotAnalysed, diagnostic.Code), - () => Assert.Equal(LintingSeverity.Warning, diagnostic.Severity)); + () => Assert.Single(result.UnreadKeys), + () => Assert.Empty(result.Diagnostics)); } [Fact] - public void Should_report_a_key_written_as_a_call() + public void Should_count_a_key_written_as_a_call_as_unread() { // Act - var diagnostics = Lint("""public void Show(object column) => _ = L[column.ToString()];"""); + var unread = UnreadKeys("""public void Show(object column) => _ = L[column.ToString()];"""); // Assert - Assert.Equal(LintingCodes.KeyNotAnalysed, Assert.Single(diagnostics).Code); + Assert.Single(unread); } [Fact] @@ -135,10 +133,10 @@ public sealed class Checkout(Microsoft.Extensions.Localization.IStringLocalizer< public void Should_leave_a_key_written_as_a_literal_alone() { // Act - var diagnostics = Lint("""public void Show() => _ = L["Today"];"""); + var unread = UnreadKeys("""public void Show() => _ = L["Today"];"""); // Assert - Assert.Empty(diagnostics); + Assert.Empty(unread); } [Fact] @@ -151,10 +149,10 @@ public void Should_leave_a_key_written_as_a_constant_alone() """; // Act - var diagnostics = Lint(Body); + var unread = UnreadKeys(Body); // Assert - Assert.Empty(diagnostics); + Assert.Empty(unread); } [Fact] @@ -203,10 +201,10 @@ public sealed class Forwarding(IStringLocale inner) : IStringLocale """); // Act - var diagnostics = Reported(compilation); + var unread = UnreadKeys(compilation); // Assert - Assert.Empty(diagnostics); + Assert.Empty(unread); } [Fact] @@ -225,14 +223,14 @@ public sealed class Forwarding : IStringLocale """); // Act - var diagnostics = Reported(compilation); + var unread = UnreadKeys(compilation); // Assert - Assert.Empty(diagnostics); + Assert.Empty(unread); } [Fact] - public void Should_report_a_forwarded_key_from_a_type_that_is_no_localizer() + public void Should_count_a_forwarded_key_from_a_type_that_is_no_localizer_as_unread() { // Arrange — the same lookup, on a type that only holds a localizer, is a genuine blind spot. var compilation = CompilationTestFactory.Unreferenced(""" @@ -247,22 +245,22 @@ public sealed class Wrapper """); // Act - var diagnostics = Reported(compilation); + var unread = UnreadKeys(compilation); // Assert - Assert.Equal(LintingCodes.KeyNotAnalysed, Assert.Single(diagnostics).Code); + Assert.Single(unread); } [Fact] - public void Should_report_a_key_a_call_writes_as_an_expression() + public void Should_count_a_key_a_call_writes_as_an_expression_as_unread() { // Act - var diagnostics = Lint(""" + var unread = UnreadKeys(""" public void Show(object column) => _ = LocalizableText.For(column.ToString()!); """); // Assert - Assert.Equal(LintingCodes.KeyNotAnalysed, Assert.Single(diagnostics).Code); + Assert.Single(unread); } [Fact] @@ -320,7 +318,7 @@ public void Should_report_a_project_loaded_without_its_restore_output() } [Fact] - public void Should_report_a_call_to_a_hinted_method_writing_its_key_as_an_expression() + public void Should_count_a_call_to_a_hinted_method_writing_its_key_as_an_expression_as_unread() { // Arrange — the library's method looks its key up, which only the hint tells, and the call writes the key as an expression. var library = CompilationTestFactory.Referenced(""" @@ -345,16 +343,17 @@ public sealed class Page var keyed = new LocaleFlow([project], [], [LocaleFlowTestFactory.KeyHint("Contoso.Widgets", "Contoso.Widgets.Labels", "Text", typeParameter: "TSource")]).KeyedMethods; // Act - var diagnostics = new SourceLinter(SourceLinterTestFactory.Finders(), SourceLinterTestFactory.Checkers()) - .LintKeyed(project, [.. compilation.SyntaxTrees.Select(tree => tree.FilePath)], keyed, TestContext.Current.CancellationToken) - .Diagnostics; + var result = new SourceLinter(SourceLinterTestFactory.Finders(), SourceLinterTestFactory.Checkers()) + .LintKeyed(project, [.. compilation.SyntaxTrees.Select(tree => tree.FilePath)], keyed, TestContext.Current.CancellationToken); // Assert - Assert.Equal(LintingCodes.KeyNotAnalysed, Assert.Single(diagnostics).Code); + Assert.Multiple( + () => Assert.Single(result.UnreadKeys), + () => Assert.Empty(result.Diagnostics)); } - private static IReadOnlyList Lint(string body) - => Reported(Compile(body)); + private static IReadOnlyList UnreadKeys(string body) + => UnreadKeys(Compile(body)); private static IReadOnlyList Lint(string body, LintingCode code) => Reported(Compile(body), code); @@ -362,8 +361,8 @@ private static IReadOnlyList Lint(string body, LintingCode co private static IReadOnlyList Lookups(string body) => Result(Compile(body)).Callsites; - private static IReadOnlyList Reported(Compilation compilation) - => Reported(compilation, LintingCodes.KeyNotAnalysed); + private static IReadOnlyList UnreadKeys(Compilation compilation) + => Result(compilation).UnreadKeys; private static IReadOnlyList Reported(Compilation compilation, LintingCode code) => [.. Result(compilation).Diagnostics.Where(diagnostic => diagnostic.Code == code)]; diff --git a/tests/Forma.Locali.Engine.Tests/Support/Sources/ProjectLinterTestFactory.cs b/tests/Forma.Locali.Engine.Tests/Support/Sources/ProjectLinterTestFactory.cs index 3e4f14c..5015b82 100644 --- a/tests/Forma.Locali.Engine.Tests/Support/Sources/ProjectLinterTestFactory.cs +++ b/tests/Forma.Locali.Engine.Tests/Support/Sources/ProjectLinterTestFactory.cs @@ -18,8 +18,6 @@ public static IReadOnlyList Checkers(ILintingConfiguration? new RootNamespaceWithoutTypesChecker(), new UnreachableLocalizationChecker(), new LocalizationCoverageChecker(), - new UnreadLocaleSourceChecker(), - new UnresolvedLocaleChecker(), new TypeNamedFolderChecker(), new CultureCoverageChecker(), new EntryConflictChecker(), diff --git a/tests/Forma.Locali.Tests/Reporting/ConsoleDiagnosticReporterTests.cs b/tests/Forma.Locali.Tests/Reporting/ConsoleDiagnosticReporterTests.cs index 6ea672c..e75c987 100644 --- a/tests/Forma.Locali.Tests/Reporting/ConsoleDiagnosticReporterTests.cs +++ b/tests/Forma.Locali.Tests/Reporting/ConsoleDiagnosticReporterTests.cs @@ -32,6 +32,22 @@ public async Task Should_write_every_diagnostic_before_the_summary() Assert.Equal([diagnostic.ToString(), "Linted 1 file(s); 1 diagnostic(s)."], lines); } + [Fact] + public async Task Should_count_the_lookups_that_went_unchecked_after_the_summary() + { + // Arrange + await using var writer = new StringWriter(); + var reporter = new ConsoleDiagnosticReporter(writer); + var coverage = LookupCoverage.None with { Lookups = 10, FullyChecked = 7, Unchecked = 3 }; + + // Act + await reporter.ReportAsync(new LintingResult([], 2, [], 0) { Coverage = coverage }, TestContext.Current.CancellationToken); + + // Assert + var lines = writer.ToString().TrimEnd().Split(Environment.NewLine); + Assert.Equal(["Linted 2 file(s); no diagnostics.", "3 of 10 lookup(s) went unchecked; pass --report to list each and why."], lines); + } + [Fact] public async Task Should_brief_the_diagnostics_the_severity_left_out() { @@ -43,7 +59,7 @@ public async Task Should_brief_the_diagnostics_the_severity_left_out() [ new(LintingCodes.MarkerNotFirst, 2), new(LintingCodes.MissingLocalization, 4), - new(LintingCodes.KeyNotAnalysed, 1), + new(LintingCodes.BareHoleKey, 1), ]; // Act @@ -58,7 +74,7 @@ public async Task Should_brief_the_diagnostics_the_severity_left_out() string.Empty, "7 diagnostic(s) not shown:", " - LOC0102 (2)", - " - LOC0207 (4), LOC0208 (1)", + " - LOC0207 (4), LOC0209 (1)", "Pass --severity warning to read them.", ], lines); From 90802b81f12615334411806b143cf94a438db18c Mon Sep 17 00:00:00 2001 From: Eyal Alon <3756641+soyeyalon@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:02:24 +0200 Subject: [PATCH 3/3] chore(locali): release 1.0.0-preview.23 --- CHANGELOG.md | 2 +- src/Forma.Locali/Forma.Locali.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 144554d..ff4c8e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ The releases before `1.0.0-preview.11` are recorded by their [tags](https://gith ## `1.0.0-preview.23` -*Unreleased* +*November 17, 2026* - Breaking: LOC0208, LOC0214 and LOC0215 are retired, LOC0208 at a library's public method included. A lookup the run could not check is no diagnostic: one writing its key as an expression, one taking its key from a parameter some call diff --git a/src/Forma.Locali/Forma.Locali.csproj b/src/Forma.Locali/Forma.Locali.csproj index 7bb007d..80ba6c1 100644 --- a/src/Forma.Locali/Forma.Locali.csproj +++ b/src/Forma.Locali/Forma.Locali.csproj @@ -15,7 +15,7 @@ true locali formaui-net.Locali - 1.0.0-preview.22 + 1.0.0-preview.23 Eyal Alon A linter for Forma.Framework.Localization: reads locale files against the runtime's rules and every IStringLocale callsite against what the runtime will do with it. localization;linter;blazor;forma