-
-
Notifications
You must be signed in to change notification settings - Fork 52
feat: RuleEnhancer & unwrapped POJOs rule #2127
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
aleksanderkatan
wants to merge
45
commits into
main
Choose a base branch
from
feat/lint-unwrapped-pojos
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
91eeaa8
Add package.json
e063b7c
Add index.ts
a558156
Add tsup config
1af79a1
Add a dummy rule for testing
d0b6651
Add testing infrastructure
bb433b8
Add a proper rule
dfbaddd
Remove the dummy rule
4eead5a
Add a readme stub
19bbcd7
Add formatting
0ec6db1
Check for a cast in parent
6712b4b
Review fixes
320563b
Add a describe to please vitest gods
b5d3a21
Add configuration for test:types
c255562
Increase old size limit
ea990e6
Bump attest
cfd112e
Fix failing build
30af466
Add recommended rules
adb6799
Add all rules
340a924
Fix configuration so that the plugin is usable
9042d4e
Update lock
2ea027a
Merge remote-tracking branch 'origin/main' into feat/type-aware-lint-…
a49362e
Review fixes
ff415f6
Remove an unnecessary dependency
0795486
smol
0c879de
Merge branch 'main' into feat/type-aware-lint-plugin-poc
460e199
Report on || instead of &&
99a4b32
Merge remote-tracking branch 'origin/main' into feat/type-aware-lint-…
8312172
Fix lock
7825379
Merge remote-tracking branch 'origin/main' into feat/type-aware-lint-…
3b6ee06
Add a base for the rule
a2cc376
Rule enhancers POC
f2a0ff1
Clean up types
252665f
Update directiveTracking API
ec684e3
Add more tests and implement rule logic
770fd03
Implement directive tracking
7c91882
Self review
2664a72
Ignores returns
8e85376
Handle nested structs
c8416f1
Merge remote-tracking branch 'origin/main' into feat/lint-unwrapped-p…
f807686
Fix import
4bd7a06
Merge remote-tracking branch 'origin/main' into feat/lint-unwrapped-p…
069be78
Format files
0c9a476
Update tests
74377b0
Remove tsup config
9a4f2d2
Merge branch 'main' into feat/lint-unwrapped-pojos
aleksanderkatan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,20 @@ | ||
| import type { TSESLint } from '@typescript-eslint/utils'; | ||
| import { integerDivision } from './rules/integerDivision.ts'; | ||
| import { unwrappedPojos } from './rules/unwrappedPojos.ts'; | ||
|
|
||
| export const rules = { | ||
| 'integer-division': integerDivision, | ||
| 'unwrapped-pojo': unwrappedPojos, | ||
| } as const; | ||
|
|
||
| type Rules = Record<`typegpu/${keyof typeof rules}`, TSESLint.FlatConfig.RuleEntry>; | ||
|
|
||
| export const recommendedRules: Rules = { | ||
| 'typegpu/integer-division': 'warn', | ||
| 'typegpu/unwrapped-pojo': 'warn', | ||
| }; | ||
|
|
||
| export const allRules: Rules = { | ||
| 'typegpu/integer-division': 'error', | ||
| 'typegpu/unwrapped-pojo': 'error', | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| import type { RuleContext, RuleListener } from '@typescript-eslint/utils/ts-eslint'; | ||
|
|
||
| export type RuleEnhancer<TState> = (context: RuleContext<string, unknown[]>) => { | ||
| visitors: RuleListener; | ||
| state: TState; | ||
| }; | ||
|
|
||
| type State<TMap extends Record<string, RuleEnhancer<unknown>>> = { | ||
| [K in keyof TMap]: TMap[K] extends RuleEnhancer<infer S> ? S : never; | ||
| }; | ||
|
|
||
| /** | ||
| * Allows enhancing rule code with additional context provided by RuleEnhancers (reusable node visitors collecting data). | ||
| * @param enhancers a record of RuleEnhancers | ||
| * @param rule a visitor with an additional `state` argument that allows access to the enhancers' data | ||
| * @returns a resulting `(context: Context) => RuleListener` function | ||
| * | ||
| * @example | ||
| * // inside of `createRule` | ||
| * create: enhanceRule({ metadata: metadataTrackingEnhancer }, (context, state) => { | ||
| * const { metadata } = state; | ||
| * | ||
| * return { | ||
| * ObjectExpression(node) { | ||
| * if (metadata.shouldReport()) { | ||
| * context.report({ node, messageId: 'error' }); | ||
| * } | ||
| * }, | ||
| * }; | ||
| */ | ||
| export function enhanceRule< | ||
| TMap extends Record<string, RuleEnhancer<unknown>>, | ||
| Context extends RuleContext<string, unknown[]>, | ||
| >(enhancers: TMap, rule: (context: Context, state: State<TMap>) => RuleListener) { | ||
| return (context: Context) => { | ||
| const enhancerVisitors: RuleListener[] = []; | ||
| const combinedState: Record<string, unknown> = {}; | ||
|
|
||
| for (const [key, enhancer] of Object.entries(enhancers)) { | ||
| const initializedEnhancer = enhancer(context); | ||
| enhancerVisitors.push(initializedEnhancer.visitors); | ||
| combinedState[key] = initializedEnhancer.state; | ||
| } | ||
|
|
||
| const initializedRule = rule(context, combinedState as State<TMap>); | ||
|
|
||
| return mergeVisitors([...enhancerVisitors, initializedRule]); | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Merges all passed visitors into one visitor. | ||
| * Retains visitor order: | ||
| * - on node enter, visitors are called in `visitorsList` order, | ||
| * - on node exit, visitors are called in reversed order. | ||
| */ | ||
| function mergeVisitors(visitors: RuleListener[]): RuleListener { | ||
| const merged: RuleListener = {}; | ||
|
|
||
| const allKeys = new Set(visitors.flatMap((v) => Object.keys(v))); | ||
|
|
||
| for (const key of allKeys) { | ||
| const listeners = visitors.map((v) => v[key]).filter((fn) => fn !== undefined); | ||
|
|
||
| if (listeners.length === 0) { | ||
| continue; | ||
| } | ||
|
|
||
| // Reverse order if node is an exit node | ||
| if (key.endsWith(':exit')) { | ||
| listeners.reverse(); | ||
| } | ||
|
|
||
| merged[key] = (...args: unknown[]) => { | ||
| // biome-ignore lint/suspicious/useIterableCallbackReturn: those functions return void | ||
| listeners.forEach((fn) => (fn as (...args: unknown[]) => void)(...args)); | ||
| }; | ||
| } | ||
|
|
||
| return merged; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| import type { TSESTree } from '@typescript-eslint/utils'; | ||
| import type { RuleListener } from '@typescript-eslint/utils/ts-eslint'; | ||
| import type { RuleEnhancer } from '../enhanceRule.ts'; | ||
|
|
||
| export type DirectiveData = { | ||
| insideUseGpu: () => boolean; | ||
| }; | ||
|
|
||
| /** | ||
| * A RuleEnhancer that tracks whether the current node is inside a 'use gpu' function. | ||
| * | ||
| * @privateRemarks | ||
| * Should the need arise, the API could be updated to expose: | ||
| * - a list of directives of the current function, | ||
| * - directives of other visited functions, | ||
| * - top level directives. | ||
| */ | ||
| export const directiveTracking: RuleEnhancer<DirectiveData> = () => { | ||
| const stack: string[][] = []; | ||
|
|
||
| const visitors: RuleListener = { | ||
| FunctionDeclaration(node) { | ||
| stack.push(getDirectives(node)); | ||
| }, | ||
| FunctionExpression(node) { | ||
| stack.push(getDirectives(node)); | ||
| }, | ||
| ArrowFunctionExpression(node) { | ||
| stack.push(getDirectives(node)); | ||
| }, | ||
|
|
||
| 'FunctionDeclaration:exit'() { | ||
| stack.pop(); | ||
| }, | ||
| 'FunctionExpression:exit'() { | ||
| stack.pop(); | ||
| }, | ||
| 'ArrowFunctionExpression:exit'() { | ||
| stack.pop(); | ||
| }, | ||
| }; | ||
|
|
||
| return { | ||
| visitors, | ||
| state: { insideUseGpu: () => (stack.at(-1) ?? []).includes('use gpu') }, | ||
| }; | ||
| }; | ||
|
|
||
| function getDirectives( | ||
| node: | ||
| | TSESTree.FunctionDeclaration | ||
| | TSESTree.FunctionExpression | ||
| | TSESTree.ArrowFunctionExpression, | ||
| ): string[] { | ||
| const body = node.body; | ||
| if (body.type !== 'BlockStatement') { | ||
| return []; | ||
| } | ||
|
|
||
| const directives: string[] = []; | ||
| for (const statement of body.body) { | ||
| if (statement.type === 'ExpressionStatement' && statement.directive) { | ||
| directives.push(statement.directive); | ||
| } else { | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| return directives; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import { enhanceRule } from '../enhanceRule.ts'; | ||
| import { directiveTracking } from '../enhancers/directiveTracking.ts'; | ||
| import { createRule } from '../ruleCreator.ts'; | ||
|
|
||
| export const unwrappedPojos = createRule({ | ||
| name: 'unwrapped-pojo', | ||
| meta: { | ||
| type: 'problem', | ||
| docs: { | ||
| description: `Wrap Plain Old JavaScript Objects with schemas.`, | ||
| }, | ||
| messages: { | ||
| unwrappedPojo: | ||
| '{{snippet}} is a POJO that is not wrapped in a schema. To allow WGSL resolution, wrap it in a schema call. You only need to wrap the outermost object.', | ||
| }, | ||
| schema: [], | ||
| }, | ||
| defaultOptions: [], | ||
|
|
||
| create: enhanceRule({ directives: directiveTracking }, (context, state) => { | ||
| const { directives } = state; | ||
|
|
||
| return { | ||
| ObjectExpression(node) { | ||
| if (!directives.insideUseGpu()) { | ||
| return; | ||
| } | ||
| if (node.parent?.type === 'Property') { | ||
| // a part of a bigger struct | ||
| return; | ||
| } | ||
| if (node.parent?.type === 'CallExpression') { | ||
| // wrapped in a schema call | ||
| return; | ||
| } | ||
| if (node.parent?.type === 'ReturnStatement') { | ||
| // likely inferred (shelled fn or shell-less entry) so we cannot report | ||
| return; | ||
| } | ||
| context.report({ | ||
| node, | ||
| messageId: 'unwrappedPojo', | ||
| data: { snippet: context.sourceCode.getText(node) }, | ||
| }); | ||
| }, | ||
| }; | ||
| }), | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { describe } from 'vitest'; | ||
| import { ruleTester } from './ruleTester.ts'; | ||
| import { unwrappedPojos } from '../src/rules/unwrappedPojos.ts'; | ||
|
|
||
| describe('unwrappedPojos', () => { | ||
| ruleTester.run('unwrappedPojos', unwrappedPojos, { | ||
| valid: [ | ||
| // correctly wrapped | ||
| "function func() { 'use gpu'; const wrapped = Schema({ a: 1 }); }", | ||
| "const func = function() { 'use gpu'; const wrapped = Schema({ a: 1 }); }", | ||
| "() => { 'use gpu'; const wrapped = Schema({ a: 1 }); }", | ||
|
|
||
| // not inside 'use gpu' function | ||
| 'const pojo = { a: 1 };', | ||
| 'function func() { const unwrapped = { a: 1 }; }', | ||
| 'const func = function () { const unwrapped = { a: 1 }; }', | ||
| '() => { const unwrapped = { a: 1 }; }', | ||
| 'function func() { return { a: 1 }; }', | ||
| 'const func = function () { return { a: 1 }; }', | ||
| '() => { return { a: 1 }; }', | ||
|
|
||
| // return from 'use gpu' function | ||
| "function func() { 'use gpu'; return { a: 1 }; }", | ||
| "const func = function() { 'use gpu'; return { a: 1 }; }", | ||
| "() => { 'use gpu'; return { a: 1 }; }", | ||
| "() => { 'use gpu'; return { a: { b: 1 } }; }", | ||
| ], | ||
| invalid: [ | ||
| { | ||
| code: "function func() { 'use gpu'; const unwrapped = { a: 1 }; }", | ||
| errors: [ | ||
| { | ||
| messageId: 'unwrappedPojo', | ||
| data: { snippet: '{ a: 1 }' }, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| code: "const func = function() { 'use gpu'; const unwrapped = { a: 1 }; }", | ||
| errors: [ | ||
| { | ||
| messageId: 'unwrappedPojo', | ||
| data: { snippet: '{ a: 1 }' }, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| code: "() => { 'use gpu'; const unwrapped = { a: 1 }; }", | ||
| errors: [ | ||
| { | ||
| messageId: 'unwrappedPojo', | ||
| data: { snippet: '{ a: 1 }' }, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| code: "function func() { 'unknown directive'; 'use gpu'; const unwrapped = { a: 1 }; }", | ||
| errors: [ | ||
| { | ||
| messageId: 'unwrappedPojo', | ||
| data: { snippet: '{ a: 1 }' }, | ||
| }, | ||
| ], | ||
| }, | ||
| { | ||
| code: "() => { 'use gpu'; const unwrapped = { a: { b: 1 } }; }", | ||
| errors: [ | ||
| { | ||
| messageId: 'unwrappedPojo', | ||
| data: { snippet: '{ a: { b: 1 } }' }, | ||
| }, | ||
| ], | ||
| }, | ||
| ], | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.