How to use ast-types - 10 common examples

To help you get started, we’ve selected a few ast-types examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github benjamn / recast / test / visit.ts View on Github external
import assert from "assert";
import * as types from "ast-types";
var namedTypes = types.namedTypes;
var builders = types.builders;
import { parse } from "../lib/parser";
import { Printer } from "../lib/printer";
import { EOL as eol } from "os";

var lines = [
    "// file comment",
    "exports.foo({",
    "    // some comment",
    "    bar: 42,",
    "    baz: this",
    "});"
];

describe("types.visit", function() {
    it("replacement", function() {
github GothAck / javascript-x-server / autogen / lib / enums.js View on Github external
for (let _enum of doc.find('enum')) {
    let name = _enum.attr('name').value();
    let values = new Map();
    let bits = new Map();

    if (name === 'Atom') {
      // TODO: Bojizzle the Atom Enum
      console.error('TODO: Implement Atom Enum');
      continue;
    }

    var parent_klass = `${_enum.find('*/bit').length ? 'Bit' : 'Value'}Enum`;

    var enum_klass = klasses.newClass(`${name}Enum`, parent_klass);
    enums.set(name, b.identifier(enum_klass.name));

    for (let item of _enum.find('item')) {
      let item_name = item.attr('name').value();
      let child = item.get('*');

      if (!child) {
        console.error('Enum item without a child, wut?!', item_name);
        continue;
      }
      let item_value = parseInt(child.text());

      switch (child.name()) {
        case 'value':
          values.set(item_value, item_name);
          break;
        case 'bit':
github stealjs / transpile / lib / cjs_amd.js View on Github external
// Add in the function wrapper.
	var wrapper = defineWrapper(options);

	var code = makeDefineFunctionCode(
		name,
		options.duplicateCjsDependencies ? collectDependenciesIds(body) : [],
		wrapper
	);

	var ast = esprima.parse(code);
	var astBody = body || [];

	var innerFunctions = 0;
	var expectedFunctions = options.needsFunctionWrapper ? 2 : 1;

	types.visit(ast, {
		visitFunctionExpression: function(path) {
			if (this.isModuleFactory()) {
				var functionBody = path.getValueProperty("body").body;

				astBody.forEach(function(part) {
					functionBody.push(part);
				});

				// stop traversing the tree
				this.abort();
			}

			// keep traversing the tree
			this.traverse(path);
		},
github probmods / webppl / src / transforms / stack.js View on Github external
var bindAddress = build.variableDeclaration('var', [
    build.variableDeclarator(
        build.identifier(localVarName),
        addressParam)]);

  // Use member expression so that this isn't cps'd. Writing as an
  // assignment statement doesn't work as it is wrapped in a thunk and
  // returned early from the function.
  var saveAddress = build.expressionStatement(
      build.callExpression(
      build.memberExpression(
      build.identifier(saveAddressFn[0]),
      build.identifier(saveAddressFn[1])
      ), [
        build.identifier(globalVarName),
        addressParam]));

  var expr = build.functionExpression(
      node.id,
      node.params,
      build.blockStatement([bindAddress, saveAddress].concat(node.body.body))
      );
  expr.loc = node.loc;
  return expr;
}
github rexxars / sql-to-graphql / steps / ast-builders / type-imports.js View on Github external
b.callExpression(
                    b.identifier('require'),
                    [b.literal('../resolve-map')]
                )
            )]
        )
    );

    // Require the graphql library
    if (graphql.length) {
        declarations.push(b.variableDeclaration('var',
            [b.variableDeclarator(
                b.identifier('GraphQL'),
                b.callExpression(
                    b.identifier('require'),
                    [b.literal('graphql')]
                )
            )]
        ));
    }

    // Relay needs the Node interface along with the globalIdField
    if (opts.relay) {
        declarations.push(b.variableDeclaration('var',
            [b.variableDeclarator(
                b.identifier('GraphQLRelay'),
                b.callExpression(
                    b.identifier('require'),
                    [b.literal('graphql-relay')]
                )
            )]
        ));
github paeckchen / paeckchen / packages / paeckchen-core / src / plugins / es6-import.ts View on Github external
function convertImport(tempIdentifier: ESTree.Identifier, specifier: ESTree.ImportSpecifier
    | ESTree.ImportDefaultSpecifier | ESTree.ImportNamespaceSpecifier): ESTree.VariableDeclarator {
  if (n.ImportSpecifier.check(specifier)) {
    // e.g. import { a as b, c } from './dep';
    return b.variableDeclarator(
      b.identifier(specifier.local.name),
      b.memberExpression(
        b.memberExpression(
          tempIdentifier,
          b.identifier('exports'),
          false
        ),
        b.literal(specifier.imported.name),
        true
      )
    );
  } else if (n.ImportDefaultSpecifier.check(specifier)) {
    // e.g. import dep from './dep';
    return b.variableDeclarator(
      b.identifier(specifier.local.name),
      b.memberExpression(
        b.memberExpression(
          tempIdentifier,
          b.identifier('exports'),
          false
        ),
        b.literal('default'),
        true
      )
github GothAck / javascript-x-server / autogen / lib / statement_body.js View on Github external
b.memberExpression(
                  b.thisExpression(), b.identifier('endian')),
                b.binaryExpression(
                  '!==',
                  b.memberExpression(
                    b.identifier('obj'), b.identifier(child_name)),
                  b.literal(66))
                )));
            // data.readUInt8(0) !== 66
          }
          write_stmts.push(
            b.expressionStatement(b.callExpression(
              b.memberExpression(
                b.thisExpression(),
                b.identifier(`write${child_type}`)),
              [b.memberExpression(
                b.identifier('obj'),
                b.identifier(child_name))])));
        }
        break;
      case 'list':
        {
          let child_name = child.attr('name').value();
          let child_type = child.attr('type').value();

          let fieldref = parseOp(child.get('*'), 'obj');
          if (fieldref !== null) {
            read_stmts.push(b.variableDeclaration(
              'var',
              [b.variableDeclarator(
                b.identifier(`${child_name}_length`),
                fieldref)]));
github probmods / webppl / src / transforms / naming.js View on Github external
function naming(node) {
  switch (node.type) {
    case Syntax.FunctionExpression:
      return build.functionExpression(node.id,
          [addresses.shift()].concat(node.params),
          node.body);

    // add a gensym onto the address variable
    case Syntax.CallExpression:
      if (isPrimitive(node.callee)) {
        return node;
      } else {
        return build.callExpression(node.callee,
            [makeAddressExtension(addresses[0])].concat(node.arguments));
      }

    default:
  }
}
github rexxars / sql-to-graphql / steps / ast-builders / type-imports.js View on Github external
'use strict';

var b = require('ast-types').builders;

function buildTypeImports(type, opts) {
    var imports = type.imports;
    var others = imports.filter(not(isGraphQL));
    var graphql = ['GraphQLObjectType'].concat(imports.filter(isGraphQL));

    return opts.es6 ?
        es6Import(graphql, others, opts) :
        cjsImport(graphql, others, opts);
}

function cjsImport(graphql, others, opts) {
    // Require the entity resolver
    var declarations = [
        b.variableDeclaration('var',
            [b.variableDeclarator(
github probmods / webppl / src / transforms / builders.js View on Github external
'use strict';

var builders = require('ast-types').builders;
var _ = require('lodash');

// The ast-type builders don't provide a convenient way to set the
// source location of a built node. As a work-around, we wrap each
// builder function with a new function that takes the source location
// as an extra argument and adds it to the new node. The source
// location argument is optional, and is given as the final argument
// when present.

function isLocationNode(node) {
  return _.has(node, 'start') && _.has(node, 'end');
}

module.exports = _.mapValues(builders, function(builder) {
  return function() {
    var args = _.toArray(arguments);