File: VALUE_OPS.ML

package info (click to toggle)
polyml 5.6-8
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 31,892 kB
  • ctags: 34,453
  • sloc: cpp: 44,983; ansic: 24,520; asm: 14,850; sh: 11,730; makefile: 551; exp: 484; python: 253; awk: 91; sed: 9
file content (1362 lines) | stat: -rw-r--r-- 61,961 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
(*
    Copyright (c) 2000
        Cambridge University Technical Services Limited

    Modified David C.J. Matthews 2008-9, 2013, 2015.

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License version 2.1 as published by the Free Software Foundation.
    
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.
    
    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*)

(*
    Title:      Operations on global and local values.
    Author:     Dave Matthews, Cambridge University Computer Laboratory
    Copyright   Cambridge University 1986
*)

functor VALUE_OPS (

structure LEX : LEXSIG;
structure CODETREE : CODETREESIG
structure STRUCTVALS : STRUCTVALSIG;
structure TYPESTRUCT : TYPETREESIG

structure PRINTTABLE :
sig
    type typeConstrs
    type codetree
  
    val addOverload: string * typeConstrs * codetree -> unit
    val getOverload: string * typeConstrs * (unit->codetree) -> codetree
    val getOverloads: string -> (typeConstrs * codetree) list
end;

structure UNIVERSALTABLE:
sig
    type universal = Universal.universal
    type univTable
    val app: (string * universal -> unit) -> univTable -> unit
end;

structure DEBUG : DEBUGSIG

structure MISC :
sig
    exception InternalError of string; (* compiler error *)
    exception Conversion of string     (* string to int conversion failure *)

    val quickSort : ('a -> 'a -> bool) -> 'a list -> 'a list
end;

structure PRETTY : PRETTYSIG
structure ADDRESS : AddressSig

structure UTILITIES :
sig
  val splitString: string -> { first:string,second:string }
end;

structure COPIER: COPIERSIG

structure TYPEIDCODE: TYPEIDCODESIG

structure DATATYPEREP: DATATYPEREPSIG

sharing STRUCTVALS.Sharing = TYPESTRUCT.Sharing = LEX.Sharing = PRETTY.Sharing
      = COPIER.Sharing = CODETREE.Sharing = PRINTTABLE = ADDRESS = UNIVERSALTABLE = MISC
      = TYPEIDCODE.Sharing = DATATYPEREP.Sharing

) : VALUEOPSSIG =

(*****************************************************************************)
(*                  VALUEOPS functor body                                    *)
(*****************************************************************************)
struct
  open MISC; 
  open PRETTY;
  
  open LEX;
  open CODETREE;
  open TYPESTRUCT; (* Open this first because unitType is in STRUCTVALS as well. *)
  open Universal; (* for tag etc. *)
  open STRUCTVALS;
  open PRINTTABLE;
  open DEBUG;
  open ADDRESS;
  open RuntimeCalls; (* for POLY_SYS and EXC numbers *)
  open UTILITIES;
  open TYPEIDCODE
  open COPIER
  open DATATYPEREP
  
    (* Functions to construct the values. *)

    fun mkGconstr (name, typeof, code, nullary, constrs, location) =
       makeValueConstr (name, typeof, nullary, constrs, Global code, location);

    (* Global variable *)
    fun mkGvar (name, typeOf, code, locations) : values =
        Value{ name = name, typeOf = typeOf, access = Global code, class = ValBound,
            locations = locations, references = NONE, instanceTypes=NONE };

    (* Local variable - Generated by the second pass. *)
    local
        fun makeLocalV class (name, typeOf, locations) =
            Value{ name = name, typeOf = typeOf, access = Local {addr = ref ~1 (* Must be set later *), level = ref baseLevel},
                    class = class, locations = locations, references = makeRef(),
                    instanceTypes=SOME(ref []) };
    in
        val mkValVar = makeLocalV ValBound
        and mkPattVar = makeLocalV PattBound
    end

    (* Value in a local structure or a functor argument.  May be simple value, exception
        or constructor. *)
    fun mkSelectedVar (Value { access = Formal addr, name, typeOf, class, locations, ...}, base, openLocs) =
        (* If the argument is "formal" set the base to the base structure. *)
        Value{name=name, typeOf=typeOf, class=class,
              access=Selected{addr=addr, base=base},
              locations=openLocs @ locations, references = NONE, instanceTypes=NONE}

    |   mkSelectedVar (Value { access = Global code, name, typeOf, class, locations, ...}, _, openLocs) =
        (* Global: We need to add the location information. *)
        Value{name=name, typeOf=typeOf, class=class, access=Global code,
              locations=openLocs @ locations, references = NONE, instanceTypes=NONE}

    |   mkSelectedVar(selected, _, _) = selected (* Overloaded? *);

    (* Construct a global exception. *)
    fun mkGex (name, typeof, code, locations) =
        Value{ name = name, typeOf = typeof, access = Global code,
           class = Exception, locations = locations, references = NONE, instanceTypes=NONE }
 
    (* Construct a local exception. *)
    fun mkEx (name, typeof, locations) = 
        Value{ name = name, typeOf = typeof,
           access = Local{addr = ref 0, level = ref baseLevel},
           class = Exception, locations=locations, references = NONE, instanceTypes=NONE }

    (* Locations in exception packets.  In order to have a defined ordering of the fields,
       when we put the location in an exception packet we use this datatype rather than
       the "location" type. *)
     (* *)
    datatype RuntimeLocation =
        NoLocation
    |   SomeLocation of
            (* file: *) string * 
            (*startLine:*) int *  (*startPosition:*) int *
            (*endLine:*) int * (*endPosition:*) int

    fun codeLocation({file="", startLine=0, startPosition=0, ...}) =
        mkConst(toMachineWord NoLocation) (* No useful information *)
    |   codeLocation({file, startLine, startPosition, endLine, endPosition}) =
        mkConst(toMachineWord(file, startLine, startPosition, endLine, endPosition))

(*****************************************************************************)
  (* Look-up functions. *)

    (* Look up a structure. *)
    fun lookupStructure (kind, {lookupStruct:string -> structVals option},
               name, errorMessage) =
    let
        val {first = prefix, second = suffix} = splitString name;
        val strLookedUp =
            if prefix = ""
            then lookupStruct suffix
            else case lookupStructure
                        ("Structure", {lookupStruct=lookupStruct}, prefix, errorMessage) of
                NONE => NONE (* Already reported *)
            |   SOME(str as Struct { signat, locations, ...}) =>
                let  (* Look up the first part in the structure environment. *)
                    val Signatures { tab, typeIdMap, firstBoundIndex, ... } = signat
                    val Env{lookupStruct, ...} = makeEnv tab
                    (* If we have a DeclaredAt location for the structure use this as the StructureAt.*)
                    val baseLoc =
                    case List.find (fn DeclaredAt _ => true | _ => false) locations of
                        SOME (DeclaredAt loc) => [StructureAt loc]
                    |   _ => []
                in
                    case lookupStruct suffix of
                        SOME (Struct {signat, access, name=structName, locations, ...})  =>
                        let
                            val Signatures { name=sigName, tab, typeIdMap = childMap, locations=sigLocs, ... } = signat
                            (* We need to apply the map from the parent structure to the child. *)
                            val copiedSig =
                                makeSignature(sigName, tab, firstBoundIndex, sigLocs, composeMaps(childMap, typeIdMap), [])
                            (* Convert Formal access to Selected and leave the others (Global?). *)
                            val newAccess =
                                case access of
                                    Formal sel => makeSelected (sel, str)
                                |   access => access
                        
                            val newStruct =
                                Struct { name = structName, signat = copiedSig,
                                         access = newAccess, locations = baseLoc @ locations}
                        in
                            SOME newStruct
                        end
                    |   NONE => NONE
                end
    in
        case strLookedUp of
           SOME s => SOME s
        |  NONE =>
             (* Not declared? *)
                (errorMessage (kind ^ " (" ^ suffix ^  ") has not been declared" ^
                   (if prefix = "" then "" else " in structure " ^ prefix));
                NONE)
    end

    fun mkEnv x = let val Env e = makeEnv x in e end

    (* Look up a structure but ignore the access. This is used in sharing constraints
       where we're only interested in the signature. *)
    (* It's simpler to use the common code for this. *)
    fun lookupStructureAsSignature (lookupStruct, name, errorMessage) =
        lookupStructure("Structure", { lookupStruct = lookupStruct}, name, errorMessage)

    (* Look up a value, possibly in a structure. If it is in
       a structure we may have to apply a selection. *)
    fun lookupValue (kind, {lookupVal,lookupStruct}, name, errorMessage) =
    let
        val {first = prefix, second = suffix} = splitString name;
        val found =
        if prefix = "" then lookupVal suffix
        (* Look up the first part in the structure environment. *)
        else case lookupStructure
                    ("Structure", {lookupStruct=lookupStruct}, prefix, errorMessage) of
            NONE => SOME undefinedValue
        |   SOME (baseStruct as Struct { signat, locations, ...}) =>
            let
                val Signatures { tab, typeIdMap, ...} = signat
                (* If we have a DeclaredAt location for the structure use this as the StructureAt.*)
                val baseLoc =
                    case List.find (fn DeclaredAt _ => true | _ => false) locations of
                        SOME (DeclaredAt loc) => [StructureAt loc]
                    |   _ => []
            in
                case #lookupVal (mkEnv tab) suffix of
                    SOME (Value{ name, typeOf, access, class, locations, ... }) =>
                    let
                        fun copyId(TypeId{idKind=Bound{ offset, ...}, ...}) = SOME(typeIdMap offset)
                        |   copyId _ = NONE
                        val copiedType =
                            copyType (typeOf, fn x => x,
                                fn tcon =>
                                    copyTypeConstr (tcon, copyId, fn x => x, fn s => prefix^"."^s))                            
                    in
                        SOME(mkSelectedVar (
                                Value{ name=name, typeOf=copiedType, access=access, class=class, locations=locations,
                                       references = NONE, instanceTypes=NONE },
                                baseStruct, baseLoc))
                    end
                |   NONE => NONE
            end
    in
        case found of
            SOME v => v
        |   NONE => (* Not declared? *)
            (
                errorMessage (kind ^ " (" ^ suffix ^ ") has not been declared" ^
                    (if prefix = "" then "" else " in structure " ^ prefix));
                undefinedValue
            )
    end

    fun lookupTyp ({lookupType,lookupStruct}, name, errorMessage) =
    let
        val {first = prefix, second = suffix} = splitString name;
        val found =
        if prefix = "" then lookupType suffix
        else (* Look up the first part in the structure environment. *)
            case lookupStructure
                    ("Structure", {lookupStruct=lookupStruct}, prefix, errorMessage) of
            NONE => SOME(TypeConstrSet(undefConstr, []))
        |   SOME (Struct { signat, ...}) =>
            let
                val Signatures { tab, typeIdMap, ...} = signat
            in
                case #lookupType (mkEnv tab) suffix of
                    SOME typeConstr => SOME(fullCopyDatatype(typeConstr, typeIdMap, prefix^"."))
                |   NONE => NONE
            end
    in
        case found of
            SOME v => v
        |   NONE => (* Not declared? *)
            (
                errorMessage ("Type constructor" ^ " (" ^ suffix ^ ") has not been declared" ^
                (if prefix = "" then "" else " in structure " ^ prefix));
                TypeConstrSet(undefConstr, [])
            )
    end 

 
      (* Printing. *)

    (* This name space is used to help find type identifiers.
       However, because the functions are passed through to the resulting environment
       by INITIALISE we have to use the same type as the normal top-level environment. *)
    type nameSpace =
      { 
        lookupVal:    string -> values option,
        lookupType:   string -> typeConstrSet option,
        lookupFix:    string -> fixStatus option,
        lookupStruct: string -> structVals option,
        lookupSig:    string -> signatures option,
        lookupFunct:  string -> functors option,

        enterVal:     string * values      -> unit,
        enterType:    string * typeConstrSet -> unit,
        enterFix:     string * fixStatus   -> unit,
        enterStruct:  string * structVals  -> unit,
        enterSig:     string * signatures  -> unit,
        enterFunct:   string * functors    -> unit,

        allVal:       unit -> (string*values) list,
        allType:      unit -> (string*typeConstrSet) list,
        allFix:       unit -> (string*fixStatus) list,
        allStruct:    unit -> (string*structVals) list,
        allSig:       unit -> (string*signatures) list,
        allFunct:     unit -> (string*functors) list
      };

  val nullEnvironment : nameSpace =
     {
        lookupVal = fn _ => NONE,
        lookupType = fn _ => NONE,
        lookupFix = fn _ => NONE,
        lookupStruct = fn _ => NONE,
        lookupSig = fn _ => NONE,
        lookupFunct = fn _ => NONE,
        enterVal = fn _ => (),
        enterType = fn _ => (),
        enterFix = fn _ => (),
        enterStruct = fn _ => (),
        enterSig = fn _ => (),
        enterFunct = fn _ => (),
        allVal = fn () => [],
        allType = fn () => [],
        allFix = fn () => [],
        allStruct = fn () => [],
        allSig = fn () => [],
        allFunct = fn () => []
        }

    (* Print a value given its type. *)
    fun printValueForType (value:machineWord, types, depth): pretty =
    let
        (* Constuct printer code applied to the argument and the depth.
           Code-generate and evaluate it. *)
        (* If this is polymorphic apply it to a dummy set of instance types.
           This may happen if we have val it = NONE at the top level.
           The equality attributes of the type variables must match so that
           this works correctly with justForEqualityTypes set. *)
        val addrs = ref 0 (* Make local declarations for any type values. *)
        local
            fun mkAddr n = !addrs before (addrs := !addrs + n)
        in
            val typeVarMap = TypeVarMap.defaultTypeVarMap(mkAddr, baseLevel)
        end
        val dummyTypes =
            List.map(fn tv => {value=TYPESTRUCT.unitType, equality=tvEquality tv, printity=false})
                (getPolyTypeVars(types, fn _ => NONE))
        val polyCode = applyToInstance(dummyTypes, baseLevel, typeVarMap, fn _ => mkConst value)
        val printerCode =
            mkEval(
                printerForType(types, baseLevel, typeVarMap),
                [mkTuple[polyCode, mkConst(toMachineWord depth)]])
        val pretty =
            RunCall.unsafeCast(
                valOf(evalue(genCode(CODETREE.mkEnv(TypeVarMap.getCachedTypeValues typeVarMap, printerCode), [], !addrs)())))
    in
        pretty
    end

    (* These are used to display the declarations made. *)
    fun displayFixStatus(FixStatus(name, f)): pretty =
    let
        open PRETTY
        
        val status =
            case f of
                Nonfix => PrettyString "nonfix"
            |   Infix prec =>
                    PrettyBlock(0, false, [],
                        [ PrettyString "infix", PrettyBreak (1, 0), PrettyString (Int.toString prec) ])
            |   InfixR prec =>
                    PrettyBlock(0, false, [],
                        [ PrettyString "infixr", PrettyBreak (1, 0), PrettyString (Int.toString prec) ])
    in
        PrettyBlock (0, false, [],
            [status, PrettyBreak (1, 0), PrettyString name])
    end

    (* Returns the declaration location as the location for the context. *)
    fun getLocation locations =
        case List.find(fn DeclaredAt _ => true | _ => false) locations of
            SOME(DeclaredAt loc) => [ContextLocation loc]
        |   _ => []


    (* Displays value as a block, with no external formatting.  This is used at the
       top level but it can be applied to values extracted with #lookup globalNameSpace.
       That can include constructors and overloaded functions. *)
    fun displayValues (Value{name, typeOf, class, access, locations, ...}, depth, nameSpace, sigMap): pretty =
    let
        (* Create the "val X =" part. *)
        fun valPart (valOrCons, isColon) =
        let
            val (space, equOrColon) = if isColon then (0, ":") else (1, "=")
        in
            PrettyBlock (0, false, [],
                [
                    PrettyString valOrCons,
                    PrettyBreak (1, 0),
                    PrettyBlock(0, false, getLocation locations, [PrettyString name]),
                    PrettyBreak (space, 0),
                    PrettyString equOrColon
                ]
            )
        end
        val typeEnv = (* Environment to check for type constructors. *)
            { lookupType = #lookupType nameSpace, lookupStruct = #lookupStruct nameSpace}
    in
  
        if depth <= 0 
        then PrettyString "..."

        else case class of
            ValBound =>
            let
                (* In nearly all cases if we have Global code we will have a constant.
                   There was one case where "!" was actually a Lambda that hadn't been
                   code-generated. *)
                val value =
                    case access of Global code => evalue code | _ => NONE
                val start =
                    case value of
                        SOME v =>
                        [
                            valPart("val", false),
                            PrettyBreak (1, 0),
                            printValueForType (v, typeOf, depth),
                            PrettyString ":"
                        ]
                    |   _ => [ valPart("val", true) ]
            in
                PrettyBlock (3, false, [],
                    start @ [ PrettyBreak (1, 0), displayWithMap (typeOf, depth, typeEnv, sigMap) ])
            end

        |    Exception => (* exceptions *)
             PrettyBlock (0, false, [],
                PrettyBlock (0, false, [],
                    [
                        PrettyString "exception",
                        PrettyBreak (1, 0),
                        PrettyBlock(0, false, getLocation locations, [PrettyString name])
                    ]
                )
                ::
                (
                    case getFnArgType typeOf of
                       NONE => []
                    |  SOME excType =>
                        [ PrettyBreak (1, 1), PrettyString "of", PrettyBreak (1, 3), displayWithMap (excType, depth, typeEnv, sigMap) ]
                )
            )

        | Constructor _ => (* This can only occur with #lookupVal *)
            PrettyBlock (3, false, [],
                [ valPart("constructor", true), PrettyBreak (1, 0), displayWithMap (typeOf, depth, typeEnv, sigMap) ])
     
        | PattBound => (* Can this ever occur? *)
            PrettyBlock (3, false, [],
                [ valPart("val", true), PrettyBreak (1, 0), displayWithMap (typeOf, depth, typeEnv, sigMap) ])
    end

    (* Print global values.  This is passed through the bootstrap and used in the debugger. *)
    fun printValues (Value{typeOf, class, access, ...}, depth) =
        case (class, access) of
            (ValBound, Global code) => printValueForType (valOf(evalue code), typeOf, depth)
        | _ => PrettyString "" (* Probably shouldn't occur. *)

    (* Prints "sig ... end" as a block, with no external formatting *)
    fun displaySig (Signatures{tab, typeIdMap, ...}, depth : int, _ : int,
                    { lookupType, lookupStruct, ...}, sigMap: (int-> typeId) option) : pretty =
    let
        (* Construct an environment for the types. *)

        val Env { lookupType = strType, lookupStruct = strStr, ...} = makeEnv tab

        (* Construct a map for types. *)
        val innerMap =
            case sigMap of
                NONE => SOME typeIdMap
            |   SOME outerMap => SOME(composeMaps(typeIdMap, outerMap))

        val compositeEnv =
        {
            lookupType   =
                fn s => case strType s of NONE => lookupType s | SOME t => SOME (t, innerMap),
            lookupStruct =
                fn s => case strStr s of NONE => lookupStruct s | SOME s => SOME (s, innerMap)
        }
        
        val typeEnv: printTypeEnv =
            { lookupType = #lookupType compositeEnv, lookupStruct = #lookupStruct compositeEnv }

        fun displaySpec (_, value) : pretty list =
        if (tagIs signatureVar value)
        then (* Not legal ML97 *)
            [ PrettyBreak(1,2), displaySignatures (tagProject signatureVar value, depth - 1, compositeEnv)]
           
        else if (tagIs structVar value)
        then
            [ PrettyBreak(1,2), displayStructures (tagProject structVar value, depth - 1, compositeEnv, innerMap)]
               
        else if (tagIs typeConstrVar value)
        then 
            [ PrettyBreak(1,2), displayTypeConstrsWithMap (tagProject typeConstrVar value, depth, typeEnv, innerMap) ]
      
        else if (tagIs valueVar value)
        then
        let
            (* Only print variables. Constructors are printed with their type. *)
            val value = tagProject valueVar value;
        in
            case value of
                Value{class = Constructor _, ...} => []
            |    _ =>
              [ PrettyBreak(1,2),
              (* We lookup the infix status and any exception in the global environment
                 only.  Infix status isn't a property of a structure and it's too
                 much trouble to look up exceptions in the structure. *)
                displayValues (value, depth, compositeEnv, innerMap)
              ]
        end
      
        else if (tagIs fixVar value)
        then  (* Not legal ML97 *)
            [ PrettyBreak(1,2), displayFixStatus (tagProject fixVar value) ]
 
        else []
       (* end displaySpec *)
    in
        PrettyBlock (0, true, [],
            PrettyString "sig" ::
            (
                (
                    if depth <= 1 (* If the depth is 1 each of the calls to displaySpec will
                                     print "..." so we replace them all by a single "..." here. *)
                    then [PrettyBreak (1, 0), PrettyString "..."]
                    else
                    let
                        val declist = ref nil : (string * universal) list ref
                        fun addToList nv = declist := nv :: !declist
                        (* For the moment order them by name.  We may change this to
                           order primarily by kind and secondarily by name. *)
                        fun order (s1: string, _) (s2: string, _) = s1 > s2
                    in
                        (* Put all the entries into a list. *)
                        UNIVERSALTABLE.app addToList tab;
                        (* Sort the list and print it. *)
                        List.foldl
                            (fn (a, l) => displaySpec a @ l)
                            [] (quickSort order (!declist))
                    end
                )
                @ [PrettyBreak (1, 0), PrettyString "end"]
            )
        )
        end (* displaySig *)

  (* Print: signature S = sig .... end *)
  and displaySignatures (str as Signatures{locations, name, ...}, depth : int, nameSpace) : pretty =
    if depth <= 0 then PrettyString "..."
    else
        PrettyBlock(0, false, [],
            [
                PrettyBlock(0, false, [],
                    [
                        PrettyString "signature",
                        PrettyBreak(1, 0),
                        PrettyBlock(0, false, getLocation locations, [PrettyString name]),
                        PrettyBreak(1, 0),
                        PrettyString "="
                    ]
                ),
            PrettyBreak (1, 2),
            displaySig (str, depth, 1, nameSpace, NONE)
            ])

  (* print structure in a block (no external spacing) *)
    and displayStructures (Struct{name, locations, signat, ...}, depth, nameSpace, sigMap): pretty =
    if depth <= 0 then PrettyString "..."
    else
        PrettyBlock (0, false, [],
        [
            PrettyBlock(0, false, [],
                [
                    PrettyString "structure",
                    PrettyBreak(1, 0),
                    PrettyBlock(0, false, getLocation locations, [PrettyString name]),
                    PrettyBreak(0, 0),
                    PrettyString ":"
                ]
            ),
            PrettyBreak(1, 2),
            displayNamedSig(signat, depth - 1, 1, nameSpace, sigMap)
        ])

    (* Internal function for printing structures and functors.  If a signature has a
       name print the name rather than the contents. *)
    and displayNamedSig(sign as Signatures{name = "", ...}, depth, space, nameSpace, sigMap) =
            displaySig (sign, depth, space, nameSpace, sigMap)
    |   displayNamedSig(Signatures{name, ...}, _, _, _, _) = PrettyString name

    fun displayFunctors (Functor{ name, locations, arg, result, ...}, depth, nameSpace) =
    if depth <= 0 then PrettyString "..."
    else
    let
        val arg as 
             Struct { name = argName, signat as Signatures { tab = argTab, ... }, ...} = arg
        val argEntries =
            (if argName <> ""
            then [ PrettyBlock(0, false, [], [PrettyString argName, PrettyBreak(0, 0), PrettyString ":"]), PrettyBreak(1, 2) ]
            else []) @
            [
                displayNamedSig (signat, depth - 1, 0, nameSpace, NONE),
                PrettyBreak(0, 0),
                PrettyString "):",
                PrettyBreak(1, 0)
            ]
        (* Include the argument structure name in the type environment. *)
        val argEnv =
            if argName = ""
            then
            let
                val Env { lookupType=lt, lookupStruct=ls, ...} = makeEnv argTab
            in
                {
                    lookupType =
                        fn s => case lt s of NONE => #lookupType nameSpace s | SOME t => SOME(t, NONE),
                    lookupStruct =
                        fn s => case ls s  of NONE => #lookupStruct nameSpace s | SOME s => SOME(s, NONE)
                }
            end
            else
            {
                lookupType   = #lookupType nameSpace,
                lookupStruct =
                    fn s => if s = argName then SOME(arg, NONE) else #lookupStruct nameSpace s
            }
    in
        PrettyBlock (0, false, [],
            [
                PrettyBlock(0, false, [],
                [
                    PrettyBlock(0, false, [],
                    [
                        PrettyString "functor",
                        PrettyBreak(1, 0),
                        PrettyBlock(0, false, getLocation locations, [PrettyString name]),
                        PrettyBreak(1, 0),
                        PrettyString "("
                    ]),
                    PrettyBreak(0, 2),
                    PrettyBlock(0, false, [], argEntries)
                ]),
                PrettyBreak(0, 2),
                displayNamedSig (result, depth - 1, 1, argEnv, NONE)
            ]
        )
    end

    (* Exported version. *)
    val displayValues = fn (value, depth, nameSpace) => displayValues (value, depth, nameSpace, NONE)
    and displayStructures = fn (str, depth, nameSpace) => displayStructures (str, depth, nameSpace, NONE)
   
  (* Code-generation. *)

    (* Code-generate the values. *) 
    fun codeStruct (Struct{access, ...}, level) =
        (* Global structures have no code value. Instead the
            values are held in the values of the signature. *)
        codeAccess (access, level)

    and codeAccess (Global code, _) = code
      
    |   codeAccess (Local{addr=ref locAddr, level=ref locLevel}, level) =
            mkLoad (locAddr, level, locLevel) (* Argument or local *)
     
    |   codeAccess (Selected{addr, base}, level) = (* Select from a structure. *)
            mkInd (addr, codeStruct (base, level))
     
    | codeAccess _ = raise InternalError "No access"


(*****************************************************************************)
(*                  datatype access functions                                *)
(*****************************************************************************)

    (* Get the appropriate instance of an overloaded function.  If the
       overloading has not resolved to a single type it finds the preferred
       type if possible (i.e. int for most overloadings, but possibly real,
       word, string or char for conversion functions.) *)
    fun getOverloadInstance(name, instance, isConv): codetree*string =
    let
        val constr = typeConstrFromOverload(instance, isConv)
    in
        (getOverload(name, constr, fn _ => raise InternalError "getOverloadInstance: Missing"), tcName constr)
    end

    (* This is only used in addPrettyPrint.  There's no point in
       producing a lot of detailed information. *)
    fun checkPPType (instanceType, matchType, fnName, lex, location, moreInfo) =
        case unifyTypes (instanceType, matchType) of
            NONE => ()
        |   SOME error =>
            let
                open DEBUG
                val parameters = LEX.debugParams lex
                val errorDepth = getParameter errorDepthTag parameters
            in
                reportError lex
                {
                    location = location,
                    hard = true,
                    message =
                        PrettyBlock(0, true, [],
                            [
                                PrettyString ("Argument for " ^ fnName),
                                PrettyBreak (1, 3),
                                PrettyBlock(0, false, [],
                                    [
                                        PrettyString "Required type:",
                                        PrettyBreak (1, 0),
                                        display (matchType, errorDepth, emptyTypeEnv)
                                    ]),
                                PrettyBreak (1, 3),
                                PrettyBlock(0, false, [],
                                    [
                                        PrettyString "Argument type:",
                                        PrettyBreak (1, 0),
                                        display (instanceType, errorDepth, emptyTypeEnv)
                                    ]),
                                PrettyBreak (1, 3),
                                unifyTypesErrorReport(lex, emptyTypeEnv, emptyTypeEnv, "unify") error
                            ]),
                    context = SOME (moreInfo ())
               }
            end;

    (* This is applied to the instance variables if it is polymorphic and bound by
       a val or fun binding or is a datatype constructor. *)
    fun applyToInstanceType(polyVars, ValBound, level, typeVarMap, code) =
            applyToInstance(polyVars, level, typeVarMap, code)
    |   applyToInstanceType(polyVars, Constructor _, level, typeVarMap, code) =
            applyToInstance(if justForEqualityTypes then [] else polyVars, level, typeVarMap, code)
    |   applyToInstanceType(_, PattBound, level, _, code) = code level
    |   applyToInstanceType(_, Exception, level, _, code) = code level

    val arg1     = mkLoadArgument 0 (* saves a lot of garbage *)

    fun addStatus typ = {value=typ, equality=false, printity=false}

 (* Code-generate an identifier matched to a value.  N.B. If the value is a
    constructor it returns the pair or triple representing the functions on the
    constructor. *)
 fun codeVal (Value{access = Global code, class, ...}, level: level, typeVarMap, instance, _, _) =
            applyToInstanceType(instance, class, level, typeVarMap, fn _ => code)

  |  codeVal (Value{access = Local{addr=ref locAddr, level=ref locLevel}, class, ...},
                    level, typeVarMap, instance, _, _) =
    let
        fun loadVar level = mkLoad (locAddr, level, locLevel) (* Argument or local *)
    in
        applyToInstanceType(instance, class, level, typeVarMap, loadVar)
    end

  |  codeVal (Value{access = Selected{addr, base}, class, ...}, level: level, typeVarMap, instance, _, _) =
       (* Select from a structure. *)
       applyToInstanceType(instance, class, level, typeVarMap, fn level => mkInd (addr, codeStruct (base, level)))

  |  codeVal (Value{access = Formal _, ...}, _, _, _, _, _) =
          raise InternalError "codeVal - Formal"

  |  codeVal (Value{access = Overloaded Print, ...}, _, _, [], lex, _) =
        (* If this appears in a structure return a null printer function.
           It has to have the polymorphic form with an extra lambda outside. *)
        let
            (* We should have a single entry for the type. *)
            open DEBUG
            (* The parameter is the reference used to control the print depth
               when the value is actually printed. *)
            val prettyOut = getPrintOutput (LEX.debugParams lex)
        in
            mkProc(
                mkProc(
                    CODETREE.mkEnv
                    (
                        [
                            mkNullDec
                            (mkEval(
                                mkConst(toMachineWord prettyOut),
                                [ mkConst(toMachineWord(PrettyString "?")) ])
                            )
                        ],
                        arg1 (* Returns its argument. *)
                    ),
                    1, "print()", [], 0),
                1, "print(P)", [], 0)
        end

  |  codeVal (Value{access = Overloaded Print, ...}, level: level, typeVarMap, [{value=argType, ...}], lex, _) =
        let 
            (* We should have a single entry for the type. *)
            open DEBUG
            (* The parameter is the reference used to control the print depth
               when the value is actually printed. *)
            val printDepthFun = getParameter printDepthFunTag (LEX.debugParams lex)
            and prettyOut = getPrintOutput (LEX.debugParams lex)
            val nLevel = newLevel level
        in
            (* Construct a function that gets the print code, prints it out and returns
               its argument. *)
            mkProc(
                CODETREE.mkEnv
                (
                    [
                        mkNullDec (
                            mkEval(
                                mkConst(toMachineWord prettyOut),
                                [
                                    mkEval(
                                        printerForType(argType, nLevel, typeVarMap),
                                        [
                                            mkTuple[arg1,
                                                mkEval(mkConst(toMachineWord printDepthFun), [CodeZero])]
                                        ])
                                ])
                        )
                    ],
                    arg1 (* Returns its argument. *)
                ),
                1, "print()", getClosure nLevel, 0)
        end

  |  codeVal (Value{access = Overloaded Print, ...}, _, _, _, _, _) =
        raise InternalError "Overloaded Print - wrong instance type"

  |  codeVal (Value{access = Overloaded MakeString, ...}, _, _, [], _, _) =
        (* If this appears in a structure produce a default version. *)
            mkInlproc(
                mkProc(mkConst(toMachineWord "?"), 1, "makestring()", [], 0),
                1, "makestring(P)", [], 0)

  |  codeVal (Value{access = Overloaded MakeString, ...}, level: level, typeVarMap, [{value=argType, ...}], _, _) =
        let
            val nLevel = newLevel level
        in
            (* Construct a function that gets the print code and prints it out using "uglyPrint". *)
            mkProc(
                mkEval(
                    mkConst(toMachineWord uglyPrint),
                    [
                        mkEval(
                            printerForType(argType, nLevel, typeVarMap),
                            [
                                mkTuple[arg1, mkConst(toMachineWord 10000)]
                            ])
                    ]),
                1, "makestring()", getClosure nLevel, 0)
        end

  |  codeVal (Value{access = Overloaded MakeString, ...}, _, _, _, _, _) =
        raise InternalError "Overloaded MakeString - wrong instance type"

  |  codeVal (Value{access = Overloaded GetPretty, ...}, level, typeVarMap, [], _, _) =
        let
            val nLevel = newLevel level
        in
            (* If this appears in a structure return a default function. *)
            mkProc(printerForType(badType, nLevel, typeVarMap), 1, "getPretty", getClosure nLevel, 0)
        end

  |  codeVal (Value{access = Overloaded GetPretty, ...}, level: level, typeVarMap, [{value=argType, ...}], _, _) =
       (* Get the pretty code for the specified argument. *)
            printerForType(argType, level, typeVarMap)

  |  codeVal (Value{access = Overloaded GetPretty, ...}, _, _, _, _, _) =
        raise InternalError "Overloaded GetPretty - wrong instance type"

  |  codeVal (Value{access = Overloaded AddPretty, ...}, _, _, [], _, _) =
        (* If this appears in a structure create a function that raises an exception if run. *)
        mkProc(
            mkConst (toMachineWord
                        (fn _ => raise Fail "addPrettyPrint: The argument type was not a simple type construction")),
            1, "AddPretty(P)", [], 0)

  |  codeVal (Value{access = Overloaded AddPretty, ...}, level: level, _, [{value=installType, ...}, {value=argPrints, ...}], lex, loc) =
        let 
         (* "instance" should be (int-> 'a -> 'b -> pretty) -> unit.
             We need to get the 'a and 'b.  This function installs a
             pretty printer against the type which matches 'b.
             The type 'a is related to type of 'b as follows:
             If 'b is a monotype t then 'a is ignored.
             If 'b is a unary type constructor 'c t then 'a must have
             type 'c * int -> pretty.
             If 'b is a binary or higher type constructor e.g. ('c, 'd, 'e) t
             then 'a must be a tuple of functions of the form
             ('c * int -> pretty, 'd * int -> pretty, 'e * int -> pretty).
             When the installed function is called it will be passed the
             appropriate argument functions which it can call to print the
             argument types.  *)
            val pretty = mkTypeVar (generalisable, false, false, false); (* Temporary hack. *)

            (* Find the last type constructor in the chain. We have to install
                 this against the last in the chain because type constructors in
                 different modules may be at different points in the chain. *)
              (* This does mean that it's not possible to install a
                 pretty printer for a type constructor rather than a datatype. *)
            fun followTypes (TypeConstruction{constr, args, ...}) =
                if not (tcIsAbbreviation constr)
                then SOME(tcIdentifier constr, constr, List.length args)
                else followTypes (makeEquivalent (constr, args))
            |   followTypes (TypeVar tv) =
                (
                    case tvValue tv of
                        EmptyType => NONE (* Unbound type variable *)
                    |   t => followTypes t
                )
            |   followTypes _ = NONE;

            val constrId = followTypes installType
            
            val () =
                case constrId of
                    NONE => ()
                |   SOME (_, constr, arity) =>
                    let
                        (* Check that the function tuple matches the arguments of the type
                           we're installing for. *)
                        (* Each entry should be a function of type 'a * int -> pretty *)
                        fun mkFn arg = mkFunctionType(mkProductType[arg, TYPESTRUCT.intType], pretty)
                        (* Create non-unifiable type vars to ensure this is properly polymorphic. *)
                        val typeVars = List.tabulate(arity, fn _ => mkTypeVar (0, false, true, false))
                        val tupleType =
                            case typeVars of
                                [] => (* No arg so must have unit. *)
				    unitType
                            |   [arg] => mkFn arg (* Just a single function. *)
                            |   args => mkProductType(List.map mkFn args)
                        val addPPType = mkFunctionType(argPrints, mkFunctionType(installType, pretty))
                        val testType = mkFunctionType(tupleType,
                            mkFunctionType(
                                mkTypeConstruction(tcName constr, constr, typeVars, [DeclaredAt loc]),
                                pretty))
                    in
                        checkPPType(addPPType, testType, "addPrettyPrint", lex, loc,
                            fn () =>
                                PrettyString "addPrettyPrint element functions must have type 'a * int -> pretty, 'b * int -> pretty, ... with one function for each type parameter")
                    end;

            (* Only report the error when the function is run.  Because addPrettyPrint is
               contained in the PolyML structure we may compile a reference to a polymorphic
               version of this for the structure record.  It's replaced in the final structure
               by this version. *)
        in
            case constrId of
                SOME (typeId, _, arity) =>
                    let
                        (* We need to transform the user-supplied function into the form required for
                           the reference.   The user function has type int -> 'b -> 'a -> pretty
                           where 'b is either "don't care" if this is a monotype, the print function
                           for the base type if it takes a single type argument or a tuple of base type
                           functions if it takes more than one.  The reference expects to contain a
                           function of type 'a * int -> pretty for a monotype or a function of the
                           form <'b1, 'b2...> -> 'a * int -> pretty if this is polytype where
                           <...> represents poly-style multiple arguments.  *)
                        val printFunction =
                            case arity of
                                0 => 
                                    mkProc(
                                        mkEval(
                                            mkEval(
                                                mkEval(
                                                    mkLoadClosure 0 (* The user-supplied fn *),
                                                    [mkInd(1, arg1)] (* The depth *)),
                                                [CodeZero] (* Ignored args. *)),
                                            [mkInd(0, arg1)] (* Value to print *)),
                                        1, "addPP-1", [arg1](* The user-supplied fn *), 0)

                            |   arity =>
                                let
                                    open TypeValue
                                    val args =
                                        if arity = 1
                                        then [extractPrinter(mkLoadClosure 1)]
                                        else [mkTuple(List.tabulate(arity, fn n => extractPrinter(mkLoadClosure(n+1))))]
                                in
                                    mkProc(
                                        mkProc(
                                            mkEval(
                                                mkEval(
                                                    mkEval(
                                                        mkLoadClosure 0 (* The user-supplied fn *),
                                                        [mkInd(1, arg1)] (* The depth *)),
                                                    args (* Base fns. *)),
                                                [mkInd(0, arg1)] (* Value to print *)),
                                            1, "addPP-2", mkLoadClosure 0 :: List.tabulate(arity, mkLoadArgument), 0),
                                        arity, "addPP-1", [arg1], 0)
                                end
                        val nLevel = newLevel level
                    in
                        (* Generate a function that will set the "print" ref for the type to
                           the argument function. *)
                        mkProc(
                            mkEval(
                                rtsFunction POLY_SYS_assign_word,
                                [TypeValue.extractPrinter(
                                    codeAccess(idAccess typeId, nLevel)), CodeZero, printFunction]
                                ), 1, "addPP", getClosure nLevel, 0)
                    end

            |   NONE =>
                    mkConst (toMachineWord
                        (fn _ => raise Fail "addPrettyPrint: The argument type was not a simple type construction"))
        end

  |  codeVal (Value{access = Overloaded AddPretty, ...}, _, _, _, _, _) =
        raise InternalError "Overloaded AddPretty - wrong instance type"

  |  codeVal (Value{access = Overloaded GetLocation, ...}, _, _, _, _, _) =
        (* This can't be used a value: It must be called immediately. *)
        let
            fun getLoc() =
                raise Fail "The special function PolyML.sourceLocation cannot be used as a value"
        in
            mkConst (toMachineWord getLoc)
        end

  |  codeVal (value as Value{access = Overloaded _, ...}, level: level, typeVarMap, instance, lex, lineno) =
        let
            val nLevel = newLevel level
        in
            (* AddOverload, Equal, NotEqual, TypeDep *)
            mkProc(applyFunction (value, arg1, nLevel, typeVarMap, instance, lex, lineno), 1, "", getClosure nLevel, 0)
        end

 (* Some of these have a more efficient way of calling them as functions. *)
 and applyFunction (value as Value{class=Exception, ...}, argument, level, typeVarMap, instance, lex, lineno) =
     let
       (* If we are applying it as a function we cannot be after the
          exception id, we must be constructing an exception packet. *)
       (* Get the exception id, put it in the packet with the exception name
          the argument and, currently, an empty location as the exception location. *)
         val exIden = codeVal (value, level, typeVarMap, instance, lex, lineno);
     in
         mkTuple (exIden :: mkStr (valName value) :: argument :: [mkConst(toMachineWord NoLocation)])
     end

  | applyFunction(value as Value{class=Constructor _, ...},
                    argument, level, typeVarMap, argVars, lex, lineno) =
    let
        (* If this is a value constructor we need to get the construction
           function and use that. *)
        fun getConstr level =
            ValueConstructor.extractInjection(codeVal (value, level, typeVarMap, [], lex, lineno))
        val polyConstr =
            applyToInstance(if justForEqualityTypes then [] else argVars, level, typeVarMap, getConstr)
    in
         (* Don't apply this "early".  It might be the ref constructor and that
           must not be applied until run-time.  The optimiser should take care
           of any other cases. *)
        mkEval (polyConstr, [argument])
    end

  | applyFunction (value as Value{access = Overloaded oper, name = valName, ...},
                     argument, level, typeVarMap, instance, lex, lineno) =
     (
       case oper of
            Equal => (* Get the equality function for the type. *)
            let
                (* We should have a single entry for the type. *)
                val argType =
                    case instance of
                        [{value, ...}] => value
                    |   _ => raise InternalError "Overload Equal"
                (* The instance type is a function so we have to get the first argument. *)
                val code = equalityForType(argType, level, typeVarMap)
            in
                mkEval (code, [argument])
            end
        
        | NotEqual =>
            let
                (* We should have a single entry for the type. *)
                val argType =
                    case instance of
                        [{value, ...}] => value
                    |   _ => raise InternalError "Overload NotEqual"
                (* Use the "=" function to provide inequality as well as equality. *)
                val code = equalityForType(argType, level, typeVarMap)
                val isEqual = mkEval (code, [argument])
            in
                mkNot isEqual
            end
       
        | TypeDep =>
           let
                val argType =
                    case instance of
                        [{value, ...}] => value
                    |   _ => raise InternalError "Overload TypeDep"
             val (code, _) = getOverloadInstance(valName, argType, false)
           in
             mkEval (code, [argument])
           end

       | AddOverload =>
            (* AddOverload is only intended for use by writers of library modules.
               It only does limited checking and should be regarded as "unsafe". *)
            let

            fun rmvars (TypeVar tv) = rmvars(tvValue tv)
            |   rmvars t = t
            (* instance should be ('a->'b) -> string -> unit.  For overloadings
               on most functions (e.g. abs and +) we are looking for the 'a, which
               may be a pair, but in the case of conversion functions we want the 'b. *)
            val (resultType, argType) =
                case instance of
                    [{value=alpha, ...}, {value=beta, ...}] => (rmvars alpha, rmvars beta)
                |   _ => (badType, badType)

            fun followTypes(TypeConstruction{constr as TypeConstrs {identifier = TypeId{idKind = Free _, ...},...}, ...}) = constr
 
            |   followTypes(TypeConstruction{constr as TypeConstrs {identifier = TypeId{idKind = TypeFn _, ...},...}, args, ...}) =
                    followTypes (makeEquivalent (constr, args))

            |   followTypes(TypeConstruction{constr = TypeConstrs {identifier = TypeId{idKind = Bound _, ...},...}, ...}) =
                   raise Fail "Cannot install an overload within a structure or functor"

            |   followTypes _ = raise Fail "Invalid type (not a type construction) (addOverload)"

            fun addOverloading (argCode: codetree) (name: string) =
                let
                    val typeToUse =
                        if size name > 4 andalso
                            String.substring(name, 0, 4) = "conv"
                        (* For conversion functions it's the result type we're interested in.
                           For everything else it's the argument type.  This will be a pair
                           for functions such as "+" and a single argument for "abs". *)
                        then resultType
                        else case argType of
                            LabelledType{recList=[{typeof, ...}, _], ...} => rmvars typeof
                        |   argType => argType
                            
                    val tcons = followTypes typeToUse
                in
                    addOverload(name, tcons, argCode)
                end

            (* This function is used if we can't get the codetree at
               compile time. *)
            fun addOverloadGeneral (arg: machineWord) =
                addOverloading(mkConst arg)
        in
        (* This is messy but necessary for efficiency.  If we simply treat
           addOverload as a function we would be able to pick up the
           additional overloading as a pointer to a function.  Most overloads
           are small functions or wrapped calls to RTS functions and so
           we need to get the inline code for them. *)
                (* evalue raises an exception if "argument" is not a constant,
                  or more usefully, a global value containing a constant and
                  possibly a piece of codetree to inline. *)
          case evalue(argument) of
            SOME _ => mkConst (toMachineWord (addOverloading argument))
          | NONE => mkEval (mkConst (toMachineWord addOverloadGeneral), [argument])
        end

      | GetLocation => (* Return the current location. *) mkConst(toMachineWord lineno)
        
      | _ => (* Print, MakeString, InstallPP *)
         (* Just call as functions. *) (* not early *)
            mkEval (codeVal (value, level, typeVarMap, instance, lex, lineno), [argument])
            
     ) (* overloaded *)
     
  | applyFunction (value, argument, level, typeVarMap, instance, lex, lineno) =
        mkEval (codeVal (value, level, typeVarMap, instance, lex, lineno), [argument])
    (* end applyFunction *)

  (* If the exception is being used as a value we want an exception packet
     or a function to make a packet. If it is a nullary constructor make
     an exception packet now, otherwise generate a function to construct
     an exception packet. *)
    fun codeExFunction (value, level, typeVarMap, instance, lex, lineno) =
    case getFnArgType(valTypeOf value) of (* N.B. Not "instance" *)
        NONE => applyFunction (value, CodeZero, level, typeVarMap, List.map addStatus instance, lex, lineno)
    |   SOME _ =>
            let
                val nLevel = newLevel level
            in
                mkProc 
                  (applyFunction (value, arg1, nLevel, typeVarMap, List.map addStatus instance, lex, lineno),
                    1, "", getClosure nLevel, 0)
            end

    (* Operations to compile code from the representation of a constructor. *)
    (* Code to test whether a value matches a constructor.
       This must be applied to any polymorphic variables in the instance but the
       result is always bool so we don't create a new function if the result is
       also polymorphic.
       It is just possible to have a resulting polytype here
       (N.B. that's different from having a parametric type) if we have a val binding.
        e.g. val SOME x = SOME nil.  In that case we can choose an arbitrary type
        for the test and have to parameterise the result.     *)
    fun makeGuard (value as Value{class=Constructor _, ...}, argVars, testing, level, typeVarMap) =
        let
            fun tester level =
                ValueConstructor.extractTest(codeVal (value, level, typeVarMap, [], nullLex, location nullLex))
            val testCode =
                applyToInstance(if justForEqualityTypes then [] else List.map addStatus argVars,
                                level, typeVarMap, tester)
        in
            mkEval(testCode, [testing])
        end

    |   makeGuard (value as Value{class=Exception, ...}, _, testing, level, typeVarMap) =
        (* Should only be an exception. Get the value of the exception identifier 
           and compare with the identifier in the exception packet. *)
        mkTestptreq 
            (mkInd (0, testing),
                codeVal (value, level, typeVarMap, [], nullLex, location nullLex))

    |   makeGuard _ = raise InternalError "makeGuard"

    (* Code to invert a constructor. i.e. return the value originally used as the argument.
       Apply to any polymorphic variables and construct a result. *)
    fun makeInverse(value as Value{class=Constructor{nullary=false, ...}, ...},
                    argVars, arg, level, typeVarMap): codetree =
        let
            fun getInverse level =
                ValueConstructor.extractProjection(codeVal (value, level, typeVarMap, [], nullLex, location nullLex))
            val loadCode =
                applyToInstance(if justForEqualityTypes then [] else List.map addStatus argVars,
                                level, typeVarMap, getInverse)
        in
            mkEval(loadCode, [arg])
        end

    |  makeInverse(Value{class=Constructor{nullary=true, ...}, ...}, _, _, _, _): codetree =
        (* makeInverse is called even on nullary constructors.  Return zero to keep the
           optimiser happy. *) CodeZero

    |   makeInverse (Value{class=Exception, ...}, _, arg, _, _) =
            (* Exceptions. - Get the parameter from third word *)
            (* We have to use a VarField here even though this field is present in
               every exception.  The format of the value that is returned depends
               on the exception id. *)
            mkVarField (2,arg)

    |   makeInverse _ = raise InternalError "makeInverse"

    (* Work out the polymorphism and the mapping between the formal
       type variables and the actual types.  Because flexible records
       may introduce extra polymorphism we can only do this once we've
       frozen them.  e.g. fun f x = #1 x + #2 x may be monomorphic or
       polymorphic depending on what it's subsequently applied to. *)
    (* Using unification here isn't ideal.  We have to put the equality attribute
       back on to abstypes in case the unification requires it.  There may be other
       situations where things don't work properly. *)
    fun getPolymorphism (Value{ typeOf, access, name, ...}, expType, typeVarMap) =
    let
        val (t, polyVars) =
            case access of
                Overloaded TypeDep =>
                let
                    val (t, polyVars) =
                        generaliseOverload(typeOf, List.map #1 (getOverloads name), false)
                in
                    (t, List.map (fn t => {value=t, equality=false, printity=false}) polyVars)
                end
            | _ => generaliseWithMap(typeOf, TypeVarMap.mapTypeVars typeVarMap)
        (* Ignore the result.  There are circumstances in which we can get a
           unification error as the result of failing to find a fixed record type
           where the possible records we could find have non-unifiable types.
           See Tests/Fail/Test072.ML *)
        val _ = unifyTypes(t, expType)
    in
        polyVars
    end

    (* Convert a literal constant. We can only do this once any overloading
       has been resolved. *)
    fun getLiteralValue(converter, literal, instance, error): machineWord option =
        let
            val (conv, name) =
                 getOverloadInstance(valName converter, instance, true)
        in
            SOME(RunCall.unsafeCast(valOf(evalue conv)) literal)
                handle Match => NONE (* Overload error *)
                  | Conversion s =>
                        (
                            error("Conversion exception ("^s^") raised while converting " ^
                                    literal ^ " to " ^ name);
                            NONE
                        )
                  | Overflow => 
                        (
                            error ("Overflow exception raised while converting " ^
                                    literal ^ " to " ^ name);
                            NONE
                        )
                  | Thread.Thread.Interrupt => raise Thread.Thread.Interrupt
                  | _ =>
                        (
                            error ("Exception raised while converting " ^
                                    literal ^ " to " ^ name);
                            NONE
                        )
        end

    (* Types that can be shared. *)
    structure Sharing =
    struct
        type lexan          = lexan
        type codetree       = codetree
        type types          = types
        type values         = values
        type structVals     = structVals
        type functors       = functors
        type valAccess      = valAccess
        type typeConstrs    = typeConstrs
        type typeConstrSet  = typeConstrSet
        type signatures     = signatures
        type fixStatus      = fixStatus
        type univTable      = univTable
        type pretty         = pretty
        type locationProp   = locationProp
        type typeId         = typeId
        type typeVarForm    = typeVarForm
        type typeVarMap     = typeVarMap
        type level          = level
        type machineWord    = machineWord
    end

end (* body of VALUEOPS *);