-
Notifications
You must be signed in to change notification settings - Fork 0
/
tiny.ps1
11895 lines (10608 loc) · 442 KB
/
tiny.ps1
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
###################################################################################
#
# The Tiny Language Interpreter
# =============================
#
# Copyright Bruce Payette (c) 2023
#
# This PowerShell script implements a dynamic functional/imperative
# scripting language named 'Tiny'.
#
# Documentation and tests are embedded in this script as comments. The
# documentation comments are:
# #O for operation documentation
# #H for function documentation
# #L for TinyList methods.
# #G for the grammar
#
# The script 'tinydoc.tiny' will extract these comments and generate
# an HTML page containing the information.
#
# Test comments are of the form
# #T <testName> <testText>
# #M <testName> <MacOS-specific test text>
# #X <testName> <Linux-specific test text>
# #W <testName> <Windows-specific test text>
# #U <testName> <UNIX (non-Windows) test text>
#
# The script 'tinytest.tiny' will extract and run these tests as well as run additional
# tests in the 'tests' subdirectory. Tests in the subdirectory are written in a Tiny
# DSL defined by the TinyTestUtils module.
#
###################################################################################
using namespace System
using namespace System.Text
using namespace System.Text.RegularExpressions
using namespace System.Collections
using namespace System.Collections.Generic
using namespace System.Collections.ObjectModel
using namespace System.Collections.Specialized
using namespace System.Management.Automation
using namespace System.Management.Automation.RunSpaces
using namespace System.Management.Automation.Internal
[CmdletBinding(DefaultParameterSetName='Repl')]
param (
[Parameter(Position=0, ParameterSetName='script')]
[string]
$scriptToRun,
[Parameter(ParameterSetName='expression')]
[string]
$Expression,
[Parameter()]
[Switch]
$Time,
[Parameter()]
[Switch]
$DetailedErrors,
[Parameter(ParameterSetName='norepl')]
[switch]
$NoRepl,
[Parameter(Position=1, ParameterSetName='script', ValueFromRemainingArguments)]
[object[]]
$TinyScriptArguments
)
# A debugging function
function say {
[console]::writeline("$args")
}
Set-StrictMode -version latest
[regex]::CacheSize = 20
# Make sure the 'matches' variable always exists
Set-Variable -Name "matches" -Value $null
# Value returned from a return statement
$FunctionReturnValue = $null
###################################################################################
#
# The 'tiny' Tokenizer and Token classes
#
# The various kinds of tokens in the language
enum TokenKind {
keyword = 0
name = 1
arrow = 2
lcurly = 3
rcurly = 4
lparen = 5
rparen = 6
lsquare = 7
rsquare = 8
orbar = 9
colon = 10
patOp = 11
semicolon = 12
number = 13
string = 14
regex = 15
badstring = 16
typeliteral = 17
dot = 18
comma = 19
operator = 20
elseif = 21
else = 22
in = 23
catch = 24
finally = 25
StartPP = 26
EndPP = 27
PinnedVar = 28
UnaryOperator = 29
dummy = 30
max_token = 30
}
#######################################################################
#
# Class representing a Tiny token.
#
class Token
{
Token([TokenKind] $kind, [string] $value, [int] $index, [int] $LineNo, [string] $src, [string] $filename) {
$this.kind = $kind
$this.Value = $value
$this.Index = $Index
$this.LineNo = $lineno
$this.Src = $src
$this.Filename = $fileName
}
# Create a dummy token to use as a placeholder
Token() {
$this.kind = [TokenKind]::dummy
$this.Value = [tokenizer]::CurrentString()
$this.Index = [Tokenizer]::Offset
$this.LineNo = [Tokenizer]::CurrentLineNumber
$this.Src = [tokenizer]::string
$this.FileName = [scopes]::Getvariable('__file')
}
[TokenKind] $Kind
[string] $Value
[String] $Src
[int] $index
[int] $LineNo
[string] $FileName
[string] ToString() { return "[Token(Kind=$($this.Kind),Value='$($this.Value)')]" }
}
#######################################################################
#
# A class representing the state of the tokenizer.
# Since the tokenizer is static, it's state must be saved away
# when tokening a new file in midstream which is what happens
# when a script loads a module or another script. Note that modules
# are loaded at script parse time.
#
class TokenizerState {
TokenizerState($String, $FileName, $Offset, $currentLineNumber) {
$this.String = $string
$this.FileName = $filename
$this.Offset = $offset
$this.CurrentLineNumber = $currentLineNumber
}
[string]
$String
# The filename the string came from
[string]
$FileName
# The current offset in the string being tokenized
[int]
$Offset
# The current line number in the file being parsed
[int]
$currentLineNumber
}
#######################################################################
#
# The Tiny tokenizer
#
class Tokenizer
{
# The string being tokenized
hidden static [string]
$String
# The filename the string came from
hidden static [string]
$FileName
# The current offset in the string being tokenized
hidden static [int]
$Offset
# Utility method for compiling regular expressions for the token table.
hidden static [regex] CompileRegex ($str) {
return [regex]::new("\G($str)", 'IgnoreCase,CultureInvariant,Compiled')
}
# Values for matching the tokens in the language.
# THIS TABLE MUST BE IN THE SAME ORDER AS THE TokenKind ENUM
hidden static
$TokenTable = @(
<# [TokenKind]::keyword 0 #> [tokenizer]::compileregex('fn|def|if|while|foreach|break|continue|' +
'return|matchlist|match|throw|try|undef|import|const')
<# [TokenKind]::name 1 #> [tokenizer]::compileregex('[_a-z][a-z0-9_]*')
<# [TokenKind]::arrow 2 #> '->'
<# [TokenKind]::lcurly 3 #> '{'
<# [TokenKind]::rcurly 4 #> '}'
<# [TokenKind]::lparen 5 #> '('
<# [TokenKind]::rparen 6 #> ')'
<# [TokenKind]::lsquare 7 #> '['
<# [TokenKind]::rsquare 8 #> ']'
<# [TokenKind]::orbar 9 #> '|'
<# [TokenKind]::colon 10 #> ':'
<# [TokenKind]::patOp 11 #> '::'
<# [TokenKind]::semicolon 12 #> ';'
<# [TokenKind]::number 13 #> [tokenizer]::compileregex('0x[0-9a-f_]+|' + # hex integers
'[+-]{0,1}\.[0-9_]+(e[+-]{0,1}[0-9]+){0,1}|' +
'[+-]{0,1}[0-9_]+i|' + # BigInts
'[+-]{0,1}[0-9][0-9_]*(\.[0-9_]+){0,1}(e[+-]{0,1}[0-9]+){0,1}')
<# [TokenKind]::string 14 #> [tokenizer]::compileregex('"([^"]|"")*"|' +
"'([^']|'')*'|" +
'`[^` \t\r\n]+( |$)')
<# [TokenKind]::regex 15 #> [tokenizer]::compileregex('r/([^/]|//)*/(c)?(:[_a-z][_a-z0-9]*)?')
<# [TokenKind]::badstring 16 #> [tokenizer]::compileregex('"([^"]|"")*$|' +
"'([^']|'')*$") # unterminated string
<# [TokenKind]::typeliteral 17 #> [tokenizer]::compileregex('\[<[a-z0-9., \[\]]+>\]')
<# [TokenKind]::dot 18 #> '.'
<# [TokenKind]::comma 19 #> ','
# all the binary operators; order is important - shorter operators must go last
<# [TokenKind]::operator 20 #>
[tokenizer]::compileregex( '`[a-z]+`|-f|\+=|\*=|-=|/=|\?=|' +
'<=|>=|==|!=|=|!~|/~|-~|~|\*~|\+\+|\:\+|:>|<:|!:>|!<:|>|<|' +
'&&|\|\||\?\?|\.\.|isnot|is|as|\*\*|do|then|\:\:\}|\:\:|' +
'\|>|\?\*\.|\?\.|\*\.|\.|\[<|\?\[|\[|\{|\(|->|[+*/%-]' )
<# [TokenKind]::elseif 21 #> 'elseif'
<# [TokenKind]::else 22 #> 'else'
<# [TokenKind]::in 23 #> 'in'
<# [TokenKind]::catch 24 #> 'catch'
<# [TokenKind]::finally 25 #> 'finally'
<# [TokenKind]::StartPP 26 #> '{::'
<# [TokenKind]::EndPP 27 #> '::}'
<# [TokenKind]::PinnedVar 28 #> [tokenizer]::compileregex('\^[_a-z][a-z0-9_]*')
<# [TokenKind]::UnaryOperator 29 #> [tokenizer]::compileregex('->|[!+-]')
<# [Tokenkind]::dummy 30 #> 'dummy'
)
# Maintains a count of lines in the text being processed.
static [int] $CurrentLineNumber
# Start tokenizing a new string
static Start ($string) {
[tokenizer]::String = $string
[tokenizer]::Offset = 0
[tokenizer]::CurrentLineNumber = 0
}
# used when processing module imports where the current
# token stream is pushed so the new token stream can be processed.
static PushTokenizerState() {
[Tokenizer]::TokenizerStack.Push(
[TokenizerState]::New(
[Tokenizer]::string,
[Tokenizer]::filename,
[Tokenizer]::offset,
[tokenizer]::CurrentLineNumber
))
}
static PopTokenizerState() {
$state = [Tokenizer]::TokenizerStack.Pop()
[Tokenizer]::String = $state.String
[Tokenizer]::FileName = $state.FileName
[Tokenizer]::Offset = $state.Offset
[tokenizer]::CurrentLineNumber = $state.CurrentLineNumber
}
static [Stack[TokenizerState]] $TokenizerStack = [Stack[TokenizerState]]::new()
#
# Method to eat whitespace and comments in the input stream. Handles
# both line and block comments. It also increments the line count as it
# hits newlines.
#
static EatWhitespace() {
$inComment = $false
$inBlockComment = $false
while ([tokenizer]::Offset -lt [tokenizer]::String.Length) {
$cc = [tokenizer]::String[[tokenizer]::Offset]
if ($inBlockComment) {
if ([tokenizer]::Offset -lt [tokenizer]::String.Length-1 -and
$cc -eq '#' -and
[Tokenizer]::String[[tokenizer]::Offset+1] -eq '>')
{
[Tokenizer]::Offset++
$inBlockComment = $false
}
}
elseif ($inComment) {
if ($cc -eq "`n") {
[tokenizer]::CurrentLineNumber++
$inComment = $false
}
}
elseif ($cc -eq '#') {
$inComment = $true
}
elseif ($cc -eq '<' -and
[tokenizer]::Offset -lt [tokenizer]::String.Length-1 -and
[Tokenizer]::String[[Tokenizer]::Offset+1] -eq '#')
{
[Tokenizer]::Offset++
$InBlockComment = $true
}
elseif ($cc -eq "`n") {
[tokenizer]::CurrentLineNumber++
}
elseif (-not [char]::IsWhiteSpace($cc)) {
break;
}
[tokenizer]::Offset++
}
}
#
# The main tokenizer method. You call it passing in the Kind of the token you're looking for
# If the next token in the stream is of the right kind, then it will be returned otherwise
# null will be returned. This means that tokens are contextual.
#
static [Token] Next ([TokenKind] $TokenKindExpected) {
if ([tokenizer]::offset -ge [tokenizer]::String.length) {
return $null
}
[Tokenizer]::EatWhitespace()
$tokenStart = [tokenizer]::Offset
# Handle tokens with tricky rules
switch ($TokenKindExpected) {
([TokenKind]::LSquare) {
if ([Tokenizer]::String[[Tokenizer]::Offset] -eq '[') {
if ([tokenizer]::offset + 1 -lt [tokenizer]::string.length) {
$c = [tokenizer]::string[[tokenizer]::Offset + 1]
switch ($c) {
'<' { # [<typename>]
return $null
}
}
}
[tokenizer]::Offset++
return [token]::new($TokenKindExpected, '[', $tokenStart, [tokenizer]::CurrentLineNumber,
[tokenizer]::string, [tokenizer]::FileName)
}
else {
return $null
}
}
([TokenKind]::TypeLiteral) {
if ([Tokenizer]::String[[Tokenizer]::Offset] -eq '[') {
if ([tokenizer]::offset + 1 -lt [tokenizer]::string.length) {
$c = [tokenizer]::string[[tokenizer]::Offset + 1]
if ($c -ne '<') {
return $null
}
# definitely have a type literal now, if the regex doesn't match, it's an error.
$pat = [Tokenizer]::TokenTable[$TokenKindExpected]
$res = $pat.Match([tokenizer]::string, [tokenizer]::offset)
if ($res.Success) {
$val = $res.Value
[tokenizer]::offset += $res.length
return [token]::new($TokenKindExpected, $val, $tokenStart, [tokenizer]::CurrentLineNumber,
[tokenizer]::string, [tokenizer]::FileName)
}
else {
errorMessage -dummy "Malformed type literal"
}
}
}
else {
return $null
}
}
([TokenKind]::Colon) {
if ([Tokenizer]::String[[Tokenizer]::Offset] -eq ':') {
if ([Tokenizer]::offset + 1 -lt [Tokenizer]::string.length) {
$c = [Tokenizer]::string[[Tokenizer]::Offset + 1]
switch ($c) {
':' { # ::
return $null
}
'>' { # :>
return $null
}
'+' { # :+
return $null
}
}
[Tokenizer]::Offset++
}
return [Token]::new($TokenKindExpected, ':', $tokenStart, [tokenizer]::CurrentLineNumber,
[Tokenizer]::string, [Tokenizer]::FileName)
}
else {
return $null
}
}
([TokenKind]::Orbar) {
if ([Tokenizer]::String[[Tokenizer]::Offset] -eq '|') {
if ([tokenizer]::offset + 1 -lt [tokenizer]::string.length) {
$c = [tokenizer]::string[[tokenizer]::Offset + 1]
if ($c -eq '|') {
return $null
}
[tokenizer]::Offset++
}
return [token]::new($TokenKindExpected, '|', $tokenStart, [tokenizer]::CurrentLineNumber,
[tokenizer]::string, [tokenizer]::FileName)
}
else {
return $null
}
}
}
# Handle simple tokens with no ambiguity that just require a string match
$pat = [Tokenizer]::TokenTable[$TokenKindExpected]
if ($pat -is [string]) {
$str = [tokenizer]::string
$len = $str.length
$toffset = [tokenizer]::Offset
if ($toffset + $pat.Length -gt $len) {
return $null
}
for ($poffset = 0; $poffset -lt $pat.length; $poffset++) {
if ($pat[$poffset] -ne $str[$toffset++]) {
return $null
}
}
[tokenizer]::offset += $pat.length
$token = [token]::new($TokenKindExpected, $pat, $tokenStart, [tokenizer]::CurrentLineNumber,
[tokenizer]::string, [tokenizer]::FileName)
return $token
}
# Handle the more complex tokens using regular expressions
$res = $pat.Match([Tokenizer]::string, [tokenizer]::offset)
if ($res.Success) {
$len = $res.Length
$val = $res.Value
# If this is a keyword or operator ending in a letter that is followed by a letter
# then this is not a valid keyword/operator token, return null
if (($TokenKindExpected -eq [TokenKind]::Keyword -or $TokenKindExpected -eq [TokenKind]::Operator) -and
[char]::IsLetter($val[-1]) -and
([tokenizer]::offset + $len -lt [tokenizer]::string.length) -and
([char]::IsLetter([tokenizer]::string[[tokenizer]::Offset + $len])))
{
return $null
}
# Due to token ambiguity, the arrow operator or
# the type literal prefix '[<' may show up when requesting a binary operator.
# If so, it's not a valid token in the current context so we just return null.
elseif ($TokenKindExpected -eq [TokenKind]::Operator -and ($val -eq '->' -or $val -eq '[<' -or $val -eq '::}')) {
return $null
}
[tokenizer]::offset += $len
return [token]::new($TokenKindExpected, $val, $tokenStart, [tokenizer]::CurrentLineNumber,
[tokenizer]::string, [tokenizer]::FileName)
}
else {
return $null
}
}
#
# Sets the tokenizer offset back to the offset of the ungot token
#
static Unget ([token] $token) {
if ($null -eq $token) {
errorMessage -dummy "unget: token was null"
}
[tokenizer]::offset = $token.index
}
#
# true if at the end of the string being parsed
#
static [bool] AtEof() {
[Tokenizer]::EatWhitespace()
return [tokenizer]::offset -ge [tokenizer]::string.length
}
#
# Get the character at the current offset in the input stream.
#
static [char] CurrentCharacter() {
[Tokenizer]::EatWhitespace()
if ([tokenizer]::offset -ge [tokenizer]::string.length) {
return $null
}
return [tokenizer]::string[[tokenizer]::Offset]
}
#
# Get the printable fragment of the input stream around the current offset.
#
static [string] CurrentString() {
if ([tokenizer]::offset -ge [tokenizer]::string.length) {
return "<EOF>"
}
elseif ([tokenizer]::string.length -lt [tokenizer]::offset+21) {
return [tokenizer]::string.substring([tokenizer]::offset)
}
else {
return -join ([tokenizer]::string[
[tokenizer]::Offset .. ([tokenizer]::offset+20)])
}
}
static [string] PositionMessage () {
return [tokenizer]::PositionMessage($null)
}
#
# Compute and return a position message such that the position associated with
# an error is indicated.
#
static [string] PositionMessage ([Token] $token) {
try {
$toffset = if ($token) { $token.Index } else { [tokenizer]::offset }
$src = if ($token) { $token.Src } else { [tokenizer]::string }
if ($toffset -ge $src.Length) {
$toffset = $src.Length-1
}
if ($token) {
$lineNumber = $token.LineNo
}
else {
# compute the line number by walking back through the text
$back = $toffset
$lineNumber = 0
while ($back -gt 0) {
if ($src[$back] -eq "`n") {
$linenumber++
}
$back--
}
}
# find the beginning of the line
$back = $toffset
while ($back -gt 0) {
if ($src[$back] -eq "`n") {
if ($back -lt $toffset) {
$back++
}
break;
}
$back--
}
# And the end
$forward = $toffset
while ($forward -lt $src.length) {
if ($src[$forward] -eq "`n") {
break
}
$forward++
}
$beforeString = $src.Substring($back, $toffset - $back)
$afterString= $src.Substring($toffset, $forward-$toffset)
# BUGBUGBUG - there should be no exception here
try {
if ($token.FileName) {
return "$($token.FileName):$($lineNumber+1): $beforeString>>>$afterString"
}
else {
return "Line $($lineNumber+1): $beforeString>>>$afterString"
}
}
catch {
return "Line $($lineNumber+1): $beforeString>>>$afterString"
}
}
catch {
$_ | Format-List -force * | Out-Host
$_.Exception | Out-Host
$token | Out-Host
return "<PositionMessage failed>"
}
}
}
###########################################################
#
# Exception class used as the base for all Tiny exceptions
#
class TinyException : Exception {
# The PowerShell error record associated with this error message.
[System.Management.Automation.ErrorRecord]
$ErrorRecord
# The exception associated with this error. May be null.
# If $ErrorRecord is non-null, then this should be the same
# as $ErrorRecord.Exception
[Exception]
$Exception
# The token associated with this error
[Token]
$Token
# The PowerShell script stack
[string]
$StackTrace
TinyException ([string] $message, [Token] $Token) : base($message) {
$this.Token = $token
$this.StackTrace = (Get-PSCallStack) -join "`n"
}
TinyException ([Exception] $exception, [Token] $Token) : base($exception.message) {
$this.Token = $token
$this.Exception = $exception
$this.StackTrace = (Get-PSCallStack) -join "`n"
}
TinyException( [ErrorRecord] $errorRecord, [Token] $token) : base($errorRecord.Exception.Message) {
$this.Token = $token
$this.ErrorRecord = $errorRecord
$this.Exception = $errorRecord.Exception
$this.StackTrace = $errorRecord.ScriptStackTrace.ToString()
}
[string] ToString() {
$msg = $this.Message
if ([Tiny]::DetailedErrors) {
$msg += "`n" + $this.StackTrace
if ($this.Exception) {
$msg += "`n----------------------------------------`n" +
$this.Exception | Format-List -Force * | Out-String
}
}
return "ERROR: $msg`n$([tokenizer]::PositionMessage($this.token))"
}
[string] DetailedError() {
$old = [tiny]::DetailedErrors
[tiny]::DetailedErrors = $true
$msg = ''
try {
$msg = $this.ToString()
}
finally {
[Tiny]::DetailedErrors = $old
}
return $msg
}
}
#
# Utility function for creating Tiny errors
#
function ErrorMessage ($msgOrErrorRecord, [Token] $token = $null, [switch] $dummy) {
if ($dummy -and $null -eq $token) {
# Generate a dummy token to record the position
$token = [Token]::new()
}
$err = [TinyException]::New($msgOrErrorRecord, $token)
[scopes]::scopes[-1]['TinyError'] = $err
$global:TinyError = $err
throw $err
}
###################################################################################
#
# This exception is thrown when the runtime fails to bind the function parameters
# during a function call. This is typically due to a failed pattern match or
# type constraint mismatch.
#
class BindException : TinyException
{
BindException ([string] $message, [Token] $Token) : base($message, $token) { }
BindException ([Exception] $exception, [Token] $Token) : base($exception, $token) { }
BindException( [ErrorRecord] $errorRecord, [Token] $token) : base($errorRecord, $token) { }
}
###################################################################################
#
# This exception is thrown when the text being parsed is correct but incomplete.
#
class IncompleteParseException : TinyException
{
IncompleteParseException ([string] $message, [Token] $Token) : base($message, $token) { }
IncompleteParseException ([Exception] $exception, [Token] $Token) : base($exception, $token) { }
IncompleteParseException ( [ErrorRecord] $errorRecord, [Token] $token) : base($errorRecord, $token) { }
}
#
# Utility function for throwing incomplete parse exceptions
#
function parseError ($msg, $token = $null) {
# Generate a dummy token to record the position
if ($null -eq $token) {
$token = [Token]::new()
}
$err = [IncompleteParseException]::New($msg, $token)
throw $err
}
###################################################################################
#
# The Tiny expression tree node classes. These classes constitute the executable representation
# of a Tiny script. A script is compiled directly into these Expression classes without building
# an intermediate AST. Evaluation is done by calling the eval() function on the root of the
# expression tree which then recursively evaluates the rest of the tree.
#
#
# The base class for all expressions in Tiny.
#
class Expression
{
[Token]
$Token
Visit($invokable) {
$invokable.Invoke($this)
}
[object] Eval() { throw "Expression: This method must be overridden in the derived class." }
}
###################################################################################
#
# Base class for LValue (assignable) expressions like variables, array elements, etc.
#
class Assignable : Expression
{
Set( $object ) { throw "Assignable: This method must be overridden in the derived class." }
[object] $InitialValue = [AutomationNull]::Value
}
###################################################################################
#
# The base class for all literals (strings, numbers, etc.)
#
class LiteralBase : Expression { }
###################################################################################
#
# Literal value expression
#
class Literal : LiteralBase
{
[object]
$Value
Literal ([Token] $token, $value) {
$this.token = $token
$this.value = $value
}
[object] Eval() { return $this.Value }
[string] ToString() { return "[Literal($($this.Value))]" }
}
###################################################################################
#
# Pattern R-value expression
#
class PatternLiteral : Expression
{
[object]
$Value
PatternLiteral ([Token] $token, $value) {
$this.token = $token
$this.value = $value
}
[object] Eval() { return $this.Value.Eval() }
[string] ToString() { return "[PatternLiteral($($this.Value))]" }
}
###################################################################################
#
# Represents a double-quoted string with expandable elements e.g. <pre>"Hi $name, today is ${getdate().DayOfWeek}"</pre>
#
#T ExpandString_Test1 a = 1; "$a" == '1'
#T ExpandString_Test2 a = 10; " $a " == ' 10 '
#T ExpandString_Test3 aaa = 10; bee = 20; "[$aaa,$bee]" == '[10,20]'
#T ExpandString_Test4 aaa = '$tinyhome'; "aaa=$aaa" == 'aaa=$tinyhome' # make sure no recursive expansion
#T ExpandString_Test5 "2+3=${2+3}" == '2+3=5'
#T ExpandString_Test6 "The sum is ${[1..10].sum()}." == 'The sum is 55.'
#BUGBUGBUG - only limited support of lambdas inside ${ ... } (only one level of nested parens.)
#T ExpandString_Test7 "abc ${ [1..10].sum{it} }" == 'abc 55'
# Also see LiteralString_ tests.
class ExpandableString : Expression {
[string]
$String
ExpandableString ([Token] $token, $string) {
$this.Token = $token
$this.String = $string
}
[object] Eval() {
return [ExpandableString]::ExpandStr($this.String)
}
# BUGBUGBUG - should do both variables and expressions in one pass
static [string] ExpandStr($str) {
# process variables first
$matches = @([Regex]::Matches($str, '\$([a-z_][0-9a-z_]*)|\$\{([^{]*\{[^}]*\}[^}]*|[^}]*)\}', 'CultureInvariant,Ignorecase'))
[array]::Reverse($matches)
foreach ($m in $matches) {
if ($name = $m.Groups[1].Value) {
$val = [scopes]::GetVariable($name)
$str = $str.substring(0, $m.Index) + $val +
$str.Substring($m.Index + $m.Length)
}
else {
# process expressions next
$expr = $m.Groups[2].Value
$str = $str.substring(0, $m.Index) +
[tiny]::evalexpr($expr) +
$str.Substring($m.Index + $m.Length)
}
}
return $str
}
}
###################################################################################
#
# Regex literal expression
#
class RegexLiteral : LiteralBase
{
[Regex]
$Value
[string]
$VarToSet
RegexLiteral ([Token] $token, [string] $varToSet, $pattern) {
if ($pattern -isnot [regex]) {
$pattern = [regex]::new([string] $pattern, 'CultureInvariant,Ignorecase')
}
$this.token = $token
$this.VarToSet = if ($VarToSet.Length -gt 0) { $varToSet } else { 'matches' }
$this.value = $pattern
}
[object] Eval() { return $this }
[bool] Match ([string] $str) {
$m = $this.Value.Match($str)
if ($m.Success) {
[scopes]::scopes[0][$this.VarToSet] = [MatchStatement]::GroupsToHash($m)
return $true
}
else {
return $false
}
}
[string] ToString() { return [string] $($this.Value) }
}
###################################################################################
#
# Variable or function name expression
#
class Variable : Assignable
{
# The name of the associated variable.
[string]
$Name
Variable ([Token] $token) {
$this.token = $token
$this.name = $token.value
}
# Get's the value of the variable associated with this node
[object] Eval() {
try {
return [scopes]::GetVariable($this.Name)
}
catch {
errormessage $_ $this.token
}
# Here to shut up the compiler; will never be run
return $null
}
# Set's the value of the variable associated with this node.
# The return value is used in pattern matching to decide if the match succeeded
[bool] Set ($value) {
[scopes]::SetVariable($this.Name, $value)
# In the normal case, setting a variable always succeedes
return $true
}
[string] ToString() { return $this.Name }
}
###################################################################################
#
# Implementation of a readonly variable
#
class ReadonlyVariable : Variable {
ReadonlyVariable ([Token] $token) :base($token) { }
[bool] Set ($value) {
# Quietly don't set readonly variables but still return success
return $true
}
[string] ToString() { return "[ReadOnly] $($this.Name)" }
}
###################################################################################
#
# Implementation of a type-constrained variable
#
class TypeConstrainedVariable : Variable {
TypeConstrainedVariable ([Token] $token, [Type] $typeConstraint) : base($token) {
$this.TypeConstraint = $typeConstraint
}
# Optional type constraint for the variable node
[type]
$TypeConstraint
[bool] Set ($value) {
# Enforce type constraints which are strict in Tiny. The object being assigned must be exactly that type
if ($null -ne $this.TypeConstraint -and $value -isnot $this.TypeConstraint) {
#BUGBUGBUG - this would always silently fail when it really only should do so in a pattern...
return $false
# throw [BindException]::New("Binding value '$value' to variable '[<$($this.TypeConstraint)>] $($this.name)' failed.", $this.Token)