File: Transform.cpp

package info (click to toggle)
storm-lang 0.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,028 kB
  • sloc: ansic: 261,471; cpp: 140,432; sh: 14,891; perl: 9,846; python: 2,525; lisp: 2,504; asm: 860; makefile: 678; pascal: 70; java: 52; xml: 37; awk: 12
file content (627 lines) | stat: -rw-r--r-- 18,742 bytes parent folder | download
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#include "stdafx.h"
#include "Transform.h"
#include "Exception.h"
#include "Type.h"
#include "Rule.h"
#include "Production.h"
#include "BSUtils.h"
#include "Core/Join.h"

#include "Compiler/Basic/Named.h"
#include "Compiler/Basic/Resolve.h"
#include "Compiler/Basic/WeakCast.h"
#include "Compiler/Basic/If.h"
#include "Compiler/Basic/For.h"
#include "Compiler/Basic/Operator.h"
#include "Compiler/Basic/Operators.h"

#include "Compiler/Lib/Array.h"
#include "Compiler/Lib/Maybe.h"

namespace storm {
	namespace syntax {
		using namespace bs;

		static syntax::SStr *tfmName(ProductionDecl *decl) {
			return new (decl) syntax::SStr(S("transform"), decl->pos);
		}

		static Array<ValParam> *tfmParams(Rule *rule, ProductionType *owner) {
			Array<ValParam> *v = new (rule) Array<ValParam>(*rule->params());
			v->insert(0, thisParam(owner));
			return v;
		}

		TransformFn::TransformFn(ProductionDecl *decl, ProductionType *owner, Rule *rule, Scope scope)
			: BSRawFn(rule->result(), tfmName(decl), tfmParams(rule, owner), null), scope(scope) {

			lookingFor = new (this) Set<Str *>();

			result = decl->result;
			resultParams = decl->resultParams;
			source = owner->production;

			tokenParams = new (this) Array<Params>(decl->tokens->count());
			for (Nat i = 0; i < decl->tokens->count(); i++) {
				TokenDecl *token = decl->tokens->at(i);
				if (RuleTokenDecl *ruleToken = as<RuleTokenDecl>(token)) {
					tokenParams->at(i).v = ruleToken->params;
				}
			}

			// The capture token is treated as being at the end of the token list. Add it if it
			// exists (it never takes any parameters, just like RegexTokens).
			if (source->repCapture)
				tokenParams->push(Params());
		}

		FnBody *TransformFn::createBody() {
			FnBody *root = new (this) FnBody(this, scope);

			Expr *me = createMe(root);

			// Execute members of 'me', or other things that might have side effects.
			executeMe(root, me);

			// Return 'me' if it was declared, unless we return void.
			if (Function::result != Value()) {
				if (!me) {
					throw new (this) SyntaxError(pos, S("No return value specified for a production that does not return 'void'."));
				}

				root->add(me);
			}

			// if (wcsncmp(identifier()->c_str(), S("lang.bnf."), 9) == 0)
			// 	PLN(source << S(": ") << root);
			return root;
		}

		/**
		 * Variables.
		 */

		Expr *TransformFn::createMe(ExprBlock *in) {
			// See if there is a parameter named 'me'. If so: use that!
			for (Nat i = 0; i < valParams->count(); i++) {
				if (*valParams->at(i).name == S("me")) {
					if (result)
						throw new (this) SyntaxError(pos, S("Can not use 'me' as a parameter name and specify a result."));
					LocalVar *r = in->variable(new (this) SimplePart(S("me")));
					if (!r)
						throw new (this) InternalError(S("Can not find the parameter named 'me'."));
					return new (this) LocalVarAccess(pos, r);
				}
			}

			if (!result)
				return null;

			if (!resultParams) {
				// This is not a function call, just a variable declaration!
				if (result->count() > 1) {
					Str *msg = TO_S(this, S("The variable ") << result << S(" is not declared. ")
									S("Use ") << result << S("() to call it as a function or constructor."));
					throw new (this) SyntaxError(pos, msg);
				}

				return findVar(in, result->at(0)->name);
			}

			Actuals *actual = CREATE(Actuals, this);

			for (Nat i = 0; i < resultParams->count(); i++)
				actual->add(findVar(in, resultParams->at(i)));

			Expr *init = namedExpr(in, pos, result, actual);

			if (init->result() == Value()) {
				// If 'init' returns a void value, do not create a variable.
				in->add(init);
				return null;
			}

			syntax::SStr *name = CREATE(syntax::SStr, this, S("me"), pos);
			Var *var = new (this) Var(in, name, init);
			in->add(var);

			return new (this) LocalVarAccess(pos, var->var);

		}

		static Str *firstName(Str *in) {
			Str::Iter dot = in->find(Char('.'));
			if (dot == in->end())
				return in;

			return in->substr(in->begin(), dot);
		}

		static MAYBE(Str *) restName(Str *in) {
			Str::Iter dot = in->find(Char('.'));
			if (dot == in->end())
				return null;

			dot++;
			return in->substr(dot);
		}

		Expr *TransformFn::recurse(Block *block, Str *name, Expr *root) {
			while (name = restName(name)) {
				Str *here = firstName(name);
				root = namedExpr(block, pos, here, root);
			}

			return root;
		}

		Expr *TransformFn::readVar(Block *in, Str *name) {
			Str *first = firstName(name);
			if (LocalVar *r = in->variable(new (this) SimplePart(first)))
				return recurse(in, name, new (this) LocalVarAccess(pos, r));

			if (*name == S("me"))
				throw new (this) SyntaxError(pos, S("Can not use 'me' this early!"));
			if (*name == S("pos"))
				return posVar(in);
			if (Expr *e = createLiteral(name))
				return e;

			throw new (this) InternalError(TO_S(this, S("The variable ") << first << S(" was not created before being read.")));
		}

		Expr *TransformFn::findVar(ExprBlock *in, Str *name) {
			Str *first = firstName(name);
			if (LocalVar *r = in->variable(new (this) SimplePart(first)))
				return recurse(in, name, new (this) LocalVarAccess(pos, r));

			if (*name == S("me"))
				throw new (this) SyntaxError(pos, S("Can not use 'me' this early!"));
			if (*name == S("pos"))
				return posVar(in);
			if (Expr *e = createLiteral(name))
				return e;

			// We need to create it...
			if (lookingFor->has(first))
				throw new (this) SyntaxError(pos, TO_S(this, S("The variable ") << first << S(" depends on itself.")));
			lookingFor->put(first);

			try {
				Nat pos = findToken(first);
				if (pos >= tokenCount())
					throw new (this) SyntaxError(this->pos, TO_S(this, S("The variable ") << first << S(" is not declared!")));

				LocalVar *var = createVar(in, first, pos);
				lookingFor->remove(first);

				return recurse(in, name, new (this) LocalVarAccess(this->pos, var));
			} catch (...) {
				lookingFor->remove(first);
				throw;
			}

		}

		Bool TransformFn::hasVar(ExprBlock *in, Str *name) {
			return in->variable(new (this) SimplePart(name)) != null;
		}

		Expr *TransformFn::createLiteral(Str *name) {
			Maybe<Long> l = name->asLong();
			if (l.any())
				return new (this) NumLiteral(pos, l.value());
			if (*name == S("true"))
				return new (this) BoolLiteral(pos, true);
			if (*name == S("false"))
				return new (this) BoolLiteral(pos, false);

			return null;
		}

		LocalVar *TransformFn::createVar(ExprBlock *in, Str *name, Nat pos) {
			Token *token = getToken(pos);

			if (!token->bound) {
				throw new (this) SyntaxError(this->pos, TO_S(this, S("The variable ") << name << S(" is not bound!")));
			} else if (token->raw) {
				return createPlainVar(in, name, token);
			} else {
				return createTfmVar(in, name, token, pos);
			}
		}

		LocalVar *TransformFn::createPlainVar(ExprBlock *in, Str *name, Token *token) {
			MemberVar *src = token->target;
			Expr *srcAccess = new (this) MemberVarAccess(pos, thisVar(in), src, true);

			syntax::SStr *sName = CREATE(syntax::SStr, this, name);
			Var *v = new (this) Var(in, sName, srcAccess);

			in->add(v);

			return v->var;
		}

		LocalVar *TransformFn::createTfmVar(ExprBlock *in, Str *name, Token *token, Nat pos) {
			Engine &e = engine();

			Type *srcType = tokenType(token);
			MemberVar *src = token->target;
			MemberVarAccess *srcAccess = new (this) MemberVarAccess(this->pos, thisVar(in), src, true);

			// Prepare parameters.
			Actuals *actuals = createActuals(in, pos);
			Function *tfmFn = findTransformFn(srcType, actuals);
			syntax::SStr *varName = new (e) syntax::SStr(name, this->pos);

			// Transform each part of this rule...
			Var *v = null;
			if (isMaybe(src->type)) {
				v = new (this) Var(in, wrapMaybe(tfmFn->result), varName, new (this) Actuals());
				in->add(v);
				Expr *readV = new (this) LocalVarAccess(this->pos, v->var);

				WeakCast *cast = new (this) WeakMaybeCast(srcAccess);
				If *check = new (this) If(in, cast);
				assert(check->condition->result(), L"Weak cast should overwrite stuff!");
				Expr *access = new (this) LocalVarAccess(this->pos, check->condition->result());

				// Assign something to the variable!
				actuals->addFirst(access);
				Expr *tfmCall = new (this) FnCall(this->pos, scope, tfmFn, actuals);
				OpInfo *assignOp = assignOperator(new (e) syntax::SStr(S("=")), 1);
				check->success(new (this) Operator(check->successBlock, readV, assignOp, tfmCall));
				in->add(check);

			} else if (isArray(src->type)) {
				v = new (this) Var(in, wrapArray(tfmFn->result), varName, new (this) Actuals());
				in->add(v);
				Expr *readV = new (this) LocalVarAccess(this->pos, v->var);

				// Extra block to avoid name collisions.
				ExprBlock *forBlock = new (this) ExprBlock(this->pos, in);
				Expr *arrayCount = callMember(this->pos, scope, S("count"), srcAccess);
				Var *end = new (this) Var(forBlock,
										Value(StormInfo<Nat>::type(e)),
										new (e) syntax::SStr(S("_end")),
										arrayCount);
				Expr *readEnd = new (this) LocalVarAccess(this->pos, end->var);
				forBlock->add(end);

				Var *i = new (this) Var(forBlock,
										Value(StormInfo<Nat>::type(e)),
										new (e) syntax::SStr(S("_i")),
										new (this) NumLiteral(this->pos, 0));
				Expr *readI = new (this) LocalVarAccess(this->pos, i->var);
				forBlock->add(i);

				For *loop = new (this) For(this->pos, forBlock);
				loop->test(callMember(this->pos, scope, S("<"), readI, readEnd));
				loop->update(callMember(this->pos, scope, S("++*"), readI));

				actuals->addFirst(callMember(this->pos, scope, S("[]"), srcAccess, readI));
				Expr *tfmCall = new (this) FnCall(this->pos, scope, tfmFn, actuals);
				loop->body(callMember(this->pos, scope, S("push"), readV, tfmCall));

				forBlock->add(loop);
				in->add(forBlock);

			} else {
				// Add 'this' parameter for the call.
				actuals->addFirst(srcAccess);

				// Call function and create variable!
				FnCall *tfmCall = new (this) FnCall(this->pos, scope, tfmFn, actuals);
				v = new (this) Var(in, varName, tfmCall);
				in->add(v);
			}

			return v->var;
		}


		/**
		 * Member function calling.
		 */

		void TransformFn::executeMe(ExprBlock *in, Expr *me) {
			Nat tokens = tokenCount();
			Nat firstBreak = min(source->repStart, tokens);
			Nat secondBreak = min(source->repEnd, tokens);

			// Resolve variables needed for execute steps.
			for (Nat i = 0; i < tokens; i++)
				executeLoad(in, getToken(i), i);

			// Tokens before the capture starts.
			for (Nat i = 0; i < firstBreak; i++)
				executeToken(in, me, getToken(i), i);

			// Tokens in the capture.
			switch (source->repType) {
			case repZeroOne:
				// Only Maybe<T>. If statement is sufficient!
				for (Nat i = firstBreak; i < secondBreak; i++)
					executeTokenIf(in, me, getToken(i), i);
				break;
			case repOnePlus:
			case repZeroPlus:
				// Only Array<T>. Embed inside for-loop.
				executeTokenLoop(firstBreak, secondBreak, in, me);
				break;
			default:
				// Nothing special!
				for (Nat i = firstBreak; i < secondBreak; i++)
					executeToken(in, me, getToken(i), i);
				break;
			}

			// Tokens after the capture.
			for (Nat i = secondBreak; i < tokens; i++)
				executeToken(in, me, getToken(i), i);
		}

		Bool TransformFn::shallExecute(ExprBlock *in, Token *token, Nat pos) {
			// If a token is not even stored in the syntax tree, there is not much we can do...
			if (!token->target)
				return false;

			// Always execute tokens that invoke things.
			if (token->invoke)
				return true;

			// If it is a raw token, there are no side effects to speak about...
			if (token->raw)
				return false;

			// If the token was bound to a variable, only execute it if we have not already done so.
			if (token->bound)
				if (hasVar(in, token->target->name))
					return false;

			// If we got this far, the previous step decided that this token was interesting to
			// evaluate even if it is of no immediate use in this function. Respect that decision
			// and evaluate the token!
			return true;
		}

		void TransformFn::executeToken(ExprBlock *in, Expr *me, Token *token, Nat pos) {
			// Not a token that invokes things.
			if (!shallExecute(in, token, pos))
				return;

			Expr *srcAccess = new (this) MemberVarAccess(this->pos, thisVar(in), token->target, true);
			in->add(executeToken(in, me, srcAccess, token, pos));
		}

		Expr *TransformFn::executeToken(Block *in, Expr *me, Expr *src, Token *token, Nat pos) {
			Expr *toStore = null;
			if (token->raw) {
				toStore = src;
			} else {
				Type *srcType = tokenType(token);
				Actuals *actuals = readActuals(in, pos);
				Function *tfmFn = findTransformFn(srcType, actuals);

				actuals->addFirst(src);

				toStore = new (this) FnCall(this->pos, scope, tfmFn, actuals);
			}

			if (token->invoke) {
				// Call the member function indicated in 'invoke'.
				if (!me)
					throw new (this) SyntaxError(this->pos, S("Can not invoke functions on 'me' when 'me' is undefined."));
				return callMember(this->pos, scope, token->invoke, me, toStore);
			} else {
				// We just called 'transform' for the side effects.
				return toStore;
			}
		}

		void TransformFn::executeTokenIf(ExprBlock *in, Expr *me, Token *token, Nat pos) {
			if (!shallExecute(in, token, pos))
				return;

			Expr *srcAccess = new (this) MemberVarAccess(this->pos, thisVar(in), token->target, true);
			WeakCast *cast = new (this) WeakMaybeCast(srcAccess);
			If *check = new (this) If(in, cast);

			LocalVar *overwrite = check->condition->result();
			assert(overwrite, L"Weak cast did not overwrite variable as expected.");
			Expr *e = executeToken(check->successBlock, me, new (this) LocalVarAccess(this->pos, overwrite), token, pos);
			check->success(e);
			in->add(check);
		}

		void TransformFn::executeTokenLoop(Nat from, Nat to, ExprBlock *in, Expr *me) {
			Engine &e = engine();

			// Find the minimal length to iterate...
			Expr *minExpr = null;
			for (Nat i = from; i < to; i++) {
				Token *t = getToken(i);
				if (!shallExecute(in, t, i))
					// Not interesting...
					continue;

				MemberVarAccess *srcAccess = new (this) MemberVarAccess(this->pos, thisVar(in), t->target, true);
				Expr *read = callMember(pos, scope, S("count"), srcAccess);

				if (minExpr)
					minExpr = callMember(pos, scope, S("min"), minExpr, read);
				else
					minExpr = read;
			}

			if (!minExpr)
				// Nothing to execute in here!
				return;

			ExprBlock *forBlock = new (this) ExprBlock(this->pos, in);

			Var *end = new (this) Var(forBlock,
									Value(StormInfo<Nat>::type(e)),
									new (e) syntax::SStr(S("_end")),
									minExpr);
			forBlock->add(end);
			Expr *readEnd = new (this) LocalVarAccess(this->pos, end->var);

			// Iterate...
			Var *i = new (this) Var(forBlock,
									Value(StormInfo<Nat>::type(e)),
									new (e) syntax::SStr(S("_i")),
									new (this) NumLiteral(this->pos, 0));
			Expr *readI = new (this) LocalVarAccess(this->pos, i->var);
			forBlock->add(i);

			For *loop = new (this) For(this->pos, forBlock);
			loop->test(callMember(pos, scope, S("<"), readI, readEnd));
			loop->update(callMember(pos, scope, S("++*"), readI));

			ExprBlock *inLoop = new (this) ExprBlock(this->pos, loop);

			for (Nat i = from; i < to; i++) {
				Token *t = getToken(i);
				if (!shallExecute(in, t, i))
					continue;

				MemberVarAccess *srcAccess = new (this) MemberVarAccess(this->pos, thisVar(in), t->target, true);
				Expr *element = callMember(pos, scope, S("[]"), srcAccess, readI);
				inLoop->add(executeToken(inLoop, me, element, t, i));
			}

			loop->body(inLoop);
			forBlock->add(loop);
			in->add(forBlock);
		}

		void TransformFn::executeLoad(bs::ExprBlock *in, Token *token, Nat pos) {
			// Just requesting the parameters object is enough.
			createActuals(in, pos);
		}



		/**
		 * Utilities.
		 */

		Type *TransformFn::tokenType(Token *token) {
			Value v = token->target->type;
			if (isMaybe(v)) {
				return unwrapMaybe(v).type;
			} else if (isArray(v)) {
				return unwrapArray(v).type;
			} else {
				return v.type;
			}
		}

		Expr *TransformFn::thisVar(Block *in) {
			LocalVar *var = in->variable(new (this) SimplePart(new (this) Str(S("this"))));
			assert(var, L"'this' was not found!");
			return new (this) LocalVarAccess(pos, var);
		}

		Expr *TransformFn::posVar(Block *in) {
			Rule *rule = source->rule();

			SimplePart *part = new (this) SimplePart(new (this) Str(S("pos")), thisPtr(rule));
			Named *found = rule->find(part, scope);

			MemberVar *posVar = as<MemberVar>(found);
			assert(posVar, L"'pos' not found in syntax node types!");

			return new (this) MemberVarAccess(pos, thisVar(in), posVar, true);
		}

		Nat TransformFn::findToken(Str *name) {
			Nat count = tokenCount();

			for (Nat i = 0; i < count; i++) {
				Token *token = getToken(i);

				if (token->invoke)
					// Not interesting.
					continue;

				if (!token->target)
					// Not bound to anything.
					continue;

				if (*token->target->name == *name)
					return i;
			}

			// Failed.
			return count;
		}

		Token *TransformFn::getToken(Nat pos) {
			Array<Token *> *tokens = source->tokens;
			if (pos == tokens->count())
				return source->repCapture;
			else
				return tokens->at(pos);
		}

		Nat TransformFn::tokenCount() {
			Nat r = source->tokens->count();
			if (source->repCapture)
				r++;
			return r;
		}

		Actuals *TransformFn::readActuals(Block *in, Nat n) {
			Array<Str *> *params = tokenParams->at(n).v;
			Actuals *actuals = new (this) Actuals();

			if (params) {
				for (Nat i = 0; i < params->count(); i++)
					actuals->add(readVar(in, params->at(i)));
			}

			return actuals;
		}

		Actuals *TransformFn::createActuals(ExprBlock *in, Nat n) {
			Array<Str *> *params = tokenParams->at(n).v;
			Actuals *actuals = new (this) Actuals();

			if (params) {
				for (Nat i = 0; i < params->count(); i++)
					actuals->add(findVar(in, params->at(i)));
			}

			return actuals;
		}

		Function *TransformFn::findTransformFn(Type *type, Actuals *actuals) {
			Array<Value> *types = actuals->values();
			types->insert(0, thisPtr(type));

			SimplePart *tfmName = new (this) SimplePart(new (this) Str(S("transform")), types);
			Named *foundTfm = type->find(tfmName, scope);
			Function *tfmFn = as<Function>(foundTfm);
			if (!tfmFn) {
				StrBuf *to = new (this) StrBuf();
				*to << S("Can not transform a ") << type->identifier()
					<< S(" with parameters: (") << join(actuals->values(), S(", ")) << S(").");
				throw new (this) SyntaxError(pos, to->toS());
			}
			return tfmFn;
		}


		/**
		 * Static helpers.
		 */

		Function *createTransformFn(ProductionDecl *decl, ProductionType *type, Scope scope) {
			return new (decl) TransformFn(decl, type, type->rule(), scope);
		}

	}
}