Skip to content

Commit 15a3eab

Browse files
committed
build: add tsdoc-doctest ESLint rule for linting return annotations in TSDoc examples
--- type: pre_commit_static_analysis_report description: Results of running static analysis checks when committing changes. report: - task: lint_filenames status: passed - task: lint_editorconfig status: passed - task: lint_markdown status: na - task: lint_package_json status: na - task: lint_repl_help status: na - task: lint_javascript_src status: passed - task: lint_javascript_cli status: na - task: lint_javascript_examples status: na - task: lint_javascript_tests status: na - task: lint_javascript_benchmarks status: na - task: lint_python status: na - task: lint_r status: na - task: lint_c_src status: na - task: lint_c_examples status: na - task: lint_c_benchmarks status: na - task: lint_c_tests_fixtures status: na - task: lint_shell status: na - task: lint_typescript_declarations status: na - task: lint_typescript_tests status: na - task: lint_license_headers status: passed ---
1 parent f3a51da commit 15a3eab

File tree

16 files changed

+1546
-1
lines changed

16 files changed

+1546
-1
lines changed

etc/eslint/plugins/typescript.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@ var plugins = [
3030
'eslint-plugin-jsdoc',
3131

3232
// Required for TypeScript support:
33-
'@typescript-eslint'
33+
'@typescript-eslint',
34+
35+
// Stdlib custom rules:
36+
'stdlib'
3437
];
3538

3639

etc/eslint/rules/typescript.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2712,6 +2712,17 @@ rules[ 'yoda' ] = 'error';
27122712
*/
27132713
rules[ 'expect-type/expect' ] = 'error';
27142714

2715+
/**
2716+
* Ensures return annotations in TSDoc examples match the actual output.
2717+
*
2718+
* @name stdlib/tsdoc-doctest
2719+
* @memberof rules
2720+
* @type {string}
2721+
* @default 'error'
2722+
* @see {@link module:@stdlib/_tools/eslint/rules/tsdoc-doctest}
2723+
*/
2724+
rules[ 'stdlib/tsdoc-doctest' ] = 'error';
2725+
27152726

27162727
// EXPORTS //
27172728

lib/node_modules/@stdlib/_tools/eslint/rules/lib/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1062,6 +1062,15 @@ setReadOnly( rules, 'section-headers', require( '@stdlib/_tools/eslint/rules/sec
10621062
*/
10631063
setReadOnly( rules, 'ternary-condition-parentheses', require( '@stdlib/_tools/eslint/rules/ternary-condition-parentheses' ) );
10641064

1065+
/**
1066+
* @name tsdoc-doctest
1067+
* @memberof rules
1068+
* @readonly
1069+
* @type {Function}
1070+
* @see {@link module:@stdlib/_tools/eslint/rules/tsdoc-doctest}
1071+
*/
1072+
setReadOnly( rules, 'tsdoc-doctest', require( '@stdlib/_tools/eslint/rules/tsdoc-doctest' ) );
1073+
10651074
/**
10661075
* @name uppercase-required-constants
10671076
* @memberof rules
Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2025 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# tsdoc-doctest
22+
23+
> [ESLint rule][eslint-rules] to ensure that return annotations in TSDoc examples match the actual output.
24+
25+
<section class="intro">
26+
27+
</section>
28+
29+
<!-- /.intro -->
30+
31+
<section class="usage">
32+
33+
## Usage
34+
35+
```javascript
36+
var rule = require( '@stdlib/_tools/eslint/rules/tsdoc-doctest' );
37+
```
38+
39+
#### rule
40+
41+
[ESLint rule][eslint-rules] to ensure that return annotations in TSDoc examples match the actual output. The rule validates `@example` blocks in TSDoc comments within `.d.ts` files.
42+
43+
The rule:
44+
45+
- Extracts `@example` blocks from TSDoc comments in TypeScript declaration files
46+
- Loads the actual JavaScript package corresponding to the declaration file
47+
- Executes the example code in a sandboxed environment
48+
- Compares the actual output with the expected return annotations
49+
- Supports functions, constants, classes, and namespace objects
50+
- Handles `// returns`, `// throws`, and `// =>` annotations
51+
52+
**Bad**:
53+
54+
<!-- eslint-disable stdlib/tsdoc-doctest -->
55+
56+
```typescript
57+
/**
58+
* Adds two numbers.
59+
*
60+
* @param x - first number
61+
* @param y - second number
62+
* @returns sum of x and y
63+
*
64+
* @example
65+
* var result = add( 2, 3 );
66+
* // returns 6
67+
*/
68+
declare function add( x: number, y: number ): number;
69+
70+
export = add;
71+
```
72+
73+
**Good**:
74+
75+
```typescript
76+
/**
77+
* Adds two numbers.
78+
*
79+
* @param x - first number
80+
* @param y - second number
81+
* @returns sum of x and y
82+
*
83+
* @example
84+
* var result = add( 2, 3 );
85+
* // returns 5
86+
*/
87+
declare function add( x: number, y: number ): number;
88+
89+
export = add;
90+
```
91+
92+
</section>
93+
94+
<!-- /.usage -->
95+
96+
<section class="examples">
97+
98+
## Examples
99+
100+
<!-- eslint no-undef: "error" -->
101+
102+
```javascript
103+
var Linter = require( 'eslint' ).Linter;
104+
var parser = require( '@typescript-eslint/parser' );
105+
var rule = require( '@stdlib/_tools/eslint/rules/tsdoc-doctest' );
106+
107+
var linter = new Linter();
108+
109+
// Register the TypeScript parser and ESLint rule:
110+
linter.defineParser( '@typescript-eslint/parser', parser );
111+
linter.defineRule( 'tsdoc-doctest', rule );
112+
113+
// Generate our source code with incorrect return annotation:
114+
var code = [
115+
'/**',
116+
'* Returns the absolute value of a number.',
117+
'*',
118+
'* @param x - input value',
119+
'* @returns absolute value',
120+
'*',
121+
'* @example',
122+
'* var result = abs( -3 );',
123+
'* // returns 2',
124+
'*/',
125+
'declare function abs( x: number ): number;',
126+
'',
127+
'export = abs;'
128+
].join( '\n' );
129+
130+
// Lint the code:
131+
var result = linter.verify( code, {
132+
'parser': '@typescript-eslint/parser',
133+
'parserOptions': {
134+
'ecmaVersion': 2018,
135+
'sourceType': 'module'
136+
},
137+
'rules': {
138+
'tsdoc-doctest': 'error'
139+
}
140+
}, {
141+
'filename': 'lib/node_modules/@stdlib/math/base/special/abs/docs/types/index.d.ts'
142+
});
143+
144+
console.log( result );
145+
/* =>
146+
[
147+
{
148+
'ruleId': 'tsdoc-doctest',
149+
'severity': 2,
150+
'message': 'Displayed return value is `2`, but expected `3` instead',
151+
'line': 9,
152+
'column': 1,
153+
'nodeType': null,
154+
'endLine': 10,
155+
'endColumn': 37
156+
}
157+
]
158+
*/
159+
```
160+
161+
</section>
162+
163+
<!-- /.examples -->
164+
165+
<section class="notes">
166+
167+
## Notes
168+
169+
- The rule requires that the TypeScript declaration file path follows the stdlib convention: `lib/node_modules/@stdlib/<package>/docs/types/index.d.ts`
170+
- The corresponding JavaScript package must be loadable via `require('@stdlib/<package>')`
171+
- The rule skips validation if the package cannot be loaded
172+
- Examples are executed in a sandboxed VM context with limited globals
173+
174+
</section>
175+
176+
<!-- /.notes -->
177+
178+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
179+
180+
<section class="related">
181+
182+
</section>
183+
184+
<!-- /.related -->
185+
186+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
187+
188+
<section class="links">
189+
190+
[eslint-rules]: https://eslint.org/docs/developer-guide/working-with-rules
191+
192+
</section>
193+
194+
<!-- /.links -->
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
var Linter = require( 'eslint' ).Linter;
22+
var parser = require( '@typescript-eslint/parser' );
23+
var rule = require( './../lib' );
24+
25+
var linter = new Linter();
26+
27+
// Register the TypeScript parser and ESLint rule:
28+
linter.defineParser( '@typescript-eslint/parser', parser );
29+
linter.defineRule( 'tsdoc-doctest', rule );
30+
31+
// Generate our source code with incorrect return annotation:
32+
var code = [
33+
'/**',
34+
'* Returns the absolute value of a number.',
35+
'*',
36+
'* @param x - input value',
37+
'* @returns absolute value',
38+
'*',
39+
'* @example',
40+
'* var result = abs( -3 );',
41+
'* // returns 2',
42+
'*/',
43+
'declare function abs( x: number ): number;',
44+
'',
45+
'export = abs;'
46+
].join( '\n' );
47+
48+
// Lint the code:
49+
var result = linter.verify( code, {
50+
'parser': '@typescript-eslint/parser',
51+
'parserOptions': {
52+
'ecmaVersion': 2018,
53+
'sourceType': 'module'
54+
},
55+
'rules': {
56+
'tsdoc-doctest': 'error'
57+
}
58+
}, {
59+
'filename': 'lib/node_modules/@stdlib/math/base/special/abs/docs/types/index.d.ts'
60+
});
61+
62+
console.log( result );
63+
/* =>
64+
[
65+
{
66+
'ruleId': 'tsdoc-doctest',
67+
'severity': 2,
68+
'message': 'Displayed return value is `2`, but expected `3` instead',
69+
'line': 9,
70+
'column': 1,
71+
'nodeType': null,
72+
'endLine': 10,
73+
'endColumn': 37
74+
}
75+
]
76+
*/
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// VARIABLES //
22+
23+
// Regular expressions for matching TypeScript declarations:
24+
var RE_DECLARE_FUNCTION = /declare\s+function\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*[<(]/;
25+
var RE_DECLARE_VAR = /declare\s+var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/;
26+
var RE_DECLARE_CLASS = /declare\s+class\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s/;
27+
var RE_DECLARE_VAR_NAMESPACE = /declare\s+var\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:\s*[A-Z][a-zA-Z0-9_$]*/;
28+
var RE_DECLARE_CONST = /declare\s+const\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/;
29+
30+
31+
// MAIN //
32+
33+
/**
34+
* Adds package export to scope based on TypeScript declarations.
35+
*
36+
* @param {Object} scope - VM scope object to add the package export to
37+
* @param {*} pkg - package export value to be added to scope
38+
* @param {string} sourceText - TypeScript declaration source text to parse for identifier names
39+
*/
40+
function addPackageToScope( scope, pkg, sourceText ) {
41+
var namespaceMatch;
42+
var funcMatch;
43+
44+
if ( typeof pkg === 'function' ) {
45+
// Try to match declare function pattern (handles generics with <):
46+
funcMatch = sourceText.match( RE_DECLARE_FUNCTION );
47+
if ( !funcMatch ) {
48+
// Try to match declare var pattern:
49+
funcMatch = sourceText.match( RE_DECLARE_VAR );
50+
}
51+
if ( !funcMatch ) {
52+
// Try to match declare class pattern (for constructor functions):
53+
funcMatch = sourceText.match( RE_DECLARE_CLASS );
54+
}
55+
if ( funcMatch ) {
56+
scope[ funcMatch[1] ] = pkg;
57+
}
58+
} else if ( typeof pkg === 'object' && pkg !== null ) {
59+
// Handle namespace objects and other object interfaces:
60+
namespaceMatch = sourceText.match( RE_DECLARE_VAR_NAMESPACE );
61+
if ( namespaceMatch ) {
62+
scope[ namespaceMatch[1] ] = pkg;
63+
}
64+
// Also check for const declarations (e.g., Complex64/Complex128 constants):
65+
funcMatch = sourceText.match( RE_DECLARE_CONST );
66+
if ( funcMatch ) {
67+
scope[ funcMatch[1] ] = pkg;
68+
}
69+
} else {
70+
// Try to match declare const pattern:
71+
funcMatch = sourceText.match( RE_DECLARE_CONST );
72+
if ( funcMatch ) {
73+
scope[ funcMatch[1] ] = pkg;
74+
}
75+
}
76+
}
77+
78+
79+
// EXPORTS //
80+
81+
module.exports = addPackageToScope;

0 commit comments

Comments
 (0)