|
| 1 | +/** |
| 2 | + * @name Suspicious method name declaration |
| 3 | + * @description A method declaration with a name that is a special keyword in another |
| 4 | + * context is suspicious. |
| 5 | + * @kind problem |
| 6 | + * @problem.severity warning |
| 7 | + * @id js/suspicious-method-name-declaration |
| 8 | + * @precision high |
| 9 | + * @tags correctness |
| 10 | + * typescript |
| 11 | + * methods |
| 12 | + */ |
| 13 | + |
| 14 | +import javascript |
| 15 | + |
| 16 | +/** |
| 17 | + * Holds if the method name on the given container is likely to be a mistake. |
| 18 | + */ |
| 19 | +predicate isSuspiciousMethodName(string name, ClassOrInterface container) { |
| 20 | + name = "function" |
| 21 | + or |
| 22 | + // "constructor" is only suspicious outside a class. |
| 23 | + name = "constructor" and not container instanceof ClassDefinition |
| 24 | + or |
| 25 | + // "new" is only suspicious inside a class. |
| 26 | + name = "new" and container instanceof ClassDefinition |
| 27 | +} |
| 28 | + |
| 29 | +from MethodDeclaration member, ClassOrInterface container, string name, string msg |
| 30 | +where |
| 31 | + container.getLocation().getFile().getFileType().isTypeScript() and |
| 32 | + container.getMember(name) = member and |
| 33 | + isSuspiciousMethodName(name, container) and |
| 34 | + |
| 35 | + // Cases to ignore. |
| 36 | + not ( |
| 37 | + // Assume that a "new" method is intentional if the class has an explicit constructor. |
| 38 | + name = "new" and |
| 39 | + container instanceof ClassDefinition and |
| 40 | + exists(ConstructorDeclaration constructor | |
| 41 | + container.getMember("constructor") = constructor and |
| 42 | + not constructor.isSynthetic() |
| 43 | + ) |
| 44 | + or |
| 45 | + // Explicitly declared static methods are fine. |
| 46 | + container instanceof ClassDefinition and |
| 47 | + member.isStatic() |
| 48 | + or |
| 49 | + // Only looking for declared methods. Methods with a body are OK. |
| 50 | + exists(member.getBody().getBody()) |
| 51 | + or |
| 52 | + // The developer was not confused about "function" when there are other methods in the interface. |
| 53 | + name = "function" and |
| 54 | + exists(MethodDeclaration other | other = container.getAMethod() | |
| 55 | + other.getName() != "function" and |
| 56 | + not other.(ConstructorDeclaration).isSynthetic() |
| 57 | + ) |
| 58 | + ) |
| 59 | + |
| 60 | + and |
| 61 | + |
| 62 | + ( |
| 63 | + name = "constructor" and msg = "The member name 'constructor' does not declare a constructor in interfaces, but it does in classes." |
| 64 | + or |
| 65 | + name = "new" and msg = "The member name 'new' does not declare a constructor, but 'constructor' does in class declarations." |
| 66 | + or |
| 67 | + name = "function" and msg = "The member name 'function' does not declare a function, it declares a method named 'function'." |
| 68 | + ) |
| 69 | +select member, msg |
0 commit comments