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
7.0 KiB
Raw
/**
* Compiling and checking files, with text that is not on disk yet.
*
* The tool checks a file, rewrites it, and checks the rewrite before
* writing it. The rewrite exists only in memory, so the compiler reads
* through an overlay host: a path with an override reads the override,
* everything else reads the disk. One `Compiler` is kept warm across
* files so the standard library is checked once; it is replaced every
* `ENTRIES_PER_COMPILER` files because a compiler's per-entry state is
* never collected (see packages/compiler/CONTEXT.md).
*/
import { readFile } from 'zena:fs';
import { getEnv } from 'zena:cli';
import { join2 } from 'zena:path';
import {
createCompiler, checkCompilation, CompilerHost, Compiler, PackageConfig,
ProgramCheckResult, Diagnostic, loadWorkspace,
} from 'compiler/compiler';
import { stdlibIdToRelativeFile } from 'compiler/module-resolver';
import { isWitModulePath, synthesizeWitModule } from 'compiler/wit-module-synth';
import { directoryNames } from 'compiler/fs-host';
import { CheckedFile } from './checked.zena';
export { CheckedFile } from './checked.zena';
/** How many entry points share one compiler before it is replaced. */
let ENTRIES_PER_COMPILER = 16;
/** Reads the stdlib from its root, overrides from memory, the rest from disk. */
final class OverlayHost implements CompilerHost {
#stdlibRoot: String;
overrides = new Map<String, String>();
new(stdlibRoot: String) : #stdlibRoot = stdlibRoot;
async readFile(path: String): Future<String> {
if (let (true, text) = this.overrides.get(path)) {
return text;
}
if (isWitModulePath(path)) {
return await synthesizeWitModule(this, path);
}
if (path.startsWith('zena:')) {
return await readFile(join2(this.#stdlibRoot, stdlibIdToRelativeFile(path)));
}
return await readFile(path);
}
async listDir(path: String): Future<Array<String> | null> {
return await directoryNames(path);
}
}
/**
* The project the files belong to: where the standard library is and
* which packages its workspace has, plus the warm compiler.
*/
export final class Project {
/** Where the compiler reads the standard library from. */
stdlibRoot: String;
/**
* Where the standard library's files are named on a command line, when
* that is somewhere else: the `zena` command reads them through the
* host's `/stdlib` preopen but is asked about `packages/stdlib/zena/…`.
*/
stdlibSources: String;
target: String;
#host: OverlayHost;
#packageCache: String | null;
/** The workspace's packages, read the first time a compiler needs them. */
var #packages: Map<String, PackageConfig> | null = null;
var #compiler: Compiler | null = null;
var #previous: ProgramCheckResult | null = null;
var #entriesOnCompiler = 0;
/** Whether the current file is in an import cycle; see `override`. */
var #cyclic = false;
/**
* `packageCache` is where fetched packages are, for a workspace whose
* `zena-lock.json` pins some; see `CompileFileOptions.packageCache`.
*/
new(stdlibRoot: String = 'packages/stdlib/zena', stdlibSources: String | null = null,
target: String = 'zena-component', packageCache: String | null = null)
: stdlibRoot = stdlibRoot,
stdlibSources = stdlibSources ?? stdlibRoot,
target = target,
#host = new OverlayHost(stdlibRoot),
#packageCache = packageCache;
/** A fresh compiler, dropping whatever the old one accumulated. */
async #freshCompiler(): Future<Compiler> {
var packages = this.#packages;
if (packages == null) {
let loaded = await loadWorkspace(new OverlayHost(this.stdlibRoot), '.', null, this.#packageCache);
this.#packages = loaded;
packages = loaded;
}
let compiler = createCompiler(this.#host, {
stdlibRoot: this.stdlibRoot,
packages: packages,
warnUnnecessaryCasts: true,
});
this.#compiler = compiler;
this.#previous = null;
this.#entriesOnCompiler = 0;
return compiler;
}
/**
* Text the compiler should read for `path` instead of the disk's, or
* null to read the disk again. Call before `check` for the same path.
*/
async override(path: String, text: String | null): Future<void> {
let key = this.entryIdOf(path);
if (text == null) {
this.#host.overrides.delete(key);
} else {
this.#host.overrides[key] = text;
}
if (this.#cyclic) {
// A file in an import cycle cannot be re-read on its own: the
// other members keep the types of its old parse, and the new
// parse's types do not match them ("'App' is not assignable to
// 'App'"). Start over with a compiler that has seen none of them.
this.#compiler = null;
this.#previous = null;
return;
}
let compiler = this.#compiler;
// Not `compiler?.invalidate(path)`: an optional method call does not
// lower yet (see the nullish rule).
if (compiler != null) {
await compiler.invalidate(key);
}
}
/**
* The id the compiler knows a file by. A standard library file is
* `zena:<path under the root>`: compiled by its disk path it would be a
* second copy of its library, with types that match nothing the rest
* of the standard library has (`'Encoding' is not assignable to
* 'Encoding'`).
*/
entryIdOf(path: String): String {
let root = `${this.stdlibSources}/`;
if (path.startsWith(root)) {
return `zena:${path.sliceBytes(root.length, path.length)}`;
}
return path;
}
/** Forget every override and every cached file. Call between files. */
reset(): void {
this.#host.overrides.clear();
this.#entriesOnCompiler += 1;
if (this.#entriesOnCompiler >= ENTRIES_PER_COMPILER || this.#cyclic) {
this.#compiler = null;
this.#previous = null;
}
this.#cyclic = false;
}
/**
* Compiles and checks the file at `path` (reading an override if one is
* set), or throws when it does not parse or a dependency is missing.
*/
async check(path: String): Future<CheckedFile> {
let compiler = this.#compiler ?? await this.#freshCompiler();
// The file itself may have changed since the last check; the
// dependencies are trusted until `reset`.
let id = this.entryIdOf(path);
if (getEnv('ZENA_LINT_DEBUG') != null) {
console.log(`checking ${path} as ${id} (stdlib root ${this.stdlibRoot})`);
}
await compiler.invalidate(id);
let result = await compiler.compile({entry: id, target: this.target});
if (result.hasCycle) {
this.#cyclic = true;
}
let checked = checkCompilation(result, this.#previous);
this.#previous = checked;
let entryPath = result.entry.path;
let own = new Array<Diagnostic>();
for (let diagnostic in checked.entry.diagnostics) {
let location = diagnostic.location;
if (location == null || location.file == entryPath || location.file == path ||
location.file == id) {
own.push(diagnostic);
}
}
let file = new CheckedFile(path, result.entry.source, result.entry.ast,
checked.entry.model, own);
file.isStdlib = id.startsWith('zena:');
return file;
}
}
- 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 |
|
|