ast-utils.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright (c) Microsoft Corporation.
  2. // Licensed under the MIT License.
  3. /**
  4. * @fileoverview Common utils for AST.
  5. */
  6. "use strict";
  7. module.exports = {
  8. isTypeScriptParserServices(parserServices) {
  9. // Check properties specific to @typescript-eslint/parser
  10. return (
  11. parserServices &&
  12. parserServices.program &&
  13. parserServices.esTreeNodeToTSNodeMap &&
  14. parserServices.tsNodeToESTreeNodeMap
  15. );
  16. },
  17. hasFullTypeInformation(context) {
  18. var hasFullTypeInformation = (
  19. context &&
  20. this.isTypeScriptParserServices(context.parserServices) &&
  21. context.parserServices.hasFullTypeInformation === true
  22. );
  23. return hasFullTypeInformation;
  24. },
  25. getFullTypeChecker(context) {
  26. return this.hasFullTypeInformation(context) ? context.parserServices.program.getTypeChecker() : null;
  27. },
  28. getNodeTypeAsString(fullTypeChecker, node, context) {
  29. if (fullTypeChecker && node) {
  30. const tsNode = context.parserServices.esTreeNodeToTSNodeMap.get(node);
  31. const tsType = fullTypeChecker.getTypeAtLocation(tsNode);
  32. const type = fullTypeChecker.typeToString(tsType);
  33. return type;
  34. }
  35. return "any";
  36. },
  37. isDocumentObject(node, context, fullTypeChecker) {
  38. if (fullTypeChecker) {
  39. const type = this.getNodeTypeAsString(fullTypeChecker, node, context);
  40. return (type === "Document");
  41. }
  42. // Best-effort checking without Type information
  43. switch (node.type) {
  44. case "Identifier":
  45. return node != undefined && node.name == "document";
  46. case "MemberExpression":
  47. return (
  48. node != undefined &&
  49. node.property != undefined &&
  50. node.property.name == "document" && (
  51. (node.object != undefined &&
  52. typeof node.object.name === "string" &&
  53. node.object.name.toLowerCase().endsWith('window')) ||
  54. (
  55. node.object != undefined &&
  56. node.object.property != undefined &&
  57. node.object.property.name == "window" &&
  58. (
  59. (node.object.object != undefined && node.object.object.type == "ThisExpression") ||
  60. (node.object.object != undefined && node.object.object.name == "globalThis")
  61. )
  62. )
  63. )
  64. );
  65. };
  66. return false;
  67. }
  68. };