diff --git a/packages/@stylexjs/eslint-plugin/__tests__/stylex-computed-keys-test.js b/packages/@stylexjs/eslint-plugin/__tests__/stylex-computed-keys-test.js new file mode 100644 index 000000000..11abbf3ec --- /dev/null +++ b/packages/@stylexjs/eslint-plugin/__tests__/stylex-computed-keys-test.js @@ -0,0 +1,126 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +'use strict'; + +jest.disableAutomock(); + +const { RuleTester } = require('eslint'); +const validStyles = require('../src/stylex-valid-styles').default; +const nonstandardStyles = + require('../src/stylex-no-nonstandard-styles').default; + +const tester = new RuleTester({ + parser: require.resolve('hermes-eslint'), + parserOptions: { ecmaVersion: 6, sourceType: 'module' }, +}); +const code = (body) => `import * as stylex from '@stylexjs/stylex'; ${body}`; + +tester.run('computed property keys', validStyles, { + valid: [ + code( + `const property = 'color'; stylex.create({root: {[property]: 'red'}});`, + ), + code(`const property = 'color'; const alias = property; + stylex.create({root: {[alias]: 'red'}});`), + code(`const property = 'colro'; { const property = 'color'; + stylex.create({root: {[property]: 'red'}}); }`), + code(`const property = 'color'; const alias = property; + function build(property) { return stylex.create({root: {[alias]: 'red'}}); }`), + code(`const property = 'color'; function build() { const alias = property; + { const property = alias; return stylex.create({root: {[property]: 'red'}}); } }`), + code(`const property = 'color'; + stylex.create({root: {[property]: {default: 'red', ':hover': 'blue'}}});`), + { + code: code(`const property = ('color' as const) satisfies string; + stylex.create({root: {[property]: 'red'}});`), + parser: require.resolve('@typescript-eslint/parser'), + }, + ], + invalid: [ + { + code: code(`const property = 'color'; function build(property) { + return stylex.create({root: {[property]: 'red'}}); }`), + errors: [{ message: 'Computed key cannot depend on function argument' }], + }, + { + code: code(`const property = 'color'; { const property = 'colro'; + stylex.create({root: {[property]: 'red'}}); }`), + errors: [{ message: 'This is not a key that is allowed by stylex' }], + }, + { + code: code(`let property = 'color'; property = 'width'; + stylex.create({root: {[property]: 'red'}});`), + errors: [{ message: 'Computed key cannot be resolved.' }], + }, + { + code: code(`const property = alias; const alias = property; + stylex.create({root: {[property]: 'red'}});`), + errors: [{ message: 'Computed key cannot be resolved.' }], + }, + { + code: code(`const property = alias; const alias = property; + stylex.create({root: {[property]: {default: 'red'}}});`), + errors: [{ message: 'Keys must be strings' }], + }, + { + code: code(`const property = getProperty(); + stylex.create({root: {[property]: 'red'}});`), + errors: [{ message: 'Computed key cannot be resolved.' }], + }, + ], +}); + +tester.run('computed nonstandard property keys', nonstandardStyles, { + valid: [ + code(`const property = 'float'; function build(property) { + return stylex.create({root: {[property]: 'start'}}); }`), + code(`const property = alias; const alias = property; + stylex.create({root: {[property]: {default: 'start'}}});`), + ], + invalid: [ + { + code: code(`const property = 'float'; + stylex.create({root: {[property]: {default: 'start'}}});`), + output: code(`const property = 'float'; + stylex.create({root: {[property]: {default: 'inline-start'}}});`), + errors: [ + { + message: /inline-start/, + suggestions: [ + { + desc: 'Replace "start" with "inline-start"?', + output: code(`const property = 'float'; + stylex.create({root: {[property]: {default: 'inline-start'}}});`), + }, + ], + }, + ], + }, + { + code: code( + `const property = 'float'; stylex.create({root: {[property]: 'start'}});`, + ), + output: code( + `const property = 'float'; stylex.create({root: {[property]: 'inline-start'}});`, + ), + errors: [ + { + message: /inline-start/, + suggestions: [ + { + desc: 'Replace "start" with "inline-start"?', + output: code( + `const property = 'float'; stylex.create({root: {[property]: 'inline-start'}});`, + ), + }, + ], + }, + ], + }, + ], +}); diff --git a/packages/@stylexjs/eslint-plugin/flow_modules/eslint/eslint-rule.js.flow b/packages/@stylexjs/eslint-plugin/flow_modules/eslint/eslint-rule.js.flow index e9ef66fbb..b145dc2d9 100644 --- a/packages/@stylexjs/eslint-plugin/flow_modules/eslint/eslint-rule.js.flow +++ b/packages/@stylexjs/eslint-plugin/flow_modules/eslint/eslint-rule.js.flow @@ -77,7 +77,30 @@ type SkipOptions = { filter?: ((token: AST.Token) => boolean) | undefined, }; +export type Scope = { + set: $ReadOnlyMap< + string, + { + defs: $ReadOnlyArray<{ + type: string, + node: ESTree.Node, + parent?: ?ESTree.Node, + ... + }>, + references: $ReadOnlyArray<{ + init?: boolean, + isWrite(): boolean, + ... + }>, + ... + }, + >, + upper: ?Scope, + ... +}; + export type SourceCode = { + getScope(node: ESTree.Node): Scope, lines: string[], getTokensBetween( left: $ReadOnly<{ ...ESTree.Property, ... }>, @@ -116,11 +139,11 @@ export type RuleContext = { // getDeclaredVariables(node: ESTree.Node): Scope.Variable[]; - filename: string; + filename: string, - physicalFilename: string; + physicalFilename: string, - cwd: string; + cwd: string, // getScope(): Scope.Scope; diff --git a/packages/@stylexjs/eslint-plugin/src/rules/isNumber.js b/packages/@stylexjs/eslint-plugin/src/rules/isNumber.js index 6c4e9fa28..6c6049a7c 100644 --- a/packages/@stylexjs/eslint-plugin/src/rules/isNumber.js +++ b/packages/@stylexjs/eslint-plugin/src/rules/isNumber.js @@ -34,16 +34,20 @@ export const isNumber: RuleCheck = makeVariableCheckingRule( } if (node.type === 'Identifier' && context) { - // $FlowFixMe[prop-missing] Flow libdefs doesn't know SourceCode has `getScope` let scope = getSourceCode(context).getScope(node); - while (scope.upper != null && !scope.set.has(node.name)) { - scope = scope.upper; + while (!scope.set.has(node.name)) { + const upper = scope.upper; + if (upper == null) { + break; + } + scope = upper; } const variable = scope.set.get(node.name); const def = variable?.defs?.[0]; const isLocalConst = def?.node?.type === 'VariableDeclarator' && + def.parent?.type === 'VariableDeclaration' && def.parent?.kind === 'const'; return isLocalConst || variables?.get(node.name)?.type === 'number' diff --git a/packages/@stylexjs/eslint-plugin/src/stylex-no-nonstandard-styles.js b/packages/@stylexjs/eslint-plugin/src/stylex-no-nonstandard-styles.js index 71feb17b6..a5bd8a5d9 100644 --- a/packages/@stylexjs/eslint-plugin/src/stylex-no-nonstandard-styles.js +++ b/packages/@stylexjs/eslint-plugin/src/stylex-no-nonstandard-styles.js @@ -34,6 +34,7 @@ import isStylexResolvedVarsToken from './rules/isStylexResolvedVarsToken'; import isCSSVariable from './rules/isCSSVariable'; import evaluate from './utils/evaluate'; import resolveKey from './utils/resolveKey'; +import getSourceCode from './utils/getSourceCode'; import { CSSProperties, convertToStandardProperties, @@ -180,7 +181,7 @@ const stylexNoNonstandardStyles = { : key.type === 'Identifier' ? !style.computed ? key.name - : resolveKey(key, variables) + : resolveKey(key, variables, getSourceCode(context)) : null; if (isStylexResolvedVarsToken(key, stylexResolvedVarsTokenImports)) { return; @@ -218,9 +219,11 @@ const stylexNoNonstandardStyles = { return; } if (style.computed && styleKey.type !== 'Literal') { - const val = evaluate(styleKey, variables); + const val = evaluate(styleKey, variables, getSourceCode(context)); if (val != null && val !== 'ARG') { styleKey = val; + } else { + return; } } const key = diff --git a/packages/@stylexjs/eslint-plugin/src/stylex-valid-styles.js b/packages/@stylexjs/eslint-plugin/src/stylex-valid-styles.js index ba1d3de35..0b52f8395 100644 --- a/packages/@stylexjs/eslint-plugin/src/stylex-valid-styles.js +++ b/packages/@stylexjs/eslint-plugin/src/stylex-valid-styles.js @@ -41,7 +41,6 @@ import isStylexResolvedVarsToken from './rules/isStylexResolvedVarsToken'; import isStylexEnvMember from './rules/isStylexEnvMember'; import isCSSVariable from './rules/isCSSVariable'; import evaluate from './utils/evaluate'; -import resolveKey from './utils/resolveKey'; import formatPropertiesWithNodeIndentation from './utils/formatPropertiesWithNodeIndentation'; import getSourceCode from './utils/getSourceCode'; import { @@ -662,7 +661,7 @@ const stylexValidStyles = { message: 'You cannot nest styles more than one level deep', } as Rule.ReportDescriptor); } - const key = style.key; + let key: Expression | PrivateIdentifier = style.key; if (key.type === 'PrivateIdentifier') { return context.report({ node: key, @@ -670,14 +669,6 @@ const stylexValidStyles = { message: 'Private properties are not allowed in stylex', } as Rule.ReportDescriptor); } - const keyName = - key.type === 'Literal' - ? key.value - : key.type === 'Identifier' - ? !style.computed - ? key.name - : resolveKey(key, variables) - : null; if (isStylexResolvedVarsToken(key, stylexResolvedVarsTokenImports)) { return undefined; } @@ -691,6 +682,23 @@ const stylexValidStyles = { ), ); } + if (style.computed && key.type !== 'Literal') { + const resolved = evaluate(key, variables, getSourceCode(context)); + if (resolved == null || resolved === 'ARG') { + return context.report({ + node: style.key, + loc: style.key.loc, + message: 'Keys must be strings', + } as Rule.ReportDescriptor); + } + key = resolved; + } + const keyName = + key.type === 'Literal' + ? key.value + : key.type === 'Identifier' + ? key.name + : null; if ( typeof keyName !== 'string' || (key.type !== 'Literal' && key.type !== 'Identifier') @@ -771,7 +779,7 @@ const stylexValidStyles = { styleXEnvImports, ); let isStylexWhenCall = false; - if (style.computed && styleKey.type !== 'Literal') { + if (style.computed && styleKey.type !== 'Literal' && !isStylexEnvKey) { if ( styleKey.type === 'CallExpression' && styleKey.callee.type === 'MemberExpression' @@ -789,24 +797,26 @@ const stylexValidStyles = { (calleeObject.type === 'Identifier' && styleXWhenImports.has(calleeObject.name) && calleeProperty.type === 'Identifier'); - - if (!isStylexWhenCall) { - const val = evaluate(styleKey, variables); - if (val == null) { - return context.report({ - node: style.key, - loc: style.key.loc, - message: 'Computed key cannot be resolved.', - } as Rule.ReportDescriptor); - } else if (val === 'ARG') { - return context.report({ - node: style.key, - loc: style.key.loc, - message: 'Computed key cannot depend on function argument', - } as Rule.ReportDescriptor); - } else { - styleKey = val; - } + } + if (!isStylexWhenCall) { + const val = evaluate(styleKey, variables, getSourceCode(context)); + if (val == null) { + return context.report({ + node: style.key, + loc: style.key.loc, + message: + styleKey.type === 'MemberExpression' + ? 'All keys in a stylex object must be static literal values.' + : 'Computed key cannot be resolved.', + } as Rule.ReportDescriptor); + } else if (val === 'ARG') { + return context.report({ + node: style.key, + loc: style.key.loc, + message: 'Computed key cannot depend on function argument', + } as Rule.ReportDescriptor); + } else { + styleKey = val; } } } diff --git a/packages/@stylexjs/eslint-plugin/src/utils/evaluate.js b/packages/@stylexjs/eslint-plugin/src/utils/evaluate.js index 4d0b2eca6..9e0ec697c 100644 --- a/packages/@stylexjs/eslint-plugin/src/utils/evaluate.js +++ b/packages/@stylexjs/eslint-plugin/src/utils/evaluate.js @@ -9,30 +9,66 @@ import type { Expression, Pattern, Literal } from 'estree'; import type { Variables } from '../stylex-valid-styles'; +import type { SourceCode } from 'eslint/eslint-rule'; export default function evaluate( node: Expression | Pattern, variables?: Variables, + sourceCode?: SourceCode, ): null | Literal | 'ARG' { - if ( - // $FlowFixMe[invalid-compare] - node.type === 'TSSatisfiesExpression' || - // $FlowFixMe[invalid-compare] - node.type === 'TSAsExpression' - ) { - return evaluate(node.expression, variables); - } - if (node.type === 'Identifier' && variables != null) { - const existingVar = variables.get(node.name); - if (existingVar === 'ARG') { - return 'ARG'; + const visited = new Set(); + let current = node; + while (!visited.has(current)) { + visited.add(current); + if ( + // $FlowFixMe[invalid-compare] + current.type === 'TSSatisfiesExpression' || + // $FlowFixMe[invalid-compare] + current.type === 'TSAsExpression' + ) { + current = current.expression; + continue; } - if (existingVar != null) { - return evaluate(existingVar, variables); + if (current.type === 'Identifier') { + let existingVar; + if (sourceCode != null) { + // Follow each binding in its declaration's scope, including aliases. + let scope = sourceCode.getScope(current); + while (!scope.set.has(current.name)) { + const upper = scope.upper; + if (upper == null) { + break; + } + scope = upper; + } + const variable = scope.set.get(current.name); + if (variable == null || variable.defs.length !== 1) { + return null; + } + const def = variable.defs[0]; + if (def.type === 'Parameter') { + return 'ARG'; + } + if ( + def.node.type !== 'VariableDeclarator' || + def.node.id.type !== 'Identifier' || + variable.references.some((ref) => ref.isWrite() && !ref.init) + ) { + return null; + } + existingVar = def.node.init; + } else { + existingVar = variables?.get(current.name); + } + if (existingVar === 'ARG') { + return 'ARG'; + } + if (existingVar != null) { + current = existingVar; + continue; + } } - } - if (node.type === 'Literal') { - return node; + return current.type === 'Literal' ? current : null; } return null; } diff --git a/packages/@stylexjs/eslint-plugin/src/utils/resolveKey.js b/packages/@stylexjs/eslint-plugin/src/utils/resolveKey.js index 65efec7b9..21f60acc7 100644 --- a/packages/@stylexjs/eslint-plugin/src/utils/resolveKey.js +++ b/packages/@stylexjs/eslint-plugin/src/utils/resolveKey.js @@ -9,39 +9,18 @@ import type { Identifier } from 'estree'; import type { Variables } from '../stylex-valid-styles'; +import type { SourceCode } from 'eslint/eslint-rule'; +import evaluate from './evaluate'; export default function resolveKey( property: Identifier, variables?: Variables, + sourceCode?: SourceCode, ): ?string { - const name = property.name; - let existingVar = variables?.get(name); - - while (existingVar != null) { - if (existingVar === 'ARG') { - return undefined; - } - // $FlowFixMe[invalid-compare] - if (existingVar.type === 'TSAsExpression') { - existingVar = existingVar.expression; - } - // $FlowFixMe[invalid-compare] - if (existingVar.type === 'TSSatisfiesExpression') { - existingVar = existingVar.expression; - } - - if (existingVar.type === 'Literal') { - const value = existingVar.value; - if (typeof value === 'string') { - return value; - } else { - return undefined; - } - } - if (existingVar.type === 'Identifier') { - existingVar = variables?.get(existingVar.name); - } else { - return undefined; - } - } + const resolved = evaluate(property, variables, sourceCode); + return resolved != null && + resolved !== 'ARG' && + typeof resolved.value === 'string' + ? resolved.value + : undefined; }