Skip to content

feat(unstable): add js lint plugin source code helpers #28065

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 13, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 85 additions & 14 deletions cli/js/40_lint.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,32 +192,103 @@ class Fixer {
}
}

/**
* @implements {Deno.lint.SourceCode}
*/
export class SourceCode {
/** @type {string | null} */
#source = null;

/** @type {AstContext} */
#ctx;

/**
* @param {AstContext} ctx
*/
constructor(ctx) {
this.#ctx = ctx;
}

get text() {
return this.#getSource();
}

get ast() {
const program = /** @type {*} */ (getNode(
this.#ctx,
this.#ctx.rootOffset,
));

return program;
}

/**
* @param {Deno.lint.Node} [node]
* @returns {string}
*/
getText(node) {
const source = this.#getSource();
if (node === undefined) {
return source;
}

return source.slice(node.range[0], node.range[1]);
}

/**
* @param {Deno.lint.Node} node
*/
getAncestors(node) {
const { buf } = this.#ctx;

/** @type {Deno.lint.Node[]} */
const ancestors = [];

let parent = /** @type {*} */ (node)[INTERNAL_IDX];
while ((parent = readParent(buf, parent)) > AST_IDX_INVALID) {
if (readType(buf, parent) === AST_GROUP_TYPE) continue;

const parentNode = /** @type {*} */ (getNode(this.#ctx, parent));
if (parentNode !== null) {
ancestors.push(parentNode);
}
}

ancestors.reverse();

return ancestors;
}

/**
* @returns {string}
*/
#getSource() {
if (this.#source === null) {
this.#source = op_lint_get_source();
}
return /** @type {string} */ (this.#source);
}
}

/**
* Every rule gets their own instance of this class. This is the main
* API lint rules interact with.
* @implements {Deno.lint.RuleContext}
*/
export class Context {
id;

fileName;

#source = null;
sourceCode;

/**
* @param {AstContext} ctx
* @param {string} id
* @param {string} fileName
*/
constructor(id, fileName) {
constructor(ctx, id, fileName) {
this.id = id;
this.fileName = fileName;
}

source() {
if (this.#source === null) {
this.#source = op_lint_get_source();
}
return /** @type {*} */ (this.#source);
this.sourceCode = new SourceCode(ctx);
}

/**
Expand Down Expand Up @@ -961,8 +1032,8 @@ export function runPluginsForFile(fileName, serializedAst) {
continue;
}

const ctx = new Context(id, fileName);
const visitor = rule.create(ctx);
const ruleCtx = new Context(ctx, id, fileName);
const visitor = rule.create(ruleCtx);

// deno-lint-ignore guard-for-in
for (let key in visitor) {
Expand Down Expand Up @@ -1016,7 +1087,7 @@ export function runPluginsForFile(fileName, serializedAst) {
const destroyFn = rule.destroy.bind(rule);
destroyFns.push(() => {
try {
destroyFn(ctx);
destroyFn(ruleCtx);
} catch (err) {
throw new Error(`Destroy hook of "${id}" errored`, { cause: err });
}
Expand Down
5 changes: 3 additions & 2 deletions cli/tools/lint/ast_buffer/swc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ use super::buffer::NodeRef;
use super::ts_estree::AstNode;
use super::ts_estree::MethodKind as TsEstreeMethodKind;
use super::ts_estree::PropertyKind;
use super::ts_estree::SourceKind;
use super::ts_estree::TsEsTreeBuilder;
use super::ts_estree::TsKeywordKind;
use super::ts_estree::TsModuleKind;
Expand All @@ -120,7 +121,7 @@ pub fn serialize_swc_to_buffer(
})
.collect::<Vec<_>>();

ctx.write_program(&module.span, "module", children);
ctx.write_program(&module.span, SourceKind::Module, children);
}
Program::Script(script) => {
let children = script
Expand All @@ -129,7 +130,7 @@ pub fn serialize_swc_to_buffer(
.map(|stmt| serialize_stmt(&mut ctx, stmt))
.collect::<Vec<_>>();

ctx.write_program(&script.span, "script", children);
ctx.write_program(&script.span, SourceKind::Script, children);
}
}

Expand Down
14 changes: 12 additions & 2 deletions cli/tools/lint/ast_buffer/ts_estree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,12 +499,16 @@ impl TsEsTreeBuilder {
pub fn write_program(
&mut self,
span: &Span,
source_kind: &str,
source_kind: SourceKind,
body: Vec<NodeRef>,
) -> NodeRef {
let id = self.ctx.append_node(AstNode::Program, span);

self.ctx.write_str(AstProp::SourceType, source_kind);
let kind = match source_kind {
SourceKind::Module => "module",
SourceKind::Script => "script",
};
self.ctx.write_str(AstProp::SourceType, kind);
self.ctx.write_ref_vec(AstProp::Body, &id, body);

self.ctx.set_root_idx(id.0);
Expand Down Expand Up @@ -2903,3 +2907,9 @@ pub enum MethodKind {
Method,
Set,
}

#[derive(Debug)]
pub enum SourceKind {
Module,
Script,
}
41 changes: 39 additions & 2 deletions cli/tsc/dts/lib.deno.unstable.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1391,6 +1391,31 @@ declare namespace Deno {
fix?(fixer: Fixer): FixData | Iterable<FixData>;
}

/**
* @category Linter
* @experimental
*/
export interface SourceCode {
/**
* Get the source test of a node. Omit `node` to get the
* full source code.
*/
getText(node?: Node): string;
/**
* Returns array of ancestors of the current node, excluding the
* current node.
*/
getAncestors(node: Node): Node[];
/**
* Get the full source code.
*/
text: string;
/**
* Get the root node of the file. It's always the `Program` node.
*/
ast: Program;
}

/**
* @category Linter
* @experimental
Expand All @@ -1405,9 +1430,9 @@ declare namespace Deno {
*/
fileName: string;
/**
* Retrieve the source code of the current file.
* Helper methods for working with the raw source code.
*/
source(): string;
sourceCode: SourceCode;
/**
* Report a lint error.
*/
Expand Down Expand Up @@ -1497,6 +1522,17 @@ declare namespace Deno {
source: string,
): Diagnostic[];

/**
* @category Linter
* @experimental
*/
export interface Program {
type: "Program";
range: Range;
sourceType: "module" | "script";
body: Statement[];
}

/**
* @category Linter
* @experimental
Expand Down Expand Up @@ -3857,6 +3893,7 @@ declare namespace Deno {
* @experimental
*/
export type Node =
| Program
| Expression
| Statement
| TypeNode
Expand Down
9 changes: 9 additions & 0 deletions tests/specs/lint/lint_plugin_source_code/__test__.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"tempDir": true,
"steps": [
{
"args": "lint main.ts",
"output": "log.out"
}
]
}
5 changes: 5 additions & 0 deletions tests/specs/lint/lint_plugin_source_code/deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"lint": {
"plugins": ["./plugin.ts"]
}
}
13 changes: 13 additions & 0 deletions tests/specs/lint/lint_plugin_source_code/log.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Source:
const value = "unfixed";
console.log(value);

Source VariableDeclarator:
value = "unfixed"

Ancestors:
[ "Program", "VariableDeclaration" ]

Ast:
Program
Checked 1 file
2 changes: 2 additions & 0 deletions tests/specs/lint/lint_plugin_source_code/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
const value = "unfixed";
console.log(value);
Comment on lines +1 to +2
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you update this file to contain more text including things like ligatures and emojis? Just to better stress text the utf16 codepoint handling.

28 changes: 28 additions & 0 deletions tests/specs/lint/lint_plugin_source_code/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export default {
name: "test-plugin",
rules: {
"my-rule": {
create(context) {
return {
VariableDeclarator(node) {
console.log(`Source:`);
console.log(context.sourceCode.getText());

console.log(`Source VariableDeclarator:`);
console.log(context.sourceCode.getText(node));
console.log();

console.log(`Ancestors:`);
console.log(
context.sourceCode.getAncestors(node).map((node) => node.type),
);
console.log();

console.log(`Ast:`);
console.log(context.sourceCode.ast.type);
},
};
},
},
},
} satisfies Deno.lint.Plugin;
Loading