Skip to content

Add tokenizing minifier. #14

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 1 commit into from
Feb 9, 2023
Merged
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
66 changes: 66 additions & 0 deletions minify.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
#!/usr/bin/env -S runghc-9.2.4 -XUnicodeSyntax -XBlockArguments

import Data.Char
import Data.List
import System.Environment
import System.Exit
import System.FilePath

overlay function list =
let pairs = fmap function (zip list (tail list))
in (fst . head) pairs : fmap snd pairs

specialTokens =
[ "("
, ","
, ")"
, "{"
, ";"
, "}"
, "["
, "]"
, "←"
, "→"
, "<-"
, "->"
, "∷"
, "::"
, "@"
, "\\"
]

isAllowedInName = or . flip fmap [isAlphaNum, (== '_'), (== '\'')] . flip ($)

addWhiteRoom = overlay \(this, next) →
if this `elem` specialTokens
then (this, next)
else
if (isAllowedInName . last) this && (isAllowedInName . head) next
then (this, " " <> next)
else (this, next)

cut fit list = (last . filter (fit . fst)) (zipWith splitAt [0 ..] (replicate (length list + 1) list))

main = do
target ← fmap (!! 0) getArgs
if takeExtension target /= ".hs"
then exitFailure
else tailor target

tailor target = do
cloth ← readFile target
let
(snowflakes, leftovers) = cut (all \line → (head line == '#')) (lines cloth)
tokens = words (unlines leftovers)
tokensWithWhiteRoom = addWhiteRoom tokens
cuts = flip
unfoldr
tokensWithWhiteRoom
\tokens →
if null tokens
then Nothing
else let (chunk, leftovers) = cut (\chunk → sum (fmap length chunk) <= 80) tokens in Just (concat chunk, leftovers)
shirt = unlines snowflakes <> unlines cuts
if shirt == cloth
then exitSuccess
else writeFile (replaceExtension target ".minified.hs") shirt