How to use acorn - 10 common examples

To help you get started, we’ve selected a few acorn 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 allenhwkim / ngentest / src / util.js View on Github external
static getNode (code) {
    let parsed;

    if (code.replace(/\n/g,'').match(/^{.*}$/m)) {
      code = `(${code})`;
    }
    try {
      parsed = jsParser.parse(code);
    } catch (e) {
      throw new Error(`ERROR Util.getNode JS code is invalid, "${code}"`);
    }
    // const parsed = jsParser.parse(code);
    const firstNode = parsed.body[0];
    const node = firstNode.type === 'BlockStatement' ? firstNode.body[0] :
      firstNode.type === 'ExpressionStatement' ? firstNode.expression : null;
    return node;
  }
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / process_command.js View on Github external
debug( 'Attempting to process top-level `await` expression...' );
		tmp = processAwait( code );
		if ( typeof tmp === 'string' ) {
			debug( 'Successfully processed top-level `await` expression.' );
			code = tmp;
		} else {
			debug( 'Unable to process command as a top-level `await` expression.' );
			debug( 'Error: %s', tmp.message );
		}
	} else {
		debug( 'Unable to detect a top-level `await` expression.' );
	}
	// Attempt to strictly parse the provided code string:
	debug( 'Attempting to generate an AST...' );
	try {
		ast = parse( code );
		debug( 'Successfully generated an AST.' );
	} catch ( error ) {
		debug( 'Unable to generate an AST.' );
		debug( 'Error: %s', error.message );
		err = error; // cache the error message
	}
	if ( err === void 0 ) {
		// If the body is empty, assume that we have been given a multi-line comment...
		if ( ast.body.length === 0 ) {
			debug( 'Detected multi-line comment.' );
			return code;
		}
		// Check whether the code ends in an empty block statement, and, if so, interpret as an empty object literal...
		for ( i = ast.body.length-1; i >= 0; i-- ) {
			node = ast.body[ i ];
			if ( node.type !== 'EmptyStatement' ) {
github rollup / d3-jsnext / generate / src / Module.js View on Github external
constructor ( file ) {
		this.file = file;
		this.dir = dirname( file );

		let lastIndex = 0;

		this.src = readSource( file, this.included = {} );
		this.magicString = new MagicString( this.src );

		// Attempt to parse with acorn
		try {
			this.ast = parse( this.src );
		} catch ( err ) {
			console.log( this.src );
			console.log( `error parsing ${file}: ${err.message}` );
			throw err;
		}

		this.internalDependencies = {};
		this.exportDependencies = {};

		this.internalNameByExportName = {};
		this.exports = {};

		this.analyse();

		this.definitions = this.ast._scope.names.slice();
	}
github getify / ScanTree / lib / index.js View on Github external
dependency_tree.push(curdep);
	}

	// skip already scanned file
	if (curdep.scanned) return;

	// only scan each dependency once
	curdep.scanned = true;

	// read file contents
	contents = fs.readFileSync(filepath,{ encoding: "utf8" });

	// consume all tokens so comments are extracted
	try {
		// prepare tokenizer for file
		tokenizer = acorn.tokenizer(contents,parse_options);

		do {
			token = tokenizer.getToken();
		}
		while (token && token.type != acorn.tokTypes.eof);
	}
	catch (err) {
		if (!OPTS.ignore.invalid) {
			if (/^Invalid:/.test(err.message)) {
				throw err;
			}
			else {
				throw new Error("Invalid: " + filepath + "\n" + err.toString());
			}
		}
	}
github publiclab / leaflet-environmental-layers / node_modules / acorn-node / lib / dynamic-import / index.js View on Github external
exports['default'] = dynamicImport;

var _acorn = require('acorn');

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } } /* eslint-disable no-underscore-dangle */


var DynamicImportKey = exports.DynamicImportKey = 'Import';

// NOTE: This allows `yield import()` to parse correctly.
_acorn.tokTypes._import.startsExpr = true;

function parseDynamicImport() {
  var node = this.startNode();
  this.next();
  if (this.type !== _acorn.tokTypes.parenL) {
    this.unexpected();
  }
  return this.finishNode(node, DynamicImportKey);
}

function parenAfter() {
  return (/^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos))
  );
}

function dynamicImport(Parser) {
github dortaldt / notyet / node_modules / with / index.js View on Github external
var originalSource = src
  var hasReturn = false
  var ast = reallyParse(src)
  var ref
  src = src.split('')

  // get a reference to the function that was inserted to add an inner context
  if ((ref = ast.body).length !== 1
   || (ref = ref[0]).type !== 'ExpressionStatement'
   || (ref = ref.expression).type !== 'CallExpression'
   || (ref = ref.callee).type !== 'MemberExpression' || ref.computed !== false || ref.property.name !== 'call'
   || (ref = ref.object).type !== 'FunctionExpression')
    throw new Error('AST does not seem to represent a self-calling function')
  var fn = ref

  walk.recursive(ast, null, {
    Function: function (node, st, c) {
      if (node === fn) {
        c(node.body, st, "ScopeBody");
      }
    },
    ReturnStatement: function (node) {
      hasReturn = true
      replace(node, 'return {value: ' + source(node.argument) + '};');
    }
  });
  function source(node) {
    return src.slice(node.start, node.end).join('')
  }
  function replace(node, str) {
    for (var i = node.start; i < node.end; i++) {
      src[i] = ''
github flaviuse / mern-authentication / client / node_modules / acorn-dynamic-import / src / index.js View on Github external
/* eslint-disable no-underscore-dangle */
import { tokTypes as tt } from 'acorn';

export const DynamicImportKey = 'Import';

// NOTE: This allows `yield import()` to parse correctly.
tt._import.startsExpr = true;

function parseDynamicImport() {
  const node = this.startNode();
  this.next();
  if (this.type !== tt.parenL) {
    this.unexpected();
  }
  return this.finishNode(node, DynamicImportKey);
}

function parenAfter() {
  return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
}

export default function dynamicImport(Parser) {
  return class extends Parser {
github kesne / acorn-dynamic-import / src / index.js View on Github external
/* eslint-disable no-underscore-dangle */
import { tokTypes as tt } from 'acorn';

export const DynamicImportKey = 'Import';

// NOTE: This allows `yield import()` to parse correctly.
tt._import.startsExpr = true;

function parseDynamicImport() {
  const node = this.startNode();
  this.next();
  if (this.type !== tt.parenL) {
    this.unexpected();
  }
  return this.finishNode(node, DynamicImportKey);
}

function parenAfter() {
  return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
}

export default function dynamicImport(Parser) {
  return class extends Parser {
github DavidWells / analytics / scripts / docs / parse / parse.js View on Github external
function parseCode(code) {
  let ast
  try {
    // Parse node code
    ast = Parser.parse(code)
  } catch (err) {
    // on fail, try module
    ast = Parser.parse(code, {
      sourceType: 'module'
    })
  }
  // console.log(ast)

  const foundExports = getExports(ast.body)

  // If parsing a window iife fallback and regex file
  if (!foundExports.length) {
    let m = getWindowExports(code)
    return {
      methodsByName: m.map((prop) => prop.name),
      methodsAndValues: m.map((x) => {
        return {
          name: x.name,
          type: x.statement,
github Youjingyu / vue-hap-tools / convert / utils / index.js View on Github external
function getVModelAst (vModels, e, keyToPolyfill) {
  // 将v-model监听的数据,添加到change的回调函数处理
  const jsStr = vModels.reduce((total, dataName) => {
    return total + `this.${dataName}=${e}.target.${keyToPolyfill};`
  }, '')
  return acorn.parse(jsStr, {sourceType: 'script'}).body
}