當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript ast-types.visit函數代碼示例

本文整理匯總了TypeScript中ast-types.visit函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript visit函數的具體用法?TypeScript visit怎麽用?TypeScript visit使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了visit函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: it

    it("replacement", function() {
        var source = lines.join(eol);
        var printer = new Printer;
        var ast = parse(source);
        var withThis = printer.print(ast).code;
        var thisExp = /\bthis\b/g;

        assert.ok(thisExp.test(withThis));

        types.visit(ast, {
            visitThisExpression: function() {
                return builders.identifier("self");
            }
        });

        assert.strictEqual(
            printer.print(ast).code,
            withThis.replace(thisExp, "self")
        );

        var propNames: any[] = [];
        var methods: types.Visitor = {
            visitProperty: function(path) {
                var key: any = path.node.key;
                propNames.push(key.value || key.name);
                this.traverse(path);
            }
        };

        types.visit(ast, methods);
        assert.deepEqual(propNames, ["bar", "baz"]);

        types.visit(ast, {
            visitProperty: function(path) {
                if (namedTypes.Identifier.check(path.node.value) &&
                    path.node.value.name === "self") {
                    path.replace();
                    return false;
                }

                this.traverse(path);
                return;
            }
        });

        propNames.length = 0;

        types.visit(ast, methods);
        assert.deepEqual(propNames, ["bar"]);
    });
開發者ID:benjamn,項目名稱:recast,代碼行數:50,代碼來源:visit.ts

示例2: containsWriteToGlobalSettingsObject

export function containsWriteToGlobalSettingsObject(program: estree.Program) {
  let containsWriteToGlobalSettingsObject = false;
  // Note that we look for writes to these objects exactly, not to writes to
  // members of these objects.
  const globalSettingsObjects =
      new Set<string>(['Polymer', 'Polymer.Settings', 'ShadyDOM']);

  function getNamespacedName(node: estree.Node) {
    if (node.type === 'Identifier') {
      return node.name;
    }
    const memberPath = getMemberPath(node);
    if (memberPath) {
      return memberPath.join('.');
    }
    return undefined;
  }
  astTypes.visit(program, {
    visitAssignmentExpression(path: NodePath<estree.AssignmentExpression>) {
      const name = getNamespacedName(path.node.left);
      if (globalSettingsObjects.has(name!)) {
        containsWriteToGlobalSettingsObject = true;
      }
      return false;
    },
  });

  return containsWriteToGlobalSettingsObject;
}
開發者ID:,項目名稱:,代碼行數:29,代碼來源:

示例3: rewriteSingleScopeThisReferences

/**
 * Rewrite `this` references to the explicit namespaceReference identifier
 * within a single BlockStatement if they are the start of a member expression,
 * otherwise they are rewritten to `undefined`. Don't traverse deeper into new
 * scopes.
 */
function rewriteSingleScopeThisReferences(
    blockStatement: estree.BlockStatement, namespaceReference: string) {
  astTypes.visit(blockStatement, {
    visitThisExpression(path: NodePath<estree.ThisExpression>) {
      const parent = path.parent;
      if (parent && parent.node.type !== 'MemberExpression') {
        // When a namespace object is itself referenced with `this` but isn't
        // used to reference a member of the namespace, rewrite the `this` to
        // `undefined`:
        path.replace(jsc.identifier('undefined'));
      } else {
        path.replace(jsc.identifier(namespaceReference));
      }
      return false;
    },

    visitFunctionExpression(_path: NodePath<estree.FunctionExpression>) {
      // Don't visit into new scopes
      return false;
    },
    visitFunctionDeclaration(_path: NodePath<estree.FunctionDeclaration>) {
      // Don't visit into new scopes
      return false;
    },
    visitMethodDefinition(_path: NodePath) {
      // Don't visit into new scopes
      return false;
    },
    // Note: we do visit into ArrowFunctionExpressions because they
    //     inherit the containing `this` context.
  });
}
開發者ID:,項目名稱:,代碼行數:38,代碼來源:

示例4: rewriteToplevelThis

export function rewriteToplevelThis(program: estree.Program) {
  let isStrictMode = false;
  astTypes.visit(program, {
    // Don't delve into any function or class bodies.
    visitFunctionDeclaration() {
      return false;
    },
    visitFunctionExpression() {
      return false;
    },
    visitClassBody() {
      return false;
    },

    visitLiteral(path: NodePath<estree.SimpleLiteral>) {
      // A sloppy way of detecting if the script is intended to be strict mode.
      if (path.node.value === 'use strict' && path.parent &&
          path.parent.node.type === 'ExpressionStatement' &&
          path.parent.parent && path.parent.parent.node.type === 'Program') {
        isStrictMode = true;
      }
      return false;
    },

    // Sloppy mode code that references `this` at the toplevel is actually
    // talking about `window`. Make that explicit, so it works the same in
    // strict mode.
    visitThisExpression(path: NodePath<estree.ThisExpression>) {
      if (!isStrictMode) {
        path.replace({type: 'Identifier', name: 'window'});
      }
      return false;
    }
  });
}
開發者ID:,項目名稱:,代碼行數:35,代碼來源:

示例5: removeToplevelUseStrict

export function removeToplevelUseStrict(program: estree.Program) {
  astTypes.visit(program, {
    // Don't delve into any function or class bodies.
    visitFunctionDeclaration() {
      return false;
    },
    visitFunctionExpression() {
      return false;
    },
    visitClassBody() {
      return false;
    },
    visitThisExpression() {
      return false;
    },

    visitLiteral(path: NodePath<estree.SimpleLiteral>) {
      // A sloppy way of detecting if the script is intended to be strict mode.
      if (path.node.value === 'use strict' && path.parent &&
          path.parent.node.type === 'ExpressionStatement' &&
          path.parent.parent && path.parent.parent.node.type === 'Program') {
        path.prune();
      }
      return false;
    },
  });
}
開發者ID:,項目名稱:,代碼行數:27,代碼來源:

示例6: warnOnDangerousReferences

 private warnOnDangerousReferences(program: Program) {
   const originalUrl = this.originalUrl;
   astTypes.visit(program, {
     visitMemberExpression(path: NodePath<estree.MemberExpression>) {
       const memberPath = getMemberPath(path.node);
       if (memberPath !== undefined) {
         const memberName = memberPath.join('.');
         const warningMessage = dangerousReferences.get(memberName);
         if (warningMessage) {
           // TODO(rictic): track the relationship between the programs and
           // documents so we can display real Warnings here.
           console.warn(`Issue in ${originalUrl}: ${warningMessage}`);
           // console.warn(new Warning({
           //                code: 'dangerous-ref',
           //                message: warningMessage,
           //                parsedDocument???,
           //                severity: Severity.WARNING,
           //                sourceRange???
           //              }).toString());
         }
       }
       this.traverse(path);
     }
   });
 }
開發者ID:,項目名稱:,代碼行數:25,代碼來源:

示例7: rewriteRequireStatements

export function rewriteRequireStatements(program: ESTree.Program, currentModule: string,
    context: IPaeckchenContext): void {
  visit(program, {
    visitCallExpression(path: IPath<ESTree.CallExpression>): boolean {
      const callee = path.node.callee;
      // TODO: check binding here, not name
      if (n.Identifier.check(callee) && callee.name === 'require') {
        const importPath = path.node.arguments[0];
        if (n.Literal.check(importPath)) {
          const modulePath = getModulePath(currentModule, (importPath as ESTree.Literal).value.toString(), context);
          const moduleIndex = getModuleIndex(modulePath);

          path.replace(
            b.memberExpression(
              b.callExpression(
                b.identifier('__paeckchen_require__'),
                [
                  b.literal(moduleIndex)
                ]
              ),
              b.identifier('exports'),
              false
            )
          );

          enqueueModule(modulePath);
        }
        return false;
      }
      this.traverse(path);
    }
  });
}
開發者ID:ZauberNerd,項目名稱:paeckchen,代碼行數:33,代碼來源:commonjs.ts

示例8: check

    function check(code: string, tabWidth: number) {
      var lines = fromString(code, { tabWidth: tabWidth });
      assert.strictEqual(lines.length, 1);

      function checkId(s: any, loc: types.namedTypes.SourceLocation) {
        var sliced = lines.slice(loc.start, loc.end);
        assert.strictEqual(s + "", sliced.toString());
      }

      types.visit(parse(code, {
        tabWidth: tabWidth,
        parser,
      }), {
        visitIdentifier(path) {
          var ident = path.node;
          checkId(ident.name, ident.loc!);
          this.traverse(path);
        },

        visitLiteral(path) {
          var lit = path.node;
          checkId(lit.value, lit.loc!);
          this.traverse(path);
        }
      });
    }
開發者ID:benjamn,項目名稱:recast,代碼行數:26,代碼來源:parser.ts

示例9: getNodePathInProgram

export function getNodePathInProgram(
    program: estree.Program, astNode: AstNodeWithLanguage|undefined) {
  if (astNode === undefined || astNode.language !== 'js') {
    return;
  }
  const node = astNode.node;
  let associatedNodePath: NodePath|undefined;

  astTypes.visit(program, {
    visitNode(path: NodePath<estree.Node>): boolean |
    undefined {
      // Traverse first, because we want the most specific node that exactly
      // matches the given node.
      this.traverse(path);
      if (associatedNodePath === undefined &&
          isSourceLocationEqual(path.node, babelNodeToEstreeNode(node)) &&
          path.node.type === node.type) {
        associatedNodePath = path;
        return false;
      }
      return undefined;
    }
  });

  return associatedNodePath;
}
開發者ID:,項目名稱:,代碼行數:26,代碼來源:

示例10: removeNamespaceInitializers

export function removeNamespaceInitializers(
    program: estree.Program, namespaces: ReadonlySet<string|undefined>) {
  const handleAssignment =
      (path: astTypes.NodePath,
       left: estree.Node,
       right: estree.Expression) => {
        const memberName = getMemberOrIdentifierName(left);
        if (!namespaces.has(memberName)) {
          return;
        }
        if (isNoopInitializationValue(right, memberName!)) {
          // Don't emit a noop assignment.
          path.prune();
        }
      };

  astTypes.visit(program, {
    visitVariableDeclarator(
        path: astTypes.NodePath<estree.VariableDeclarator>) {
      if (path.node.init != null) {
        handleAssignment(path, path.node.id, path.node.init);
      }
      return false;
    },
    visitAssignmentExpression(
        path: astTypes.NodePath<estree.AssignmentExpression>) {
      if (path.node.operator !== '=') {
        return false;
      }
      handleAssignment(path, path.node.left, path.node.right);
      return false;
    }
  });
}
開發者ID:,項目名稱:,代碼行數:34,代碼來源:


注:本文中的ast-types.visit函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。