Skip to content
Writing
Engineering
· · 3 min

When a regular expression becomes a compiler

Package
listen to this article from the Wonder Why? podcast
Listen

Years ago, I built a small CLI called Unit CSS. If I remember correctly, I'd become interested in using throughout my stylesheets and found myself repeatedly converting pixel values using an online calculator.

A particularly miserable use of an afternoon.

Eventually, I reduced the process to a terminal command.

unitcss styles/

The arithmetic behind the tool was incredibly uninteresting.

const toRem = (px, base = 16) => `${px / base}rem`;

The interesting problem was applying that arithmetic to an entire codebase without changing something I didn't intend to.

The ambiguity of a string

Consider the following stylesheet:

.card-400px {
  width: calc(100% - 32px);
  padding: 16px 24px;
  content: "Made with 16px";
  background: url("image-400px.png");
  border: 1px solid black;
  --offset: -12.5px;
}

A regular expression can identify every occurrence of a pixel measurement relatively easily.

const pattern = /(-?\d*\.?\d+)px\b/g;

css.replace(pattern, (_, n) =>
  `${Number(n) / 16}rem`
);

But it also changes the class name, the contents of a string and the filename of an image.

The expression correctly identifies a textual pattern. It just doesn't understand the context in which that pattern exists.

8 changed · 4 aren't lengths
.card-400px {↑ class name
width: calc(100% - 32px);
padding: 16px 24px;
content: "Made with 16px";↑ inside a string
background: url("image-400px.png");↑ a filename
border: 1px solid black;
--offset: -12.5px;↑ custom property
}
Not recommended: Regular expression: matches text
4 lengths changed
.card-400px {
width: calc(100% - 32px);
padding: 16px 24px;
content: "Made with 16px";
background: url("image-400px.png");
border: 1px solid black;
--offset: -12.5px;
}
Recommended: Parser: matches syntax
Switch to Converted. The pattern changes anything that ends in px; the parser changes only the lengths.

What I'm actually looking for isn't a string ending in px. It's a dimension representing a length within an appropriate CSS declaration.

That's a different problem entirely.

Give the text some structure

CSS distinguishes between strings, identifiers, dimensions, functions and various .

The character sequence 16px can therefore have entirely different meanings depending on where it appears.

padding: 16px;
content: "16px";
width: calc(100% - 16px);

In the first example, it's a dimension. In the second, it's part of a string. In the third, it's a dimension within a mathematical expression.

A parser gives us a representation in which these differences are explicit.

ParseTraverseTransformSerialise
styles.css
.card {
  padding: 16px;
  content: "16px";
  width: calc(100% - 16px);
}
  • rule.card
  • declpadding
  • word16px
  • declcontent
  • string"16px"
  • declwidth
  • functioncalc
  • word100%
  • word-
  • word16px
Walk the tree. Only words that are px dimensions change; the string is never a word, so it's never touched.

Using and a , a modern reconstruction of the transformation might look something like this:

import postcss from "postcss";
import parse from "postcss-value-parser";

function convert(css, base = 16) {
  const root = postcss.parse(css);

  root.walkDecls(decl => {
    if (decl.prop.startsWith("--")) return;

    const value = parse(decl.value);

    value.walk(node => {
      if (node.type === "function" &&
          node.value.toLowerCase() === "url") {
        return false;
      }

      if (node.type !== "word") return;

      const dimension = parse.unit(node.value);

      if (dimension &&
          dimension.unit.toLowerCase() === "px") {
        node.value =
          `${Number(dimension.number) / base}rem`;
      }
    });

    decl.value = value.toString();
  });

  return root.toString();
}

Rather than attempting to teach a regular expression everything about CSS, I'm restricting the transformation to particular nodes within a parsed representation.

This is essentially a small source-to-source transformation pipeline.

Parse, traverse, transform and serialise.

Syntax is not semantics

Unfortunately, successfully identifying a dimension doesn't necessarily mean we understand whether converting it is appropriate.

Consider:

html {
  font-size: 20px;
}

.card {
  width: 320px;
}

Converting 320px using a base of 16 produces 20rem. But with a computed root font size of 20px, that resolves to 400px.

We've introduced an 80px discrepancy through mathematically correct arithmetic.

html { font-size: 20px; }
.card { width: 20rem; border: 1px solid; }
20rem × 20px = 400px+80px
320px
Invoice #1042Paid
Studio plan · March£240.00
Drag the root font size. The arithmetic stays correct; the card stops being 320px wide.

The actual relationship is:

resolved length = converted value × root font size

error = original length × (actual root / base − 1)

Media queries introduce another complication. Font-relative units in media queries resolve against initial font metrics rather than an author-defined root font size.

can carry token sequences whose eventual meaning depends on where they're substituted.

Even something as innocent as a 1px border requires a policy decision. Should its thickness scale with the user's font preference?

A parser can tell me what something is. It cannot independently decide what I intended it to become.

A migration should have guarantees

One of the features I included in Unit CSS was a preview command. It reported the occurrence of units before modifying the files.

I'd take that idea considerably further today.

Rather than immediately rewriting a stylesheet, I'd produce a collection of proposed edits, each containing its source location, original value and replacement.

type Edit = {
  start: number;
  end: number;
  before: string;
  after: string;
};

Applying these edits from the end of the file towards the beginning preserves the validity of their original offsets.

function applyEdits(source: string, edits: Edit[]) {
  return [...edits]
    .sort((a, b) => b.start - a.start)
    .reduce(
      (text, edit) =>
        text.slice(0, edit.start) +
        edit.after +
        text.slice(edit.end),
      source
    );
}

Given validated, non-overlapping edits, this allows us to preserve unrelated formatting rather than serialising the entire document again.

I'd also expect a unidirectional migration to be .

transform(transform(source)) === transform(source)

Running the command twice shouldn't introduce additional changes.

The actual conversion policy would determine which dimensions are eligible, how precision is handled and which declarations are excluded.

Looking back, Unit CSS was a fairly small solution to a fairly mundane problem. But I find source transformations particularly interesting because their correctness isn't exclusively defined by what they change.

It's equally defined by everything they manage to leave alone.

— Adenekan

Thoughts on this one?

Tell me what it made you think, or where you think I got it wrong.

Still working on the last 10%.0:00pm in london