Skip to content
This repository was archived by the owner on Sep 14, 2022. It is now read-only.

Commit 9db37b4

Browse files
committed
feat: add parser
1 parent 91f0d54 commit 9db37b4

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

src/lib/parser.ts

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import { analyze } from "@typescript-eslint/scope-manager";
2+
import { visitorKeys } from "@typescript-eslint/typescript-estree";
3+
import { astConverter } from "../../node_modules/@typescript-eslint/typescript-estree/dist/ast-converter";
4+
import { createAstAndProgram } from "@/lib/create-ast-program";
5+
import type { ParserOptions, TSESTree } from "@typescript-eslint/types";
6+
import type {
7+
ParserServices,
8+
TSESTreeOptions,
9+
} from "@typescript-eslint/typescript-estree";
10+
import type { AST } from "@typescript-eslint/typescript-estree";
11+
12+
interface ParseForESLintResult {
13+
ast: TSESTree.Program & {
14+
range?: [number, number];
15+
tokens?: TSESTree.Token[];
16+
comments?: TSESTree.Comment[];
17+
};
18+
services: ParserServices;
19+
visitorKeys: typeof visitorKeys;
20+
scopeManager: any;
21+
}
22+
23+
const extra: any = {
24+
code: "",
25+
comment: true,
26+
comments: [],
27+
createDefaultProgram: false,
28+
debugLevel: new Set(),
29+
errorOnTypeScriptSyntacticAndSemanticIssues: false,
30+
errorOnUnknownASTType: false,
31+
extraFileExtensions: [],
32+
filePath: "",
33+
jsx: false,
34+
loc: true,
35+
log: console.log, // eslint-disable-line no-console
36+
preserveNodeMaps: true,
37+
projects: [],
38+
range: true,
39+
strict: false,
40+
tokens: [],
41+
tsconfigRootDir: "/",
42+
useJSXTextNode: false,
43+
};
44+
45+
interface ParseAndGenerateServicesResult<T extends TSESTreeOptions> {
46+
ast: AST<T>;
47+
services: ParserServices;
48+
}
49+
50+
function parseAndGenerateServices<T extends TSESTreeOptions = TSESTreeOptions>(
51+
code: string,
52+
options: T
53+
): ParseAndGenerateServicesResult<T> {
54+
const { ast, program } = createAstAndProgram(code);
55+
extra.code = code;
56+
const { estree, astMaps } = astConverter(ast!, extra, true);
57+
return {
58+
ast: estree as AST<T>,
59+
services: {
60+
hasFullTypeInformation: true,
61+
program,
62+
esTreeNodeToTSNodeMap: astMaps.esTreeNodeToTSNodeMap,
63+
tsNodeToESTreeNodeMap: astMaps.tsNodeToESTreeNodeMap,
64+
},
65+
};
66+
}
67+
68+
export function parseForESLint(
69+
code: string,
70+
options: ParserOptions
71+
): ParseForESLintResult {
72+
const { ast, services } = parseAndGenerateServices(code, {});
73+
const scopeManager = analyze(ast, options);
74+
return { ast, services, scopeManager, visitorKeys };
75+
}
76+
77+
export function parse(
78+
code: string,
79+
options: ParserOptions
80+
): ParseForESLintResult["ast"] {
81+
return parseForESLint(code, options).ast;
82+
}

0 commit comments

Comments
 (0)