-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnake-ex.js
1588 lines (1435 loc) · 38.4 KB
/
snake-ex.js
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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
SnakeEx
2D Text Pattern-matching language by Brian MacIntosh
www.brianmacintosh.com - [email protected]
Designed For:
https://codegolf.stackexchange.com/questions/47311/language-design-2-d-pattern-matching
Online Interpreter Interface/Sample Code:
https://www.brianmacintosh.com/snakeex
Full Language Spec:
https://www.brianmacintosh.com/snakeex/spec.html
This source code is the full interpreter, capable of taking code and input text
and producing matches.
Usage:
1. Call snakeEx.run, which takes two string parameters - the code to run, and
the input to provide. (If necessary, you can call the three stages of the
interpreter seperately: scan, parse, and find. See the body of snakeEx.run.)
2. If there are any errors, run returns false and snakeEx.errors is an array
containing strings describing the errors.
Otherwise, snakeEx.successes is an array containing the matches found.
Matches are Javascript objects with the following fields:
- 'origX': The start column for this match
- 'origY': The start line for this match
- 'marks': An array of integers. Each pair of integers represents the X and
Y coordinate of a character that was matched by the program.
- Other less useful state information about the final state of the program.
28 Mar 2015: Added '`' syntax, fixed a problem where exclusive snakes would fail
when moving onto a marked tile even if not asked to match it.
29 Mar 2015: Treat non-breaking spaces as spaces.
4 April 2015: Add S and L parameters, fixed a problem where piggyback didn't
reset snake flags.
8 April 2015: Made absolute direction '.' combinable, and fixed empty matches
returning duplicates
This source code is licensed under the MIT license, which appears below.
Copyright (c)2015 Brian MacIntosh
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.
*/
var snakeEx =
{
//types for tokens in the scan stage
TOK_INVALID: 0,
TOK_STRING: 1,
TOK_SPECIAL: 2,
TOK_ESCAPE: 3,
//types for AST nodes in parse and run stages
NODE_INVALID: 0,
NODE_PROGRAM: 1,
NODE_DECLARATION: 2,
NODE_STRING: 3,
NODE_CLASS: 4,
NODE_CALL: 5,
NODE_GROUP: 6,
NODE_DIRECTION: 7,
NODE_CLOSURE: 8,
NODE_STATEMENTLIST: 9,
NODE_OUTOFBOUNDS: 10,
NODE_WILDCARD: 11,
NODE_PARAMS: 12,
NODE_CHARCLASS: 13,
NODE_PRECEDING: 14,
//ops for statementlist
OP_AND: 0,
OP_OR: 1,
DEBUG_SCANNER: false,
DEBUG_PARSER: false
};
Math.sign = Math.sign || function(a) { return a >= 0 ? (a === 0 ? 0 : 1) : -1; }
/// performs all three stages of interpretation using the provided code and input strings
snakeEx.run = function(code, input, stricterDupes)
{
this.successes = [];
this.errors = [];
this.scan(code);
if (this.errors.length > 0) return false;
if (this.DEBUG_SCANNER)
{
var tokens = this.tokens;
for (var i = 0; i < tokens.length; i++) console.log("(" + tokens[i].line + "," + tokens[i].col + " " + tokens[i].type + " '" + tokens[i].token + "')");
}
this.parseProgram();
if (this.errors.length > 0) return false;
if (this.DEBUG_PARSER)
{
console.log(this.program);
}
this.find(input, stricterDupes);
if (this.errors.length > 0) return false;
return this.successes;
}
/// scan the code into tokens
snakeEx.scan = function(code)
{
this.errors.length = 0;
var tokens = [];
var line = 1;
var col = 0;
var tokenline = 1;
var tokencol = 1;
var tokenStartPos = 0;
for (var c = 0; c < code.length; c++)
{
col++;
var match = false;
if (this.isSpecialCharacter(code.charAt(c))
|| (c < code.length-1 && this.isSpecialCharacter(code.charAt(c+1)))
|| c == code.length-1)
{
var tok = code.substr(tokenStartPos,c-tokenStartPos+1);
var obj = {
token:tok, type:this.TOK_INVALID,
line:tokenline, col:tokencol }
tokens.push(obj);
//Mark token type
if (tok=='\\')
obj.type = this.TOK_ESCAPE;
else if (this.isSpecialCharacter(tok))
obj.type = this.TOK_SPECIAL;
else
obj.type = this.TOK_STRING;
tokenline = line;
tokencol = col+1;
tokenStartPos = c+1;
match = true;
}
if (code.charAt(c) == '\n')
{
line++;
col = 0;
if (match)
{
tokenline = line;
tokencol = 1;
}
}
}
//Remove empty lines
var was = false;
for (var c = 0; c < tokens.length; c++)
{
if (tokens[c].token == '\n')
{
if (was)
tokens.splice(c--,1);
else
was = true
}
else
was = false;
}
//Transform backslash expressions
var was = false;
for (var c = 0; c < tokens.length; c++)
{
if (was)
{
if (tokens[c].type == this.TOK_SPECIAL || tokens[c].type == this.TOK_ESCAPE)
tokens[c].type = this.TOK_STRING;
else if (tokens[c].type == this.TOK_STRING)
{
if (tokens[c].token.charAt(0) == 'n')
tokens[c].token = '\n' + tokens[c].token.substr(1);
else if (tokens[c].token.charAt(0) == 't')
tokens[c].token = '\t' + tokens[c].token.substr(1);
else if (tokens[c].token.charAt(0) == 'r')
tokens[c].token = '\r' + tokens[c].token.substr(1);
else
this.errors.push(this.errloc(tokens[c].line, tokens[c].col) + " Invalid escape code '" + tokens[c].token + "'.");
}
else
this.errors.push(this.errloc(tokens[c].line, tokens[c].col) + " Unrecognized token '" + tokens[c].token + "'.");
was = false;
}
else if (tokens[c].type == this.TOK_ESCAPE)
{
was = true;
tokens.splice(c--,1);
}
}
//Transform character ranges
//HACK: hacky
for (var c = 0; c < tokens.length; c++)
{
if (tokens[c].type == this.TOK_SPECIAL && tokens[c].token == "-")
{
var pre = tokens[c-1];
var post = tokens[c+1];
var loc = this.errloc(tokens[c].line, tokens[c].col);
if (!pre || pre.type != this.TOK_STRING || pre.token.length == 0)
{
this.errors.push(loc + " range must be preceded by a string.");
continue;
}
if (!post || post.type != this.TOK_STRING || pre.token.length == 0)
{
this.errors.push(loc + " range must be followed by a string.");
continue;
}
//Extract range character
var first, last;
if (pre.token.length == 1)
{
first = pre.token;
tokens.splice(c-1, 1);
c--;
}
else
{
first = pre.token.charAt(pre.token.length-1);
pre.token = pre.token.substr(0, pre.token.length-1);
}
if (post.token.length == 1)
{
last = post.token;
tokens.splice(c+1, 1);
}
else
{
last = post.token.charAt(0);
post.token = post.token.substr(1);
}
//Build range string
var newstr = "";
for (var d = first.charCodeAt(0); d <= last.charCodeAt(0); d++)
newstr += String.fromCharCode(d);
//Replace range token with string
tokens[c].type = this.TOK_STRING;
tokens[c].token = newstr;
}
}
//Merge newly created strings
for (var c = 0; c < tokens.length - 1; c++)
{
if (tokens[c].type == this.TOK_STRING && tokens[c+1].type == this.TOK_STRING)
{
tokens[c].token += tokens[c+1].token;
tokens.splice(c+1,1);
c--;
}
}
//Ensure the program ends with a newline
if (tokens.length == 0 || tokens[tokens.length-1].type != this.TOK_SPECIAL || tokens[tokens.length-1].token != '\n')
tokens.push({ type: this.TOK_SPECIAL, token: '\n', line: 0, col: 0 });
this.tokens = tokens;
}
snakeEx.errloc = function(ln, col) { return "(ln " + ln + ", col " + col + ")"; }
snakeEx.expectError = function(token, expect)
{
if (token)
var got = token.token;
else
var got = "end of code";
this.errors.push(this.errloc(token.line, token.col) + " expected " + expect + ", got '" + got + "'.");
}
snakeEx.parseToken = function()
{
var tok = this.tokens[this.currentToken++];
if (tok)
return tok;
else
return { type: this.TOK_INVALID, token: "end of code" };
}
snakeEx.peekToken = function()
{
var tok = this.tokens[this.currentToken];
if (tok)
return tok;
else
return { type: this.TOK_INVALID, token: "end of code" };
}
snakeEx.closesStatementList = function(token)
{
return token.type == this.TOK_SPECIAL && (token.token==')'||token.token=='}'||token.token==']'||token.token=='>'||token.token=='\n');
}
snakeEx.isClosure = function(token)
{
return token.type == this.TOK_SPECIAL && (token.token=='*'||token.token=='?'||token.token=='+'||token.token=='%');
}
/// true if the specified string describes a direction or set of directions
snakeEx.isDirection = function(str)
{
for (var c = 0; c < str.length; c++)
{
var ch = str.charAt(c);
if (ch !== 'R' && ch !=='L' && ch != 'F' && ch != 'B' && ch != 'P' && ch != 'T' && ch != 'X')
return false
}
return true;
}
/// true if the specified special character describes a direction
snakeEx.isSpecialDirection = function(str)
{
return str == '*' || str == '+' || str == '.'|| str == '!';
}
/// parse tokens into an abstract syntax tree
snakeEx.parseProgram = function()
{
this.errors.length = 0;
this.currentToken = 0;
this.program = { type: this.NODE_PROGRAM, declarations:[] };
while (this.currentToken < this.tokens.length && this.errors.length == 0)
{
var declaration = this.parseDeclaration()
this.program.declarations.push(declaration);
}
}
snakeEx.parseDeclaration = function()
{
if (this.DEBUG_PARSER) console.log("declaration");
var declaration = { type: this.NODE_DECLARATION };
var label = this.parseToken();
if (label.type == this.TOK_STRING)
{
declaration.name = label.token;
var lookat = this.parseToken();
//Optional declaration params
if (lookat.type == this.TOK_SPECIAL && lookat.token == '{')
{
declaration.params = this.parseParams();
lookat = this.parseToken();
if (lookat.type == this.TOK_SPECIAL && lookat.token == '}')
lookat = this.parseToken();
else
this.expectError(lookat, "'}'");
}
//Declaration close
if (lookat.type == this.TOK_SPECIAL && lookat.token == ':')
{
declaration.statements = this.parseStatementList(this.OP_AND);
var newline = this.parseToken();
if (newline.type == this.TOK_SPECIAL && newline.token == '\n')
;
else
this.expectError(newline, "newline");
}
else
this.expectError(lookat, "':'");
}
else
this.expectError(label, "label");
return declaration;
}
snakeEx.parseCharacterClass = function()
{
//HACK: this whole system for negating gets pretty hacky
var obj = { type: this.NODE_CHARCLASS };
var peek = this.peekToken();
if (peek.type == this.TOK_SPECIAL && peek.token == "^")
{
obj.negate = true;
this.parseToken();
}
var token = this.parseToken()
if (token.type == this.TOK_STRING)
{
obj.string = token.token;
}
else
this.expectError(token, "string");
return obj;
}
snakeEx.parseStatementList = function(op)
{
//Make this a character class instead if it's negated
//HACK: treat other things as character classes?
var peek = this.peekToken();
if (peek.type == this.TOK_SPECIAL && peek.token == "^")
{
return snakeEx.parseCharacterClass();
}
if (this.DEBUG_PARSER) console.log("statementlist");
var obj = { type: this.NODE_STATEMENTLIST, op: op }
var statements = [];
while (!this.closesStatementList(this.peekToken()) && this.errors.length == 0)
{
statements.push(this.parseStatement());
}
//Fix-up: break up strings under OR semantics
if (op == this.OP_OR)
{
for (var c = 0; c < statements.length; c++)
{
if (statements[c].type == this.NODE_STRING && statements[c].string.length > 1)
{
var working = statements[c].string
statements[c].string = statements[c].string.charAt(0);
for (var d = 1; d < working.length; d++)
{
//HACK: messes up the order, doesn't really matter though
var newstatement = { type: this.NODE_STRING, string: working.charAt(d) };
statements.splice(c, 0, newstatement);
c++;
}
}
}
}
//Fix-up: break up closures and ops tacked on to unparenthetical strings
//HACK: see closure code
for (var c = 0; c < statements.length; c++)
{
var inner = statements[c].statement;
if (statements[c].type == this.NODE_CLOSURE && inner.type == this.NODE_STRING && inner.string.length > 1)
{
var newstatement = { type: this.NODE_STRING, string: inner.string.substr(0, inner.string.length-1) };
inner.string = inner.string.substr(inner.string.length-1, 1);
statements.splice(c, 0, newstatement);
c++;
}
else if (statements[c].type == this.NODE_PRECEDING && inner.type == this.NODE_STRING && inner.string.length > 1)
{
//TODO: BAD: this fails if enclosing a closure
var newstatement = { type: this.NODE_STRING, string: inner.string.substr(1, inner.string.length-1) };
inner.string = inner.string.substr(0, 1);
statements.splice(c+1, 0, newstatement);
c++;
}
}
obj.statements = statements;
return obj;
}
snakeEx.parseStatement = function()
{
if (this.DEBUG_PARSER) console.log("statement");
var statement = { type: this.NODE_INVALID };
var token = this.peekToken();
if (token.type == this.TOK_SPECIAL)
{
if (token.token == '(')
{
var open = this.parseToken();
if (open.type == this.TOK_SPECIAL && open.token == '(')
{
statement = this.parseStatementList(this.OP_AND);
var close = this.parseToken();
if (close.type == this.TOK_SPECIAL && close.token == ')')
;
else
this.expectError(close, "')'");
}
else
this.expectError(open, "'('");
}
else if (token.token == '<')
{
statement = this.parseDirection();
}
else if (token.token == '{')
{
statement = this.parseCall();
}
else if (token.token == '[')
{
statement = this.parseClass();
}
else if (token.token == '$')
{
this.parseToken();
statement.type = this.NODE_OUTOFBOUNDS;
}
else if (token.token == '.')
{
this.parseToken();
statement.type = this.NODE_WILDCARD;
}
else if (token.token == '!' || token.token == '~' || token.token == '`')
{
this.parseToken();
statement.type = this.NODE_PRECEDING;
statement.op = token.token;
statement.statement = this.parseStatement();
}
else
{
this.expectError(token, "statement");
return statement;
}
}
else if (token.type == this.TOK_STRING)
{
statement.type = this.NODE_STRING;
statement.string = this.parseToken().token;
}
else
{
this.expectError(token, "statement");
return statement;
}
//Parse closures
//HACK: should be done differently
while (this.isClosure(this.peekToken()) && this.errors.length == 0)
{
if (this.DEBUG_PARSER) console.log("(closure)");
statement = { type: this.NODE_CLOSURE, statement: statement, op: this.parseToken().token };
if (statement.op == '%')
statement.bounds = this.parseBounds();
}
return statement;
}
snakeEx.parseBounds = function()
{
var bounds = {};
var token = this.parseToken();
if (token.type == this.TOK_SPECIAL && token.token == '{')
{
var token = this.parseToken();
if (token.type == this.TOK_STRING)
{
var split = token.token.split(',');
if (split.length == 0)
this.errors.push(this.errloc(token.line, token.col) + " not enough values in bounds.");
else if (split.length == 1)
{
bounds.min = bounds.max = parseInt(split[0]);
if (isNaN(bounds.min))
this.expectError(token, "integer");
}
else if (split.length == 2)
{
if (split[0].length > 0)
{
bounds.min = parseInt(split[0]);
if (isNaN(bounds.min))
this.expectError(token, "integer");
}
if (split[1].length > 0)
{
bounds.max = parseInt(split[1]);
if (isNaN(bounds.max))
this.expectError(token, "integer");
}
}
else
this.errors.push(this.errloc(token.line, token.col) + " too many values in bounds.");
var token = this.parseToken();
if (token.type == this.TOK_SPECIAL && token.token == "}")
;
else
this.expectError(token, "}");
}
else
this.expectError(token, "number or ','");
}
else
this.expectError(token, "'{'");
return bounds;
}
snakeEx.parseDirection = function()
{
if (this.DEBUG_PARSER) console.log("direction");
var direction = { type: this.NODE_DIRECTION, direction:"" };
var open = this.parseToken();
if (open.type == this.TOK_SPECIAL && open.token == '<')
{
var dirtoken = this.parseToken();
while ((dirtoken.type == this.TOK_STRING && this.isDirection(dirtoken.token))
|| (dirtoken.type == this.TOK_SPECIAL && this.isSpecialDirection(dirtoken.token)))
{
//TODO: special characters other than . not by themselves is an error
if (dirtoken.type == this.TOK_SPECIAL && dirtoken.token == '.')
direction.abs = true;
else
direction.direction += dirtoken.token;
dirtoken = this.parseToken();
}
if (dirtoken.type == this.TOK_SPECIAL && dirtoken.token == '>')
;
else
this.expectError(dirtoken, "'>'");
if (direction.direction == "")
{
//Fill empty direction
direction.direction = 'F';
}
}
else
this.expectError(open, "'<'");
return direction;
}
snakeEx.parseCall = function()
{
if (this.DEBUG_PARSER) console.log("call");
var call = { type: this.NODE_CALL };
var open = this.parseToken();
if (open.type == this.TOK_SPECIAL && open.token == '{')
{
var name = this.parseToken();
if (name.type == this.TOK_STRING)
{
call.name = name.token;
call.direction = this.parseDirection();
var close = this.peekToken();
if (close.type == this.TOK_STRING)
{
//Parse parameters
call.params = this.parseParams();
}
var close = this.parseToken();
if (close.type == this.TOK_SPECIAL && close.token == '}')
;
else
this.expectError(close, "'}'");
}
else
this.expectError(name, "label");
}
else
this.expectError(open, "'{'");
return call;
}
snakeEx.parseParams = function()
{
if (this.DEBUG_PARSER) console.log("params");
var close = this.parseToken();
var call = { type: this.NODE_PARAMS };
var params = close.token;
for (var d = 0; d < params.length; d++)
{
if (params.charAt(d) == 'P')
call.piggyback = true;
else if (params.charAt(d) == 'H')
call.wrapX = true;
else if (params.charAt(d) == 'V')
call.wrapY = true;
else if (params.charAt(d) == 'W')
call.wrapX = call.wrapY = true;
else if (params.charAt(d) == 'E')
call.exclusive = true;
else if (params.charAt(d) == 'I')
call.insensitive = true;
else if (params.charAt(d) == 'A')
call.advance = true;
else if (params.charAt(d) == 'S')
call.noMark = true;
else if (params.charAt(d) == 'L')
call.onlyMarked = true;
else if (params.charAt(d) >= '0' && params.charAt(d) <= '9')
call.group = params.charAt(d) - '0';
else
this.errors.push(this.errloc(close.line, close.col) + " Unrecognized call parameter '" + params.charAt(d) + "'.");
}
return call;
}
snakeEx.parseClass = function()
{
if (this.DEBUG_PARSER) console.log("class");
var rclass = { type: this.NODE_CLASS };
var open = this.parseToken();
if (open.type == this.TOK_SPECIAL && open.token == '[')
{
rclass.statements = this.parseStatementList(this.OP_OR);
var lookat = this.parseToken();
if (lookat.type == this.TOK_SPECIAL && lookat.token == ']')
;
else
this.expectError(lookat, "']'");
}
else
this.expectError(open, "'['");
return rclass;
}
snakeEx.specialCharacters = ":+*?~%<>()[]{}!.$-^\n\\`";
snakeEx.isSpecialCharacter = function(c)
{
for (var d = 0; d < this.specialCharacters.length; d++)
{
if (this.specialCharacters.charAt(d)===c)
return true;
}
return false;
}
snakeEx.runtimeError = function(error)
{
this.errors.push(error);
}
snakeEx.getDeclaration = function(name)
{
if (!this.program || !this.program.declarations || this.program.declarations.length == 0)
return null;
for (var c = 0; c < this.program.declarations.length; c++)
{
if (this.program.declarations[c].name == name)
return this.program.declarations[c];
}
return null;
}
snakeEx.cloneState = function(state)
{
if (state.length !== undefined)
{
var newstate = [];
for (var i = 0; i < state.length; i++)
newstate.push(this.cloneState(state[i]));
return newstate;
}
var newState = { x:state.x, y:state.y, dx:state.dx, dy:state.dy, age:state.age };
if (state.noMark) newState.noMark = true;
if (state.wrapX) newState.wrapX = true;
if (state.wrapY) newState.wrapY = true;
if (state.excl) newState.excl = true; //exclusive
if (state.ins) newState.ins = true //case-insensitive
if (state.wrapped) newState.wrapped = state.wrapped;
if (state.onlyMarked) newState.onlyMarked = true;
if (state.marks)
{
newState.marks = [];
for (var c = 0; c < state.marks.length; c++)
newState.marks.push(state.marks[c]);
}
if (state.g)
{
newState.g = {};
for (var i in state.g)
newState.g[i] = state.g[i];
}
return newState;
}
snakeEx.checkStateGroup = function(state, group, age)
{
if (group === undefined)
return state;
if (!state.g)
state.g = {};
if (state.g[group] === undefined)
state.g[group] = age;
else if (state.g[group] !== age)
return null;
return state;
}
/// resets the state after returning from a call
snakeEx.resetStateTo = function(state, oldstate, piggyback)
{
if (!state) return state;
if (!piggyback)
{
state.x = oldstate.x; state.y = oldstate.y;
state.dx = oldstate.dx; state.dy = oldstate.dy;
}
state.wrapX = oldstate.wrapX; state.wrapY = oldstate.wrapY;
state.excl = oldstate.excl; state.ins = oldstate.ins;
state.age = oldstate.age; state.wrapped = oldstate.wrapped;
state.onlyMarked = oldstate.onlyMarked;
state.noMark = oldstate.noMark;
return state;
}
snakeEx.advanceState = function(state, noMark)
{
if (state.length !== undefined)
{
for (var c = 0; c < state.length; c++)
{
if (!(state[c] = this.advanceState(state[c], noMark)))
state.splice(c--,1);
}
return state;
}
if (state.marks && state.onlyMarked)
{
//only marked: fail if we try to match an unmarked node
var found = false;
for (var c = 0; c < state.marks.length; c += 2)
{
if (state.x == state.marks[c] && state.y == state.marks[c+1])
{
found = true;
break;
}
}
if (!found) return null;
}
else if (state.marks && state.excl && !state.onlyMarked)
{
//Exclusivity: fail if we try to match an already-marked node
for (var c = 0; c < state.marks.length; c += 2)
{
if (state.x == state.marks[c] && state.y == state.marks[c+1])
{
return null;
}
}
}
if (!noMark)
this.stateMarkCurrent(state);
state.x += state.dx;
state.y += state.dy;
if (state.wrapped) state.wrapped = false;
//Handle wrap
if (state.wrapY)
{
if (state.y < 0)
{
state.y = this.searchGrid.length-1;
state.wrapped = true;
}
if (state.y >= this.searchGrid.length)
{
state.y = 0;
state.wrapped = true;
}
}
if (state.wrapX)
{
if (state.x < 0)
{
state.x = this.searchGrid[state.y].length-1;
state.wrapped = true;
}
if (state.x >= this.searchGrid[state.y].length)
{
state.x = 0;
state.wrapped = true;
}
}
state.age++;
return state;
}
snakeEx.caseInsensitiveMatch = function(ch1, ch2)
{
return ch1.toUpperCase() == ch2.toUpperCase();
}
snakeEx.tryRead = function(state, target)
{
if (state.y >= 0 && state.y < this.searchGrid.length && state.x >= 0 && state.x < this.searchGrid[state.y].length)
{
var match = false;
if (this.searchGrid[state.y][state.x] == target)
match = true;
else if (state.ins && this.searchGrid[state.y][state.x].toUpperCase() == target.toUpperCase())
match = true;
if (match)
{
state = this.advanceState(state);
return state;
}
else
return null;
}
else
return null;
}
snakeEx.addStateToArray = function(array, state)
{
if (array.length === undefined)
array = [ array ];
if (state.length !== undefined)
{
for (var i = 0; i < state.length; i++)
array.push(state[i]);
}
else
{
array.push(state);
}
return array;
}
snakeEx.tryReadClass = function(state, element)
{
if (state.y >= 0 && state.y < this.searchGrid.length && state.x >= 0 && state.x < this.searchGrid[state.y].length)
{
var match = false;
var readHead = this.searchGrid[state.y][state.x];
//treat nbsp as space
if (readHead.charCodeAt(0) === 0xA0) readHead = ' ';
for (var c = 0; !match && c < element.string.length; c++)
{
var target = element.string.charAt(c);
if (readHead === target)
match = true;
else if (state.ins && readHead.toUpperCase() === target.toUpperCase())
match = true;
}
if (match != element.negate)
{
state = this.advanceState(state);
return state;
}
else
return null;
}
else
return null;