How to use the acorn-loose.parse function in acorn-loose

To help you get started, we’ve selected a few acorn-loose 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 sverweij / dependency-cruiser / src / extract / parse / toJavascriptAST.js View on Github external
try {
    // console.log(
    //   JSON.stringify(
    //     acorn.parse(lJavaScriptSource, { sourceType: "module", ecmaVersion: 11 }),
    //     null,
    //     "  "
    //   )
    // );
    // ecmaVersion 11 necessary for acorn to understand dynamic imports
    // default ecmaVersion for acorn 7 is still 10.
    return acorn.parse(lJavaScriptSource, {
      sourceType: "module",
      ecmaVersion: 11
    });
  } catch (e) {
    return acornLoose.parse(lJavaScriptSource, { sourceType: "module" });
  }
}
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / process_line.js View on Github external
// Check if the command has valid syntax...
		debug( 'Processing command...' );
		tmp = processCommand( cmd );
		if ( tmp instanceof Error ) {
			debug( 'Unable to process command.' );
			debug( 'Error: %s', tmp.message );
			debug( 'Attempting to detect multi-line input...' );
			if ( hasMultilineError( cmd ) ) {
				debug( 'Detected multi-line input. Waiting for additional lines...' );
				repl._cmd.push( line );
				repl._multiline_mode = true;
				displayPrompt( repl, false );
				return;
			}
			// Still possible that a user is attempting to enter an object literal across multiple lines...
			ast = parseLoose( cmd );

			// Check for a trailing node which is being interpreted as a block statement, as this could be an object literal...
			node = ast.body[ ast.body.length-1 ];
			if ( node.type === 'BlockStatement' && node.end === ast.end ) {
				tmp = cmd.slice( node.start, node.end );
				if ( hasMultilineError( tmp ) ) {
					debug( 'Detected multi-line input. Waiting for additional lines...' );
					repl._cmd.push( line );
					repl._multiline_mode = true;
					displayPrompt( repl, false );
					return;
				}
			}
			debug( 'Multi-line input not detected.' );
			repl._ostream.write( 'Error: '+tmp.message+'\n' );
			repl._cmd.length = 0;
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / complete_expression.js View on Github external
var script;
	var node;
	var opts;
	var ast;
	var obj;
	var res;

	// Case: `<|>` (a command devoid of expressions/statements)
	if ( trim( expression ) === '' ) {
		debug( 'Auto-completion triggered without a filter. Empty expression.' );
		out.push.apply( out, objectKeys( context ) );
		out.push.apply( out, RESERVED_KEYWORDS_COMMON );
		return '';
	}
	debug( 'Parsing expression into an AST.' );
	ast = parse( expression );

	debug( 'Resolving local scopes within the AST.' );
	ast = resolveLocalScopes( ast );

	// Get the last program top-level AST "node":
	debug( 'Number of statements: %d', ast.body.length );
	node = ast.body[ ast.body.length-1 ];

	// Check for an empty trailing "expression"...
	if (
		node.end !== ast.end &&
		expression[ node.end ] === ';' &&
		trim( expression.slice( node.end+1 ) ) === ''
	) {
		debug( 'Auto-completion triggered without a filter. Empty expression.' );
		out.push.apply( out, RESERVED_KEYWORDS_COMMON );
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / complete_fs.js View on Github external
var files;
	var stats;
	var args;
	var ast;
	var arg;
	var dir;
	var f;
	var i;

	// Get the list of argument types for the desired file system API:
	debug( 'File system API: %s', alias );
	args = fsAliasArgs( alias );

	// Parse the expression into an AST:
	debug( 'Expression: %s', expression );
	ast = parse( expression );

	// Check whether the argument which triggered TAB completion has a corresponding argument type which is completable:
	debug( 'Checking if argument is completable...' );
	arg = args[ ast.body[ 0 ].expression.arguments.length-1 ];
	if ( !arg ) {
		debug( 'Argument which triggered TAB completion is not completable.' );
		return '';
	}
	debug( 'Argument is completable.' );

	// Split the path to complete into two components: subdirectory path and filter...
	subdir = path.match( pathRegExp() );
	filter = subdir[ 2 ];
	subdir = subdir[ 1 ] || '';

	debug( 'Searching for completion candidates...' );
github stdlib-js / stdlib / lib / node_modules / @stdlib / repl / lib / process_command.js View on Github external
}
		// To ensure that "un-silenced" variable/function declarations produce a return value, check the last node for declarations...
		else if ( node.type === 'VariableDeclaration' ) {
			debug( 'Found a trailing variable declaration which is not silenced. Appending expression...' );
			tmp = node.declarations[ node.declarations.length-1 ];
			code += ';' + tmp.id.name; // return the assigned value of last declared variable
		} else if ( node.type === 'FunctionDeclaration' ) {
			debug( 'Found a trailing function declaration which is not silenced. Appending expression...' );
			code += ';' + node.id.name;
		}
		return code;
	}
	debug( 'Checking for a trailing object literal...' );

	// Make a best-effort attempt to parse the code string into an AST:
	ast = parseLoose( code );

	// If the body is empty, assume that we have been given an unterminated comment...
	if ( ast.body.length === 0 ) {
		debug( 'Detected unterminated comment.' );
		return err; // original error message
	}
	// Get the last (non-empty) node:
	for ( i = ast.body.length-1; i >= 0; i-- ) {
		node = ast.body[ i ];
		if ( node.type !== 'EmptyStatement' ) {
			break;
		}
	}
	// Check for a trailing node which is interpreted as a block statement, as this node could be an object literal...
	if ( node.type === 'BlockStatement' ) {
		debug( 'Last (non-empty) statement interpreted as a block statement. Checking if object literal...' );
github Thorium-Sim / thorium / generateTests.js View on Github external
.reduce((acc, next) => {
    const path = `./src/components/views/${next.replace(".stories.js", "")}`;
    const file = fs.readFileSync(`./src/stories/${next}`, "utf8");

    const ast = acorn.parse(file, {sourceType: "module"});

    const imports = ast.body.reduce((acc, next) => {
      const obj = {};
      if (next.type === "ImportDeclaration") {
        const defaultSpecifier = next.specifiers.find(
          c => c.type === "ImportDefaultSpecifier",
        );
        if (
          defaultSpecifier &&
          (specifiers.includes(defaultSpecifier.local.name) ||
            defaultSpecifier.local.name.includes("Mock"))
        ) {
          obj.source = next.source.value;
          obj.type = defaultSpecifier.local.name;
          obj.imports = [];
          next.specifiers.forEach(s => {
github adobe / athena / src / utils.js View on Github external
exports.parseAstExpressions = (script) => {
    const ast = AstParser.parse(script);
    if (!ast.body || !script) return [];

    return ast.body.map(e => script.substring(e.start, e.end)) || [];
};
github mikro-orm / mikro-orm / lib / utils / Utils.ts View on Github external
static getParamNames(func: Function | string, methodName?: string): string[] {
    const ret: string[] = [];
    const parsed = parse(func.toString());

    const checkNode = (node: any, methodName?: string) => {
      if (methodName && !(node.key && (node.key as any).name === methodName)) {
        return;
      }

      const params = node.value ? node.value.params : node.params;
      ret.push(...params.map((p: any) => {
        switch (p.type) {
          case 'AssignmentPattern':
            return p.left.name;
          case 'RestElement':
            return '...' + p.argument.name;
          default:
            return p.name;
        }
github M-Izadmehr / deadfile / src / ASTPlugins / index.js View on Github external
const ParserWithJsx = entry => Parser.parse(parseJsx(entry));

acorn-loose

Error-tolerant ECMAScript parser

MIT
Latest version published 1 year ago

Package Health Score

85 / 100
Full package analysis

Popular acorn-loose functions

Similar packages