aboutsummaryrefslogtreecommitdiff
path: root/src/js/mapvalues.js
blob: bb6fc861deeb1e1ad310f4c3c2ac7af0ecdf0a66 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// reads the values of a machine map from its memmap.h. the #define lines may use
// other names and small sums (ZFP + 2, DSLO + 1100), so each value is evaluated
// with its names substituted. shared by mklayout.js and extract_lsp.js.
const fs = require('fs');

function mapValues(mapPath, names) {
    const text = fs.readFileSync(mapPath, 'utf8');
    const defs = {};
    for (const m of text.matchAll(/^#define[ \t]+(\w+)[ \t]+(.+)$/gm)) defs[m[1]] = m[2].trim();
    function value(name, depth = 0) {
        if (depth > 20) throw new Error('map loop at ' + name);
        const expr = defs[name];
        if (expr === undefined) throw new Error(mapPath + ' has no ' + name);
        const sub = expr.replace(/\b[A-Za-z_]\w*\b/g, id => '(' + value(id, depth + 1) + ')');
        return Function('return (' + sub + ');')();
    }
    const out = {};
    for (const k of names) out[k] = value(k);
    return out;
}

module.exports = { mapValues };