lint 0.0.2-preview.1
Lint rules for Zena source, each with a fix
lint#
Lint rules for Zena source code, each with an automated fix. The compiler and type checker drive every rule, and when a fix is applied it is type-checked again before it is kept.
Usage#
Command Line#
zena lint [--fix] [--only a,b] [--skip a,b] <paths...>
zena lint --list-rules
A path is a .zena file or a directory, searched for them. Without --fix the command prints each finding as path:line:column: message [rule] and exits 1 when there is one; with --fix it rewrites the files. -v on the command lists every fix and the text of any rejected one.
The language server (zena lsp) publishes the findings as warnings and offers each as a quick fix, plus a source.fixAll.zena code action for the whole file.
Library API#
import { LintOptions, lintFile } from 'lint';
import { Project } from 'lint/checking';
import { allRules } from 'lint/rules';
let project = new Project();
let options = new LintOptions(allRules());
let report = await lintFile(project, 'src/main.zena', options);
Rules#
| Rule | Rewrite |
|---|---|
function-declaration |
top-level let f = (…) => … → function f(…) { … } |
unnecessary-cast |
x as T where x: T → x (from the checker's warning, less contextually typed operands) |
unnecessary-optional-chain |
x?.f, x?[i], f?(…) on a non-nullable target → x.f, x[i], f(…) |
unnecessary-annotation |
let x: T = e with e: T; return types the body implies; callback parameter types |
collection-literal |
new Array<T>() + push runs → growable<T>([…]); new Map<K, V>() + []= → {k => v} |
if-initializer |
var x = d; if (c) { x = a; } → let x = if (c) a else d |
nullish |
if (x != null) x else d → x ?? d; if (x != null) x.f else null → x?.f |
match-to-if |
one- and two-arm match → if, if (x is T), if (let P = x) |
else-if |
else { if (…) { … } } → else if (…) { … } |
for-in |
index loops that read only xs[i] → for (let x in xs) |
boolean-return |
if (c) { return true; } return false; → return c;; if (c) true else false → c |
template-literal |
three or more +-joined strings → a template literal |
console-to-string |
console.log(`${x}`) and console.log(i32ToString(x)) → console.log(x) |
arrow-body |
(x) => { return e; } → (x) => e |
prefer-let |
var never assigned again → let |
immutable-field |
var field nothing assigns → immutable field (#private, or the class is not exported) |
empty-constructor |
new() {} on a class with no other constructor → removed; the default is synthesized |
Libraries#
lint/lint/lint— lint driver (lintFile,lintSource,LintOptions,FileReport)lint/checking— compiler project wrapper and overlay host (Project,CheckedFile)lint/checked— checked module wrapper (CheckedFile)lint/rules— rule registry (allRules,ruleNamed)lint/rule— rule runner (NamedRule,proposeEdits,messageOf)lint/context— rule traversal context (RuleContext)lint/source— byte-range edits (Edit,applyEdits,columnOf)lint/files—.zenafile discovery (collectZenaFiles)
License#
MIT
9.9 KiB
Raw
/**
* Null tests that spell out what `??` and `?.` mean.
*
* if (x != null) x else d → x ?? d
* if (x != null) x.a else null → x?.a
* if (x != null) x.name else d → x?.name ?? d (x.name not nullable)
* if (x != null) { return x; } → return x ?? d;
* return d;
*
* `x` is a name or a field path (`this.#cache`), so that reading it twice
* reads the same thing. Only one field or index access is made optional:
* `x?.a.b` does not short-circuit `.b` (#396), and a call behind `?.`
* does not lower (#398). A default is only folded onto an access whose
* own type is not nullable, since `??` would also replace a legitimate
* `null` result.
*/
import {
Node, Module, Statement, BlockStatement, Expression, IfExpression, IfStatement,
BinaryExpression, NullLiteral, Identifier, MemberExpression, IndexExpression,
CallExpression, ExpressionStatement, ReturnStatement, LetPatternCondition,
ThisExpression,
} from 'compiler/ast';
import { walkEnter } from 'compiler/visitor';
import { RuleContext } from '../context.zena';
import { typeToString, ClassType, UnionType } from 'compiler/types';
export function nullishOperators(ctx: RuleContext): void {
walkEnter(ctx.ast, (n) => {
match (n) {
case IfExpression {}: { ifExpression(ctx, n); }
case Module {body}: { returnPairs(ctx, body); }
case BlockStatement {body}: { returnPairs(ctx, body); }
case _: {}
}
});
}
/** The reference a null test compares, and which way the test goes. */
final class NullTest(reference: Expression, positive: boolean)
/** `x != null`, `null == x`, … where `x` is a simple reference of nullable type. */
function nullTestOf(ctx: RuleContext, test: Node): NullTest | null {
if (let BinaryExpression {operator, left, right} = test) {
let positive = operator == '!=' || operator == '!==';
let negative = operator == '==' || operator == '===';
if (!positive && !negative) {
return null;
}
let reference: Expression | null = if (right is NullLiteral) {
left
} else if (left is NullLiteral) {
right
} else {
null
};
if (reference == null || !ctx.isSimpleReference(reference)) {
if (ctx.debug) {
console.log(`nullish: ${ctx.text(test)} is not a simple reference`);
}
return null;
}
if (!ctx.isNullable(ctx.typeOf(reference))) {
if (ctx.debug) {
let t = ctx.typeOf(reference);
console.log(`nullish: ${ctx.text(reference)} has type ${if (t != null) typeToString(t) else '<none>'}, not nullable`);
}
return null;
}
if (isExtensionInstance(ctx, reference)) {
// `x?.member` on an extension class type-checks but does not lower:
// the instance is erased to the wrapped value at run time, and the
// member is looked up on that (#395). See
// tests/language/execution/optional-chaining/extension_class_member.zena.
if (ctx.debug) {
console.log(`nullish: ${ctx.text(reference)} is an extension class instance`);
}
return null;
}
return new NullTest(reference, positive);
}
return null;
}
/** Whether the reference's type, less `null`, is an extension class. */
function isExtensionInstance(ctx: RuleContext, reference: Expression): boolean {
let t = ctx.typeOf(reference);
if (t == null) {
return false;
}
let u = ctx.unwrap(t);
if (u is UnionType) {
for (let member in u.types) {
let m = ctx.unwrap(member);
if (m is ClassType && m.isExtension) {
return true;
}
}
return false;
}
return u is ClassType && u.isExtension;
}
/**
* `chain` with its root — the occurrence of `reference` it starts from —
* made optional: `x.a` → `x?.a`. Null when `chain` is not one access on
* `reference` — a field, an index, a call, or a method call — or mentions
* it again. One access only: `x?.a.b` does not short-circuit `.b` in
* Zena (#396), so a longer chain would need `?.` at every step and a
* different meaning.
*/
function optionalChain(ctx: RuleContext, chain: Expression, reference: Expression): String | null {
let referenceText = ctx.text(reference);
// A call behind `?.` — a method call or a call of a function-typed
// field — type-checks but does not lower yet (#398), so only a field
// or an index is made optional.
if (chain is CallExpression) {
if (ctx.debug) {
console.log(`nullish: ${ctx.text(chain)} is a call, which does not lower behind ?.`);
}
return null;
}
var root: Node = chain;
var steps = 0;
while (true) {
let next = match (root) {
case MemberExpression {object}: object
case IndexExpression {object}: object
case CallExpression {callee}: callee
case _: null
};
if (next == null) {
break;
}
root = next;
steps += 1;
}
if (steps != 1 || ctx.text(root) != referenceText || ctx.start(root) != ctx.start(chain)) {
if (ctx.debug) {
console.log(`nullish: chain root ${ctx.text(root)} after ${i32ToString(steps)} steps, starts ${i32ToString(ctx.start(root))} vs ${i32ToString(ctx.start(chain))}`);
}
return null;
}
// The root is the only mention: a second one would not be narrowed.
if (countReferences(ctx, chain, reference) != 1) {
if (ctx.debug) {
console.log(`nullish: ${referenceText} is mentioned again in ${ctx.text(chain)}`);
}
return null;
}
let rootEnd = ctx.end(root);
return `${referenceText}?${ctx.slice(rootEnd, ctx.end(chain))}`;
}
/**
* How many times `chain` reads `reference`: by binding for a name, by
* spelling for a field path such as `this.#cache`.
*/
function countReferences(ctx: RuleContext, chain: Node, reference: Expression): i32 {
var count = 0;
if (reference is Identifier) {
let sym = ctx.symbolOf(reference);
if (sym == null) {
return 0;
}
walkEnter(chain, (n) => {
if (n is Identifier) {
let s = ctx.symbolOf(n);
if (s != null && (s.id as i32) == (sym.id as i32)) {
count += 1;
}
}
});
return count;
}
let text = ctx.text(reference);
walkEnter(chain, (n) => {
if (n is MemberExpression && ctx.isSimpleReference(n) && ctx.text(n) == text) {
count += 1;
}
});
return count;
}
function ifExpression(ctx: RuleContext, node: IfExpression): void {
let alternate = node.alternate;
if (ctx.debug) {
console.log(`nullish: if-expression at line ${i32ToString(ctx.lineOf(node))}, test ${ctx.text(node.test)}, alternate ${if (alternate == null) 'none' else 'present'}`);
}
if (alternate == null) {
return;
}
let test = nullTestOf(ctx, node.test);
if (test == null) {
if (ctx.debug) {
console.log(`nullish: not a null test`);
}
return;
}
let whenNonNull = ctx.singleExpression(if (test.positive) node.consequent else alternate);
let whenNull = ctx.singleExpression(if (test.positive) alternate else node.consequent);
if (whenNonNull == null || whenNull == null) {
if (ctx.debug) {
console.log(`nullish: a branch is not a single expression`);
}
return;
}
if (ctx.hasComment(node)) {
if (ctx.debug) {
console.log(`nullish: has a comment`);
}
return;
}
let referenceText = ctx.text(test.reference);
if (ctx.text(whenNonNull) == referenceText) {
ctx.replace(node, `${referenceText} ?? ${ctx.text(whenNull)}`);
return;
}
let chain = optionalChain(ctx, whenNonNull, test.reference);
if (chain == null) {
if (ctx.debug) {
console.log(`nullish: ${ctx.text(whenNonNull)} is not a chain on ${referenceText}`);
}
return;
}
if (whenNull is NullLiteral) {
// A primitive behind `?.` has to be coalesced at once; the original
// could not have had this shape then either.
if (ctx.isPrimitive(ctx.typeOf(whenNonNull))) {
return;
}
ctx.replace(node, chain);
return;
}
if (ctx.isNullable(ctx.typeOf(whenNonNull))) {
if (ctx.debug) {
let t = ctx.typeOf(whenNonNull);
console.log(`nullish: ${ctx.text(whenNonNull)} is nullable (${if (t != null) typeToString(t) else '<none>'}), so a default cannot fold onto it`);
}
return;
}
ctx.replace(node, `${chain} ?? ${ctx.text(whenNull)}`);
}
/** `if (x != null) { return x; } return d;` → `return x ?? d;` */
function returnPairs(ctx: RuleContext, statements: GrowableArray<Statement>): void {
var i = 0;
while (i + 1 < statements.length) {
let first = statements[i];
let second = statements[i + 1];
i += 1;
if (!(first is IfStatement) || !(second is ReturnStatement)) {
continue;
}
let guard = first;
if (guard.alternate != null) {
continue;
}
let test = nullTestOf(ctx, guard.test);
if (test == null) {
continue;
}
let returned = singleReturn(guard.consequent);
let after = second.argument;
if (returned == null || after == null) {
continue;
}
let start = ctx.start(first);
let end = ctx.statementEnd(second);
if (ctx.hasCommentIn(start, end)) {
continue;
}
let referenceText = ctx.text(test.reference);
if (test.positive) {
if (ctx.text(returned) == referenceText) {
ctx.replaceRange(start, end, `return ${referenceText} ?? ${ctx.text(after)};`);
} else {
let chain = optionalChain(ctx, returned, test.reference);
if (chain != null && !ctx.isNullable(ctx.typeOf(returned))) {
ctx.replaceRange(start, end, `return ${chain} ?? ${ctx.text(after)};`);
}
}
} else if (ctx.text(after) == referenceText) {
ctx.replaceRange(start, end, `return ${referenceText} ?? ${ctx.text(returned)};`);
}
}
}
/** The argument of the single `return` a branch consists of, else null. */
function singleReturn(branch: Node): Expression | null {
let statement = match (branch) {
case BlockStatement {body}: if (body.length == 1) body[0] else null
case Statement as s: s
case _: null
};
if (statement == null) {
return null;
}
if (let ReturnStatement {argument} = statement) {
return argument;
}
return null;
}
- compiler compiler.zena-lang.pkg.zena-lang.dev 0.0.2-preview.1
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.2-preview.1 | 2026-11-19 |
|
|