File: WordBuilder.cs

package info (click to toggle)
bearssl 0.6%2Bdfsg.1-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 4,484 kB
  • sloc: ansic: 49,044; cs: 3,473; sh: 524; makefile: 40
file content (385 lines) | stat: -rw-r--r-- 8,677 bytes parent folder | download | duplicates (3)
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*
 * Copyright (c) 2016 Thomas Pornin <pornin@bolet.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining 
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be 
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

using System;
using System.Collections.Generic;

/*
 * A WordBuilder instance organizes construction of a new interpreted word.
 *
 * Opcodes are accumulated with specific methods. A control-flow stack
 * is maintained to resolve jumps.
 *
 * Each instance shall be used for only one word.
 */

class WordBuilder {

	T0Comp TC;
	string name;
	int[] cfStack;
	int cfPtr;
	List<Opcode> code;
	List<string> toResolve;
	Dictionary<string, int> locals;
	bool jumpToLast;

	internal SType StackEffect {
		get; set;
	}

	/*
	 * Create a new instance, with the specified word name.
	 */
	internal WordBuilder(T0Comp TC, string name)
	{
		this.TC = TC;
		this.name = name;
		cfStack = new int[16];
		cfPtr = -1;
		code = new List<Opcode>();
		toResolve = new List<string>();
		locals = new Dictionary<string, int>();
		jumpToLast = true;
		StackEffect = SType.UNKNOWN;
	}

	/*
	 * Build the word. The control-flow stack must be empty. A 'ret'
	 * opcode is automatically appended if required.
	 */
	internal Word Build()
	{
		if (cfPtr != -1) {
			throw new Exception("control-flow stack is not empty");
		}
		if (jumpToLast || code[code.Count - 1].MayFallThrough) {
			Ret();
		}
		Word w = new WordInterpreted(TC, name, locals.Count,
			code.ToArray(), toResolve.ToArray());
		w.StackEffect = StackEffect;
		return w;
	}

	void Add(Opcode op)
	{
		Add(op, null);
	}

	void Add(Opcode op, string refName)
	{
		code.Add(op);
		toResolve.Add(refName);
		jumpToLast = false;
	}

	/*
	 * Rotate the control-flow stack at depth 'depth'.
	 */
	internal void CSRoll(int depth)
	{
		int x = cfStack[cfPtr - depth];
		Array.Copy(cfStack, cfPtr - (depth - 1),
			cfStack, cfPtr - depth, depth);
		cfStack[cfPtr] = x;
	}

	/*
	 * Make a copy of the control-flow element at depth 'depth', and
	 * push it on top of the control-flow stack.
	 */
	internal void CSPick(int depth)
	{
		int x = cfStack[cfPtr - depth];
		CSPush(x);
	}

	void CSPush(int x)
	{
		int len = cfStack.Length;
		if (++ cfPtr == len) {
			int[] ncf = new int[len << 1];
			Array.Copy(cfStack, 0, ncf, 0, len);
			cfStack = ncf;
		}
		cfStack[cfPtr] = x;
	}

	int CSPop()
	{
		return cfStack[cfPtr --];
	}

	/*
	 * Push an origin on the control-flow stack, corresponding to the
	 * next opcode to add.
	 */
	internal void CSPushOrig()
	{
		CSPush(code.Count);
	}

	/*
	 * Push a destination on the control-flow stack, corresponding to
	 * the next opcode to add.
	 */
	internal void CSPushDest()
	{
		CSPush(-code.Count - 1);
	}

	/*
	 * Pop an origin from the control-flow stack. An exception is
	 * thrown if the value is not an origin.
	 */
	internal int CSPopOrig()
	{
		int x = CSPop();
		if (x < 0) {
			throw new Exception("not an origin");
		}
		return x;
	}

	/*
	 * Pop a destination from the control-flow stack. An exception is
	 * thrown if the value is not a destination.
	 */
	internal int CSPopDest()
	{
		int x = CSPop();
		if (x >= 0) {
			throw new Exception("not a destination");
		}
		return -x - 1;
	}

	/*
	 * Add a "push literal" opcode.
	 */
	internal void Literal(TValue v)
	{
		Add(new OpcodeConst(v));
	}

	/*
	 * Compile a "call" by name. This method implements the support
	 * for local variables:
	 *
	 *  - If the target is '>' followed by a local variable name, then
	 *    a "put local" opcode is added.
	 *
	 *  - Otherwise, if the target is a local variable name, then a
	 *    "get local" opcode is added.
	 *
	 *  - Otherwise, a call to the named word is added. The target name
	 *    will be resolved later on (typically, when the word containing
	 *    the call opcode is first invoked, or when C code is generated).
	 */
	internal void Call(string target)
	{
		string lname;
		bool write;
		if (target.StartsWith(">")) {
			lname = target.Substring(1);
			write = true;
		} else {
			lname = target;
			write = false;
		}
		int lnum;
		if (locals.TryGetValue(lname, out lnum)) {
			if (write) {
				Add(new OpcodePutLocal(lnum));
			} else {
				Add(new OpcodeGetLocal(lnum));
			}
		} else {
			Add(new OpcodeCall(), target);
		}
	}

	/*
	 * Add a "call" opcode to the designated word.
	 */
	internal void CallExt(Word wtarget)
	{
		Add(new OpcodeCall(wtarget), null);
	}

	/*
	 * Add a "call" opcode to a word which is not currently resolved.
	 * This method ignores local variables.
	 */
	internal void CallExt(string target)
	{
		Add(new OpcodeCall(), target);
	}

	/*
	 * Add a "get local" opcode; the provided local name must already
	 * be defined.
	 */
	internal void GetLocal(string name)
	{
		int lnum;
		if (locals.TryGetValue(name, out lnum)) {
			Add(new OpcodeGetLocal(lnum));
		} else {
			throw new Exception("no such local: " + name);
		}
	}

	/*
	 * Add a "put local" opcode; the provided local name must already
	 * be defined.
	 */
	internal void PutLocal(string name)
	{
		int lnum;
		if (locals.TryGetValue(name, out lnum)) {
			Add(new OpcodePutLocal(lnum));
		} else {
			throw new Exception("no such local: " + name);
		}
	}

	/*
	 * Define a new local name.
	 */
	internal void DefLocal(string lname)
	{
		if (locals.ContainsKey(lname)) {
			throw new Exception(String.Format(
				"local already defined: {0}", lname));
		}
		locals[lname] = locals.Count;
	}

	/*
	 * Add a "call" opcode whose target is an XT value (which may be
	 * resolved or as yet unresolved).
	 */
	internal void Call(TPointerXT xt)
	{
		if (xt.Target == null) {
			Add(new OpcodeCall(), xt.Name);
		} else {
			Add(new OpcodeCall(xt.Target));
		}
	}

	/*
	 * Add a "ret" opcode.
	 */
	internal void Ret()
	{
		Add(new OpcodeRet());
	}

	/*
	 * Add a forward unconditional jump. The new opcode address is
	 * pushed on the control-flow stack as an origin.
	 */
	internal void Ahead()
	{
		CSPushOrig();
		Add(new OpcodeJumpUncond());
	}

	/*
	 * Add a forward conditional jump, which will be taken at runtime
	 * if the top-of-stack value is 'true'. The new opcode address is
	 * pushed on the control-flow stack as an origin.
	 */
	internal void AheadIf()
	{
		CSPushOrig();
		Add(new OpcodeJumpIf());
	}

	/*
	 * Add a forward conditional jump, which will be taken at runtime
	 * if the top-of-stack value is 'false'. The new opcode address is
	 * pushed on the control-flow stack as an origin.
	 */
	internal void AheadIfNot()
	{
		CSPushOrig();
		Add(new OpcodeJumpIfNot());
	}

	/*
	 * Resolve a previous forward jump to the current code address.
	 * The top of control-flow stack is popped and must be an origin.
	 */
	internal void Then()
	{
		int x = CSPopOrig();
		code[x].ResolveJump(code.Count - x - 1);
		jumpToLast = true;
	}

	/*
	 * Push the current code address on the control-flow stack as a
	 * destination, to be used by an ulterior backward jump.
	 */
	internal void Begin()
	{
		CSPushDest();
	}

	/*
	 * Add a backward unconditional jump. The jump target is popped
	 * from the control-flow stack as a destination.
	 */
	internal void Again()
	{
		int x = CSPopDest();
		Add(new OpcodeJumpUncond(x - code.Count - 1));
	}

	/*
	 * Add a backward conditional jump, which will be taken at runtime
	 * if the top-of-stack value is 'true'. The jump target is popped
	 * from the control-flow stack as a destination.
	 */
	internal void AgainIf()
	{
		int x = CSPopDest();
		Add(new OpcodeJumpIf(x - code.Count - 1));
	}

	/*
	 * Add a backward conditional jump, which will be taken at runtime
	 * if the top-of-stack value is 'false'. The jump target is popped
	 * from the control-flow stack as a destination.
	 */
	internal void AgainIfNot()
	{
		int x = CSPopDest();
		Add(new OpcodeJumpIfNot(x - code.Count - 1));
	}
}