-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacros.ts
More file actions
303 lines (279 loc) · 11.4 KB
/
macros.ts
File metadata and controls
303 lines (279 loc) · 11.4 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import { CompilationContext, Reducible, CompileData, BreakPoint, HangingLabel, locs, RootLevelCompileData } from './typesConstansts.ts';
import { DefaultMap } from './tools.ts';
export enum OpMode {
pointer = 0,
absolute = 1,
stack = 2,
}
export type Arg = (context?: CompilationContext) => {
constant: boolean,
value: CompileData,
insert: CompileData[],
mode: OpMode,
};
export const addReducible = (dependents: CompileData[]): Reducible => {
return new Reducible(dependents, (vals) => vals.reduce((a,n) => a + n, 0n), []);
}
export const multReducible = (dependents: CompileData[]): Reducible => {
return new Reducible(dependents, (vals) => vals.reduce((a,n) => a * n, 1n), []);
}
export const addLabel = (data: CompileData, label?: symbol): CompileData => {
if(!label) return data;
if(typeof data === 'object'){
data.labels.push(label);
return data;
}
return {
value: data,
labels: [label],
}
}
export const formatCall = (context: CompilationContext | undefined, opCode: bigint, args: Arg[], tag?: symbol): CompileData[] => {
const evaluatedArgs = args.map((arg, i) => {
const evaled = arg(context);
opCode += BigInt(evaled.mode) * 10n ** BigInt(i+2);
return evaled;
});
return [
...evaluatedArgs.flatMap(arg => arg.insert),
tag ? { value: opCode, labels: [tag] } : opCode,
...evaluatedArgs.flatMap(arg => arg.value),
];
}
export const ptr = (value: CompileData, tag?: symbol): Arg => () => ({value: addLabel(value, tag), insert: [], mode: OpMode.pointer, constant: !tag });
export const abs = (value: CompileData, tag?: symbol): Arg => () => ({value: addLabel(value, tag), insert: [], mode: OpMode.absolute, constant: !tag });
export const stack = (value: CompileData, tag?: symbol): Arg => () => ({value: addLabel(value, tag), insert: [], mode: OpMode.stack, constant: !tag });
/**
* The adds to the literal value, be it an address or stack position
* mode of the second arg is preserved
*/
export const addArgs = (offset: Arg, arg: Arg): Arg => context => {
const tag = Symbol('addConstantTarget');
const {value, insert, mode, constant} = arg(context);
// collapse at compile time
// both args are constant and the offset is absolute so there there is no pointer that needs to be followed to resolve it
const evaledOffset = offset(context);
if(constant && evaledOffset.constant && evaledOffset.mode === OpMode.absolute) {
return {
constant: true,
value: addReducible([value, evaledOffset.value]),
insert: [
// I honestly cant think of a situation where constant operations have code inserted
// it would feel weird to exclude this though
// maybe if I pack side effects into inserted code it could make sense
// could be useful for debugging
...evaledOffset.insert,
...insert,
],
mode,
}
}
return {
constant: false,
value: addLabel(0, tag),
insert: [
...insert,
...ops.add(abs(value), offset, ptr(tag), context)
],
mode,
}
}
/**
* The adds to the literal value, be it an address or stack position
* mode of the second arg is preserved
*/
export const multArgs = (offset: Arg, arg: Arg): Arg => context => {
const tag = Symbol('addConstantTarget');
const {value, insert, mode, constant} = arg(context);
// collapse at compile time
// both args are constant and the offset is absolute so there there is no pointer that needs to be followed to resolve it
const evaledOffset = offset(context);
if(constant && evaledOffset.constant && evaledOffset.mode === OpMode.absolute) {
return {
constant: true,
value: multReducible([value, evaledOffset.value]),
insert: [
// I honestly cant think of a situation where constant operations have code inserted
// it would feel weird to exclude this though
// maybe if I pack side effects into inserted code it could make sense
// could be useful for debugging
...evaledOffset.insert,
...insert,
],
mode,
}
}
return {
constant: false,
value: addLabel(0, tag),
insert: [
...insert,
...ops.mult(abs(value), offset, ptr(tag), context)
],
mode,
}
}
/**
* Arg to resolve must be type pointer!
* example: if arg is ptr(10) it returns the value in address 10 as abs
* always returns abs mode
*/
export const resolvePtr = (arg: Arg): Arg => context => {
const tag = Symbol('resolvePtrTarget');
const {value, insert, mode} = arg(context);
if(mode !== OpMode.pointer) throw new Error('Cannot resolve as pointer!');
return {
constant: false,
value: addLabel(0, tag),
insert: [
...insert,
...ops.copy(ptr(value), ptr(tag), context),
],
mode: OpMode.absolute,
}
}
/**
* takes an absolute arg and returns a pointer arg
*/
export const absToPtr = (arg: Arg): Arg => context => {
const {value, insert, mode, constant} = arg(context);
if(mode === OpMode.pointer) throw new Error('Cannot change pointer to pointer!');
return { constant, value, insert, mode: OpMode.pointer }
}
/**
* takes a pointer arg and returns an absolute arg
*/
export const ptrToAbs = (arg: Arg): Arg => context => {
const {value, insert, mode, constant} = arg(context);
if(mode === OpMode.absolute) throw new Error('Cannot change absolute to absolute!');
return { constant, value, insert, mode: OpMode.absolute }
}
/**
* takes an resolves the value at stack location and returns it as a pointer
*/
export const stackToPtr = (arg: Arg): Arg => context => {
const {value, insert, mode, constant} = arg(context);
if(mode !== OpMode.stack) throw new Error('Cannot change not stack to pointer');
const returnLoc = Symbol('stackToPtrTarget');
return {
constant: false,
value: addLabel(0, returnLoc),
insert: ops.copy(stack(value), ptr(returnLoc), context),
mode: OpMode.pointer,
}
}
/**
* given a string this returns the location of the variable within the scope as a pointer
*/
export const resolveRef = (ref: string, scopePos: number = -2): Arg => context => {
if(!context) throw new Error('Context required for this argument');
const location = context.scope.get(ref);
if(!location) {
console.log(ref, context.scope)
throw new Error(`Cannot locate reference "${ref}" at ${context.meta.line}:${context.meta.column}`);
}
if('location' in location) {
// this reduces to a constant
return absToPtr(addArgs(abs(location.location), abs(location.forward + 1)))(context);
}
const {up, forward} = location;
const returnTo = Symbol('resolveRefTarget');
return {
constant: false,
value: addLabel(0, returnTo), // labeled for that it can be used to store temporary values
insert: [
...ops.copy(stack(scopePos), ptr(returnTo), context), // copy scope pointer into return location
...new Array(up).fill(0).flatMap(() => { // repeat to climb to parent scopes
// return ops.copy(absToPtr(addArgs(ptr(returnTo), abs(1))), ptr(returnTo))
return ops.copy(absToPtr(resolvePtr(ptr(returnTo))), ptr(returnTo))
}),
...ops.copy(addArgs(ptr(returnTo), abs(1 + forward)), ptr(returnTo)), // move forward and land on the pointer to the desired value
],
mode: OpMode.pointer,
}
}
export const ops = {
add: (a: Arg, b: Arg, out: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 1n, [a,b,out], tag),
addTo: (a: Arg, out: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => {
if(Math.random() < 0.5) return ops.add(a, out, out, context, tag);
return ops.add(out, a, out, context, tag);
},
mult: (a: Arg, b: Arg, out: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 2n, [a,b,out], tag),
copy: (from: Arg, to: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => {
return ops.add(abs(0), from, to, context, tag);
const x = Math.random();
if(x < 0.25) return ops.mult(from, abs(1), to, context, tag);
if(x < 0.5) return ops.mult(abs(1), from, to, context, tag);
if(x < 0.75) return ops.add(from, abs(0), to, context, tag);
return ops.add(abs(0), from, to, context, tag);
},
read: (out: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 3n, [out], tag),
write: (val: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 4n, [val], tag),
jt: (val: Arg, to: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 5n, [val, to], tag),
jump: (to: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => {
return ops.jt(abs(1), to, context, tag);
if(Math.random() < 0.66) return ops.jt(abs(Math.floor(Math.random()*999)+1), to, context, tag);
return ops.jf(abs(0), to, context, tag);
},
jf: (val: Arg, to: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 6n, [val, to], tag),
lt: (a: Arg, b: Arg, out: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 7n, [a,b,out], tag),
eq: (a: Arg, b: Arg, out: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 8n, [a,b,out], tag),
rebase: (val: Arg, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 9n, [val], tag),
moveStack: (val: number | bigint, context?: CompilationContext, tag?: symbol): CompileData[] => formatCall(context, 9n, [abs(val)], tag),
exit: (tag?: symbol): CompileData[] => [addLabel(99, tag)],
}
export const writeToRam = (val: Arg, context?: CompilationContext): CompileData[] => {
return [
...ops.copy(val, absToPtr(resolvePtr(ptr(locs.ramPointer))), context),
...ops.addTo(abs(1), ptr(locs.ramPointer), context),
];
}
export const finalize = (prog: RootLevelCompileData[]): {
program: bigint[],
breakpoints: Map<bigint, string>,
labels: Map<bigint, string[]>,
} => {
// collapse hanging labels
const newProg: CompileData[] = [];
const breakpoints = new Map<bigint, string>();
for(let i = 0; i < prog.length; i++){
const entry = prog[i];
if(typeof entry === 'object' && entry instanceof HangingLabel){
let skip = 1;
while(prog[i+skip] instanceof BreakPoint) skip++;
prog[i+skip] = addLabel(prog[i+skip] as CompileData, entry.labels[0]);
} else if(typeof entry === 'object' && entry instanceof BreakPoint){
breakpoints.set(BigInt(newProg.length), entry.label)
}
else newProg.push(entry);
}
const positions = new Map<symbol, bigint>();
for(let i = 0; i < newProg.length; i++){
const entry = newProg[i];
if(typeof entry === 'object'){
for(const label of entry.labels) positions.set(label, BigInt(i));
}
}
const processCompileData = (entry: CompileData) => {
let data: symbol | bigint | number;
if(typeof entry === 'object'){
if(entry instanceof Reducible) data = entry.reducer(entry.dependents.map(processCompileData));
else if(entry instanceof HangingLabel) throw 'never'; // hanging label was already removed
else data = entry.value;
}else data = entry;
if(typeof data === 'bigint') return data;
if(typeof data === 'number') return BigInt(data);
if(!positions.has(data)) throw new Error(`Unlocated symbol pointer! ${data.toString()}`);
return positions.get(data)!;
}
const labels = new DefaultMap<bigint, string[]>(() => []);
for(const [sym, pos] of positions){
labels.get(pos).push(sym.description || "unnamed");
}
const compiled = newProg.map(processCompileData);
return {
program: compiled,
breakpoints,
labels,
}
}