|
| 1 | +import { createRule } from '../ruleCreator.ts'; |
| 2 | +import { enhanceRule } from '../enhanceRule.ts'; |
| 3 | +import { directiveTracking } from '../enhancers/directiveTracking.ts'; |
| 4 | +import type { RuleContext } from '@typescript-eslint/utils/ts-eslint'; |
| 5 | +import { ASTUtils, type TSESTree } from '@typescript-eslint/utils'; |
| 6 | + |
| 7 | +export const math = createRule({ |
| 8 | + name: 'math', |
| 9 | + meta: { |
| 10 | + type: 'suggestion', |
| 11 | + docs: { |
| 12 | + description: `Disallow usage of JavaScript 'Math' methods inside 'use gpu' functions; use 'std' instead.`, |
| 13 | + }, |
| 14 | + messages: { |
| 15 | + math: "Using Math methods, such as '{{snippet}}', is not advised, and may not work as expected. Use 'std' instead.", |
| 16 | + }, |
| 17 | + schema: [], |
| 18 | + }, |
| 19 | + defaultOptions: [], |
| 20 | + |
| 21 | + create: enhanceRule({ directives: directiveTracking }, (context, state) => { |
| 22 | + const { directives } = state; |
| 23 | + |
| 24 | + return { |
| 25 | + CallExpression(node) { |
| 26 | + if (!directives.insideUseGpu()) { |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + if ( |
| 31 | + node.callee.type === 'MemberExpression' && |
| 32 | + node.callee.object.type === 'Identifier' && |
| 33 | + node.callee.object.name === 'Math' && |
| 34 | + isGlobalIdentifier(context, node.callee.object) |
| 35 | + ) { |
| 36 | + context.report({ |
| 37 | + node, |
| 38 | + messageId: 'math', |
| 39 | + data: { snippet: context.sourceCode.getText(node) }, |
| 40 | + }); |
| 41 | + } |
| 42 | + }, |
| 43 | + }; |
| 44 | + }), |
| 45 | +}); |
| 46 | + |
| 47 | +function isGlobalIdentifier( |
| 48 | + context: Readonly<RuleContext<string, unknown[]>>, |
| 49 | + node: TSESTree.Identifier, |
| 50 | +) { |
| 51 | + const variable = ASTUtils.findVariable(context.sourceCode.getScope(node), node); |
| 52 | + if (!variable) { |
| 53 | + throw new Error(`Couldn't find variable ${node.name}.`); |
| 54 | + } |
| 55 | + return variable.defs.length === 0; |
| 56 | +} |
0 commit comments