Skip to content

AI-native design editor. Open-source Figma alternative.

5.5 KB
Raw Blame
import {
  arrayMethodTarget,
  isKnownArrayExpression,
  resolveArrayBinding,
  unwrapArrayExpression
} from '#oxlint-plugin/support/array-method'
import { constInitializer } from '#oxlint-plugin/support/scope'
import { defineRule } from '@oxlint/plugins'
import type { ESTree, SourceCode, Variable } from '@oxlint/plugins'

function enclosingReducer(node: ESTree.Node) {
  let parent = node.parent
  while (parent !== null) {
    if (parent.type === 'FunctionDeclaration') return null
    if (parent.type === 'ArrowFunctionExpression' || parent.type === 'FunctionExpression') {
      const callback = parent
      let owner: ESTree.Node | null = callback.parent
      while (owner !== null && unwrapArrayExpression(owner) === callback) owner = owner.parent
      if (owner?.type !== 'CallExpression') return null
      const method = arrayMethodTarget(owner.callee)
      const firstArgument = owner.arguments[0]
      if (
        method === null ||
        (method.name !== 'reduce' && method.name !== 'reduceRight') ||
        owner.arguments.length > 2 ||
        firstArgument === undefined ||
        unwrapArrayExpression(firstArgument) !== callback
      )
        return null
      const firstParameter = callback.params[0]
      const accumulator =
        firstParameter?.type === 'AssignmentPattern' ? firstParameter.left : firstParameter
      if (accumulator?.type !== 'Identifier') return null
      return { callback, accumulator, initialValue: owner.arguments[1] }
    }
    parent = parent.parent
  }
  return null
}

function referencesAccumulator(
  sourceCode: SourceCode,
  node: ESTree.Node,
  accumulator: Variable,
  visited = new Set<Variable>()
): boolean {
  const variable = resolveArrayBinding(sourceCode, node)
  if (variable === null || visited.has(variable)) return false
  if (variable === accumulator) return true
  visited.add(variable)
  if (variable.references.some((reference) => reference.isWrite() && !reference.init)) return false
  const initializer = constInitializer(variable)
  if (initializer) return referencesAccumulator(sourceCode, initializer, accumulator, visited)
  return false
}

function isGlobalCopyOwner(sourceCode: SourceCode, node: ESTree.Node, name: string): boolean {
  node = unwrapArrayExpression(node)
  if (node.type !== 'Identifier' || node.name !== name) return false
  const variable = resolveArrayBinding(sourceCode, node)
  return variable === null || variable.defs.length === 0
}

function numericLiteral(node: ESTree.Node | undefined): number | null {
  if (node?.type === 'Literal' && typeof node.value === 'number') return node.value
  if (node?.type === 'UnaryExpression' && node.operator === '-') {
    const value = numericLiteral(node.argument)
    return value === null ? null : -value
  }
  return null
}

function isBoundedSlice(node: ESTree.CallExpression): boolean {
  const start = numericLiteral(node.arguments[0])
  const end = numericLiteral(node.arguments[1])
  return (
    (start !== null && Number.isFinite(start) && Math.trunc(start) < 0) ||
    (end !== null && Number.isFinite(end) && Math.trunc(end) >= 0)
  )
}

/** Reject unbounded copies of reducer accumulators; pair with oxc/no-accumulating-spread. */
export const noReduceAccumulatorCopyRule = defineRule({
  meta: {
    type: 'problem',
    docs: {
      description:
        'Disallow copying growing reducer accumulators with Object.assign, Array.from, or array copy methods.'
    },
    messages: {
      accumulatorCopy:
        'Do not copy the reducer accumulator on every iteration; growing copies can cause quadratic work. Mutate a fresh, locally owned accumulator and return it, or use an iterator pipeline/flatMap.'
    }
  },
  createOnce(context) {
    return {
      CallExpression(node) {
        const method = arrayMethodTarget(node.callee)
        if (method === null) return
        const reducer = enclosingReducer(node)
        if (reducer === null) return
        const accumulator = context.sourceCode
          .getDeclaredVariables(reducer.callback)
          .find((variable) =>
            variable.identifiers.some(
              (identifier) => identifier.start === reducer.accumulator.start
            )
          )
        if (accumulator === undefined) return
        const isAccumulator = (expression: ESTree.Node) =>
          referencesAccumulator(context.sourceCode, expression, accumulator)
        let copiesAccumulator = false
        if (
          method.name === 'assign' &&
          isGlobalCopyOwner(context.sourceCode, method.object, 'Object')
        ) {
          const target = node.arguments[0]
          copiesAccumulator =
            target !== undefined &&
            unwrapArrayExpression(target).type === 'ObjectExpression' &&
            node.arguments.slice(1).some(isAccumulator)
        } else if (
          method.name === 'from' &&
          isGlobalCopyOwner(context.sourceCode, method.object, 'Array')
        ) {
          const source = node.arguments[0]
          copiesAccumulator = source !== undefined && isAccumulator(source)
        } else if (
          ['concat', 'slice', 'toSpliced', 'toSorted', 'toReversed', 'with'].includes(method.name)
        ) {
          const initialValue = reducer.initialValue
          const arrayAccumulator =
            initialValue !== undefined && isKnownArrayExpression(context.sourceCode, initialValue)
          copiesAccumulator =
            arrayAccumulator &&
            isAccumulator(method.object) &&
            !(method.name === 'slice' && isBoundedSlice(node))
        }
        if (copiesAccumulator) context.report({ node, messageId: 'accumulatorCopy' })
      }
    }
  }
})