How to use the parse function from acorn

Find comprehensive JavaScript acorn.parse code examples handpicked from public code repositorys.

acorn.parse is a JavaScript parser that generates an abstract syntax tree (AST) from a given source code string.

4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622


function generateBinding (exp) {
  if (exp && typeof exp === 'string') {
    var ast = null;
    try {
      ast = acorn.parse(("(" + exp + ")"));
    } catch (e) {
      // warn(`Failed to parse the expression: "${exp}"`)
      return ''
    }
fork icon0
star icon11
watch icon1

+ 4 other calls in file

232
233
234
235
236
237
238
239
240
241
function declaresThis(node) {
  return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
}

function reallyParse(source) {
  return acorn.parse(source, {
    allowReturnOutsideFunction: true,
    allowImportExportEverywhere: true,
    allowHashBang: true
  });
fork icon0
star icon1
watch icon1

+ 5 other calls in file

How does acorn.parse work?

acorn.parse is a JavaScript parser that takes in a source code string and produces an abstract syntax tree (AST) that represents the structure of the code. It performs lexical analysis by tokenizing the source code and then parsing the tokens into a tree-like structure. The resulting AST can be used for various purposes such as code analysis, transformation, and generation. The parser is highly configurable, allowing for customization of language features and syntax. It is commonly used in JavaScript tools and frameworks to analyze and manipulate code.

153
154
155
156
157
158
159
160
161
162
}
if (type === 'module') {
  cache.libs.add(fileName.replace(`${appRoot}/`, '').replace(`${JUST_TARGET}/`, ''))
}
const src = just.fs.readFile(fileName)
acorn.parse(src, {
  ecmaVersion: 2020,
  sourceType: type,
  onToken: token => {
    if (token.value === 'require') {
fork icon107
star icon0
watch icon66

13
14
15
16
17
18
19
20
21
    sourceType: 'module',
    locations: true,
    onToken: extractedTokens,
  };

  acorn.parse(script, ACORN_OPTIONS);

  return extractedTokens.filter(token => isAVueGettextFunction(token));
}
fork icon48
star icon0
watch icon1

Ai Example

1
2
3
4
5
6
7
const acorn = require("acorn");

const code = "const sum = (a, b) => a + b;";
const options = { ecmaVersion: 2021 };

const ast = acorn.parse(code, options);
console.log(ast);

In this example, acorn.parse is used to parse a string of JavaScript code stored in the code variable, using the ecmaVersion option to specify that the code conforms to ECMAScript 2021. The resulting Abstract Syntax Tree (AST) is logged to the console using console.log.

9
10
11
12
13
14
15
16
17
18
19
20


module.exports = function unpack(source, opts) {
  var ast =
    typeof source === "object" && typeof source.type === "string"
      ? source
      : acorn.parse(source, { ecmaVersion: 2021 });


  if (opts && opts.source) {
    source = opts.source;
  }
fork icon3
star icon9
watch icon1

+ 3 other calls in file

44
45
46
47
48
49
50
51
52
53
console.log('Current version:', waVersion)
// This one list of types is so long that it's split into two JavaScript declarations.
// The module finder below can't handle it, so just patch it manually here.
const patchedQrData = qrData.replace('t.ActionLinkSpec=void 0,t.TemplateButtonSpec', 't.ActionLinkSpec=t.TemplateButtonSpec')
//const patchedQrData = qrData.replace("Spec=void 0,t.", "Spec=t.")
const qrModules = acorn.parse(patchedQrData).body[0].expression.arguments[0].elements[1].properties

const result = qrModules.filter(m => {
	const hasProto = !!m.value.body.body.find(b => {
		const expressions = extractAllExpressions(b)
fork icon0
star icon0
watch icon0

+ 4 other calls in file

2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
// Collect all JS code comments to this array so that we can retain them in the outputted code
// if --closureFriendly was requested.
const sourceComments = [];
let ast;
try {
  ast = acorn.parse(input, {
    // Keep in sync with --language_in that we pass to closure in building.py
    ecmaVersion: 2020,
    preserveParens: closureFriendly,
    onComment: closureFriendly ? sourceComments : undefined,
fork icon0
star icon0
watch icon1

+ 3 other calls in file

204
205
206
207
208
209
210
211
212
213
214
215
  });
  return progress;
}


function runOnJsText(js, pretty = false) {
  const ast = acorn.parse(js, {ecmaVersion: 6});


  optPassSimplifyModuleInitialization(ast);
  optPassRemoveRedundantOperatorNews(ast);

fork icon0
star icon0
watch icon1

+ 3 other calls in file

47
48
49
50
51
52
53
54
55
56
  options = {};
}

const comments = [];
const tokens = [];
const ast = acorn.parse(code, {
  allowReturnOutsideFunction: true,
  ranges: true,
  // collect comments in Esprima's format
  onComment: comments,
fork icon0
star icon0
watch icon1

23
24
25
26
27
28
29
30
31
32
      allowReturnOutsideFunction: true,
      allowImportExportEverywhere: true,
      allowHashBang: true
    }
  );
  return acorn.parse(source, parseOptions);
}
module.exports = findGlobals;
module.exports.parse = reallyParse;
function findGlobals(source, options) {
fork icon0
star icon0
watch icon1

23
24
25
26
27
28
29
30
31
32
33
34


function uniffe(contents) {
  var comments = [];
  var tokens = [];


  var ast = acorn.parse(contents, {
    ranges: true,
    onComment: comments,
    onToken: tokens
  });
fork icon0
star icon0
watch icon5

+ 3 other calls in file

224
225
226
227
228
229
230
231
232
233
  return originalCompile.apply(this, arguments);
}

let body;
try {
  body = acorn.parse(content, {
    ecmaVersion: '2024',
    sourceType: 'source',
  }).body;
} catch (x) {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

765
766
767
768
769
770
771
772
773
774
775
var extraInfoStart = input.lastIndexOf('// EXTRA_INFO:')
var extraInfo = null;
if (extraInfoStart > 0) {
  extraInfo = JSON.parse(input.substr(extraInfoStart + 14));
}
var ast = acorn.parse(input, { ecmaVersion: 6 });


var minifyWhitespace = false;
var noPrint = false;

fork icon0
star icon0
watch icon1

+ 7 other calls in file

454
455
456
457
458
459
460
461
462
463
const insertCode = `export const toc = ${JSON.stringify(toc, null, 2)};`;
tree.children.push({
  type: "mdxjsEsm",
  value: insertCode,
  data: {
    estree: _acorn.parse.call(void 0, insertCode, {
      ecmaVersion: 2020,
      sourceType: "module"
    })
  }
fork icon0
star icon0
watch icon1

+ 4 other calls in file

42
43
44
45
46
47
48
49
50
51

result.source = fs.readFileSync(exercisePath, 'utf8');

if (options.parse) {
  try {
    result.rootNode = acorn.parse(result.source, { ecmaVersion: 2020 });
  } catch (_) {
    // Leave rootNode prop undefined
  }
}
fork icon0
star icon0
watch icon1

+ 2 other calls in file

35
36
37
38
39
40
41
42
43
44
lastSRC = src;
lastConstants = constants;
if (!isExpression(src)) return lastRes = false;
var ast;
try {
  ast = acorn.parse(src, {
    ecmaVersion: 6,
    allowReturnOutsideFunction: true,
    allowImportExportEverywhere: true,
    allowHashBang: true
fork icon0
star icon0
watch icon1

+ 2 other calls in file