Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions docs/CODE_MAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ Browser
| Solid rule `solid-returned-cleanup` (a function returned from `onMount`/`createEffect`, which Solid ignores) on files that import `solid-js` | `server/app/services/findings/solid.py` |
| Await-in-loop rule (`await-in-loop`, `[db]` rank when the loop walks an awaited `prisma.*`/`findMany` result); skips pagination/retry/chain loops, `tx.*` in transactions, `Promise.all` chunks, sleeps and tests | `server/app/services/findings/async_loops.py` |
| Duplicate-type rule (`duplicate-type`): a non-exported top-level object type (`type X = {…}` or `interface`) whose name another non-test file exports, when at least 3 of its fields, and at least half, match that type by name and declared type text; tests and `.d.ts` skipped | `server/app/services/findings/duplicate_types.py` (`object_types`, `find_copies`, `DuplicateTypeTool`); test `server/tests/test_duplicate_types.py` |
| Copied-type cast rule (`copied-type-cast`): a cast (`x as T`, payloads of `Promise<…>` compared) whose operand type and `T` are different named declarations with one name, one of them the project's own; runs `copied_type_casts.mjs` with the project's `typescript` per tsc config; anonymous types, lib-vs-lib, tests and portable snapshots skipped | `server/app/services/findings/copied_type_casts.py` (`plan`, `CopiedTypeCastTool`, `parse_output`) and `copied_type_casts.mjs`; test `server/tests/test_copied_type_casts.py` |
| Rule-pack runner: a project's ast-grep YAML rules in `.srcly/rules/` (`ast-grep scan --json=stream`, binary from `SRCLY_AST_GREP`, `node_modules/.bin`, or PATH; missing → N/A); starter rules in `docs/rule-packs/` | `server/app/services/findings/astgrep.py` (`plan`, `AstGrepTool`, `parse_output`) |
| `srcly findings [path] --rule <id>`: every finding as `path:line rule message` with a count per rule (`--format json`); a count is N/A with the reason when a checker that could report the rule failed or checked no file (srcly tools and ast-grep declare `Tool.rules`; `typescript.unscheduled` lists configured checks that were not planned) | `server/app/services/findings/listing.py` (`build`, `render`, `run`); CLI in `server/app/run.py`; test `server/tests/test_findings_listing.py` |
| `srcly fix`: findings carry `fix` (byte edits or a file delete); diff by default, `--write` applies, deletes only with `--rule unreachable-file`; fixers are `reachability.py` (drop `export`, delete file) and `solid.py` (`onCleanup`) | `server/app/services/findings/fixes.py` (`plan`, `diff`, `run`); CLI in `server/app/run.py`; proof in `server/tests/test_fixes.py` (real `tsc` before and after) |
Expand Down
157 changes: 157 additions & 0 deletions server/app/services/findings/copied_type_casts.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
// srcly's `copied-type-cast` checker: one tsconfig's casts onto a same-name copy of the operand's type.
// Run by copied_type_casts.py: node copied_type_casts.mjs <tsconfig> <scope dir>
// It loads the project's own `typescript` (resolved from the tsconfig), so the
// checker sees the project the way its tsc does. Prints one JSON object.
import { createRequire } from "node:module";
import fs from "node:fs";
import path from "node:path";

const realpath = (file) => {
try {
return fs.realpathSync(file);
} catch {
return path.resolve(file);
}
};

const [configPath, scopeDir] = process.argv.slice(2);
let ts;
try {
ts = createRequire(path.resolve(configPath))("typescript");
} catch {
console.log(JSON.stringify({ error: "the project has no `typescript` package" }));
process.exit(0);
}

const configError = [];
const config = ts.getParsedCommandLineOfConfigFile(configPath, {}, {
...ts.sys,
onUnRecoverableConfigFileDiagnostic: (d) => configError.push(ts.flattenDiagnosticMessageText(d.messageText, " ")),
});
// A broken config (a missing `extends` base) changes what the checker sees: N/A, not a clean 0.
// TS18003 (no inputs) is an empty project, which checks nothing.
const fatal = config?.errors.find((d) => d.code !== 18003);
if (fatal) configError.push(ts.flattenDiagnosticMessageText(fatal.messageText, " "));
if (!config || configError.length) {
console.log(JSON.stringify({ error: `tsconfig: ${configError[0] ?? "unreadable"}` }));
process.exit(0);
}
const options = { ...config.options, noEmit: true, disableSourceOfProjectReferenceRedirect: false };
const host = ts.createCompilerHost(options);
// Read a project reference's sources, as editors do, not its built `.d.ts`:
// an unbuilt reference (TS6305) would otherwise leave its types unresolved and read as a clean 0.
host.useSourceOfProjectReferenceRedirect = () => true;
const program = ts.createProgram({ rootNames: config.fileNames, options, projectReferences: config.projectReferences, host });
const checker = program.getTypeChecker();
// The scan root: a folder, or one file.
const scope = path.resolve(scopeDir);
const inScope = (file) => file === scope || file.startsWith(scope + path.sep);
const inNodeModules = (file) => file.split(/[\\/]/).includes("node_modules");
const isProjectFile = (sf) =>
!sf.isDeclarationFile && !inNodeModules(sf.fileName) && inScope(path.resolve(sf.fileName));
// A declaration the project wrote, as opposed to one from a library or lib.d.ts.
const isOwn = (sf) =>
!program.isSourceFileDefaultLibrary(sf) && !program.isSourceFileFromExternalLibrary(sf) && !inNodeModules(sf.fileName);

function unwrapPromise(type) {
if (type.getSymbol()?.getName() !== "Promise") return null;
const args = checker.getTypeArguments(type);
return args?.length === 1 ? args[0] : null;
}

const isLibPromise = (sym) =>
sym?.getName() === "Promise" &&
!!sym.declarations?.length &&
sym.declarations.every((d) => program.isSourceFileDefaultLibrary(d.getSourceFile()));

// Only these declare a type with a name another file can copy.
const NAMED = ts.SymbolFlags.TypeAlias | ts.SymbolFlags.Interface | ts.SymbolFlags.Class | ts.SymbolFlags.Enum;

// The named declaration behind a type: its alias (`type X = …`) or its
// class/interface/enum symbol. An enum member (`Status.Ready`, or the one
// member of a one-member enum) stands for its enum. Anonymous object types,
// type parameters and anything else are left out.
function named(type) {
if (type.flags & ts.TypeFlags.TypeParameter) return null;
return declared(type.aliasSymbol ?? type.getSymbol());
}

// The cast's target as written: `as Other` names `Other` even when
// `type Other = Doc` folds to `Doc` in the checker. Imports resolve to what they bind.
function written(typeNode) {
while (ts.isParenthesizedTypeNode(typeNode)) typeNode = typeNode.type;
if (!ts.isTypeReferenceNode(typeNode)) return null;
let sym = checker.getSymbolAtLocation(typeNode.typeName);
if (sym && sym.flags & ts.SymbolFlags.Alias) sym = checker.getAliasedSymbol(sym);
return declared(sym);
}

function declared(sym) {
if (sym && sym.flags & ts.SymbolFlags.EnumMember) sym = sym.parent;
const decl = sym?.declarations?.[0];
if (!sym || !decl || !(sym.flags & NAMED)) return null;
const sf = decl.getSourceFile();
return {
sym,
name: sym.getName(),
file: path.resolve(sf.fileName),
real: realpath(sf.fileName),
line: sf.getLineAndCharacterOfPosition(decl.getStart(sf)).line + 1,
own: isOwn(sf),
};
}

const files = [];
const casts = [];
for (const sf of program.getSourceFiles()) {
if (!isProjectFile(sf)) continue;
files.push(path.resolve(sf.fileName));
const visit = (node) => {
if (ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) {
const typeNode = node.type;
const isConst = ts.isTypeReferenceNode(typeNode) && typeNode.typeName.getText(sf) === "const";
if (!isConst) check(sf, node);
}
ts.forEachChild(node, visit);
};
visit(sf);
}

function check(sf, node) {
let src = checker.getTypeAtLocation(node.expression);
let tgt = checker.getTypeFromTypeNode(node.type);
let tgtNode = node.type;
// `fetchDoc(id) as Promise<DocDetail>`: the copy hides in the payload.
const ps = unwrapPromise(src), pt = unwrapPromise(tgt);
if (ps && pt) {
[src, tgt] = [ps, pt];
// The written argument is the payload only for `Promise<X>` itself; an alias such as
// `Wrapped<T> = Promise<{ data: T }>` may wrap or replace it, so the checker's payload decides.
while (ts.isParenthesizedTypeNode(tgtNode)) tgtNode = tgtNode.type;
const isPromise = ts.isTypeReferenceNode(tgtNode) && isLibPromise(checker.getSymbolAtLocation(tgtNode.typeName));
const args = ts.isTypeReferenceNode(tgtNode) ? tgtNode.typeArguments : undefined;
tgtNode = isPromise && args?.length === 1 ? args[0] : null;
}
const a = named(src), b = (tgtNode && written(tgtNode)) ?? named(tgt);
if (!a || !b || a.name !== b.name || a.sym === b.sym) return;
// One declaration reached as a merged and an unmerged symbol (a global augmentation) is not a copy.
if (a.sym.declarations.some((d) => b.sym.declarations.includes(d))) return;
// One file loaded twice (`preserveSymlinks`, a workspace link and a relative path) is one declaration.
if (a.real === b.real && a.line === b.line) return;
// Two library declarations (DOM's and Node's `ReadableStream`) are not the project's copy.
if (!a.own && !b.own) return;
const start = sf.getLineAndCharacterOfPosition(node.getStart(sf));
const end = sf.getLineAndCharacterOfPosition(node.getEnd());
casts.push({
file: path.resolve(sf.fileName),
line: start.line + 1,
endLine: end.line + 1,
column: start.character + 1,
text: node.getText(sf).replace(/\s+/g, " ").slice(0, 80),
name: a.name,
source: { file: a.file, line: a.line },
target: { file: b.file, line: b.line },
});
}

console.log(JSON.stringify({ files, casts }));
200 changes: 200 additions & 0 deletions server/app/services/findings/copied_type_casts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
"""srcly's ``copied-type-cast`` rule: a cast onto a same-name copy of the operand's type.

``fetchDoc(id) as Promise<DocDetail>`` where ``fetchDoc`` returns the
``DocDetail`` from ``docs.queries.ts`` and the file casts it to its own
``DocDetail``. The two types share a name but are two declarations, and the
cast is what keeps tsc from comparing them. ``duplicate-type`` finds the copied
declaration by its fields; this rule finds the cast that hides it, so it also
catches copies of a library type (``t.status as ChatThreadStatus`` onto a local
copy of Prisma's enum) and copies whose fields have drifted.

A cast (``x as T`` or ``<T>x``, not ``as const``) is reported when:

- the operand's type and ``T`` are both named types (a type alias, interface,
class or enum) with the same name; for ``Promise<A> as Promise<B>`` the
payloads ``A`` and ``B`` are compared;
- they are different symbols, so not one declaration seen twice or one
interface merged across files;
- at least one of the two is declared in the project, not in a library or
``lib.d.ts`` (DOM's and Node's ``ReadableStream`` are not the project's copy).

Anonymous object types (``as { x: number }``) have no name and are left out.
The rule needs the type checker, so it runs a small Node script
(``copied_type_casts.mjs``) with the project's own ``typescript`` once per
tsconfig, for projects that install ``typescript``. Test files and ``.d.ts``
files are skipped. It is not run for portable (compare) snapshots.
"""

from __future__ import annotations

import hashlib
import json
import os
from pathlib import Path
from typing import Optional

from app.services.deps.common import is_test_path
from app.services.findings import typescript
from app.services.findings.model import Finding, rel_label
from app.services.findings.tools import _PRUNED_DIRS, Tool, ToolFailed, find_up, first_line, run_process, timeout_for

SCRIPT = Path(__file__).with_name("copied_type_casts.mjs")
RULE = "copied-type-cast"


def _where(file: str, line: int, root: Path) -> str:
"""A declaration as ``path:line``: relative to the root, or from the package for a library."""
path = Path(file)
try:
return f"{path.relative_to(root).as_posix()}:{line}"
except ValueError:
pass
parts = path.parts
if "node_modules" in parts:
last = len(parts) - 1 - parts[::-1].index("node_modules")
return f"{'/'.join(parts[last + 1:])}:{line}"
return f"{path.name}:{line}"


def _base(root: Path) -> Path:
return root if root.is_dir() else root.parent


def parse_output(stdout: str, root: Path, tool_id: str, project: Optional[Path] = None) -> tuple[list[Finding], list[str]]:
"""The script's JSON as findings.

``project`` (the repository root) is the one base for test classification
and shown paths, so a scan of one file judges it like a scan of its
folder, and two tsconfigs that check one cast give one message.
"""
try:
data = json.loads(stdout)
except json.JSONDecodeError as exc:
raise ToolFailed(f"unreadable JSON output ({exc.msg})") from exc
if data.get("error"):
raise ToolFailed(str(data["error"]))
shown = project if project is not None and project.is_dir() else _base(root)

def keep(file: str) -> bool:
path = Path(file)
if path != root and root not in path.parents:
return False
base = shown if shown in path.parents else _base(root)
return not is_test_path(path.relative_to(base).as_posix())

files = [f for f in data.get("files", []) if keep(f)]
findings = []
for cast in data.get("casts", []):
if not keep(cast["file"]):
continue
name, src, tgt = cast["name"], cast["source"], cast["target"]
findings.append(
Finding(
path=cast["file"],
line=cast["line"],
end_line=cast["endLine"],
column=cast["column"],
rule=RULE,
message=(
f"`{cast['text']}` casts the `{name}` from {_where(src['file'], src['line'], shown)} "
f"to a different `{name}`, declared in {_where(tgt['file'], tgt['line'], shown)}. "
f"The cast keeps tsc from comparing the two copies. Keep one declaration, import it, "
f"and drop the cast."
),
severity="warning",
tool=tool_id,
)
)
return findings, files


_INPUTS = typescript.TS_EXTENSIONS + (".json",)


def project_inputs(directory: Path) -> str:
"""A digest of the TS and JSON files under a tsconfig's folder (path, size, mtime).

The checker reads files outside the scanned folder (a sibling's exported
type), so the scan's own fingerprint cannot tell when a cached result is stale.
"""
digest = hashlib.sha256()
for dirpath, dirnames, filenames in os.walk(directory):
dirnames[:] = sorted(d for d in dirnames if d not in _PRUNED_DIRS and not d.startswith("."))
for name in sorted(filenames):
if name.endswith(_INPUTS):
try:
st = os.stat(os.path.join(dirpath, name))
except OSError:
continue
digest.update(f"{dirpath}/{name}:{st.st_size}:{st.st_mtime_ns}\n".encode())
return digest.hexdigest()[:16]


class CopiedTypeCastTool(Tool):
rules = (RULE,)

def __init__(self, root: Path, config: Path, node: str, label_base: Path) -> None:
name = rel_label(config, label_base)
super().__init__(
id=f"srcly-casts:{name}",
tool="srcly-casts",
label=f"srcly copied-type casts ({name})",
source="srcly defaults",
root=root,
extensions=typescript.TS_EXTENSIONS,
timeout=timeout_for("srcly-casts"),
signature_paths=(config, SCRIPT),
)
self.config = config
self.node = node
self.project = label_base

def signature(self) -> str:
# The checker can read any file in the repository (a workspace package, `../shared`).
inputs = self.project if self.project.is_dir() else self.config.parent
return f"{super().signature()}|inputs={project_inputs(inputs)}"

def check(self):
root = self.root.resolve()
out = run_process([self.node, str(SCRIPT), str(self.config), str(root)], self.config.parent, self.timeout)
if out.returncode != 0:
raise ToolFailed(first_line(out.stderr or out.stdout) or f"exit code {out.returncode}")
return parse_output(out.stdout, root, self.id, self.project)


def _configs(root: Path, stop: Optional[Path]) -> list[tuple[Path, str]]:
"""Every tsconfig for ``root``, with why the rule cannot check it (empty when it can)."""
from app.services.dataflow.availability import locate_node

node = locate_node()
out = []
for index, config in enumerate(typescript.tsconfigs(root, stop)):
why = ""
if index >= typescript.MAX_TSC_PROJECTS:
why = f"over the limit of {typescript.MAX_TSC_PROJECTS} projects"
elif not find_up(config.parent, "node_modules/typescript/package.json"):
why = "no node_modules/typescript"
elif node is None:
why = "no Node on PATH (set SRCLY_NODE)"
out.append((config, why))
return out


def plan(root: Path, stop: Optional[Path] = None) -> list[Tool]:
"""One run per tsconfig the rule can check, as many as ``tsc`` gets."""
from app.services.dataflow.availability import locate_node

label_base = stop or root
configs = [config for config, why in _configs(root, stop) if not why]
node = locate_node() if configs else None
return [CopiedTypeCastTool(root, config, node, label_base) for config in configs] if node else []


def unscheduled(root: Path, stop: Optional[Path] = None) -> list[tuple[str, str, str]]:
"""Configs ``plan`` leaves out: (tool, label, reason). ``srcly findings`` reads the rule's count as N/A for them."""
label_base = stop or root
return [
("srcly-casts", f"srcly copied-type casts ({rel_label(config, label_base)})", why)
for config, why in _configs(root, stop)
if why
]
11 changes: 7 additions & 4 deletions server/app/services/findings/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@


class FindingsJob:
def __init__(self, root: Path, fingerprint: Optional[str]) -> None:
def __init__(self, root: Path, fingerprint: Optional[str], signature: str = "") -> None:
self.root = root
self.fingerprint = fingerprint
self.signature = signature
"""The planned tools' signatures: a checker can read files outside ``root``."""
self._result: Optional[FindingsResult] = None
self._done = threading.Event()

Expand Down Expand Up @@ -54,13 +56,14 @@ def __init__(self) -> None:
self._lock = threading.Lock()

def start(self, root: Path, fingerprint: Optional[str]) -> FindingsJob:
"""The job for ``root`` at ``fingerprint``, started if new."""
"""The job for ``root`` at ``fingerprint`` and the same tool signatures, started if new."""
root = root.resolve()
signature = runner.tools_signature(root) if fingerprint is not None else ""
with self._lock:
for job in reversed(self._jobs):
if job.root == root and job.fingerprint == fingerprint and fingerprint is not None:
if job.root == root and job.fingerprint == fingerprint and fingerprint is not None and job.signature == signature:
return job
job = FindingsJob(root, fingerprint)
job = FindingsJob(root, fingerprint, signature)
self._jobs.append(job)
del self._jobs[:-MAX_JOBS]
threading.Thread(target=job.run, name="srcly-findings-job", daemon=True).start()
Expand Down
Loading
Loading