Skip to content

fix(get-static-value): incorrect return when variable has object mutation #257

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 123 additions & 22 deletions src/get-static-value.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import { findVariable } from "./find-variable.mjs"
/** @typedef {import("./types.mjs").StaticValue} StaticValue */
/** @typedef {import("eslint").Scope.Scope} Scope */
/** @typedef {import("eslint").Scope.Variable} Variable */
/** @typedef {import("estree").Node} Node */
/** @typedef {import("@typescript-eslint/types").TSESTree.Node} TSESTreeNode */
/** @typedef {import("@typescript-eslint/types").TSESTree.AST_NODE_TYPES} TSESTreeNodeTypes */
Expand All @@ -23,8 +24,8 @@
typeof window !== "undefined"
? // @ts-ignore
window
: typeof global !== "undefined"

Check failure on line 27 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test ([email protected] - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 27 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test ([email protected] - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 27 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test ([email protected] - [email protected] - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 27 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test (Node@12 - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 27 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test (Node@14 - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.
? global

Check failure on line 28 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test ([email protected] - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 28 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test ([email protected] - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 28 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test ([email protected] - [email protected] - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 28 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test (Node@12 - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.

Check failure on line 28 in src/get-static-value.mjs

View workflow job for this annotation

GitHub Actions / 🧪 Test (Node@14 - ESLint@8 - ubuntu-latest)

Cannot find name 'global'.
: {}

const builtinNames = Object.freeze(
Expand Down Expand Up @@ -266,9 +267,40 @@
return valueList
}

/**
* Checks if a variable is a built-in global.
* @param {Variable|null} variable The variable to check.
* @returns {variable is Variable & {defs:[]}}
*/
function isBuiltinGlobal(variable) {
return (
variable != null &&
variable.defs.length === 0 &&
builtinNames.has(variable.name) &&
variable.name in globalObject
)
}

/**
* Checks if a variable can be considered as a constant.
* @param {Variable} variable
* @returns {variable is Variable & {defs: [import("eslint").Scope.Definition & { type: "Variable" }]}} True if the variable can be considered as a constant.
*/
function canBeConsideredConst(variable) {
if (variable.defs.length !== 1) {
return false
}
const def = variable.defs[0]
return Boolean(
def.parent &&
def.type === "Variable" &&
(def.parent.kind === "const" || isEffectivelyConst(variable)),
)
}

/**
* Returns whether the given variable is never written to after initialization.
* @param {import("eslint").Scope.Variable} variable
* @param {Variable} variable
* @returns {boolean}
*/
function isEffectivelyConst(variable) {
Expand All @@ -283,6 +315,68 @@
return false
}

/**
* Checks if a variable has mutation in its property.
* @param {Variable} variable The variable to check.
* @param {Scope|null} initialScope The scope to start finding variable. Optional. If the node is a computed property node and this scope was given, this checks the computed property name by the `getStringIfConstant` function with the scope, and returns the value of it.
* @returns {boolean} True if the variable has mutation in its property.
*/
function hasMutationInProperty(variable, initialScope) {
Copy link

@fisker fisker Jul 30, 2025

Choose a reason for hiding this comment

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

I'm not sure about this, there are too many ways to mutate an object, make an exception for property assignment not really helping IMHO. Maybe we should add extra property the result to indicate if the value is absolutely safe to use?

Copy link
Member Author

@ota-meshi ota-meshi Jul 30, 2025

Choose a reason for hiding this comment

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

Thank you for your comment!

there are too many ways to mutate an object

I agree with it, but I think it's at least a step forward from where we are now 😅

Maybe we should add extra property the result to indicate if the value is absolutely safe to use?

I think we could add a property, but under what specific conditions would that be absolutely safe?
Either way, I think that can be handled in a separate PR. This PR would allow us to return null for non-static values.

Copy link

@fisker fisker Jul 30, 2025

Choose a reason for hiding this comment

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

but under what specific conditions would that be absolutely safe?

Only defined, no other reference, except property access(read primitive value).

Copy link
Member Author

Choose a reason for hiding this comment

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

I think the a variable in the last statement of the script below won't get that mark, is that correct?
So, I think the user should consider that if the value is an object, it is potentially dangerous (not absolutely safe).

const a = {foo: 'a'};

// ... 

a; // <--

This PR finds mutations of a in the following script, so I think it would be better to make adding new properties a separate task.

const a = {foo: 'a'};
a.bar = 'b';
a; // <--

for (const ref of variable.references) {
let node = /** @type {TSESTreeNode} */ (ref.identifier)
while (node && node.parent && node.parent.type === "MemberExpression") {
node = node.parent
}
if (!node || !node.parent) {
continue
}
if (
(node.parent.type === "AssignmentExpression" &&
node.parent.left === node) ||
(node.parent.type === "UpdateExpression" &&
node.parent.argument === node)
) {
// This is a mutation.
return true
}
if (
node.parent.type === "CallExpression" &&
node.parent.callee === node &&
node.type === "MemberExpression"
) {
const methodName = getStaticPropertyNameValue(node, initialScope)
if (isNameOfMutationArrayMethod(methodName)) {
// This is a mutation.
return true
}
}
}
return false

/**
* Checks if a method name is one of the mutation array methods.
* @param {StaticValue|null} methodName The method name to check.
* @returns {boolean} True if the method name is a mutation array method.
*/
function isNameOfMutationArrayMethod(methodName) {
if (methodName == null || methodName.value == null) {
return false
}
const name = methodName.value
return (
name === "copyWithin" ||
name === "fill" ||
name === "pop" ||
name === "push" ||
name === "reverse" ||
name === "shift" ||
name === "sort" ||
name === "splice" ||
name === "unshift"
)
}
}

/**
* @template {TSESTreeNodeTypes} T
* @callback VisitorCallback
Expand Down Expand Up @@ -512,28 +606,35 @@
if (initialScope != null) {
const variable = findVariable(initialScope, node)

// Built-in globals.
if (
variable != null &&
variable.defs.length === 0 &&
builtinNames.has(variable.name) &&
variable.name in globalObject
) {
return { value: globalObject[variable.name] }
}
if (variable != null) {
// Built-in globals.
if (isBuiltinGlobal(variable)) {
return { value: globalObject[variable.name] }
}

// Constants.
if (variable != null && variable.defs.length === 1) {
const def = variable.defs[0]
if (
def.parent &&
def.type === "Variable" &&
(def.parent.kind === "const" ||
isEffectivelyConst(variable)) &&
// TODO(mysticatea): don't support destructuring here.
def.node.id.type === "Identifier"
) {
return getStaticValueR(def.node.init, initialScope)
// Constants.
if (canBeConsideredConst(variable)) {
const def = variable.defs[0]
if (
// TODO(mysticatea): don't support destructuring here.
def.node.id.type === "Identifier"
) {
const init = getStaticValueR(
def.node.init,
initialScope,
)
if (
init &&
typeof init.value === "object" &&
init.value !== null
) {
if (hasMutationInProperty(variable, initialScope)) {
// This variable has mutation in its property.
return null
}
}
return init
}
}
}
}
Expand Down
49 changes: 49 additions & 0 deletions test/get-static-value.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,55 @@ const aMap = Object.freeze({
},
]
: []),
// Mutations
{
code: "const a = {foo: 'a'}; a.bar = 'b'; a",
expected: null,
},
{
code: "const a = ['a']; a[0] = 'b'; a.join()",
expected: null,
},
{
code: "const a = ['a']; a.copyWithin(0, 1); a.join()",
expected: null,
},
{
code: "const a = ['a']; a.fill('b'); a.join()",
expected: null,
},
{
code: "const a = ['a']; a.pop(); a.join()",
expected: null,
},
{
code: "const a = ['a']; a.push('b'); a.join()",
expected: null,
},
{
code: "const a = ['a', 'b']; a.reverse(); a.join()",
expected: null,
},
{
code: "const a = ['a']; a.shift(); a.join()",
expected: null,
},
{
code: "const a = ['b', 'a', 'c']; a.sort(); a.join()",
expected: null,
},
{
code: "const a = ['a', 'c']; a.splice(1, 0, 'b'); a.join()",
expected: null,
},
{
code: "const a = ['a']; a.unshift('b'); a.join()",
expected: null,
},
{
code: "const a = {foo: ['a']}; a.foo.shift(); a",
expected: null,
},
// TypeScript support
{
code: `const a = 42; a as number;`,
Expand Down
Loading