forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCalculus.lisp
3107 lines (2636 loc) · 139 KB
/
Calculus.lisp
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 contents of this file are subject to the Netscape Public License
;;; Version 1.0 (the "NPL"); you may not use this file except in
;;; compliance with the NPL. You may obtain a copy of the NPL at
;;; http://www.mozilla.org/NPL/
;;;
;;; Software distributed under the NPL is distributed on an "AS IS" basis,
;;; WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL
;;; for the specific language governing rights and limitations under the
;;; NPL.
;;;
;;; The Initial Developer of this code under the NPL is Netscape
;;; Communications Corporation. Portions created by Netscape are
;;; Copyright (C) 1998 Netscape Communications Corporation. All Rights
;;; Reserved.
;;;
;;; ECMAScript semantic calculus
;;;
;;; Waldemar Horwat ([email protected])
;;;
(defvar *trace-variables* nil)
#+mcl (dolist (indent-spec '((production . 3) (rule . 2) (function . 1) (letexc . 1) (deftype . 1) (tuple . 1) (%text . 1)))
(pushnew indent-spec ccl:*fred-special-indent-alist* :test #'equal))
; A strict version of and.
(defun and2 (a b)
(and a b))
; A strict version of or.
(defun or2 (a b)
(or a b))
; A strict version of xor.
(defun xor2 (a b)
(or (and a (not b)) (and (not a) b)))
(defun digit-char-36 (char)
(assert-non-null (digit-char-p char 36)))
;;; ------------------------------------------------------------------------------------------------------
;;; DOUBLE-PRECISION FLOATING-POINT NUMBERS
(deftype double ()
'(or float (member :+inf :-inf :nan)))
(defun double? (n)
(or (floatp n)
(member n '(:+inf :-inf :nan))))
; Evaluate expr. If it evaluates successfully, return its values.
; If not, evaluate sign; if it returns a positive value, return :+inf;
; otherwise return :-inf. sign should not return zero.
(defmacro handle-overflow (expr &body sign)
`(handler-case ,expr
(floating-point-overflow () (if (minusp (progn ,@sign)) :-inf :+inf))))
(defun rational-to-double (r)
(handle-overflow (coerce r 'double-float) r))
; Return true if n is +0 or -0 and false otherwise.
(declaim (inline double-is-zero))
(defun double-is-zero (n)
(and (floatp n) (zerop n)))
; Return true if n is NaN and false otherwise.
(declaim (inline double-is-nan))
(defun double-is-nan (n)
(eq n :nan))
; Return true if n is :+inf or :-inf and false otherwise.
(declaim (inline double-is-infinite))
(defun double-is-infinite (n)
(or (eq n :+inf) (eq n :-inf)))
; Return:
; less if n<m;
; equal if n=m;
; greater if n>m;
; unordered if either n or m is :nan.
(defun double-compare (n m less equal greater unordered)
(cond
((or (double-is-nan n) (double-is-nan m)) unordered)
((eql n m) equal)
((or (eq n :+inf) (eq m :-inf)) greater)
((or (eq m :+inf) (eq n :-inf)) less)
((< n m) less)
((> n m) greater)
(t equal)))
; Return
; 1 if n is +0.0, :+inf, or any positive floating-point number;
; -1 if n is -0.0, :-inf, or any positive floating-point number;
; 0 if n is :nan.
(defun double-sign (n)
(case n
(:+inf 1)
(:-inf -1)
(:nan 0)
(t (round (float-sign n)))))
; Return
; 0 if either n or m is :nan;
; 1 if n and m have the same double-sign;
; -1 if n and m have different double-signs.
(defun double-sign-xor (n m)
(* (double-sign n) (double-sign m)))
; Return the absolute value of n.
(defun double-abs (n)
(case n
((:+inf :-inf) :+inf)
(:nan :nan)
(t (abs n))))
; Return -n.
(defun double-neg (n)
(case n
(:+inf :-inf)
(:-inf :+inf)
(:nan :nan)
(t (- n))))
; Return n+m.
(defun double-add (n m)
(case n
(:+inf (case m
(:-inf :nan)
(:nan :nan)
(t :+inf)))
(:-inf (case m
(:+inf :nan)
(:nan :nan)
(t :-inf)))
(:nan :nan)
(t (case m
(:+inf :+inf)
(:-inf :-inf)
(:nan :nan)
(t (handle-overflow (+ n m)
(let ((n-sign (float-sign n))
(m-sign (float-sign m)))
(assert-true (= n-sign m-sign)) ;If the signs are opposite, we can't overflow.
n-sign)))))))
; Return n-m.
(defun double-subtract (n m)
(double-add n (double-neg m)))
; Return n*m.
(defun double-multiply (n m)
(let ((sign (double-sign-xor n m))
(n (double-abs n))
(m (double-abs m)))
(let ((result (cond
((zerop sign) :nan)
((eq n :+inf) (if (double-is-zero m) :nan :+inf))
((eq m :+inf) (if (double-is-zero n) :nan :+inf))
(t (handle-overflow (* n m) 1)))))
(if (minusp sign)
(double-neg result)
result))))
; Return n/m.
(defun double-divide (n m)
(let ((sign (double-sign-xor n m))
(n (double-abs n))
(m (double-abs m)))
(let ((result (cond
((zerop sign) :nan)
((eq n :+inf) (if (eq m :+inf) :nan :+inf))
((eq m :+inf) 0d0)
((zerop m) (if (zerop n) :nan :+inf))
(t (handle-overflow (/ n m) 1)))))
(if (minusp sign)
(double-neg result)
result))))
; Return n%m, using the ECMAScript definition of %.
(defun double-remainder (n m)
(cond
((or (double-is-nan n) (double-is-nan m) (double-is-infinite n) (double-is-zero m)) :nan)
((or (double-is-infinite m) (double-is-zero n)) n)
(t (float (rem (rational n) (rational m))))))
; Return d truncated towards zero into a 32-bit integer. Overflows wrap around.
(defun double-to-uint32 (d)
(case d
((:+inf :-inf :nan) 0)
(t (mod (truncate d) #x100000000))))
;;; ------------------------------------------------------------------------------------------------------
;;; SET UTILITIES
(defun integer-set-min (intset)
(or (intset-min intset)
(error "min of empty integer-set")))
(defun character-set-min (intset)
(code-char (or (intset-min intset)
(error "min of empty character-set"))))
(defun integer-set-max (intset)
(or (intset-max intset)
(error "max of empty integer-set")))
(defun character-set-max (intset)
(code-char (or (intset-max intset)
(error "max of empty character-set"))))
(defun integer-set-member (elt intset)
(intset-member? intset elt))
(defun character-set-member (elt intset)
(intset-member? intset (char-code elt)))
;;; ------------------------------------------------------------------------------------------------------
;;; CODE GENERATION
; Return `(progn ,@statements), optimizing where possible.
(defun gen-progn (&rest statements)
(if (and (= (length statements) 1)
(let ((first-statement (first statements)))
(not (and (consp first-statement)
(eq (first first-statement) 'declare)))))
(first statements)
(cons 'progn statements)))
; Return `(funcall ,function-value ,@arg-values), optimizing where possible.
(defun gen-apply (function-value &rest arg-values)
(if (and (consp function-value)
(eq (first function-value) 'function)
(consp (rest function-value))
(second function-value)
(null (cddr function-value)))
(let ((stripped-function-value (second function-value)))
(if (and (consp stripped-function-value)
(eq (first stripped-function-value) 'function)
(listp (second stripped-function-value))
(cddr stripped-function-value)
(every #'(lambda (arg)
(and (identifier? arg)
(not (eql (first-symbol-char arg) #\&))))
(second stripped-function-value)))
(let ((function-args (second stripped-function-value))
(function-body (cddr stripped-function-value)))
(assert-true (= (length function-args) (length arg-values)))
(if function-args
(list* 'let
(mapcar #'list function-args arg-values)
function-body)
(apply #'gen-progn function-body)))
(cons stripped-function-value arg-values)))
(list* 'funcall function-value arg-values)))
; Return `#'(lambda ,args (declare (ignore-if-unused ,@args)) ,body-code), optimizing
; where possible.
(defun gen-lambda (args body-code)
(if args
`#'(lambda ,args (declare (ignore-if-unused . ,args)) ,body-code)
`#'(lambda () ,body-code)))
; If expr is a lambda-expression, return an equivalent expression that has
; the given name (which may be a symbol or a string; if it's a string, it is interned
; in the given package). Otherwise, return expr unchanged.
; Attaching a name to lambda-expressions helps in debugging code by identifying
; functions in debugger backtraces.
(defun name-lambda (expr name &optional package)
(if (and (consp expr)
(eq (first expr) 'function)
(consp (rest expr))
(consp (second expr))
(eq (first (second expr)) 'lambda)
(null (cddr expr)))
(let ((name (if (symbolp name)
name
(intern name package))))
;Avoid trouble when name is a lisp special form like if or lambda.
(when (special-form-p name)
(setq name (gensym name)))
`(flet ((,name ,@(rest (second expr))))
#',name))
expr))
; Intern n symbols in the current package with names <prefix>0, <prefix>1, ...,
; <prefix>n-1, where <prefix> is the value of the prefix string.
; Return a list of these n symbols concatenated to the front of rest.
(defun intern-n-vars-with-prefix (prefix n rest)
(if (zerop n)
rest
(intern-n-vars-with-prefix prefix (1- n) (cons (intern (format nil "~A~D" prefix n)) rest))))
;;; ------------------------------------------------------------------------------------------------------
;;; GRAMMAR-INFO
(defstruct (grammar-info (:constructor make-grammar-info (name grammar &optional lexer))
(:copier nil)
(:predicate grammar-info?))
(name nil :type symbol :read-only t) ;The name of this grammar
(grammar nil :type grammar :read-only t) ;This grammar
(lexer nil :type (or null lexer) :read-only t)) ;This grammar's lexer if this is a lexer grammar; nil if not
; Return the charclass that defines the given lexer nonterminal or nil if none.
(defun grammar-info-charclass (grammar-info nonterminal)
(let ((lexer (grammar-info-lexer grammar-info)))
(and lexer (lexer-charclass lexer nonterminal))))
; Return the charclass or partition that defines the given lexer nonterminal or nil if none.
(defun grammar-info-charclass-or-partition (grammar-info nonterminal)
(let ((lexer (grammar-info-lexer grammar-info)))
(and lexer (or (lexer-charclass lexer nonterminal)
(gethash nonterminal (lexer-partitions lexer))))))
;;; ------------------------------------------------------------------------------------------------------
;;; WORLDS
(defstruct (world (:constructor allocate-world)
(:copier nil)
(:predicate world?))
(package nil :type package) ;The package in which this world's identifiers are interned
(n-type-names 0 :type integer) ;Number of type names defined so far
(types-reverse nil :type (or null hash-table)) ;Hash table of (kind tags parameters) -> type; nil if invalid
(oneof-tags nil :type (or null hash-table)) ;Hash table of (oneof-tag . field-type) -> (must-be-unique oneof-type ... oneof-type); nil if invalid
(bottom-type nil :type (or null type)) ;Subtype of all types used for nonterminating computations
(void-type nil :type (or null type)) ;Type used for placeholders
(boolean-type nil :type (or null type)) ;Type used for booleans
(integer-type nil :type (or null type)) ;Type used for integers
(rational-type nil :type (or null type)) ;Type used for rational numbers
(double-type nil :type (or null type)) ;Type used for double-precision floating-point numbers
(character-type nil :type (or null type)) ;Type used for characters
(string-type nil :type (or null type)) ;Type used for strings (vectors of characters)
(grammar-infos nil :type list) ;List of grammar-info
(commands-source nil :type list)) ;List of source code of all commands applied to this world
; Return the name of the world.
(defun world-name (world)
(package-name (world-package world)))
; Return a symbol in the given package whose value is that package's world structure.
(defun world-access-symbol (package)
(find-symbol "*WORLD*" package))
; Return the world that created the given package.
(declaim (inline package-world))
(defun package-world (package)
(symbol-value (world-access-symbol package)))
; Return the world that contains the given symbol.
(defun symbol-world (symbol)
(package-world (symbol-package symbol)))
; Delete the world and its package.
(defun delete-world (world)
(let ((package (world-package world)))
(when package
(delete-package package)))
(setf (world-package world) nil))
; Create a world using a package with the given name.
; If the package is already used for another world, its contents
; are erased and the other world deleted.
(defun make-world (name)
(assert-type name string)
(let ((p (find-package name)))
(when p
(let* ((access-symbol (world-access-symbol p))
(p-world (and (boundp access-symbol) (symbol-value access-symbol))))
(unless p-world
(error "Package ~A already in use" name))
(assert-true (eq (world-package p-world) p))
(delete-world p-world))))
(let* ((p (make-package name :use nil))
(world (allocate-world
:package p
:types-reverse (make-hash-table :test #'equal)
:oneof-tags (make-hash-table :test #'equal)))
(access-symbol (intern "*WORLD*" p)))
(set access-symbol world)
(export access-symbol p)
world))
; Intern s (which should be a symbol or a string) in this world's
; package and return the resulting symbol.
(defun world-intern (world s)
(intern (string s) (world-package world)))
; Export symbol in its package, which must belong to some world.
(defun export-symbol (symbol)
(assert-true (symbol-in-any-world symbol))
(export symbol (symbol-package symbol)))
; Call f on each external symbol defined in the world's package.
(declaim (inline each-world-external-symbol))
(defun each-world-external-symbol (world f)
(each-package-external-symbol (world-package world) f))
; Call f on each external symbol defined in the world's package that has
; a property with the given name.
; f takes two arguments:
; the symbol
; the value of the property
(defun each-world-external-symbol-with-property (world property f)
(each-world-external-symbol
world
#'(lambda (symbol)
(let ((value (get symbol property *get2-nonce*)))
(unless (eq value *get2-nonce*)
(funcall f symbol value))))))
; Return a list of all external symbols defined in the world's package that have
; a property with the given name.
; The list is sorted by symbol names.
(defun all-world-external-symbols-with-property (world property)
(let ((list nil))
(each-world-external-symbol
world
#'(lambda (symbol)
(let ((value (get symbol property *get2-nonce*)))
(unless (eq value *get2-nonce*)
(push symbol list)))))
(sort list #'string<)))
; Return true if s is a symbol that is defined in this world's package.
(declaim (inline symbol-in-world))
(defun symbol-in-world (world s)
(and (symbolp s) (eq (symbol-package s) (world-package world))))
; Return true if s is a symbol that is defined in any world's package.
(defun symbol-in-any-world (s)
(and (symbolp s)
(let* ((package (symbol-package s))
(access-symbol (world-access-symbol package)))
(and (boundp access-symbol) (typep (symbol-value access-symbol) 'world)))))
; Return a list of grammars in the world
(defun world-grammars (world)
(mapcar #'grammar-info-grammar (world-grammar-infos world)))
; Return the grammar-info with the given name in the world
(defun world-grammar-info (world name)
(find name (world-grammar-infos world) :key #'grammar-info-name))
; Return the grammar with the given name in the world
(defun world-grammar (world name)
(let ((grammar-info (world-grammar-info world name)))
(and grammar-info (grammar-info-grammar grammar-info))))
; Return the lexer with the given name in the world
(defun world-lexer (world name)
(let ((grammar-info (world-grammar-info world name)))
(and grammar-info (grammar-info-lexer grammar-info))))
;;; ------------------------------------------------------------------------------------------------------
;;; SYMBOLS
;;; The following properties are attached to exported symbols in the world:
;;;
;;; :preprocess preprocessor function ((preprocessor-state id . form-arg-list) -> form-list re-preprocess) if this identifier
;;; is a preprocessor command like 'grammar, 'lexer, or 'production
;;;
;;; :command expression code generation function ((world grammar-info-var . form-arg-list) -> void) if this identifier
;;; is a command like 'deftype or 'define
;;; :special-form expression code generation function ((world type-env id . form-arg-list) -> code, type, annotated-expr)
;;; if this identifier is a special form like 'if or 'function
;;;
;;; :primitive primitive structure if this identifier is a primitive
;;;
;;; :macro lisp expansion function ((world type-env . form-arg-list) -> expansion) if this identifier is a macro
;;;
;;; :type-constructor expression code generation function ((world allow-forward-references . form-arg-list) -> type) if this
;;; identifier is a type constructor like '->, 'vector, 'set, 'tuple, 'oneof, or 'address
;;; :deftype type if this identifier is a type; nil if this identifier is a forward-referenced type
;;;
;;; <value> value of this identifier if it is a variable
;;; :value-code lisp code that was evaluated to produce <value>
;;; :value-expr unparsed expression defining the value of this identifier if it is a variable
;;; :type type of this identifier if it is a variable
;;; :type-expr unparsed expression defining the type of this identifier if it is a variable
;;;
;;; :action list of (grammar-info . grammar-symbol) that declare this action if this identifier is an action name
;;;
;;; :depict-command depictor function ((markup-stream world depict-env . form-arg-list) -> void)
;;; :depict-type-constructor depictor function ((markup-stream world level . form-arg-list) -> void)
;;; :depict-special-form depictor function ((markup-stream world level . form-annotated-arg-list) -> void)
;;; :depict-macro depictor function ((markup-stream world level . form-annotated-arg-list) -> void)
;;;
; Return the code of the value associated with the given symbol or default if none.
; This macro is appropriate for use with setf.
(defmacro symbol-code (symbol &optional default)
`(get ,symbol :code ,@(and default (list default))))
; Return the preprocessor action associated with the given symbol or nil if none.
; This macro is appropriate for use with setf.
(defmacro symbol-preprocessor-function (symbol)
`(get ,symbol :preprocess))
; Return the macro definition associated with the given symbol or nil if none.
; This macro is appropriate for use with setf.
(defmacro symbol-macro (symbol)
`(get ,symbol :macro))
; Return the primitive definition associated with the given symbol or nil if none.
; This macro is appropriate for use with setf.
(defmacro symbol-primitive (symbol)
`(get ,symbol :primitive))
; Return the type definition associated with the given symbol.
; Return nil if the symbol is a forward-referenced type.
; If the symbol has no type definition at all, return default
; (or nil if not specified).
; This macro is appropriate for use with setf.
(defmacro symbol-type-definition (symbol &optional default)
`(get ,symbol :deftype ,@(and default (list default))))
; Return true if this symbol's symbol-type-definition is user-defined.
; This macro is appropriate for use with setf.
(defmacro symbol-type-user-defined (symbol)
`(get ,symbol 'type-user-defined))
; Call f on each type definition, including forward-referenced types, in the world.
; f takes two arguments:
; the symbol
; the type (nil if forward-referenced)
(defun each-type-definition (world f)
(each-world-external-symbol-with-property world :deftype f))
; Return a sorted list of the names of all type definitions, including
; forward-referenced types, in the world.
(defun world-type-definitions (world)
(all-world-external-symbols-with-property world :deftype))
; Return the type of the variable associated with the given symbol or nil if none.
; This macro is appropriate for use with setf.
(defmacro symbol-type (symbol)
`(get ,symbol :type))
; Return true if there is a variable associated with the given symbol.
(declaim (inline symbol-has-variable))
(defun symbol-has-variable (symbol)
(not (eq (get symbol *get2-nonce*) *get2-nonce*)))
; Return a list of (grammar-info . grammar-symbol) pairs that each indicate
; a grammar and a grammar-symbol in that grammar that has an action named by the given symbol.
; This macro is appropriate for use with setf.
(defmacro symbol-action (symbol)
`(get ,symbol :action))
;;; ------------------------------------------------------------------------------------------------------
;;; TYPES
(deftype typekind ()
'(member ;tags ;parameters
:bottom ;nil ;nil
:void ;nil ;nil
:boolean ;nil ;nil
:integer ;nil ;nil
:rational ;nil ;nil
:double ;nil ;nil
:character ;nil ;nil
:-> ;nil ;(result-type arg1-type arg2-type ... argn-type)
:vector ;nil ;(element-type)
:set ;nil ;(element-type)
:tuple ;(tag1 ... tagn) ;(element1-type ... elementn-type)
:oneof ;(tag1 ... tagn) ;(element1-type ... elementn-type)
:address)) ;nil ;(element-type)
; Return true if typekind1 is the same or more specific (i.e. a subtype) than typekind2.
(defun typekind<= (typekind1 typekind2)
(or (eq typekind1 typekind2)
(eq typekind1 :bottom)
(and (eq typekind1 :integer) (eq typekind2 :rational))))
(defstruct (type (:constructor allocate-type (kind tags parameters))
(:predicate type?))
(name nil :type symbol) ;This type's name; nil if this type is anonymous
(name-serial-number nil :type (or null integer)) ;This type's name's serial number; nil if this type is anonymous
(kind nil :type typekind :read-only t) ;This type's kind
(tags nil :type list :read-only t) ;List of tuple or oneof tags
(parameters nil :type list :read-only t)) ;List of parameter types (either types or symbols if forward-referenced) describing a compound type
(declaim (inline make-->-type))
(defun make-->-type (world argument-types result-type)
(make-type world :-> nil (cons result-type argument-types)))
(declaim (inline ->-argument-types))
(defun ->-argument-types (type)
(assert-true (eq (type-kind type) :->))
(cdr (type-parameters type)))
(declaim (inline ->-result-type))
(defun ->-result-type (type)
(assert-true (eq (type-kind type) :->))
(car (type-parameters type)))
(declaim (inline make-vector-type))
(defun make-vector-type (world element-type)
(make-type world :vector nil (list element-type)))
(declaim (inline vector-element-type))
(defun vector-element-type (type)
(assert-true (eq (type-kind type) :vector))
(car (type-parameters type)))
(declaim (inline make-set-type))
(defun make-set-type (world element-type)
(make-type world :set nil (list element-type)))
(declaim (inline set-element-type))
(defun set-element-type (type)
(assert-true (eq (type-kind type) :set))
(car (type-parameters type)))
; Return the type of the oneof's or tuple's field corresponding to the given tag
; or nil if the tag is not present in the oneof's or tuple's tags.
(defun field-type (type tag)
(assert-true (member (type-kind type) '(:oneof :tuple)))
(let ((pos (position tag (type-tags type))))
(and pos (nth pos (type-parameters type)))))
(declaim (inline make-address-type))
(defun make-address-type (world element-type)
(make-type world :address nil (list element-type)))
(declaim (inline address-element-type))
(defun address-element-type (type)
(assert-true (eq (type-kind type) :address))
(car (type-parameters type)))
; Return true if type1 is the same or more specific (i.e. a subtype) than type2.
(defun type<= (type1 type2)
(or (eq type1 type2)
(let ((kind1 (type-kind type1))
(kind2 (type-kind type2)))
(or (eq kind1 :bottom)
(and (eq kind1 :integer) (eq kind2 :rational))
(and (eq kind1 :->) (eq kind2 :->)
; For now we require the argument types to match exactly.
(equal (->-argument-types type1) (->-argument-types type2))
; This might fall into an infinite loop, but it's OK for now.
(type<= (->-result-type type1) (->-result-type type2)))))))
; Return the most specific common supertype of type1 and type2 or nil if there is none.
(defun type-lub (type1 type2)
(cond
((type<= type1 type2) type2)
((type<= type2 type1) type1)
(t nil)))
; Return true if serial-number-1 is less than serial-number-2.
; Each serial-number is either an integer or nil, which is considered to
; be positive infinity.
(defun serial-number-< (serial-number-1 serial-number-2)
(and serial-number-1
(or (null serial-number-2)
(< serial-number-1 serial-number-2))))
; Print the type nicely on the given stream. If expand1 is true then print
; the type's top level even if it has a name. In all other cases expand
; anonymous types but abbreviate named types by their names.
(defun print-type (type &optional (stream t) expand1)
(if (and (type-name type) (not expand1))
(write-string (symbol-name (type-name type)) stream)
(labels
((print-tuple-or-oneof (kind-string)
(pprint-logical-block (stream (mapcar #'cons (type-tags type) (type-parameters type))
:prefix "(" :suffix ")")
(write-string kind-string stream)
(pprint-exit-if-list-exhausted)
(format stream " ~@_")
(pprint-indent :current 0 stream)
(loop
(let ((tag-and-type (pprint-pop)))
(pprint-logical-block (stream nil :prefix "(" :suffix ")")
(write (car tag-and-type) :stream stream)
(format stream " ~@_")
(print-type (cdr tag-and-type) stream))
(pprint-exit-if-list-exhausted)
(format stream " ~:_")))
(format stream " ~_")
(print-type (->-result-type type) stream))))
(case (type-kind type)
(:bottom (write-string "bottom" stream))
(:void (write-string "void" stream))
(:boolean (write-string "boolean" stream))
(:integer (write-string "integer" stream))
(:rational (write-string "rational" stream))
(:double (write-string "double" stream))
(:character (write-string "character" stream))
(:-> (pprint-logical-block (stream nil :prefix "(" :suffix ")")
(format stream "-> ~@_")
(pprint-indent :current 0 stream)
(pprint-logical-block (stream (->-argument-types type) :prefix "(" :suffix ")")
(pprint-exit-if-list-exhausted)
(loop
(print-type (pprint-pop) stream)
(pprint-exit-if-list-exhausted)
(format stream " ~:_")))
(format stream " ~_")
(print-type (->-result-type type) stream)))
(:vector (pprint-logical-block (stream nil :prefix "(" :suffix ")")
(format stream "vector ~@_")
(print-type (vector-element-type type) stream)))
(:set (pprint-logical-block (stream nil :prefix "(" :suffix ")")
(format stream "set ~@_")
(print-type (set-element-type type) stream)))
(:tuple (print-tuple-or-oneof "tuple"))
(:oneof (print-tuple-or-oneof "oneof"))
(:address (pprint-logical-block (stream nil :prefix "(" :suffix ")")
(format stream "address ~@_")
(print-type (address-element-type type) stream)))
(t (error "Bad typekind ~S" (type-kind type)))))))
; Same as print-type except that accumulates the output in a string
; and returns that string.
(defun print-type-to-string (type &optional expand1)
(with-output-to-string (stream)
(print-type type stream expand1)))
(defmethod print-object ((type type) stream)
(print-unreadable-object (type stream)
(format stream "type ~@_")
(let ((name (type-name type)))
(when name
(format stream "~A = ~@_" name)))
(print-type type stream t)))
; Register all of the oneof type's tags in the world's oneof-tags hash table.
; The hash table is indexed by pairs (tag . field-type) and is used to look up a
; oneof type given just a tag and its field's type. The data in the hash table
; consists of lists (flag oneof-type ... oneof-type). The flag is true if such a
; lookup has been performed (in which case the data must contain exactly one oneof-type
; and it is an error to add another one).
(defun register-oneof-tags (world oneof-type)
(let ((oneof-tags-hash (world-oneof-tags world)))
(mapc #'(lambda (tag field-type)
(let* ((key (cons tag field-type))
(data (gethash key oneof-tags-hash)))
(cond
((null data)
(setf (gethash key oneof-tags-hash) (list nil oneof-type)))
((not (car data))
(push oneof-type (cdr data)))
(t (error "Ambiguous oneof lookup of tag ~A: ~A. Possibilities are ~A or ~A"
tag
(print-type-to-string field-type)
(print-type-to-string (second data))
(print-type-to-string oneof-type))))))
(type-tags oneof-type)
(type-parameters oneof-type))))
; Look up a oneof type given one of its tags and the corresponding field type.
; Signal an error if there is no such type or there is more than one matching type.
(defun lookup-oneof-tag (world tag field-type)
(let ((data (gethash (cons tag field-type) (world-oneof-tags world))))
(cond
((null data)
(error "No known oneof type with tag ~A: ~A" tag (print-type-to-string field-type)))
((cddr data)
(error "Ambiguous oneof lookup of tag ~A: ~A. Possibilities are ~S" tag (print-type-to-string field-type) (cdr data)))
(t
(setf (first data) t)
(second data)))))
; Create or reuse a type with the given kind, tags, and parameters.
; A type is reused if one already exists with equal kind, tags, and parameters.
; Return the type.
(defun make-type (world kind tags parameters)
(let ((reverse-key (list kind tags parameters)))
(or (gethash reverse-key (world-types-reverse world))
(let ((type (allocate-type kind tags parameters)))
(when (eq kind :oneof)
(register-oneof-tags world type))
(setf (gethash reverse-key (world-types-reverse world)) type)))))
; Provide a new symbol for the type. A type can have zero or more names.
; Signal an error if the name is already used.
; user-defined is true if this is a user-defined type rather than a predefined type.
(defun add-type-name (world type symbol user-defined)
(assert-true (symbol-in-world world symbol))
(when (symbol-type-definition symbol)
(error "Attempt to redefine type ~A" symbol))
;If the old type was anonymous, give it this name.
(unless (type-name type)
(setf (type-name type) symbol)
(setf (type-name-serial-number type) (world-n-type-names world)))
(incf (world-n-type-names world))
(setf (symbol-type-definition symbol) type)
(when user-defined
(setf (symbol-type-user-defined symbol) t))
(export-symbol symbol))
; Return an existing type with the given symbol, which must be interned in a world's package.
; Signal an error if there isn't an existing type. If allow-forward-references is true and
; symbol is an undefined type identifier, allow it, create a forward-referenced type, and return symbol.
(defun get-type (symbol &optional allow-forward-references)
(or (symbol-type-definition symbol)
(if allow-forward-references
(progn
(setf (symbol-type-definition symbol) nil)
symbol)
(error "Undefined type ~A" symbol))))
; Scan a type-expr to produce a type. Return that type.
; If allow-forward-references is true and type-expr is an undefined type identifier,
; allow it, create a forward-referenced type in the world, and return type-expr unchanged.
; If allow-forward-references is true, also allow undefined type
; identifiers deeper within type-expr (anywhere except at its top level).
; If type-expr is already a type, return it unchanged.
(defun scan-type (world type-expr &optional allow-forward-references)
(cond
((identifier? type-expr)
(get-type (world-intern world type-expr) allow-forward-references))
((type? type-expr)
type-expr)
(t (let ((type-constructor (and (consp type-expr)
(symbolp (first type-expr))
(get (world-intern world (first type-expr)) :type-constructor))))
(if type-constructor
(apply type-constructor world allow-forward-references (rest type-expr))
(error "Bad type ~S" type-expr))))))
; Same as scan-type except that ensure that the type has the expected kind.
; Return the type.
(defun scan-kinded-type (world type-expr expected-type-kind)
(let ((type (scan-type world type-expr)))
(unless (eq (type-kind type) expected-type-kind)
(error "Expected ~(~A~) but got ~A" expected-type-kind (print-type-to-string type)))
type))
; (-> (<arg-type1> ... <arg-typen>) <result-type>)
(defun scan--> (world allow-forward-references arg-type-exprs result-type-expr)
(unless (listp arg-type-exprs)
(error "Bad -> argument type list ~S" arg-type-exprs))
(make-->-type world
(mapcar #'(lambda (te) (scan-type world te allow-forward-references)) arg-type-exprs)
(scan-type world result-type-expr allow-forward-references)))
; (vector <element-type>)
(defun scan-vector (world allow-forward-references element-type)
(make-vector-type world (scan-type world element-type allow-forward-references)))
; (set <element-type>)
(defun scan-set (world allow-forward-references element-type)
(make-set-type world (scan-type world element-type allow-forward-references)))
; (address <element-type>)
(defun scan-address (world allow-forward-references element-type)
(make-address-type world (scan-type world element-type allow-forward-references)))
(defun scan-tuple-or-oneof (world allow-forward-references kind tag-pairs tags-so-far types-so-far)
(if tag-pairs
(let ((tag-pair (car tag-pairs)))
(when (and (identifier? tag-pair) (eq kind :oneof))
(setq tag-pair (list tag-pair 'void)))
(unless (and (consp tag-pair) (identifier? (first tag-pair))
(second tag-pair) (null (cddr tag-pair)))
(error "Bad oneof or tuple pair ~S" tag-pair))
(let ((tag (first tag-pair)))
(when (member tag tags-so-far)
(error "Duplicate oneof or tuple tag ~S" tag))
(scan-tuple-or-oneof
world
allow-forward-references
kind
(cdr tag-pairs)
(cons tag tags-so-far)
(cons (scan-type world (second tag-pair) allow-forward-references) types-so-far))))
(make-type world kind (nreverse tags-so-far) (nreverse types-so-far))))
; (oneof (<tag1> <type1>) ... (<tagn> <typen>))
(defun scan-oneof (world allow-forward-references &rest tags-and-types)
(scan-tuple-or-oneof world allow-forward-references :oneof tags-and-types nil nil))
; (tuple (<tag1> <type1>) ... (<tagn> <typen>))
(defun scan-tuple (world allow-forward-references &rest tags-and-types)
(scan-tuple-or-oneof world allow-forward-references :tuple tags-and-types nil nil))
; Scan tag to produce a tag that is present in the given tuple or oneof type.
; Return the tag and its field type.
(defun scan-tag (type tag)
(let ((field-type (field-type type tag)))
(unless field-type
(error "Tag ~S not present in ~A" tag (print-type-to-string type)))
(values tag field-type)))
; Resolve all forward type references to refer to their target types.
; Signal an error if any unresolved type references remain.
; Only types reachable from some type name are affected. It is the caller's
; responsibility to make sure that these are the only types that exist.
; Return a list of all type structures encountered.
(defun resolve-forward-types (world)
(setf (world-types-reverse world) nil)
(setf (world-oneof-tags world) nil)
(let ((visited-types (make-hash-table :test #'eq)))
(labels
((resolve-in-type (type)
(unless (gethash type visited-types)
(setf (gethash type visited-types) t)
(do ((parameter-types (type-parameters type) (cdr parameter-types)))
((endp parameter-types))
(let ((parameter-type (car parameter-types)))
(unless (typep parameter-type 'type)
(setq parameter-type (get-type parameter-type))
(setf (car parameter-types) parameter-type))
(resolve-in-type parameter-type))))))
(each-type-definition
world
#'(lambda (symbol type)
(unless type