summaryrefslogtreecommitdiff
path: root/codegen.ts
blob: da16ab808f38b8f88b36a995a9fd170628e23f20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { writeFileSync } from "fs";
import { argv } from "process";

interface LibPack {
  header: string;
  source: string;
  test: string;
  testHeader: string;
}

const std = `
#include <stdlib.h>
#include <stdio.h>
`;

const makeHeader = (includeGuard: string, stdinclude: boolean) =>
  `
#ifndef ${includeGuard}
#define ${includeGuard}

${stdinclude ? std : ""}

#endif
`;

const makeSource = (libname: string, stdinclude: boolean) => `
#include "${libname}.h"
${stdinclude ? std : ""}
`;

const makeTest = (libname: string) =>
  `
#include "test-lib.h"
#include "${libname}.h"

${std}
`;

const makeTestHeader = (includeGuard: string, stdinclude: boolean) =>
  makeHeader(`${includeGuard}_TEST`, stdinclude);

function makeCLib(
  libname: string,
  includeGuard: string,
  stdinclude: boolean = true
): LibPack {
  return {
    header: makeHeader(includeGuard, stdinclude),
    source: makeSource(libname, stdinclude),
    test: makeTest(libname),
    testHeader: makeTestHeader(includeGuard, stdinclude)
  };
}

function write(filename: string, blob: string) {
  return writeFileSync(`${__dirname}/${filename}`, blob);
}

function writeCLib(libname: string, libpack: LibPack) {
  write(`${libname}.c`, libpack.source);
  write(`${libname}.h`, libpack.header);
  write(`${libname}.test.c`, libpack.test);
  write(`${libname}.test.h`, libpack.testHeader);
}

(function() {
  const pack = makeCLib(argv[2], argv[3], argv[4] === "true");
  writeCLib(argv[2], pack);
})();