TExcelTAD
Home › GNU Make & Ninja › Model: A Mini Make

Model: A Mini Make

You have now seen Make's behaviour from the outside. This lesson rebuilds its core in about 80 lines of JavaScript: parse rules, walk the graph depth-first, compare time stamps, run "recipes" and record new time stamps. Nothing touches a real disk; a Map of file names to times plays the file system, and a counter plays the clock. Edit the scenarios and run them again.

The engine

The model supports explicit rules, pattern rules with %, .PHONY and order-only prerequisites, detects cycles, and reports each decision in Make's own words.

js · try it yourself
function parse(text) {
  const rules = [], phony = new Set();
  let cur = null;
  for (const line of text.split('\n')) {
    if (line.startsWith('\t')) { cur.recipe.push(line.slice(1)); continue; }
    const m = line.match(/^([^:]+):(.*)$/);
    if (!m) continue;
    const [normal, orderOnly = ''] = m[2].split('|');
    const targets = m[1].trim().split(/\s+/);
    if (targets[0] === '.PHONY') { normal.trim().split(/\s+/).forEach((t) => phony.add(t)); continue; }
    cur = { targets, prereqs: normal.trim().split(/\s+/).filter(Boolean),
            orderOnly: orderOnly.trim().split(/\s+/).filter(Boolean), recipe: [] };
    rules.push(cur);
  }
  return { rules, phony };
}

class MiniMake {
  constructor(text, files) { Object.assign(this, parse(text)); this.fs = new Map(Object.entries(files)); this.clock = 1000; }

  findRule(target) {
    for (const r of this.rules) if (r.targets.includes(target)) return { ...r, stem: '' };
    for (const r of this.rules) {                       // pattern rules: '%' matches a stem
      const [pre, post] = r.targets[0].split('%');
      if (r.targets[0].includes('%') && target.startsWith(pre) && target.endsWith(post)) {
        const stem = target.slice(pre.length, target.length - post.length);
        const sub = (p) => p.replace('%', stem);
        const prereqs = r.prereqs.map(sub);
        if (prereqs.every((p) => this.fs.has(p) || this.findRule(p))) return { ...r, prereqs, orderOnly: r.orderOnly.map(sub), stem };
      }
    }
    return null;
  }

  make(target, stack = [], log = []) {
    if (stack.includes(target)) { log.push(`Circular ${stack.at(-1)} <- ${target} dependency dropped.`); return log; }
    const rule = this.findRule(target);
    if (!rule) {
      if (!this.fs.has(target)) throw new Error(`No rule to make target '${target}'` + (stack.length ? `, needed by '${stack.at(-1)}'` : ''));
      return log;                                           // a plain source file
    }
    for (const p of [...rule.prereqs, ...rule.orderOnly]) this.make(p, [...stack, target], log);
    const isPhony = this.phony.has(target);
    const t = this.fs.get(target);
    const newer = rule.prereqs.filter((p) => this.phony.has(p) || this.fs.get(p) > t);
    let why = null;
    if (isPhony) why = 'phony';
    else if (t === undefined) why = 'does not exist';
    else if (newer.length) why = `older than ${newer.join(', ')}`;
    if (!why) { if (!stack.length) log.push(`'${target}' is up to date.`); return log; }
    const auto = (s) => s.replaceAll('$@', target).replaceAll('
lt;', rule.prereqs[0] ?? '') .replaceAll('$^', rule.prereqs.join(' ')).replaceAll('$*', rule.stem); log.push(`${target} (${why}):`); for (const line of rule.recipe) log.push(' ' + auto(line)); if (!isPhony) this.fs.set(target, ++this.clock); // the recipe "created" the target return log; } touch(file) { this.fs.set(file, ++this.clock); } run(goal) { try { console.log(this.make(goal).join('\n')); } catch (e) { console.log(`make: *** ${e.message}. Stop.`); } } } const makefile = ` .PHONY: all clean all: app app: main.o util.o \tcc $^ -o $@ %.o: %.c | build \tcc -c
lt; -o $@ build: \tmkdir -p build clean: \trm -f app *.o `; const mk = new MiniMake(makefile, { 'main.c': 1, 'util.c': 2, 'util.h': 3 }); console.log('== first build'); mk.run('all'); console.log('== nothing changed'); mk.run('app'); console.log('== edit util.c'); mk.touch('util.c'); mk.run('app'); console.log('== edit util.h (not declared!)'); mk.touch('util.h'); mk.run('app'); console.log('== clean is phony'); mk.run('clean'); console.log('== a typo'); mk.run('mian.o');
== first build
build (does not exist):
    mkdir -p build
main.o (does not exist):
    cc -c main.c -o main.o
util.o (does not exist):
    cc -c util.c -o util.o
app (does not exist):
    cc main.o util.o -o app
all (phony):
== nothing changed
'app' is up to date.
== edit util.c
util.o (older than util.c):
    cc -c util.c -o util.o
app (older than util.o):
    cc main.o util.o -o app
== edit util.h (not declared!)
'app' is up to date.
== clean is phony
clean (phony):
    rm -f app *.o
== a typo
make: *** No rule to make target 'mian.o'.  Stop.

Everything you saw in the real sessions appears here: the depth-first order, build made first because it's an order-only prerequisite, the undeclared header that doesn't trigger a rebuild, and the phony target that always runs. Note what the model doesn't do: it never looks inside files or at commands. Neither does Make. That's the gap Ninja's command log closes.

Adding automatic header dependencies

Real projects fix the undeclared-header problem by reading the compiler's .d files. In the model that's one extra recipe-less rule per object, merged into the pattern rule's prerequisites. This variant shows the merge and also a dependency cycle, which Make reports and drops:

js · try it yourself
const rules = new Map([
  ['app', ['main.o', 'util.o']],
  ['main.o', ['main.c', 'util.h']],          // from main.d
  ['util.o', ['util.c', 'util.h']],          // from util.d
  ['util.h', ['gen.txt']],                   // a generated header
  ['gen.txt', ['app']],                      // oops: depends on the final program
]);
const mtime = new Map([['main.c', 1], ['util.c', 1], ['gen.txt', 1], ['util.h', 2], ['main.o', 3], ['util.o', 3], ['app', 4]]);
let clock = 10;
const visited = new Set();                             // Make considers each target once per run

function make(t, stack = []) {
  if (visited.has(t)) return;
  visited.add(t);
  const deps = [];
  for (const d of rules.get(t) ?? []) {
    if (stack.includes(d) || d === t) {                // an edge back into the current path
      console.log(`make: Circular ${t} <- ${d} dependency dropped.`);
      continue;                                        // drop the edge, keep going
    }
    make(d, [...stack, t]);
    deps.push(d);
  }
  const stale = deps.filter((d) => mtime.get(d) > (mtime.get(t) ?? -1));
  if (deps.length && (stale.length || !mtime.has(t))) {
    console.log(`remake ${t} (newer: ${stale.join(', ') || 'missing'})`);
    mtime.set(t, ++clock);
  }
}

mtime.set('util.h', ++clock);   // someone edits the header
make('app');
make: Circular gen.txt <- app dependency dropped.
remake main.o (newer: util.h)
remake util.o (newer: util.h)
remake app (newer: main.o, util.o)

GNU Make prints the same Circular … dependency dropped. message and carries on without that edge, which usually hides a design mistake rather than fixing it. Ninja treats a cycle as a hard error instead.

Test yourself

In the model, why does editing util.h not trigger a rebuild in the first scenario?

  1. The model has a bug
  2. util.h is not a prerequisite of any rule, exactly like a real Makefile without header dependencies
  3. Headers are never compared
  4. The clock didn't advance

What does the model (and Make) do to decide whether to run a recipe?

  1. Hash the target's contents
  2. Compare the target's time stamp with its prerequisites', after bringing those up to date
  3. Compare recipe text with the last run
  4. Ask the user

How does GNU Make handle a dependency cycle?

  1. It loops forever
  2. It prints Circular ... dependency dropped. and ignores that edge
  3. It deletes the files
  4. It switches to Ninja