First cut at a Trace system.
[ustaxlib.git] / src / core / Trace.ts
1 // Copyright 2020 Blue Static <https://www.bluestatic.org>
2 // This program is free software licensed under the GNU General Public License,
3 // version 3.0. The full text of the license can be found in LICENSE.txt.
4 // SPDX-License-Identifier: GPL-3.0-only
5
6 import { Line } from './Line';
7
8 var current: Trace = null;
9
10 var traces: Trace[] = [];
11
12 export default class Trace {
13 private _stack: Set<string>[] = [];
14 private _index = 0;
15 private _name: string;
16
17 constructor(line: Line<any>) {
18 this._name = this._formatLine(line);
19 const s = new Set<string>();
20
21 s.add(`Start: ${this._name}`);
22
23 if (current === null) {
24 current = this;
25 } else {
26 ++current._index;
27 }
28
29 current._stack.push(s);
30 }
31
32 static add(id: string) {
33 if (current === null)
34 return;
35 current._stack[current._index].add(id);
36 }
37
38 end() {
39 --current._index;
40 if (current === this) {
41 current = null;
42 traces.push(this);
43 }
44 }
45
46 get traceList(): readonly string[][] {
47 return this._stack.map(s => [...s.values()]);
48 }
49
50 private _formatLine(line: Line<any>): string {
51 if (line.form === undefined)
52 return `${line.constructor.name} (${line.description})`;
53 return `${line.form.name}-${line.id} (${line.description})`;
54 }
55 };
56
57 export function getLastTraceList(): readonly string[][] {
58 if (traces.length == 0)
59 return null;
60 return traces[traces.length - 1].traceList;
61 }