/
kitchen_sink.ds
819 lines (717 loc) · 20.3 KB
/
kitchen_sink.ds
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
# The Doomsday Engine Project
#
# Copyright (c) 2009-2017 Jaakko Keränen <jaakko.keranen@iki.fi>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
# ================
# THE KITCHEN SINK
# ================
# This script tests *all* features of the Doomsday Script Language.
# Behold its power and glory.
import sections
# ---------------------------------------------------------------------------
sections.begin('BASIC EXPRESSIONS')
sections.subsection('Basic types (number, text, array, dictionary, time).')
print 5, 5.5, -3.141592657
print 0x100, 0X123
print 'Using underscores for readability: %x' % 0x0012_3456
print "Hello", 'World'
print """I can span
newlines."""
print [1, 2, 3]
print [1, [2, 3], 4]
print {'a': 10, 'b': Pi}
print {'a': 'b', 1: ['b', {5:6, 6:7}], ['array', 'as', 'key']: 'oh my'}
print 'The time is now:', Time()
sections.subsection('Constants: True, False, None, Pi.')
print True, False, None, Pi
sections.subsection('Built-in functions: len(), dictkeys(), dictvalues().')
print 'len("abcd") =', len("abcd")
print 'len([1, 2, 3, 4]) =', len([1, 2, 3, 4])
print 'len({1:2, 3:5, 8:13}) =', len({1:2, 3:5, 8:13})
print 'dictkeys({1:2, 3:5, 8:13}) =', dictkeys({1:2, 3:5, 8:13})
print 'dictvalues({1:2, 3:5, 8:13}) =', dictvalues({1:2, 3:5, 8:13})
sections.subsection('Built-in functions: Text(), Number(), Time(), timedelta().')
print Text(123), Number("123")
print "Beginning of March 2011:", Time("2011-03-01")
print Time("2000-01-02 03:04:05.678")
print 'Invalid time:', Time("123-123"), Time("")
print 'Thousand seconds later:', timedelta(Time(), Time() + 1000)
sections.subsection('Built-in functions: serialize() and deserialize().')
a = [1, 'One', {1:'One'}]
print 'a =', a
b = serialize(a)
print 'serialize(a) =', b
print 'deserialize(serialize(a)) =', deserialize(b)
del a, b
sections.subsection('Built-in function: eval().')
a = eval(""" 'arg' + 'ument' """)
eval("""print "Printed from eval(): %s" % a""")
# ---------------------------------------------------------------------------
sections.begin('OPERATOR EXPRESSIONS')
sections.subsection('Operators: +')
print 'Numbers:', 1 + 1, -.5 + .5
print 'Larger than 32-bit:', 0xffffffffff + 0xffffffffff
print 'Text:', 'Hello' + 'World'
print 'Array:', [1, 2, 3] + ['a', 'b', 'c']
print 'Dictionary:', {1:2, 3:4} + {'a':'b', 'c':'d'}
print 'Time:', Time() + 3600
sections.subsection('Operators: -')
print 'Numbers:', 1 - 1, -.5 - .5
print 'Larger than 32-bit:', 0xffffffffff - 0xffffffffff
print 'Dictionary:', {'a':'A', 'b':'B'} - 'a'
print 'Time:', Time() - 3600, timedelta(Time(), Time() - 3600)
sections.subsection('Operators: *')
print 'Numbers:', 1 * 2, 2.5 * 4, (2 + 6) * 45
print 'Text:', 'Word' * 3, 'Longword' * 3.5
sections.subsection('Operators: /')
print 'Numbers:', 2 / 2, 10 / 4, 1 / 0
print 'Path concatenation:', 'folder' / 'filename.ext', 'folder/' / 'filename.ext'
sections.subsection('Operators: %')
print 'Numbers:', 7 % 3
print 'String formatting:', \
'%s with "%3i" arguments. Hex %x, capital hex %X, float %f, precision %.10f.' % [
'Formatted', 2, 240, 240, Pi, Pi]
print 'More formatting: Width and precision: "%10.5f"' % Pi
sections.subsection('Operators: +=, -=, *=, /=, %=')
a = 1
print 'a =', a
print 'a =', a += 3
print 'a =', a -= 3
print 'a =', a *= 100
print 'a =', a /= 10
print 'a =', a %= 3
print 'a =', a
path = '/some/path/'
print 'path =', path
print 'path =', path /= 'filename.ext'
print 'path =', path
sections.subsection('Operators: []')
transports = ['planes', 'trains', 'automobiles', 'bicycles']
print transports[2]
xlat = {'hi': 'hello', 'globe': 'world'}
print xlat['hi'], xlat['globe']
matrix = [[1, 2], [3, 4]]
print 'Two level indexing:', matrix[0][1], matrix[1][1]
matrix2 = [matrix, matrix]
print 'Three level indexing:', matrix2[1][1][0], 'from', matrix2
sections.subsection('Operators: slice.')
fullArray = [1, 2, 3, 4, 5, 6, 7]
print 'Full:', fullArray
print 'Sliced:', fullArray[2:4], fullArray[3:], fullArray[:3]
print 'Nega-sliced:', fullArray[-4:-2]
print 'Reversing:', fullArray[::-1]
print 'Reverse slice:', fullArray[4:2:-1]
print 'Stepping:', fullArray[::2], fullArray[1:6:2]
print 'Text can be sliced as well...'
fullString = "abcdefg"
print 'Full:', fullString
print 'Sliced:', fullString[2:4], fullString[3:], fullString[:3]
print 'Nega-sliced:', fullString[-4:-2]
print 'Reversing:', fullString[::-1]
print 'Reverse slice:', fullString[4:2:-1]
print 'Stepping:', fullString[::2], fullString[1:6:2]
sections.subsection('Operators: not.')
print not True
print not False
print not 'Is this true?'
sections.subsection('Operators: and/or.')
print True and True
print True and False
print True or True
print True or False
print False or False
print "'and' has higher precedence than 'or':", True and False or True
print 'and/or have early termination:'
def returnValue(a)
print '- called with', a
return a
end
print 'True and True:'
if returnValue(True) and returnValue(True): pass
print 'False and True:'
if returnValue(False) and returnValue(True): pass
print 'False or True:'
if returnValue(False) or returnValue(True): pass
print 'True or True:'
if returnValue(True) or returnValue(True): pass
sections.subsection('Operators: comparisons.')
print 'Numbers:', 1 > 3, 1 < 3, 2 >= 2, 4 >= 2, 2 <= 2, 4 <= 2
print 'Text:', "hello" > "world", "hello" < "world", 'hello' == 'hello'
print 'True/False:', True == True, True != False
print 'Arrays:', [1, 0] == [1, 0], [1, 0] < [1, 1], [1, 0] > [1, 1], [2, 0] > [1, 0], [2, 0] < [1, 0]
sections.subsection('Operators: in.')
print 'transports =', transports
if 'bicycles' in transports: print "Got a bicycle."
if not 'jet' in transports: print "No jet."
# ---------------------------------------------------------------------------
sections.begin('STATEMENTS & COMPOUNDS')
sections.subsection('Separating statements with semicolon.')
print 'Statement 1.'; print 'Statement 2.'
sections.subsection('if/elsif/else statements.')
if True
end
if True
if True
if True
if True
end
end
end
end
if True
print 'Regular compound.'
else
print "You won't see this."
end
if True: print "One statement compound."
else: print "Not printed."
if True
print "Compound A"
if False
print "Compound B"
else: print "Compound C"
end
if False: print "Lots of useless stuff here"
elsif True
print "From the elsif"
end
if False
print 'a)'
elsif False
print 'b)'
elsif True > False
print 'c)'
end
print 'After the a), b), c)'
if True: print 'Everything on one line.'; else: print 'Goes unseen.'
if False; print 'Goes unseen again.'; else; print 'And with semicolons (requires "end").'; end
sections.subsection('Assign statement.')
print 'Assigning 10 to i...'
i = 10
print '...and i ==', i
i = 'abc'
print "Now i ==", i
sections.subsection('Assign statement: assigning into elements.')
array = [1, 2, 3, 4]
originalArray = array # by value
print array
array[1] = 100
print array
array[1] = ['a', 'b', 'c']
print array
array[1][1] = 'Bee'
print array
array[1] = {1:2, 'Three':4}
print array
array[1][4] = 'Four'
print array
array[2] = array[1]
print array
array[2]['Three'] = '300'
print array
print originalArray
sections.subsection('Assign statement: weak assignment with ?=.')
print "'z' in locals():", 'z' in locals()
z ?= 3
print "'z' in locals():", 'z' in locals()
print 'z =', z
print 'Trying weak assignment: z ?= 10'
z ?= 10
print 'z =', z
sections.subsection('Assign statement: const assignment to make read-only variables.')
z = 1
print 'z =', z
const z = 10
print 'z has been consted to', z
try
z = 10
print 'It is allowed to reassign the same value...'
z = 5
catch ReadOnlyError
print 'Have to delete z before its value can change.'
end
del z
z = 2
print 'Now z =', 2
sections.subsection('Delete statement: deleting identifiers.')
def funky()
i = 1
k = 2
print locals()
del i
print 'After deletion:'
print locals()
end
funky()
del funky
sections.subsection('while statement.')
i = 5
while i > 0
print 'Still looping because %i > 0' % i
i -= 1
end
sections.subsection('break statement.')
while True
print "I won't stay here."
break
print "Jumped over me."
end
print "Out of the while."
while False: print "Never going in."
while True
while True
print "Uh-oh, now I'm in trouble!"
break 2
end
end
print "Guess again!"
sections.subsection('for statement.')
for i in ['planes', 'trains', 'automobiles']
print "I would like:", i
end
print 'Value of i after the "for" loop is', i
sections.subsection('continue statement.')
i = 3
while i > 0
print 'i =', i
i -= 1
if i == 1: continue
print 'Bottom of loop.'
end
for i in ['planes', 'trains', 'automobiles']
if i == 'trains': continue
print i, 'are cool!'
end
sections.subsection('pass statement: no operation.')
if True: print "'Tis true."; else: pass
# ---------------------------------------------------------------------------
sections.begin('EXCEPTIONS')
sections.subsection('Simple try/catch.')
try: print 'Nothing thrown yet.'
catch: print 'Skipped.'
try: throw "OMG!"
catch: print 'Whoa there.'
try
throw "OMG!"
catch
print 'Not so fast!'
end
try: throw "OMG!"
catch Error
print 'Hold your horses.'
end
try
throw "OMG!"
catch Error: print "Whatcha tryin' to pull?"
sections.subsection('Minimal catch.')
try: throw 'OMG!'
catch: pass
sections.subsection('Assigning exception message to local variable.')
try: throw "OMG!"
catch Error, er
print 'Caught:', er
end
try: throw "OMG!"
catch Error, er: print 'Caught:', er
sections.subsection('Nesting try/catch statements.')
try
try
try
throw 'Deep.'
catch BogusError
end
catch BogusError
end
catch Error, er: print 'Got it:', er
try
try
try
throw 'Deep 2.'
catch BogusError
end
catch BogusError: pass
try
catch Error, er
print 'Should *not* be caught here.'
end
catch Error, er
print 'Should be caught here:', er
end
sections.subsection('Throwing exception in a function.')
def erroneous()
throw "I can't handle the truth!"
end
try
print "Calling erroneous()"
erroneous()
try
print 'This will be skipped!'
catch
print 'I am on the wrong catch level.'
end
catch
print 'Fumbled it...'
end
sections.subsection('Catching a specific type of exception.')
try
record temp
reference = temp
del temp
print reference
catch NullError, er
print 'Oh noes:', er
end
sections.subsection('Multiple catch statements.')
try
throw 'For the 2nd catch.'
catch NullError: print 'Got NullError'
catch Error, er: print er
catch: print 'Never here.'
sections.subsection('Exception thrown in another module.')
try
sections.throwError()
catch Error, er
print 'Got error from another module:', er
end
sections.subsection('Exception thrown in recursive call.')
def recursive(i)
print i
if i == 10: throw 'Reached 10!'
recursive(i + 1)
end
try
recursive(1)
catch Error, er
print er
end
sections.subsection('Exception from trying to change a read-only variable.')
const SOME_CONSTANT = 3.1415
print 'SOME_CONSTANT =', SOME_CONSTANT
try
SOME_CONSTANT = 3
catch ReadOnlyError, er
print 'Cannot do it.', er
end
try
const SOME_CONSTANT = 3
catch ReadOnlyError, er
print 'Will not work either:', er
end
# ---------------------------------------------------------------------------
sections.begin('RECORDS')
sections.subsection('Creating a record with a statement.')
record myrec
print len(myrec)
print "Alternative way using Record()."
del myrec
myrec = Record()
print len(myrec)
sections.subsection('Creating a record using an expression.')
del myrec
(record myrec).expressionCreated = True
myrec.(record subexp).alsoExpCreated = True
print myrec
del myrec.subexp
sections.subsection('Creating variables into a record.')
myrec.newMember = 100
print len(myrec)
print 'myrec.newMember =', myrec.newMember
print "Here's the record:"
print myrec
sections.subsection('Creating a subrecord.')
record myrec.subrec
print len(myrec), len(myrec.subrec)
const myrec.subrec.something = 200
try
myrec.subrec.something = 201
print 'THIS IS AN ERROR -- EXCEPTION SHOULD HAVE BEEN THROWN! --'
catch ReadOnlyError, er
print 'Cannot change const member.'
print er
end
print 'myrec.subrec.something =', myrec.subrec.something
print "Here's the record:"
print myrec
sections.subsection('Checking whether members exist in record.')
print 'subrec' in myrec, 'newMember' in myrec, 'not-there' in myrec.subrec
sections.subsection('Built-in functions: members(), subrecords().')
print 'members of myrec:', members(myrec)
print 'subrecords of myrec:', subrecords(myrec)
sections.subsection('Alternative ways to access members and subrecords.')
print myrec['newMember']
print myrec['subrec']
print myrec['subrec']['something']
print members(myrec)['newMember']
sections.subsection('Creating new members using [].')
myrec['assignedElement'] = 3000
print myrec
sections.subsection('Copying members using recutil.')
import recutil
record copyTarget
recutil.copyMissingMembers(myrec, copyTarget)
print "Copied:\n", copyTarget
del recutil
sections.subsection('Having two variables reference the same record.')
reference = myrec
print len(reference)
reference.otherMember = 150
print "Here's the record:"
print myrec
reference.memberViaRef = 'added via ref'
print "Added a member via a reference:"
print reference
sections.subsection('Accessing members through a record reference.')
record other
other.refd = reference
print 'The other is:'
print other
other.refd.newMember = 300
print 'myrec after modifications:'
print myrec
sections.subsection('Making a copy of a record.')
def recCopyTest()
print "Record() can be used to make a copy of a record."
reference = Record(myrec)
print reference
print "Now we can modify the new record without affecting myrec."
reference.superGreat = 'wow'
del reference.subrec
print reference
print "Original:"
print myrec
print "Locals:"
print locals()
end
recCopyTest()
sections.subsection('Deleting members from record.')
print 'Before deleting:'
print myrec
del myrec.subrec.something
print 'After deleting:'
print myrec
print "subrec isn't gone, though: len(myrec.subrec) =", len(myrec.subrec)
sections.subsection('Deleting a record pointed to by two variables.')
record soonDeleted
reference = soonDeleted
del soonDeleted
try: print reference
catch Error, er: print "Can't print reference:", er
del reference
sections.subsection('Serializing records.')
print 'serialize(myrec) =', serialize(myrec)
print 'deserialize(serialize(myrec)) ='
print deserialize(serialize(myrec))
# ---------------------------------------------------------------------------
sections.begin('FUNCTIONS')
sections.subsection('Defining a function (empty body).')
def func1(): return
func1()
def func1b()
end
func1b()
sections.subsection('Returning values from the function.')
def func2(): return 'World'
print 'Hello', func2()
def func2b(a)
if a
return "It is true!"
else
return "Nay, it is false."
end
end
print func2b(1), func2b(''), func2b(True), func2b(False)
sections.subsection('Returning a record from a function.')
def recFunc()
record a
a.value = "recFunc"
return a
end
try: print recFunc()
catch NullError
print "Records are passed by reference; the returned record went out of scope."
end
del recFunc
def recFunc()
record a
a.value = "recFunc"
return Record(a)
end
print "Let's try again, making a copy for the return value."
print recFunc()
del recFunc
sections.subsection('Passing arguments.')
a = 'At process scope.'
def func3(a, b, c)
print 'The arguments were:', a, b, c
return b
end
print 'returned:', func3(1, 2, 3)
print a
sections.subsection('Passing record as argument.')
myrec.passed = 'Original'
print 'myrec.passed =', myrec.passed
def recArg(r)
r.passed = 'Changed'
end
recArg(myrec)
print 'myrec.passed =', myrec.passed
sections.subsection('Default values to function arguments.')
def func4(a, b='default', c=100)
print 'Given:', a, b, c
end
func4(1)
func4(1, 2)
func4([1,2], c='world', b='hello')
print 'func4 =', func4
sections.subsection('Defining function in a record.')
def myrec.func5(a, b)
return a + b
end
print myrec.func5("The record is\n", Text(myrec))
sections.subsection('Defining a function within a function.')
def func6()
print 'Inside func6.'
print 'func2() =', func2()
def func2(): return 'Shadows the global level.'
print 'func2() =', func2()
end
func6()
print 'func2() =', func2()
sections.subsection("Accessing function's locals within a subfunction.")
def func7()
a = 100
print 'Inside func7: a =', a
def func()
print 'Inside func: a =', a
end
func()
end
func7()
sections.subsection('Reference to function.')
reference = func2
print 'func2() =', func2()
print 'reference() =', reference()
print 'reference =', reference
sections.subsection('Callback function as argument.')
def doCallback(a, b, cb)
print cb(a, b)
end
doCallback(10, 15, myrec.func5)
sections.subsection('Returning a local function from a function.')
a = 'Process scope.'
def testfun()
a = 'testfun() scope.'
def returningFunc()
print 'I come from another place.', a
end
returningFunc() # 'a' found in local namespace
return returningFunc
end
testfun()() # 'a' found in global namespace! (testfun()'s local scope does not exist here)
ar = [testfun]
ar[0]()()
# ---------------------------------------------------------------------------
sections.begin('SCOPES')
sections.subsection('Global assignment with :=.')
a = 1
print 'a =', a
def normalAssign()
a = 2
print 'in normalAssign(), a =', a
end
normalAssign()
print 'a =', a
def globalAssign()
a := 2
print 'in globalAssign(), a =', a
end
globalAssign()
print 'a =', a
sections.subsection('Exporting variable from a function.')
def exporting()
abc = 'Value from exporting()'
export abc
end
abc = 'Value in global namespace'
print 'Before: abc =', abc
exporting()
print 'After: abc =', abc
sections.subsection('Exporting a record.')
def exporting2()
record bunny
bunny.ear = 'value'
export bunny
end
exporting2()
print 'bunny =', bunny
sections.subsection('Exporting while assigning.')
del abc
def exporting3()
export abc = 'Value from exporting3()'
end
exporting3()
print 'abc =', abc
sections.subsection('Built-in function locals() returns the local namespace as a record.')
print 'At global level:'
print locals()
print
print 'Within a function:'
def func8()
justMe = "Function's local namespace."
print locals()
end
func8()
sections.subsection('Importing modules: built-in module Config.')
import Config
print "Here's the Config:"
print Config
sections.subsection('Serializing namespaces.')
sns = serialize(locals())
print 'sns =', sns
print 'That deserializes into:'
dsns = deserialize(sns)
print dsns
print 'Calling deserialized function...'
print dsns.func3(1, 2, 3)
print 'Calling deserialized function that throws an exception...'
try: dsns.erroneous(); catch: print 'Caught.'
del dsns
sections.subsection('Serializing record references.')
def recordRefTest()
record hello
hello.entry = 'World'
record hello.subrec
hello.subrec.another = 123
hello.recref = hello.subrec
print 'Original record:'
print hello
hello.subrec.another = 456
print 'Modified:'
print hello
print 'After serialization:'
print deserialize(serialize(hello))
end
recordRefTest()
sections.subsection('Importing modules: import record.')
print 'Getting rid of the imported sections module (which is just a reference).'
print "Note that this has no effect on sections's own namespace."
del sections
print 'import record sections'
import record sections
print 'The sections namespace has become a local record.'
print locals()
# ---------------------------------------------------------------------------
sections.begin('SCRIPT RETURN VALUE')
sections.subsection('Returning value from the script: the final expression.')
"I am the return value."