ValidateNoCapitalizedCalls checks capitalized methods

This commit is contained in:
Joe Savona
2024-04-03 08:02:40 -07:00
parent 4c1aae4f3b
commit 90dd2084e2
3 changed files with 55 additions and 0 deletions
@@ -27,6 +27,7 @@ export function validateNoCapitalizedCalls(fn: HIRFunction): void {
};
const capitalLoadGlobals = new Map<IdentifierId, string>();
const capitalizedProperties = new Map<IdentifierId, string>();
for (const [, block] of fn.body.blocks) {
for (const { lvalue, value } of block.instructions) {
switch (value.kind) {
@@ -54,6 +55,27 @@ export function validateNoCapitalizedCalls(fn: HIRFunction): void {
suggestions: null,
});
}
break;
}
case "PropertyLoad": {
// Start conservative and disallow all capitalized method calls
if (/^[A-Z]/.test(value.property)) {
capitalizedProperties.set(lvalue.identifier.id, value.property);
}
break;
}
case "MethodCall": {
const propertyIdentifier = value.property.identifier.id;
const propertyName = capitalizedProperties.get(propertyIdentifier);
if (propertyName != null) {
CompilerError.throwInvalidReact({
reason: `Capitalized method calls may be calling components that use hooks, which make them dangerous to memoize. Ensure there are no hook calls in the function and rename it to begin with a lowercase letter to fix this error`,
description: `${propertyName} may be a component.`,
loc: value.loc,
suggestions: null,
});
}
break;
}
}
}
@@ -0,0 +1,27 @@
## Input
```javascript
// @validateNoCapitalizedCalls
function Component() {
const x = someGlobal.SomeFunc();
return x;
}
```
## Error
```
1 | // @validateNoCapitalizedCalls
2 | function Component() {
> 3 | const x = someGlobal.SomeFunc();
| ^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Capitalized method calls may be calling components that use hooks, which make them dangerous to memoize. Ensure there are no hook calls in the function and rename it to begin with a lowercase letter to fix this error. SomeFunc may be a component. (3:3)
4 |
5 | return x;
6 | }
```
@@ -0,0 +1,6 @@
// @validateNoCapitalizedCalls
function Component() {
const x = someGlobal.SomeFunc();
return x;
}