MCPcopy
hub / github.com/benjamn/recast / parse

Function parse

lib/parser.ts:12–124  ·  view source on GitHub ↗
(source: string, options?: Partial<Options>)

Source from the content-addressed store, hash-verified

10import { Options } from "./options";
11
12export function parse(source: string, options?: Partial<Options>) {
13 options = normalizeOptions(options);
14
15 const lines = fromString(source, options);
16
17 const sourceWithoutTabs = lines.toString({
18 tabWidth: options.tabWidth,
19 reuseWhitespace: false,
20 useTabs: false,
21 });
22
23 let comments: any[] = [];
24 const ast = options.parser.parse(sourceWithoutTabs, {
25 jsx: true,
26 loc: true,
27 locations: true,
28 range: options.range,
29 comment: true,
30 onComment: comments,
31 tolerant: util.getOption(options, "tolerant", true),
32 ecmaVersion: 6,
33 sourceType: util.getOption(options, "sourceType", "module"),
34 });
35
36 // Use ast.tokens if possible, and otherwise fall back to the Esprima
37 // tokenizer. All the preconfigured ../parsers/* expose ast.tokens
38 // automatically, but custom parsers might need additional configuration
39 // to avoid this fallback.
40 const tokens: any[] = Array.isArray(ast.tokens)
41 ? ast.tokens
42 : require("esprima").tokenize(sourceWithoutTabs, {
43 loc: true,
44 });
45
46 // We will reattach the tokens array to the file object below.
47 delete ast.tokens;
48
49 // Make sure every token has a token.value string.
50 tokens.forEach(function (token) {
51 if (typeof token.value !== "string") {
52 token.value = lines.sliceString(token.loc.start, token.loc.end);
53 }
54 });
55
56 if (Array.isArray(ast.comments)) {
57 comments = ast.comments;
58 delete ast.comments;
59 }
60
61 if (ast.loc) {
62 // If the source was empty, some parsers give loc.{start,end}.line
63 // values of 0, instead of the minimum of 1.
64 util.fixFaultyLocations(ast, lines);
65 } else {
66 ast.loc = {
67 start: lines.firstPos(),
68 end: lines.lastPos(),
69 };

Callers 15

runStringFunction · 0.90
checkFunction · 0.90
checkEquivFunction · 0.90
checkFunction · 0.90
parens.tsFile · 0.90
checkFunction · 0.90
checkFunction · 0.90
runTestsForParserFunction · 0.90
syntax.tsFile · 0.90
checkFunction · 0.90
parens-extra.tsFile · 0.90
visit.tsFile · 0.90

Calls 6

fromStringFunction · 0.90
sliceStringMethod · 0.80
firstPosMethod · 0.80
lastPosMethod · 0.80
toStringMethod · 0.65
copyMethod · 0.65

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…