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
3 changes: 2 additions & 1 deletion .oxlintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,5 +63,6 @@
},
"env": {
"builtin": true
}
},
"ignorePatterns": ["types/**"]
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"lint": "oxlint . && tsc && oxfmt --check",
"fmt": "oxfmt",
"benchmark:arithmetic-chains": "node scripts/benchmark-arithmetic-chains.mjs",
"benchmark:nested-fallbacks": "node scripts/benchmark-nested-fallbacks.mjs",
"test": "node --test --test-reporter=dot 'test/**/*.test.mjs' test/index.cjs test/convertUnit.cjs",
"test:mutation:corpus": "node test/mutation/corpus-selection.mjs",
"test:corpus:full": "POSTCSS_CALC_FULL_CORPUS=1 node --test test/conformance/corpus.test.mjs"
Expand Down
2 changes: 2 additions & 0 deletions scripts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

None of these run in `pnpm test` or CI — run directly with `node scripts/<name>.mjs`.

- **`benchmark-arithmetic-chains.mjs`** — times parser construction and flattening across long arithmetic chains.
- **`benchmark-nested-fallbacks.mjs`** — measures parser scaling for nested var() fallbacks with increasing depths.
- **`harvest-github.mjs`** — scrapes real-world `calc()` expressions from
public GitHub into `test/corpus/github/expressions.txt`.
- **`split-corpus.mjs`** — splits that file into `github-pure.txt` (feeds
Expand Down
65 changes: 65 additions & 0 deletions scripts/benchmark-nested-fallbacks.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Benchmark parser scaling for nested var() fallbacks.
// Tokenization is performed once per depth so timings isolate parsing cost.
import { parse } from '../src/lib/parser.js';
import { tokenize } from '../src/lib/tokenizer.js';

const DEPTHS = [50, 100, 200, 400];
const WARMUP_RUNS = 5;
const SAMPLES = 9;
const PARSES_PER_SAMPLE = 10;

/** @param {number[]} values */
function median(values) {
const sorted = [...values].sort((a, b) => a - b);
return sorted[Math.floor(sorted.length / 2)];
}

/**
* Build alternating calc(var(--x, ...)) expressions of given depth.
* @param {number} depth
* @return {string}
*/
function buildNestedFallbacks(depth) {
let expr = 'calc(1px + 2px)';
for (let i = depth; i >= 1; i--) {
expr = `calc(var(--x${i}, ${expr}))`;
}
return expr;
}

/** @param {number} depth */
function benchmark(depth) {
const input = buildNestedFallbacks(depth);
const tokens = tokenize(input);

for (let i = 0; i < WARMUP_RUNS; i++) {
parse(tokens);
}

const samples = [];
for (let sample = 0; sample < SAMPLES; sample++) {
const start = performance.now();
for (let iteration = 0; iteration < PARSES_PER_SAMPLE; iteration++) {
parse(tokens);
}
samples.push((performance.now() - start) / PARSES_PER_SAMPLE);
}
return median(samples);
}

console.log(
`Nested var() fallback parser timing: ${WARMUP_RUNS} warmups, ${SAMPLES} median samples, ` +
`${PARSES_PER_SAMPLE} parses/sample\n`
);

let previous = null;
for (const depth of DEPTHS) {
const elapsedMs = benchmark(depth);
const growth =
previous === null ? '—' : `${(elapsedMs / previous).toFixed(2)}×`;
console.log(
` ${depth.toString().padStart(5)} depth ` +
`${elapsedMs.toFixed(3).padStart(8)} ms growth ${growth}`
);
previous = elapsedMs;
}
16 changes: 15 additions & 1 deletion src/lib/convertUnits.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,4 +139,18 @@ function convert(value, from, to) {
return (value * f) / t;
}

export { baseOf, convert };
/**
* Return a base type only for units present in the static conversion table.
* Units with context-dependent values (em, rem, vw, etc.) return null.
* @param {string} unit
* @return {BaseType | null}
*/
function staticBaseOf(unit) {
const key = unit.toLowerCase();
if (TO_CANONICAL[key] === undefined) {
return null;
}
return UNIT_TO_BASE[key] ?? null;
}

export { baseOf, staticBaseOf, convert };
31 changes: 20 additions & 11 deletions src/lib/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@

/**
* @typedef {{type: 'Num', value: number}} Num
* @typedef {{type: 'Dim', value: number, unit: string}} Dim
* @typedef {{type: 'Ident', name: string}} Ident
* @typedef {{type: 'Call', name: string, args: Node[]}} Call
* @typedef {{type: 'Dim', value: number, unit: string, rawUnit?: string}} Dim
* @typedef {{type: 'Ident', name: string, rawName?: string}} Ident
* @typedef {{type: 'Call', name: string, args: Node[], rawName?: string}} Call
* @typedef {{sign: 1 | -1, node: Node}} SumTerm Sign is always +1 when node is Num or Dim.
* @typedef {{type: 'Sum', terms: SumTerm[], grouped?: boolean}} Sum
* @typedef {{exponent: 1 | -1, node: Node}} ProductFactor exponent +1 = numerator, -1 = denominator.
Expand All @@ -37,27 +37,36 @@ function num(value) {
/**
* @param {number} value
* @param {string} unit
* @param {string} [rawUnit]
* @return {Dim}
*/
function dim(value, unit) {
return { type: 'Dim', value, unit };
function dim(value, unit, rawUnit) {
return rawUnit === undefined
? { type: 'Dim', value, unit }
: { type: 'Dim', value, unit, rawUnit };
}

/**
* @param {string} name
* @param {string} [rawName]
* @return {Ident}
*/
function ident(name) {
return { type: 'Ident', name };
function ident(name, rawName) {
return rawName === undefined
? { type: 'Ident', name }
: { type: 'Ident', name, rawName };
}

/**
* @param {string} name
* @param {Node[]} args
* @param {string} [rawName]
* @return {Call}
*/
function call(name, args) {
return { type: 'Call', name, args };
function call(name, args, rawName) {
return rawName === undefined
? { type: 'Call', name, args }
: { type: 'Call', name, args, rawName };
}

/**
Expand Down Expand Up @@ -104,7 +113,7 @@ function pushSumTerm(out, term) {
node = num(-node.value);
sign = 1;
} else if (node.type === 'Dim') {
node = dim(-node.value, node.unit);
node = dim(-node.value, node.unit, node.rawUnit);
sign = 1;
}
}
Expand Down Expand Up @@ -169,7 +178,7 @@ function negate(node) {
return num(-node.value);
}
if (node.type === 'Dim') {
return dim(-node.value, node.unit);
return dim(-node.value, node.unit, node.rawUnit);
}
if (node.type === 'Sum') {
const result = mkSum(
Expand Down
40 changes: 40 additions & 0 deletions src/lib/opaque.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Private metadata for opaque component values (currently var() fallbacks).
// Keeping it in a WeakMap means the public calculation AST remains unchanged.
/** @typedef {import('./node.js').Node} Node */
/** @typedef {string | Node | Component[]} Component */
/** @type {WeakMap<Extract<Node, {type: 'Call'}>, Component[]>} */
const components = new WeakMap();
/** @param {Extract<Node, {type: 'Call'}>} node @param {Component[]} tree */
function setComponents(node, tree) {
components.set(node, tree);
return node;
}
/** @param {Extract<Node, {type: 'Call'}>} node */
function getComponents(node) {
return components.get(node);
}
/** @param {Component[]} tree @param {(node: Node) => Node} simplify @return {Component[]} */
function simplifyComponents(tree, simplify) {
return tree.map((part) => {
if (typeof part === 'string') return part;
if (Array.isArray(part)) return simplifyComponents(part, simplify);
return simplify(part);
});
}
/** @param {Component[]} tree @param {(node: Node) => string} serialize @return {string} */
function serializeComponents(tree, serialize) {
let result = '';
for (const part of tree) {
if (typeof part === 'string') result += part;
else if (Array.isArray(part))
result += serializeComponents(part, serialize);
else result += serialize(part);
}
return result;
}
export {
getComponents,
setComponents,
simplifyComponents,
serializeComponents,
};
Loading