/
elaborate-core.fun
3948 lines (3863 loc) · 182 KB
/
elaborate-core.fun
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
(* Copyright (C) 2009-2012,2015,2017,2019-2020,2024 Matthew Fluet.
* Copyright (C) 1999-2008 Henry Cejtin, Matthew Fluet, Suresh
* Jagannathan, and Stephen Weeks.
* Copyright (C) 1997-2000 NEC Research Institute.
*
* MLton is released under a HPND-style license.
* See the file MLton-LICENSE for details.
*)
functor ElaborateCore (S: ELABORATE_CORE_STRUCTS): ELABORATE_CORE =
struct
open S
local
open Control.Elaborate
in
val nonexhaustiveBind = fn () => current nonexhaustiveBind
val nonexhaustiveExnBind = fn () => current nonexhaustiveExnBind
val nonexhaustiveExnMatch = fn () => current nonexhaustiveExnMatch
val nonexhaustiveExnRaise = fn () => current nonexhaustiveExnRaise
val nonexhaustiveMatch = fn () => current nonexhaustiveMatch
val nonexhaustiveRaise = fn () => current nonexhaustiveRaise
val redundantBind = fn () => current redundantBind
val redundantMatch = fn () => current redundantMatch
val redundantRaise = fn () => current redundantRaise
val resolveScope = fn () => current resolveScope
val sequenceNonUnit = fn () => current sequenceNonUnit
val valrecConstr = fn () => current valrecConstr
fun check (c: (bool,bool) t, keyword: string, region) =
if current c
then ()
else
let
open Layout
in
Control.error
(region,
str (concat (if expert c
then [keyword, " disallowed"]
else [keyword, " disallowed, compile with -default-ann '",
name c, " true'"])),
empty)
end
end
structure ElabControl = Control.Elaborate
local
open Layout
in
val align = align
val empty = empty
val seq = seq
val str = str
end
fun approximateN (l: Layout.t, prefixMax, suffixMax): Layout.t =
let
val s = Layout.toString l
val n = String.size s
in
str
(case suffixMax of
NONE =>
if n <= prefixMax
then s
else concat [String.prefix (s, prefixMax - 5), " ..."]
| SOME suffixMax =>
if n <= prefixMax + suffixMax
then s
else concat [String.prefix (s, prefixMax - 2),
" ... ",
String.suffix (s, suffixMax - 5)])
end
fun approximate (l: Layout.t): Layout.t =
approximateN (l, 35, SOME 25)
fun approximatePrefix (l: Layout.t): Layout.t =
approximateN (l, 15, NONE)
local
open Ast
in
structure Aconst = Const
structure Adec = Dec
structure Aexp = Exp
structure Amatch = Match
structure Apat = Pat
structure Atype = Type
structure Avar = Var
structure Avid = Vid
structure DatatypeRhs = DatatypeRhs
structure DatBind = DatBind
structure EbRhs = EbRhs
structure Fixop = Fixop
structure Longtycon = Longtycon
structure Longvid = Longvid
structure PrimKind = PrimKind
structure ImportExportAttribute = PrimKind.ImportExportAttribute
structure SymbolAttribute = PrimKind.SymbolAttribute
structure Priority = Priority
structure Record = Record
structure SortedRecord = SortedRecord
structure Symbol = Symbol
structure TypBind = TypBind
end
local
open Env
in
structure Kind = Kind
structure TypeEnv = TypeEnv
structure TypeStr = TypeStr
structure TyvarEnv = TyvarEnv
structure Vid = Vid
end
local
open TypeEnv
in
structure Scheme = Scheme
structure Time = Time
structure Type = Type
end
local
open CoreML
in
structure CFunction = CFunction
structure CKind = CFunction.Kind
structure CSymbol = CSymbol
structure SymbolScope = CSymbolScope
structure CType = CType
structure CharSize = CharSize
structure Con = Con
structure Const = Const
structure Convention = CFunction.Convention
structure Cdec = Dec
structure Cexp = Exp
structure Ffi = Ffi
structure IntSize = IntSize
structure Lambda = Lambda
structure Cpat = Pat
structure Prim = Prim
structure RealSize = RealSize
structure RealX = RealX
structure SourceInfo = SourceInfo
structure Tycon = Tycon
structure Tyvar = Tyvar
structure Var = Var
structure WordSize = WordSize
structure WordX = WordX
structure WordXVector = WordXVector
end
structure Tycon =
struct
open Tycon
open TypeEnv.TyconExt
end
structure Tyvar =
struct
open Tyvar
open TypeEnv.TyvarExt
end
fun matchDiagsFromNoMatch noMatch =
case noMatch of
Cexp.Impossible =>
{nonexhaustiveExn = Control.Elaborate.DiagDI.Default,
nonexhaustive = Control.Elaborate.DiagEIW.Ignore,
redundant = Control.Elaborate.DiagEIW.Ignore}
| Cexp.RaiseAgain =>
{nonexhaustiveExn = nonexhaustiveExnRaise (),
nonexhaustive = nonexhaustiveRaise (),
redundant = redundantRaise ()}
| Cexp.RaiseBind =>
{nonexhaustiveExn = nonexhaustiveExnBind (),
nonexhaustive = nonexhaustiveBind (),
redundant = redundantBind ()}
| Cexp.RaiseMatch =>
{nonexhaustiveExn = nonexhaustiveExnMatch (),
nonexhaustive = nonexhaustiveMatch (),
redundant = redundantMatch ()}
structure AdmitsEquality = Tycon.AdmitsEquality
local
open Record
in
structure Field = Field
end
structure Parse = PrecedenceParse (structure Ast = Ast
structure Env = Env)
structure Scope = Scope (structure Ast = Ast)
structure Apat =
struct
open Apat
fun getName (p: t): string option =
case node p of
Var {name, ...} => SOME (Longvid.toString name)
| Constraint (p, _) => getName p
| FlatApp v =>
if 1 = Vector.length v
then getName (Vector.first v)
else NONE
| Layered {var, ...} => SOME (Avar.toString var)
| _ => NONE
val getName =
Trace.trace ("ElaborateCore.Apat.getName", layout, Option.layout String.layout)
getName
end
fun elaborateType (ty: Atype.t, E: Env.t,
{bogusAsUnknown: bool}): Type.t =
let
fun makeBogus (mc, ts) =
if bogusAsUnknown
then Type.new ()
else let
val arity = Vector.length ts
val (name, region) =
Option.fold
(mc, ("t", NONE), fn (c, _) =>
(Longtycon.toString c,
SOME (Longtycon.region c)))
val c =
Tycon.makeBogus
{name = name,
kind = Kind.Arity arity,
region = region}
in
Type.con (c, ts)
end
fun loop (ty: Atype.t): Type.t =
case Atype.node ty of
Atype.Var a => (* rule 44 *)
(case TyvarEnv.lookupTyvar a of
NONE => makeBogus (NONE, Vector.new0 ())
| SOME a => Type.var a)
| Atype.Con (c, ts) => (* rules 46, 47 *)
let
val ts = Vector.map (ts, loop)
fun normal () =
case Env.lookupLongtycon (E, c) of
NONE => makeBogus (SOME c, ts)
| SOME s =>
let
val kind = TypeStr.kind s
val numArgs = Vector.length ts
val ts =
case kind of
Kind.Arity n =>
let
fun error () =
let
open Layout
fun doit n =
seq [str "[",
case n of
0 => empty
| 1 => str "_"
| _ => seq [str "(",
(seq o separate)
(List.tabulate (n, fn _ => str "_"),
", "),
str ")"],
str "] ",
Ast.Longtycon.layout c]
in
Control.error
(Atype.region ty,
seq [str "type constructor applied to incorrect number of type arguments: ",
Ast.Longtycon.layout c],
align [seq [str "expects: ", doit n],
seq [str "but got: ", doit numArgs],
seq [str "in: ", Atype.layout ty]])
end
in
case Int.compare (n, numArgs) of
LESS =>
(error (); Vector.prefix (ts, n))
| EQUAL => ts
| GREATER =>
(error ()
; Vector.concat
[ts,
Vector.tabulate
(n - numArgs, fn _ =>
makeBogus
(NONE, Vector.new0 ()))])
end
| Kind.Nary => ts
in
TypeStr.apply (s, ts)
end
in
case (Ast.Longtycon.split c, Vector.length ts) of
(([], c), 2) =>
if Ast.Tycon.equals (c, Ast.Tycon.arrow)
then Type.arrow (Vector.sub (ts, 0),
Vector.sub (ts, 1))
else normal ()
| _ => normal ()
end
| Atype.Paren t => loop t
| Atype.Record r => (* rules 45, 49 *)
Type.record
(SortedRecord.fromVector
(Vector.map
(Record.toVector r,
fn (f, (_, t)) => (f, loop t))))
in
loop ty
end
val overloadChecks: (Ast.Priority.t * (unit -> unit)) list ref = ref []
fun resolveOverloads () =
(* List.insertionSort is anti-stable; hence, it sorts and reverses the overloads. *)
(List.foreach (List.insertionSort
(!overloadChecks, fn ((p1,_),(p2,_)) =>
Priority.<= (p2, p1)),
fn (_,th) => th ())
; overloadChecks := [])
val unresolvedFlexRecordChecks: (unit -> unit) list ref = ref []
fun reportUnresolvedFlexRecords () =
(List.foreach (rev (!unresolvedFlexRecordChecks), fn th => th ())
; unresolvedFlexRecordChecks := [])
val undeterminedTypeChecks: (unit -> unit) list ref = ref []
fun reportUndeterminedTypes () =
(List.foreach (rev (!undeterminedTypeChecks), fn th => th ())
; undeterminedTypeChecks := [])
val sequenceNonUnitChecks: (unit -> unit) list ref = ref []
fun reportSequenceNonUnit () =
(List.foreach (rev (!sequenceNonUnitChecks), fn th => th ())
; sequenceNonUnitChecks := [])
val {hom = typeTycon: Type.t -> Tycon.t option, ...} =
Type.makeHom {con = fn (c, _) => SOME c,
expandOpaque = false,
var = fn _ => NONE}
val typeTycon =
Trace.trace
("ElaborateCore.typeTycon", Type.layout, Option.layout Tycon.layout)
typeTycon
fun 'a elabConst (c: Aconst.t,
{layoutPrettyType: Type.t -> Layout.t},
make: (unit -> Const.t) * Type.t -> 'a,
{false = f: 'a, true = t: 'a}): 'a =
let
fun error (kind: string, ty: Type.t): unit =
Control.error
(Aconst.region c,
seq [str kind, str " too large for type: ", Aconst.layout c],
seq [str "type: ", layoutPrettyType ty])
fun choose (tycon, all, sizeTycon, make) =
case List.peek (all, fn s => Tycon.equals (tycon, sizeTycon s)) of
NONE => Const.string "<bogus>"
| SOME s => make s
fun delay (ty: unit -> Type.t, resolve: Type.t -> Const.t): 'a =
let
val ty = ty ()
val resolve = Promise.lazy (fn () => resolve ty)
val _ = List.push (overloadChecks, (Priority.default, ignore o resolve))
in
make (resolve, ty)
end
val typeTycon =
fn ty =>
case typeTycon ty of
NONE => Tycon.bogus
| SOME c => c
in
case Aconst.value c of
Aconst.Bool b => if b then t else f
| Aconst.Char ch =>
delay
(Type.unresolvedChar, fn ty =>
choose (typeTycon ty,
CharSize.all,
Tycon.word o WordSize.fromBits o CharSize.bits,
fn cs =>
let
val ws = WordSize.fromBits (CharSize.bits cs)
in
Const.Word
(if CharSize.isInRange (cs, ch)
then WordX.fromIntInf (ch, ws)
else (error ("char constant", ty); WordX.zero ws))
end))
| Aconst.Int i =>
delay
(Type.unresolvedInt, fn ty =>
let
val tycon = typeTycon ty
in
if Tycon.equals (tycon, Tycon.intInf)
then Const.IntInf i
else
choose (tycon, WordSize.all, Tycon.word, fn s =>
Const.Word
(if WordSize.isInRange (s, i, {signed = true})
then WordX.fromIntInf (i, s)
else (error ("int constant", ty); WordX.zero s)))
end)
| Aconst.Real r =>
delay
(Type.unresolvedReal, fn ty =>
choose (typeTycon ty, RealSize.all, Tycon.real, fn s =>
Const.Real (case RealX.make (r, s) of
NONE => (error ("real constant", ty); RealX.zero s)
| SOME r => r)))
| Aconst.String v =>
delay
(Type.unresolvedString, fn ty =>
choose (typeTycon (Type.deVector ty),
CharSize.all,
Tycon.word o WordSize.fromBits o CharSize.bits,
fn cs =>
let
val ws = WordSize.fromBits (CharSize.bits cs)
val bigs = ref []
val wv =
Const.WordVector
(WordXVector.tabulate
({elementSize = ws}, Vector.length v, fn i =>
let
val {char = ch, yytext} = Vector.sub (v, i)
in
if CharSize.isInRange (cs, ch)
then WordX.fromIntInf (ch, ws)
else (List.push (bigs, yytext)
; WordX.zero ws)
end))
val () =
if List.isEmpty (!bigs)
then ()
else Control.error
(Aconst.region c,
seq [str "string constant with ",
str (case !bigs of
[_] => "character"
| _ => "characters"),
str " too large for type: ",
seq (Layout.separate
(List.revMap
(!bigs, fn yytext =>
seq [str "#\"", str yytext, str "\""]),
", "))],
align [seq [str "type: ", layoutPrettyType ty],
seq [str "in: ", Aconst.layout c]])
in
wv
end))
| Aconst.Word w =>
delay
(Type.unresolvedWord, fn ty =>
choose (typeTycon ty, WordSize.all, Tycon.word, fn s =>
Const.Word
(if WordSize.isInRange (s, w, {signed = false})
then WordX.fromIntInf (w, s)
else (error ("word constant", ty); WordX.zero s))))
end
fun lookConst {default: string option, expandedTy, name, region}: unit -> Const.t =
let
fun badType () =
let
val _ =
Control.error
(region,
seq [str "strange constant type: ",
Type.layout expandedTy],
empty)
in
Error.bug "ElaborateCore.lookConst"
end
fun notFound () =
Error.bug
(concat ["ElaborateCore.lookConst: constant ", name,
" not found"])
fun badConversion (value, ty) =
Error.bug
(concat ["ElaborateCore.lookConst: constant ", name,
" expects a ", ty, " but got ", value])
fun boolConstFromString v =
case Bool.fromString v of
NONE => badConversion (v, "bool")
| SOME b => Const.Word (WordX.fromIntInf (if b then 1 else 0, WordSize.bool))
fun realConstFromString rs v =
case RealX.make (v, rs) of
NONE => badConversion (v, "real")
| SOME r => Const.Real r
fun strConstFromString v = Const.string v
fun wordConstFromString ws v =
case IntInf.fromString v of
NONE => badConversion (v, "word")
| SOME ii => Const.Word (WordX.fromIntInf (ii, ws))
fun intInfConstFromString v =
case IntInf.fromString v of
NONE => badConversion (v, "intInf")
| SOME ii => Const.IntInf ii
in
case Type.deConOpt expandedTy of
NONE => badType ()
| SOME (c, ts) =>
let
val constFromString =
if Tycon.equals (c, Tycon.bool)
then boolConstFromString
else if Tycon.isIntX c
then (case Tycon.deIntX c of
NONE => intInfConstFromString
| SOME is => wordConstFromString (WordSize.fromBits (IntSize.bits is)))
else if Tycon.isRealX c
then realConstFromString (Tycon.deRealX c)
else if Tycon.isWordX c
then wordConstFromString (Tycon.deWordX c)
else if Tycon.equals (c, Tycon.vector)
andalso 1 = Vector.length ts
andalso (case Type.deConOpt (Vector.first ts) of
NONE => false
| SOME (c, _) =>
Tycon.isCharX c
andalso (Tycon.deCharX c = CharSize.C8))
then strConstFromString
else badType ()
in
fn () =>
let
val value =
case List.peekMap ([Control.commandLineConsts,
Promise.force Control.buildConsts,
Promise.force Control.Target.consts], fn consts =>
Control.StrMap.peek (consts, name)) of
NONE => (case default of
NONE => notFound ()
| SOME value => value)
| SOME value => value
val const = constFromString value
in
const
end
end
end
local
fun unifySeq (seqTy, seqStr,
trs: (Type.t * Region.t) vector,
unify): Type.t =
if Vector.isEmpty trs
then seqTy (Type.new ())
else
let
val (t, _) = Vector.first trs
val _ =
Vector.foreach
(trs, fn (t', r) =>
unify (t, t', fn (l, l') =>
(r,
str (seqStr ^ " with element of different type"),
align [seq [str "element: ", l'],
seq [str "previous: ", l]])))
in
seqTy t
end
in
fun unifyList (trs: (Type.t * Region.t) vector, unify): Type.t =
unifySeq (Type.list, "list", trs, unify)
fun unifyVector (trs: (Type.t * Region.t) vector, unify): Type.t =
unifySeq (Type.vector, "vector", trs, unify)
end
val elabPatInfo = Trace.info "ElaborateCore.elabPat"
structure Var =
struct
open Var
val fromAst = newString o Avar.toString
end
structure DiagUtils =
struct
type t = {layoutPrettyType: Type.t -> LayoutPretty.t,
layoutPrettyTycon: Tycon.t -> Layout.t,
layoutPrettyTyvar: Tyvar.t -> Layout.t,
unify: Type.t * Type.t * (Layout.t * Layout.t -> Region.t * Layout.t * Layout.t) -> unit}
fun make E : t =
let
val {layoutPrettyTycon, ...} =
Env.makeLayoutPrettyTycon (E, {prefixUnset = true})
val {layoutPretty = layoutPrettyTyvar, ...} =
TyvarEnv.makeLayoutPretty ()
val layoutPrettyType = fn t =>
Type.layoutPretty
(t, {expandOpaque = false,
layoutPrettyTycon = layoutPrettyTycon,
layoutPrettyTyvar = layoutPrettyTyvar})
fun unify (t, t', error) =
let
val error = fn (l, l', {notes}) =>
let
val (r, m, d) = error (l, l')
in
Control.error
(r, m, align [d, notes ()])
end
in
Type.unify
(t, t', {error = error,
layoutPretty = layoutPrettyType,
layoutPrettyTycon = layoutPrettyTycon,
layoutPrettyTyvar = layoutPrettyTyvar})
end
in
{layoutPrettyType = layoutPrettyType,
layoutPrettyTycon = layoutPrettyTycon,
layoutPrettyTyvar = layoutPrettyTyvar,
unify = unify}
end
end
val elaboratePat:
unit
-> Apat.t * Env.t * {bind: bool, isRvb: bool}
-> Cpat.t * (Avar.t * Var.t * Type.t) vector =
fn () =>
let
val others: (Apat.t * (Avar.t * Var.t * Type.t) vector) list ref = ref []
in
fn (p: Apat.t, E: Env.t, {bind = bindInEnv, isRvb}) =>
let
val {layoutPrettyType, unify, ...} = DiagUtils.make E
fun ctxtTop () =
seq [str "in: ", approximate (Apat.layout p)]
val rename =
let
val renames: (Avar.t * Var.t) list ref = ref []
in
fn x =>
case List.peek (!renames, fn (y, _) => Avar.equals (x, y)) of
NONE => let val x' = Var.fromAst x
in (List.push (renames, (x, x')); x')
end
| SOME (_, x') => x'
end
val xts: (Avar.t * Var.t * Type.t) list ref = ref []
fun bindToType (x: Avar.t, t: Type.t): Var.t =
let
val _ =
Avid.checkRedefineSpecial
(Avid.fromVar x,
{allowIt = true,
ctxt = ctxtTop,
keyword = if isRvb then "val rec" else "pattern"})
val x' = rename x
val () =
case List.peek (!xts, fn (y, _, _) => Avar.equals (x, y)) of
NONE => ()
| SOME _ =>
Control.error
(Avar.region x,
seq [str "duplicate variable in pattern: ", Avar.layout x],
ctxtTop ())
val _ = List.push (xts, (x, x', t))
in
x'
end
fun bind (x: Avar.t): Var.t * Type.t =
let
val t = Type.new ()
in
(bindToType (x, t), t)
end
fun elabType (t: Atype.t): Type.t =
elaborateType (t, E, {bogusAsUnknown = true})
fun loop (arg: Apat.t) =
Trace.traceInfo' (elabPatInfo, Apat.layout, Cpat.layout)
(fn (p: Apat.t) =>
let
val region = Apat.region p
fun ctxt () =
seq [str "in: ", approximate (Apat.layout p)]
val unify = fn (a, b, f) =>
unify (a, b, fn z =>
let
val (r, m, d) = f z
in
(r, m, align [d, ctxt ()])
end)
fun unifyPatternConstraint (p, c) =
unify
(p, c, fn (l1, l2) =>
(region,
str "pattern and constraint disagree",
align [seq [str "pattern: ", l1],
seq [str "constraint: ", l2]]))
fun dontCare () =
Cpat.wild (Type.new ())
in
case Apat.node p of
Apat.App {con = c, arg = p, ...} =>
(case Env.lookupLongcon (E, c) of
NONE => dontCare ()
| SOME (con, s) =>
let
val {args, instance} = Scheme.instantiate s
val args = args ()
val p = loop p
val (argType, resultType) =
case Type.deArrowOpt instance of
SOME types => types
| NONE =>
let
val types =
(Type.new (), Type.new ())
val _ =
unify
(instance, Type.arrow types,
fn _ =>
(region,
str "constant constructor applied to argument in pattern",
Layout.empty))
in
types
end
val _ =
unify
(Cpat.ty p, argType, fn (l, l') =>
(region,
str "constructor applied to incorrect argument in pattern",
align [seq [str "expects: ", l'],
seq [str "but got: ", l]]))
in
Cpat.make (Cpat.Con {arg = SOME p,
con = con,
targs = args},
resultType)
end)
| Apat.Const c =>
elabConst
(c,
{layoutPrettyType = #1 o layoutPrettyType},
fn (resolve, ty) => Cpat.make (Cpat.Const resolve, ty),
{false = Cpat.falsee,
true = Cpat.truee})
| Apat.Constraint (p, t) =>
let
val p' = loop p
val _ =
unifyPatternConstraint
(Cpat.ty p', elabType t)
in
p'
end
| Apat.FlatApp items =>
loop (Parse.parsePat
(items, E, fn () => ctxt ()))
| Apat.Layered {var = x, constraint, pat, ...} =>
let
val t =
case constraint of
NONE => Type.new ()
| SOME t => elabType t
val xc = Avid.toCon (Avid.fromVar x)
val x =
case Env.peekLongcon (E, Ast.Longcon.short xc) of
NONE => bindToType (x, t)
| SOME _ =>
let
val _ =
Control.error
(region,
seq [str "constructor cannot be redefined by as: ",
Avar.layout x],
ctxt ())
in
Var.fromAst x
end
val pat' = loop pat
val _ =
unifyPatternConstraint (Cpat.ty pat', t)
in
Cpat.make (Cpat.Layered (x, pat'), t)
end
| Apat.List ps =>
let
val ps' = Vector.map (ps, loop)
in
Cpat.make (Cpat.List ps',
unifyList
(Vector.map2 (ps, ps', fn (p, p') =>
(Cpat.ty p', Apat.region p)),
unify))
end
| Apat.Or ps =>
let
val _ = check (Control.Elaborate.allowOrPats, "Or patterns", region)
val xtsOrig = !xts
val n = Vector.length ps
val ps =
Vector.map
(ps, fn p =>
let
val _ = xts := []
val p' = loop p
in
(p, p', !xts)
end)
val ps' = Vector.map (ps, fn (_, p', _) => p')
val xtsPats =
Vector.fold
(ps, [], fn ((p, _, xtsPat), xtsPats) =>
List.fold
(xtsPat, xtsPats, fn ((x, x', t), xtsPats) =>
case List.peek (xtsPats, fn (y, _, _, _) => Avar.equals (x, y)) of
NONE => (x, x', t, ref [x])::xtsPats
| SOME (_, _, t', l) =>
let
val _ = List.push (l, x)
val _ =
unify
(t', t, fn (l', l) =>
(Avar.region x,
seq [str "or-pattern with variable of different type: ",
Avar.layout x],
align [seq [str "variable: ", l],
seq [str "previous: ", l'],
seq [str "in: ", approximate (Apat.layout p)]]))
in
xtsPats
end))
val _ =
List.foreach
(xtsPats, fn (x, _, _, l) =>
if List.length (!l) <> n
then let
val _ =
Control.error
(Apat.region p,
seq [str "variable does not occur in all patterns of or-pattern: ",
Avar.layout x],
ctxt ())
in
()
end
else ())
val t = Type.new ()
val _ =
Vector.foreach
(ps, fn (p, p', _) =>
unify
(t, Cpat.ty p', fn (l, l') =>
(Apat.region p,
str "or-pattern with pattern of different type",
align [seq [str "pattern: ", l'],
seq [str "previous: ", l],
seq [str "in: ", approximate (Apat.layout p)]])))
val xtsMerge =
List.fold
(xtsPats, xtsOrig, fn ((x, x', t, l), xtsMerge) =>
case List.peek (xtsMerge, fn (y, _, _) => Avar.equals (x, y)) of
NONE => (x, x', t)::xtsMerge
| SOME _ =>
let
val _ =
List.foreach
(List.rev (!l), fn x =>
Control.error
(Avar.region x,
seq [str "duplicate variable in pattern: ", Avar.layout x],
ctxtTop ()))
in
(x, x', t)::xtsMerge
end)
val _ = xts := xtsMerge
in
Cpat.make (Cpat.Or ps', t)
end
| Apat.Paren p => loop p
| Apat.Record {flexible, items} =>
(* rules 36, 38, 39 and Appendix A, p.57 *)
let
val (fs, ps) =
Vector.unzip
(Vector.map
(items,
fn (f, _, i) =>
(f,
case i of
Apat.Item.Field p => p
| Apat.Item.Vid (vid, tyo, po) =>
let
val p =
case po of
NONE =>
Apat.longvid (Longvid.short vid)
| SOME p =>
Apat.layered
{fixop = Fixop.None,
var = Ast.Vid.toVar vid,
constraint = NONE,
pat = p}
in
case tyo of
NONE => p
| SOME ty => Apat.constraint (p, ty)
end)))
val ps = Vector.map (ps, loop)
val r = SortedRecord.zip (fs, Vector.map (ps, Cpat.ty))
val ty =
if flexible
then
let
val (t, isResolved) = Type.flexRecord r
fun resolve () =
if isResolved ()
then ()
else
Control.error
(region,
str "unresolved ... in record pattern",
ctxt ())
val _ = List.push (unresolvedFlexRecordChecks, resolve)
in
t
end
else
Type.record r
in
Cpat.make
(Cpat.Record (Record.fromVector (Vector.zip (fs, ps))),
ty)
end
| Apat.Tuple ps =>
Cpat.tuple (Vector.map (ps, loop))
| Apat.Var {name, ...} =>
let
val (strids, x) = Ast.Longvid.split name
fun var () =
let
val (x, t) = bind (Ast.Vid.toVar x)
in
Cpat.make (Cpat.Var x, t)
end
in
case Env.peekLongcon (E, Ast.Longvid.toLongcon name) of
NONE =>
if List.isEmpty strids
then var ()
else
let
val _ =
Control.error
(region,
seq [str "undefined constructor: ",
Ast.Longvid.layout name],
empty)
in
Cpat.make (Cpat.Wild, Type.new ())
end
| SOME (c, s) =>
if List.isEmpty strids andalso isRvb
then var ()
else let
val {args, instance} =
Scheme.instantiate s
in
if Type.isArrow instance
then
(Control.error
(region,
seq [str "constructor used without argument in pattern: ",
Ast.Longvid.layout name],
empty)
; dontCare ())
else
Cpat.make
(Cpat.Con {arg = NONE,
con = c,
targs = args ()},
instance)
end
end
| Apat.Vector ps =>