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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/opt/ulm/ballinrobe/bin/astl-ulmc-free

sub descend(nestlevel, node) {
    var result = "";
    if (isoperator(node)) {
        result = " " x nestlevel & "{ name: \"" & operator(node) & "\"";
        if (len(node) > 0) {
            result = result & ",\n" & " " x nestlevel & "  children: [";
            foreach operand in (node) {
                result = result & "\n" & descend(nestlevel + 3, operand) & ",";
            }
            result = result & "\n" & " " x nestlevel & "  ]\n";
        }
        result = result & " " x nestlevel & "}";
        // result = result & " @" & location(node);
    } else {
        var val = tokenliteral(node);
        var res;
        if (res = val =~ m{"(.*)"}) {
            val = "\\\"" & res[0] & "\\\"";
        }
        result = " " x nestlevel & "{ name: \"" & val & "\" }";
    }
    return result;
}

sub usage {
    var msg = "Usage: " & cmdname & " [-o outfile] id infile";
    println(stderr, msg);
    exit(1);
}


sub main(argv) {
    var output_file = "graph.html";
    var unit = root;

    // process command line
    while (len(argv) > 0 && argv[0] =~ m{^-}) {
        var option = pop(argv);
        if (option == "-o") {
            if (len(argv) == 0) {
                usage();
            }
            output_file = pop(argv);
        } else {
            usage();
        }
    }

    // process command line
    var units = [];
    if (len(argv) != 2) {
        usage();
        var input = open(stdin);
        var res = parse(stdin);
        if (type(res) == "string") {
            println(stderr, res); exit(1);
        }
        push(units, res);
    }
    var id = pop(argv);

    while (len(argv) > 0) {
        var input_file = pop(argv);

        // parse input file
        var input = open(input_file);
        if (!input) {
            println(stderr, input_file, ": cannot open for reading"); exit(1);
        }
        var res = parse(input);
        if (type(res) == "string") {
            println(stderr, res); exit(1);
        }
        push(units, res);
    }

    if (len(units) == 1) {
        root = units[0];
    } else {
        root = join(units);
    }

    // open output file
    var output = open(output_file, "w");
    if (!output) {
        println(stderr, output_file, ": cannot open for writing"); exit(1);
    }

    println(output, "<div style=\"width:100%\"><div id=\"" & id & "\" class=\"graph\"></div>");
    println(output, "<script>");
    println(output, "makeGraphId(\"#" & id & "\",");
    println(output, "" & descend(4, root) & "");
    println(output, ")");
    println(output, "</script></div>");
}