Thanks to visit codestin.com
Credit goes to github.com

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

Commit 25092fd

Browse files
authored
feat(typescript-estree): add parserOption to turn on debug logs (typescript-eslint#1413)
1 parent d8445d5 commit 25092fd

File tree

10 files changed

+390
-65
lines changed

10 files changed

+390
-65
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
"cz": "git-cz",
2323
"check:docs": "lerna run check:docs",
2424
"check:configs": "lerna run check:configs",
25-
"check:spelling": "cspell --config=.cspell.json **/*.{md,ts,js}",
25+
"check:spelling": "cspell --config=.cspell.json \"**/*.{md,ts,js}\"",
2626
"generate-contributors": "yarn ts-node --transpile-only ./tools/generate-contributors.ts && yarn all-contributors generate",
2727
"format": "prettier --write \"./**/*.{ts,js,json,md}\"",
2828
"format-check": "prettier --list-different \"./**/*.{ts,js,json,md}\"",

packages/experimental-utils/src/ts-eslint/ParserOptions.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { TSESTreeOptions } from '@typescript-eslint/typescript-estree';
2+
13
export interface ParserOptions {
24
comment?: boolean;
35
ecmaFeatures?: {
@@ -9,6 +11,7 @@ export interface ParserOptions {
911
errorOnUnknownASTType?: boolean;
1012
extraFileExtensions?: string[];
1113
// ts-estree specific
14+
debugLevel?: TSESTreeOptions['debugLevel'];
1215
filePath?: string;
1316
loc?: boolean;
1417
noWatch?: boolean;

packages/typescript-estree/README.md

Lines changed: 160 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -29,54 +29,140 @@ yarn add -D @typescript-eslint/typescript-estree
2929

3030
## API
3131

32-
### parse(code, options)
32+
### Parsing
3333

34-
Parses the given string of code with the options provided and returns an ESTree-compatible AST. The options object has the following properties:
34+
#### `parse(code, options)`
3535

36-
```js
37-
{
38-
// attach range information to each node
39-
range: false,
36+
Parses the given string of code with the options provided and returns an ESTree-compatible AST.
4037

41-
// attach line/column location information to each node
42-
loc: false,
38+
```ts
39+
interface ParseOptions {
40+
/**
41+
* create a top-level comments array containing all comments
42+
*/
43+
comment?: boolean;
4344

44-
// create a top-level tokens array containing all tokens
45-
tokens: false,
45+
/**
46+
* An array of modules to turn explicit debugging on for.
47+
* - 'typescript-eslint' is the same as setting the env var `DEBUG=typescript-eslint:*`
48+
* - 'eslint' is the same as setting the env var `DEBUG=eslint:*`
49+
* - 'typescript' is the same as setting `extendedDiagnostics: true` in your tsconfig compilerOptions
50+
*
51+
* For convenience, also supports a boolean:
52+
* - true === ['typescript-eslint']
53+
* - false === []
54+
*/
55+
debugLevel?: boolean | ('typescript-eslint' | 'eslint' | 'typescript')[];
4656

47-
// create a top-level comments array containing all comments
48-
comment: false,
57+
/**
58+
* Cause the parser to error if it encounters an unknown AST node type (useful for testing).
59+
* This case only usually occurs when TypeScript releases new features.
60+
*/
61+
errorOnUnknownASTType?: boolean;
4962

50-
/*
51-
* enable parsing JSX. For more details, see https://www.typescriptlang.org/docs/handbook/jsx.html
63+
/**
64+
* The absolute path to the file being parsed.
65+
*/
66+
filePath?: string;
67+
68+
/**
69+
* Enable parsing of JSX.
70+
* For more details, see https://www.typescriptlang.org/docs/handbook/jsx.html
5271
*
5372
* NOTE: this setting does not effect known file types (.js, .jsx, .ts, .tsx, .json) because the
5473
* TypeScript compiler has its own internal handling for known file extensions.
5574
*
56-
* Exact behaviour:
57-
* - .js, .jsx, .tsx files are parsed as if this is true
58-
* - .ts files are parsed as if this is false
59-
* - unknown extensions (.md, .vue) will respect this setting
75+
* For the exact behavior, see https://github.com/typescript-eslint/typescript-eslint/tree/master/packages/parser#parseroptionsecmafeaturesjsx
6076
*/
61-
jsx: false,
77+
jsx?: boolean;
78+
79+
/**
80+
* Controls whether the `loc` information to each node.
81+
* The `loc` property is an object which contains the exact line/column the node starts/ends on.
82+
* This is similar to the `range` property, except it is line/column relative.
83+
*/
84+
loc?: boolean;
85+
86+
/*
87+
* Allows overriding of function used for logging.
88+
* When value is `false`, no logging will occur.
89+
* When value is not provided, `console.log()` will be used.
90+
*/
91+
loggerFn?: Function | false;
92+
93+
/**
94+
* Controls whether the `range` property is included on AST nodes.
95+
* The `range` property is a [number, number] which indicates the start/end index of the node in the file contents.
96+
* This is similar to the `loc` property, except this is the absolute index.
97+
*/
98+
range?: boolean;
99+
100+
/**
101+
* Set to true to create a top-level array containing all tokens from the file.
102+
*/
103+
tokens?: boolean;
62104

63105
/*
64106
* The JSX AST changed the node type for string literals
65107
* inside a JSX Element from `Literal` to `JSXText`.
66108
* When value is `true`, these nodes will be parsed as type `JSXText`.
67109
* When value is `false`, these nodes will be parsed as type `Literal`.
68110
*/
69-
useJSXTextNode: false,
111+
useJSXTextNode?: boolean;
112+
}
70113

71-
// Cause the parser to error if it encounters an unknown AST node type (useful for testing)
114+
const PARSE_DEFAULT_OPTIONS: ParseOptions = {
115+
comment: false,
72116
errorOnUnknownASTType: false,
117+
filePath: 'estree.ts', // or 'estree.tsx', if you pass jsx: true
118+
jsx: false,
119+
loc: false,
120+
loggerFn: undefined,
121+
range: false,
122+
tokens: false,
123+
useJSXTextNode: false,
124+
};
73125

74-
/*
75-
* Allows overriding of function used for logging.
76-
* When value is `false`, no logging will occur.
77-
* When value is not provided, `console.log()` will be used.
126+
declare function parse(
127+
code: string,
128+
options: ParseOptions = PARSE_DEFAULT_OPTIONS,
129+
): TSESTree.Program;
130+
```
131+
132+
Example usage:
133+
134+
```js
135+
import { parse } from '@typescript-eslint/typescript-estree';
136+
137+
const code = `const hello: string = 'world';`;
138+
const ast = parse(code, {
139+
loc: true,
140+
range: true,
141+
});
142+
```
143+
144+
#### `parseAndGenerateServices(code, options)`
145+
146+
Parses the given string of code with the options provided and returns an ESTree-compatible AST. Accepts additional options which can be used to generate type information along with the AST.
147+
148+
```ts
149+
interface ParseAndGenerateServicesOptions extends ParseOptions {
150+
/**
151+
* Causes the parser to error if the TypeScript compiler returns any unexpected syntax/semantic errors.
78152
*/
79-
loggerFn: undefined,
153+
errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
154+
155+
/**
156+
* When `project` is provided, this controls the non-standard file extensions which will be parsed.
157+
* It accepts an array of file extensions, each preceded by a `.`.
158+
*/
159+
extraFileExtensions?: string[];
160+
161+
/**
162+
* The absolute path to the file being parsed.
163+
* When `project` is provided, this is required, as it is used to fetch the file from the TypeScript compiler's cache.
164+
*/
165+
filePath?: string;
80166

81167
/**
82168
* Allows the user to control whether or not two-way AST node maps are preserved
@@ -88,42 +174,67 @@ Parses the given string of code with the options provided and returns an ESTree-
88174
* NOTE: If `preserveNodeMaps` is explicitly set by the user, it will be respected,
89175
* regardless of whether or not `project` is in use.
90176
*/
91-
preserveNodeMaps: undefined
177+
preserveNodeMaps?: boolean;
178+
179+
/**
180+
* Absolute (or relative to `tsconfigRootDir`) paths to the tsconfig(s).
181+
* If this is provided, type information will be returned.
182+
*/
183+
project?: string | string[];
184+
185+
/**
186+
* The absolute path to the root directory for all provided `project`s.
187+
*/
188+
tsconfigRootDir?: string;
189+
190+
/**
191+
***************************************************************************************
192+
* IT IS RECOMMENDED THAT YOU DO NOT USE THIS OPTION, AS IT CAUSES PERFORMANCE ISSUES. *
193+
***************************************************************************************
194+
*
195+
* When passed with `project`, this allows the parser to create a catch-all, default program.
196+
* This means that if the parser encounters a file not included in any of the provided `project`s,
197+
* it will not error, but will instead parse the file and its dependencies in a new program.
198+
*/
199+
createDefaultProgram?: boolean;
92200
}
201+
202+
const PARSE_AND_GENERATE_SERVICES_DEFAULT_OPTIONS: ParseOptions = {
203+
...PARSE_DEFAULT_OPTIONS,
204+
errorOnTypeScriptSyntacticAndSemanticIssues: false,
205+
extraFileExtensions: [],
206+
preserveNodeMaps: false, // or true, if you do not set this, but pass `project`
207+
project: undefined,
208+
tsconfigRootDir: process.cwd(),
209+
};
210+
211+
declare function parseAndGenerateServices(
212+
code: string,
213+
options: ParseOptions = PARSE_DEFAULT_OPTIONS,
214+
): TSESTree.Program;
93215
```
94216

95217
Example usage:
96218

97219
```js
98-
const parser = require('@typescript-eslint/typescript-estree');
220+
import { parseAndGenerateServices } from '@typescript-eslint/typescript-estree';
221+
99222
const code = `const hello: string = 'world';`;
100-
const ast = parser.parse(code, {
101-
range: true,
223+
const ast = parseAndGenerateServices(code, {
224+
filePath: '/some/path/to/file/foo.ts',
102225
loc: true,
226+
project: './tsconfig.json',
227+
range: true,
103228
});
104229
```
105230

106-
### version
231+
### `TSESTree`, `AST_NODE_TYPES` and `AST_TOKEN_TYPES`
107232

108-
Exposes the current version of `typescript-estree` as specified in `package.json`.
233+
Types for the AST produced by the parse functions.
109234

110-
Example usage:
111-
112-
```js
113-
const parser = require('@typescript-eslint/typescript-estree');
114-
const version = parser.version;
115-
```
116-
117-
### `AST_NODE_TYPES`
118-
119-
Exposes an object that contains the AST node types produced by the parser.
120-
121-
Example usage:
122-
123-
```js
124-
const parser = require('@typescript-eslint/typescript-estree');
125-
const astNodeTypes = parser.AST_NODE_TYPES;
126-
```
235+
- `TSESTree` is a namespace which contains object types representing all of the AST Nodes produced by the parser.
236+
- `AST_NODE_TYPES` is an enum which provides the values for every single AST node's `type` property.
237+
- `AST_TOKEN_TYPES` is an enum which provides the values for every single AST token's `type` property.
127238

128239
## Supported TypeScript Version
129240

packages/typescript-estree/src/create-program/createDefaultProgram.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ import path from 'path';
33
import * as ts from 'typescript';
44
import { Extra } from '../parser-options';
55
import {
6-
getTsconfigPath,
7-
DEFAULT_COMPILER_OPTIONS,
86
ASTAndProgram,
7+
getTsconfigPath,
8+
createDefaultCompilerOptionsFromExtra,
99
} from './shared';
1010

1111
const log = debug('typescript-eslint:typescript-estree:createDefaultProgram');
@@ -31,7 +31,7 @@ function createDefaultProgram(
3131

3232
const commandLine = ts.getParsedCommandLineOfConfigFile(
3333
tsconfigPath,
34-
DEFAULT_COMPILER_OPTIONS,
34+
createDefaultCompilerOptionsFromExtra(extra),
3535
{ ...ts.sys, onUnRecoverableConfigFileDiagnostic: () => {} },
3636
);
3737

packages/typescript-estree/src/create-program/createIsolatedProgram.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as ts from 'typescript';
33
import { Extra } from '../parser-options';
44
import {
55
ASTAndProgram,
6-
DEFAULT_COMPILER_OPTIONS,
6+
createDefaultCompilerOptionsFromExtra,
77
getScriptKind,
88
} from './shared';
99

@@ -67,7 +67,7 @@ function createIsolatedProgram(code: string, extra: Extra): ASTAndProgram {
6767
noResolve: true,
6868
target: ts.ScriptTarget.Latest,
6969
jsx: extra.jsx ? ts.JsxEmit.Preserve : undefined,
70-
...DEFAULT_COMPILER_OPTIONS,
70+
...createDefaultCompilerOptionsFromExtra(extra),
7171
},
7272
compilerHost,
7373
);

packages/typescript-estree/src/create-program/createWatchProgram.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@ import { WatchCompilerHostOfConfigFile } from './WatchCompilerHostOfConfigFile';
66
import {
77
canonicalDirname,
88
CanonicalPath,
9-
getTsconfigPath,
10-
DEFAULT_COMPILER_OPTIONS,
9+
createDefaultCompilerOptionsFromExtra,
1110
getCanonicalFileName,
11+
getTsconfigPath,
1212
} from './shared';
1313

1414
const log = debug('typescript-eslint:typescript-estree:createWatchProgram');
@@ -233,7 +233,7 @@ function createWatchProgram(
233233
// create compiler host
234234
const watchCompilerHost = ts.createWatchCompilerHost(
235235
tsconfigPath,
236-
DEFAULT_COMPILER_OPTIONS,
236+
createDefaultCompilerOptionsFromExtra(extra),
237237
ts.sys,
238238
ts.createSemanticDiagnosticsBuilderProgram,
239239
diagnosticReporter,

packages/typescript-estree/src/create-program/shared.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ const DEFAULT_COMPILER_OPTIONS: ts.CompilerOptions = {
2020
noUnusedParameters: true,
2121
};
2222

23+
function createDefaultCompilerOptionsFromExtra(
24+
extra: Extra,
25+
): ts.CompilerOptions {
26+
if (extra.debugLevel.has('typescript')) {
27+
return {
28+
...DEFAULT_COMPILER_OPTIONS,
29+
extendedDiagnostics: true,
30+
};
31+
}
32+
33+
return DEFAULT_COMPILER_OPTIONS;
34+
}
35+
2336
// This narrows the type so we can be sure we're passing canonical names in the correct places
2437
type CanonicalPath = string & { __brand: unknown };
2538

@@ -85,7 +98,7 @@ export {
8598
ASTAndProgram,
8699
canonicalDirname,
87100
CanonicalPath,
88-
DEFAULT_COMPILER_OPTIONS,
101+
createDefaultCompilerOptionsFromExtra,
89102
ensureAbsolutePath,
90103
getCanonicalFileName,
91104
getScriptKind,

0 commit comments

Comments
 (0)