Skip to content

Instantly share code, notes, and snippets.

@7hoenix
Forked from lydell/README.md
Created March 21, 2024 17:53
Show Gist options
  • Save 7hoenix/c204c851d16caa220c51d4da7cdd5b60 to your computer and use it in GitHub Desktop.
Save 7hoenix/c204c851d16caa220c51d4da7cdd5b60 to your computer and use it in GitHub Desktop.
Find unused Elm record fields

Find unused Elm record fields

This script finds some unused record fields (but not all).

First run npm ci, and then:

git grep -l '^main =' | xargs elm make --output elm.js && node find-unused-record-fields.js < elm.js
const fs = require("fs");
const jsTokens = require("js-tokens");
const projectPrefix = "$author$project$";
const code = fs.readFileSync(process.stdin.fd, "utf8");
const fields = new Map();
const usedFields = new Set();
let prevPrevPrevToken = { type: "LineTerminatorSequence", value: "\n" };
let prevPrevToken = { type: "LineTerminatorSequence", value: "\n" };
let prevToken = { type: "LineTerminatorSequence", value: "\n" };
let currentProjectFunction = undefined;
for (const token of jsTokens(code)) {
if (
prevPrevPrevToken.type === "LineTerminatorSequence" &&
prevPrevToken.value === "var" &&
prevToken.type === "WhiteSpace"
) {
if (token.value.startsWith(projectPrefix)) {
currentProjectFunction = token.value
.slice(projectPrefix.length)
.replace(/\$/g, ".");
} else {
currentProjectFunction = undefined;
}
} else if (
currentProjectFunction !== undefined &&
prevPrevToken.type === "IdentifierName" &&
!prevPrevToken.value.startsWith("_") &&
prevToken.value === ":" &&
token.type !== "LineTerminatorSequence"
) {
const name = prevPrevToken.value;
const previous = fields.get(name);
if (previous === undefined) {
fields.set(name, new Set([currentProjectFunction]));
} else {
previous.add(currentProjectFunction);
}
} else if (prevToken.value === "." && token.type === "IdentifierName") {
usedFields.add(token.value);
}
prevPrevPrevToken = prevPrevToken;
prevPrevToken = prevToken;
prevToken = token;
}
for (const [field, functionNames] of fields) {
if (!usedFields.has(field)) {
console.log(`${field} in ${Array.from(functionNames).join(", ")}`);
}
}
{
"name": "elm-unused-record-fields",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"dependencies": {
"js-tokens": "8.0.1"
}
},
"node_modules/js-tokens": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-8.0.1.tgz",
"integrity": "sha512-3AGrZT6tuMm1ZWWn9mLXh7XMfi2YtiLNPALCVxBCiUVq0LD1OQMxV/AdS/s7rLJU5o9i/jBZw/N4vXXL5dm29A=="
}
},
"dependencies": {
"js-tokens": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-8.0.1.tgz",
"integrity": "sha512-3AGrZT6tuMm1ZWWn9mLXh7XMfi2YtiLNPALCVxBCiUVq0LD1OQMxV/AdS/s7rLJU5o9i/jBZw/N4vXXL5dm29A=="
}
}
}
{
"private": true,
"dependencies": {
"js-tokens": "8.0.1"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment