2 /* --------------------------------------------------------------------------
3 * GHC interface file processing for Hugs
5 * Copyright (c) The University of Nottingham and Yale University, 1994-1997.
6 * All rights reserved. See NOTICE for details and conditions of use etc...
7 * Hugs version 1.4, December 1997
9 * $RCSfile: interface.c,v $
11 * $Date: 1999/12/20 16:55:26 $
12 * ------------------------------------------------------------------------*/
20 #include "Assembler.h" /* for wrapping GHC objects */
27 extern void print ( Cell, Int );
29 /* --------------------------------------------------------------------------
30 * (This comment is now out of date. JRS, 991216).
31 * The "addGHC*" functions act as "impedence matchers" between GHC
32 * interface files and Hugs. Their main job is to convert abstract
33 * syntax trees into Hugs' internal representations.
35 * The main trick here is how we deal with mutually recursive interface
38 * o As we read an import decl, we add it to a list of required imports
39 * (unless it's already loaded, of course).
41 * o Processing of declarations is split into two phases:
43 * 1) While reading the interface files, we construct all the Names,
44 * Tycons, etc declared in the interface file but we don't try to
45 * resolve references to any entities the declaration mentions.
47 * This is done by the "addGHC*" functions.
49 * 2) After reading all the interface files, we finish processing the
50 * declarations by resolving any references in the declarations
51 * and doing any other processing that may be required.
53 * This is done by the "finishGHC*" functions which use the
54 * "fixup*" functions to assist them.
56 * The interface between these two phases are the "ghc*Decls" which
57 * contain lists of decls that haven't been completed yet.
59 * ------------------------------------------------------------------------*/
63 New comment, 991216, explaining roughly how it all works.
64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 Interfaces can contain references to unboxed types, and these need to
67 be handled carefully. The following is a summary of how the interface
68 loader now works. It is applied to groups of interfaces simultaneously,
69 viz, the entire Prelude at once:
71 0. Parse interfaces, chasing imports until a complete
72 strongly-connected-component of ifaces has been parsed.
73 All interfaces in this scc are processed together, in
76 1. Throw away any entity not mentioned in the export lists.
78 2. Delete type (not data or newtype) definitions which refer to
79 unknown types in their right hand sides. Because Hugs doesn't
80 know of any unboxed types, this has the side effect of removing
81 all type defns referring to unboxed types. Repeat step 2 until
82 a fixed point is reached.
84 3. Make abstract all data/newtype defns which refer to an unknown
85 type. eg, data Word = MkW Word# becomes data Word, because
86 Word# is unknown. Hugs is happy to know about abstract boxed
87 Words, but not about Word#s.
89 4. Step 2 could delete types referred to by values, instances and
90 classes. So filter all entities, and delete those referring to
91 unknown types _or_ classes. This could cause other entities
92 to become invalid, so iterate step 4 to a fixed point.
94 After step 4, the interfaces no longer contain anything
97 5. Steps 1-4 operate purely on the iface syntax trees. We now start
98 creating symbol table entries. First, create a module table
99 entry for each interface, and locate and read in the corresponding
100 object file. This is done by the startGHCModule function.
102 6. Traverse all interfaces. For each entity, create an entry in
103 the name, tycon, class or instance table, and fill in relevant
104 fields, but do not attempt to link tycon/class/instance/name uses
105 to their symbol table entries. This is done by the startGHC*
108 7. Revisit all symbol table entries created in step 6. We should
109 now be able to replace all references to tycons/classes/instances/
110 names with the relevant symbol table entries. This is done by
111 the finishGHC* functions.
113 8. Traverse all interfaces. For each iface, examine the export lists
114 and use it to build export lists in the module table. Do the
115 implicit 'import Prelude' thing if necessary. Finally, resolve
116 references in the object code for this module. This is done
117 by the finishGHCModule function.
120 /* --------------------------------------------------------------------------
121 * local function prototypes:
122 * ------------------------------------------------------------------------*/
124 static Void startGHCValue Args((Int,VarId,Type));
125 static Void finishGHCValue Args((VarId));
127 static Void startGHCSynonym Args((Int,Cell,List,Type));
128 static Void finishGHCSynonym Args((Tycon));
130 static Void startGHCClass Args((Int,List,Cell,List,List));
131 static Void finishGHCClass Args((Class));
133 static Inst startGHCInstance Args((Int,List,Pair,VarId));
134 static Void finishGHCInstance Args((Inst));
136 static Void startGHCImports Args((ConId,List));
137 static Void finishGHCImports Args((ConId,List));
139 static Void startGHCExports Args((ConId,List));
140 static Void finishGHCExports Args((ConId,List));
142 static Void finishGHCModule Args((Cell));
143 static Void startGHCModule Args((Text, Int, Text));
145 static Void startGHCDataDecl Args((Int,List,Cell,List,List));
146 static Void finishGHCDataDecl ( ConId tyc );
148 static Void startGHCNewType Args((Int,List,Cell,List,Cell));
149 static Void finishGHCNewType ( ConId tyc );
152 /* Supporting stuff for {start|finish}GHCDataDecl */
153 static List startGHCConstrs Args((Int,List,List));
154 static Name startGHCSel Args((Int,Pair));
155 static Name startGHCConstr Args((Int,Int,Triple));
159 static Kinds tvsToKind Args((List));
160 static Int arityFromType Args((Type));
161 static Int arityInclDictParams Args((Type));
162 static Bool allTypesKnown ( Type type, List aktys /* [QualId] */, ConId thisMod );
164 static List ifTyvarsIn Args((Type));
166 static Type tvsToOffsets Args((Int,Type,List));
167 static Type conidcellsToTycons Args((Int,Type));
169 static void* lookupObjName ( char* );
175 /* --------------------------------------------------------------------------
176 * Top-level interface processing
177 * ------------------------------------------------------------------------*/
179 /* getIEntityName :: I_IMPORT..I_VALUE -> ConVarId | NIL */
180 ConVarId getIEntityName ( Cell c )
183 case I_IMPORT: return NIL;
184 case I_INSTIMPORT: return NIL;
185 case I_EXPORT: return NIL;
186 case I_FIXDECL: return zthd3(unap(I_FIXDECL,c));
187 case I_INSTANCE: return NIL;
188 case I_TYPE: return zsel24(unap(I_TYPE,c));
189 case I_DATA: return zsel35(unap(I_DATA,c));
190 case I_NEWTYPE: return zsel35(unap(I_NEWTYPE,c));
191 case I_CLASS: return zsel35(unap(I_CLASS,c));
192 case I_VALUE: return zsnd3(unap(I_VALUE,c));
193 default: internal("getIEntityName");
198 /* Filter the contents of an interface, using the supplied predicate.
199 For flexibility, the predicate is passed as a second arg the value
200 extraArgs. This is a hack to get round the lack of partial applications
201 in C. Pred should not have any side effects. The dumpaction param
202 gives us the chance to print a message or some such for dumped items.
203 When a named entity is deleted, filterInterface also deletes the name
206 Cell filterInterface ( Cell root,
207 Bool (*pred)(Cell,Cell),
209 Void (*dumpAction)(Cell) )
212 Cell iface = unap(I_INTERFACE,root);
214 List deleted_ids = NIL; /* :: [ConVarId] */
216 for (tops = zsnd(iface); nonNull(tops); tops=tl(tops)) {
217 if (pred(hd(tops),extraArgs)) {
218 tops2 = cons( hd(tops), tops2 );
220 ConVarId deleted_id = getIEntityName ( hd(tops) );
221 if (nonNull(deleted_id))
222 deleted_ids = cons ( deleted_id, deleted_ids );
224 dumpAction ( hd(tops) );
227 tops2 = reverse(tops2);
229 /* Clean up the export list now. */
230 for (tops=tops2; nonNull(tops); tops=tl(tops)) {
231 if (whatIs(hd(tops))==I_EXPORT) {
232 Cell exdecl = unap(I_EXPORT,hd(tops));
233 List exlist = zsnd(exdecl);
235 for (; nonNull(exlist); exlist=tl(exlist)) {
236 Cell ex = hd(exlist);
237 ConVarId exid = isZPair(ex) ? zfst(ex) : ex;
238 assert (isCon(exid) || isVar(exid));
239 if (!varIsMember(textOf(exid),deleted_ids))
240 exlist2 = cons(ex, exlist2);
242 hd(tops) = ap(I_EXPORT,zpair(zfst(exdecl),exlist2));
246 return ap(I_INTERFACE, zpair(zfst(iface),tops2));
250 ZPair readInterface(String fname, Long fileSize)
254 ZPair iface = parseInterface(fname,fileSize);
255 assert (whatIs(iface)==I_INTERFACE);
257 for (tops = zsnd(unap(I_INTERFACE,iface)); nonNull(tops); tops=tl(tops))
258 if (whatIs(hd(tops)) == I_IMPORT) {
259 ZPair imp_decl = unap(I_IMPORT,hd(tops));
260 ConId m_to_imp = zfst(imp_decl);
261 if (textOf(m_to_imp) != findText("PrelGHC")) {
262 imports = cons(m_to_imp,imports);
263 /* fprintf(stderr, "add iface %s\n", textToStr(textOf(m_to_imp))); */
266 return zpair(iface,imports);
270 /* getExportDeclsInIFace :: I_INTERFACE -> [I_EXPORT] */
271 static List getExportDeclsInIFace ( Cell root )
273 Cell iface = unap(I_INTERFACE,root);
274 List decls = zsnd(iface);
277 for (ds=decls; nonNull(ds); ds=tl(ds))
278 if (whatIs(hd(ds))==I_EXPORT)
279 exports = cons(hd(ds), exports);
285 static Bool isExportedIFaceEntity ( Cell ife, List exlist_list )
287 /* ife :: I_IMPORT..I_VALUE */
288 /* exlist_list :: [[ ConVarId | ((ConId, [ConVarId])) ]] */
293 ConVarId ife_id = getIEntityName ( ife );
295 if (isNull(ife_id)) return TRUE;
297 tnm = textOf(ife_id);
299 /* for each export list ... */
300 for (; nonNull(exlist_list); exlist_list=tl(exlist_list)) {
301 exlist = hd(exlist_list);
303 /* for each entity in an export list ... */
304 for (t=exlist; nonNull(t); t=tl(t)) {
305 if (isZPair(hd(t))) {
306 /* A pair, which means an export entry
307 of the form ClassName(foo,bar). */
308 List subents = cons(zfst(hd(t)),zsnd(hd(t)));
309 for (; nonNull(subents); subents=tl(subents))
310 if (textOf(hd(subents)) == tnm) goto retain;
312 /* Single name in the list. */
313 if (textOf(hd(t)) == tnm) goto retain;
318 fprintf ( stderr, " dump %s\n", textToStr(tnm) );
322 fprintf ( stderr, " retain %s\n", textToStr(tnm) );
327 static Bool isExportedAbstractly ( ConId ife_id, List exlist_list )
329 /* ife_id :: ConId */
330 /* exlist_list :: [[ ConVarId | ((ConId, [ConVarId])) ]] */
335 assert (isCon(ife_id));
336 tnm = textOf(ife_id);
338 /* for each export list ... */
339 for (; nonNull(exlist_list); exlist_list=tl(exlist_list)) {
340 exlist = hd(exlist_list);
342 /* for each entity in an export list ... */
343 for (t=exlist; nonNull(t); t=tl(t)) {
344 if (isZPair(hd(t))) {
345 /* A pair, which means an export entry
346 of the form ClassName(foo,bar). */
347 if (textOf(zfst(hd(t))) == tnm) return FALSE;
349 if (textOf(hd(t)) == tnm) return TRUE;
353 internal("isExportedAbstractly");
354 return FALSE; /*notreached*/
358 /* Remove entities not mentioned in any of the export lists. */
359 static Cell deleteUnexportedIFaceEntities ( Cell root )
361 Cell iface = unap(I_INTERFACE,root);
362 ConId iname = zfst(iface);
363 List decls = zsnd(iface);
365 List exlist_list = NIL;
368 fprintf(stderr, "\ncleanIFace: %s\n", textToStr(textOf(iname)));
370 exlist_list = getExportDeclsInIFace ( root );
371 /* exlist_list :: [I_EXPORT] */
373 for (t=exlist_list; nonNull(t); t=tl(t))
374 hd(t) = zsnd(unap(I_EXPORT,hd(t)));
375 /* exlist_list :: [[ ConVarId | ((ConId, [ConVarId])) ]] */
377 if (isNull(exlist_list)) {
378 ERRMSG(0) "Can't find any export lists in interface file"
382 return filterInterface ( root, isExportedIFaceEntity,
387 /* addTyconsAndClassesFromIFace :: I_INTERFACE -> [QualId] -> [QualId] */
388 List addTyconsAndClassesFromIFace ( Cell root, List aktys )
390 Cell iface = unap(I_INTERFACE,root);
391 Text mname = textOf(zfst(iface));
392 List defns = zsnd(iface);
393 for (; nonNull(defns); defns = tl(defns)) {
394 Cell defn = hd(defns);
395 Cell what = whatIs(defn);
396 if (what==I_TYPE || what==I_DATA
397 || what==I_NEWTYPE || what==I_CLASS) {
398 QualId q = mkQCon ( mname, textOf(getIEntityName(defn)) );
399 if (!qualidIsMember ( q, aktys ))
400 aktys = cons ( q, aktys );
407 Void ifentityAllTypesKnown_dumpmsg ( Cell entity )
409 ConVarId id = getIEntityName ( entity );
411 "dumping %s because of unknown type(s)\n",
412 isNull(id) ? "(nameless entity?!)" : textToStr(textOf(id)) );
415 /* ifentityAllTypesKnown :: I_IMPORT..I_VALUE -> (([QualId], ConId)) -> Bool */
416 /* mod is the current module being processed -- so we can qualify unqual'd
417 names. Strange calling convention for aktys and mod is so we can call this
418 from filterInterface.
420 Bool ifentityAllTypesKnown ( Cell entity, ZPair aktys_mod )
423 List aktys = zfst ( aktys_mod );
424 ConId mod = zsnd ( aktys_mod );
425 switch (whatIs(entity)) {
432 Cell inst = unap(I_INSTANCE,entity);
433 List ctx = zsel25 ( inst ); /* :: [((QConId,VarId))] */
434 Type cls = zsel35 ( inst ); /* :: Type */
435 for (t = ctx; nonNull(t); t=tl(t))
436 if (!allTypesKnown(zfst(hd(t)),aktys,mod)) return FALSE;
437 if (!allTypesKnown(cls, aktys,mod)) return FALSE;
441 return allTypesKnown( zsel44(unap(I_TYPE,entity)), aktys,mod );
443 Cell data = unap(I_DATA,entity);
444 List ctx = zsel25 ( data ); /* :: [((QConId,VarId))] */
445 List constrs = zsel55 ( data ); /* :: [ ((ConId, [((Type,VarId,Int))] )) ] */
446 for (t = ctx; nonNull(t); t=tl(t))
447 if (!allTypesKnown(zfst(hd(t)),aktys,mod)) return FALSE;
448 for (t = constrs; nonNull(t); t=tl(t))
449 for (u = zsnd(hd(t)); nonNull(u); u=tl(u))
450 if (!allTypesKnown(zfst3(hd(u)),aktys,mod)) return FALSE;
454 Cell newty = unap(I_NEWTYPE,entity);
455 List ctx = zsel25(newty); /* :: [((QConId,VarId))] */
456 ZPair constr = zsel55 ( newty ); /* :: ((ConId,Type)) */
457 for (t = ctx; nonNull(t); t=tl(t))
458 if (!allTypesKnown(zfst(hd(t)),aktys,mod)) return FALSE;
460 && !allTypesKnown(zsnd(constr),aktys,mod)) return FALSE;
464 Cell klass = unap(I_CLASS,entity);
465 List ctx = zsel25(klass); /* :: [((QConId,VarId))] */
466 List sigs = zsel55(klass); /* :: [((VarId,Type))] */
467 for (t = ctx; nonNull(t); t=tl(t))
468 if (!allTypesKnown(zfst(hd(t)),aktys,mod)) return FALSE;
469 for (t = sigs; nonNull(t); t=tl(t))
470 if (!allTypesKnown(zsnd(hd(t)),aktys,mod)) return FALSE;
474 return allTypesKnown( zthd3(unap(I_VALUE,entity)), aktys,mod );
476 internal("ifentityAllTypesKnown");
482 I hope this can be nuked.
483 /* Kludge. Stuff imported from PrelGHC isn't referred to in a
484 qualified way, so arrange it so it is.
486 QualId magicRequalify ( ConId id )
493 fprintf ( stderr, "$--$--$--$--$--$ magicRequalify: %s",
496 if (tid == findText("[]")) {
497 tmid = findText("PrelList");
499 if (tid == findText("Ratio")) {
500 tmid = findText("PrelNum");
502 if (tid == findText("Char")) {
503 tmid = findText("PrelGHC");
505 fprintf(stderr, "??? \n");
509 fprintf ( stderr, " -> %s.%s\n",
510 textToStr(tmid), textToStr(tid) );
511 return mkQualId ( mkCon(tmid), id );
516 /* ifTypeDoesntRefUnknownTycon :: I_IMPORT..I_VALUE -> (([QualId], ConId)) -> Bool */
517 /* mod is the current module being processed -- so we can qualify unqual'd
518 names. Strange calling convention for aktys and mod is so we can call this
519 from filterInterface.
521 Bool ifTypeDoesntRefUnknownTycon ( Cell entity, ZPair aktys_mod )
524 List aktys = zfst ( aktys_mod );
525 ConId mod = zsnd ( aktys_mod );
526 if (whatIs(entity) != I_TYPE) {
529 return allTypesKnown( zsel44(unap(I_TYPE,entity)), aktys,mod );
533 Void ifTypeDoesntRefUnknownTycon_dumpmsg ( Cell entity )
535 ConVarId id = getIEntityName ( entity );
536 assert (whatIs(entity)==I_TYPE);
539 "dumping type %s because of unknown tycon(s)\n",
540 textToStr(textOf(id)) );
544 /* abstractifyExport :: I_EXPORT -> ConId -> I_EXPORT
546 List abstractifyExDecl ( Cell root, ConId toabs )
548 ZPair exdecl = unap(I_EXPORT,root);
549 List exlist = zsnd(exdecl);
551 for (; nonNull(exlist); exlist = tl(exlist)) {
552 if (isZPair(hd(exlist))
553 && textOf(toabs) == textOf(zfst(hd(exlist)))) {
554 /* it's toabs, exported non-abstractly */
555 res = cons ( zfst(hd(exlist)), res );
557 res = cons ( hd(exlist), res );
560 return ap(I_EXPORT,zpair(zfst(exdecl),reverse(res)));
564 Void ppModule ( Text modt )
566 fflush(stderr); fflush(stdout);
567 fprintf(stderr, "---------------- MODULE %s ----------------\n",
572 /* ifaces_outstanding holds a list of parsed interfaces
573 for which we need to load objects and create symbol
576 Void processInterfaces ( void )
587 List all_known_types;
590 List ifaces = NIL; /* :: List I_INTERFACE */
591 List iface_sizes = NIL; /* :: List Int */
592 List iface_onames = NIL; /* :: List Text */
595 "processInterfaces: %d interfaces to process\n",
596 length(ifaces_outstanding) );
599 /* unzip3 ifaces_outstanding into ifaces, iface_sizes, iface_onames */
600 for (xs = ifaces_outstanding; nonNull(xs); xs=tl(xs)) {
601 ifaces = cons ( zfst3(hd(xs)), ifaces );
602 iface_onames = cons ( zsnd3(hd(xs)), iface_onames );
603 iface_sizes = cons ( zthd3(hd(xs)), iface_sizes );
606 ifaces = reverse(ifaces);
607 iface_onames = reverse(iface_onames);
608 iface_sizes = reverse(iface_sizes);
610 /* Clean up interfaces -- dump non-exported value, class, type decls */
611 for (xs = ifaces; nonNull(xs); xs = tl(xs))
612 hd(xs) = deleteUnexportedIFaceEntities(hd(xs));
615 /* Iteratively delete any type declarations which refer to unknown
618 num_known_types = 999999999;
622 /* Construct a list of all known tycons. This is a list of QualIds.
623 Unfortunately it also has to contain all known class names, since
624 allTypesKnown cannot distinguish between tycons and classes -- a
625 deficiency of the iface abs syntax.
627 all_known_types = getAllKnownTyconsAndClasses();
628 for (xs = ifaces; nonNull(xs); xs=tl(xs))
629 all_known_types = addTyconsAndClassesFromIFace ( hd(xs), all_known_types );
631 /* Have we reached a fixed point? */
632 i = length(all_known_types);
633 printf ( "\n============= %d known types =============\n", i );
634 if (num_known_types == i) break;
637 /* Delete all entities which refer to unknown tycons. */
638 for (xs = ifaces; nonNull(xs); xs = tl(xs)) {
639 ConId mod = zfst(unap(I_INTERFACE,hd(xs)));
640 assert(nonNull(mod));
641 hd(xs) = filterInterface ( hd(xs),
642 ifTypeDoesntRefUnknownTycon,
643 zpair(all_known_types,mod),
644 ifTypeDoesntRefUnknownTycon_dumpmsg );
648 /* Now abstractify any datas and newtypes which refer to unknown tycons
649 -- including, of course, the type decls just deleted.
651 for (xs = ifaces; nonNull(xs); xs = tl(xs)) {
652 List absify = NIL; /* :: [ConId] */
653 ZPair iface = unap(I_INTERFACE,hd(xs)); /* ((ConId, [I_IMPORT..I_VALUE])) */
654 ConId mod = zfst(iface);
655 List aktys = all_known_types; /* just a renaming */
659 /* Compute into absify the list of all ConIds (tycons) we need to
662 for (es = zsnd(iface); nonNull(es); es=tl(es)) {
664 Bool allKnown = TRUE;
666 if (whatIs(ent)==I_DATA) {
667 Cell data = unap(I_DATA,ent);
668 List ctx = zsel25 ( data ); /* :: [((QConId,VarId))] */
669 List constrs = zsel55 ( data ); /* :: [ ((ConId, [((Type,VarId,Int))] )) ] */
670 for (t = ctx; nonNull(t); t=tl(t))
671 if (!allTypesKnown(zfst(hd(t)),aktys,mod)) allKnown = FALSE;
672 for (t = constrs; nonNull(t); t=tl(t))
673 for (u = zsnd(hd(t)); nonNull(u); u=tl(u))
674 if (!allTypesKnown(zfst3(hd(u)),aktys,mod)) allKnown = FALSE;
676 else if (whatIs(ent)==I_NEWTYPE) {
677 Cell newty = unap(I_NEWTYPE,ent);
678 List ctx = zsel25(newty); /* :: [((QConId,VarId))] */
679 ZPair constr = zsel55 ( newty ); /* :: ((ConId,Type)) */
680 for (t = ctx; nonNull(t); t=tl(t))
681 if (!allTypesKnown(zfst(hd(t)),aktys,mod)) allKnown = FALSE;
682 if (!allTypesKnown(zsnd(constr),aktys,mod)) allKnown = FALSE;
686 absify = cons ( getIEntityName(ent), absify );
688 "abstractifying %s because it uses an unknown type\n",
689 textToStr(textOf(getIEntityName(ent))) );
693 /* mark in exports as abstract all names in absify (modifies iface) */
694 for (; nonNull(absify); absify=tl(absify)) {
695 ConId toAbs = hd(absify);
696 for (es = zsnd(iface); nonNull(es); es=tl(es)) {
697 if (whatIs(hd(es)) != I_EXPORT) continue;
698 hd(es) = abstractifyExDecl ( hd(es), toAbs );
702 /* For each data/newtype in the export list marked as abstract,
703 remove the constructor lists. This catches all abstractification
704 caused by the code above, and it also catches tycons which really
705 were exported abstractly.
708 exlist_list = getExportDeclsInIFace ( ap(I_INTERFACE,iface) );
709 /* exlist_list :: [I_EXPORT] */
710 for (t=exlist_list; nonNull(t); t=tl(t))
711 hd(t) = zsnd(unap(I_EXPORT,hd(t)));
712 /* exlist_list :: [[ ConVarId | ((ConId, [ConVarId])) ]] */
714 for (es = zsnd(iface); nonNull(es); es=tl(es)) {
716 if (whatIs(ent)==I_DATA
717 && isExportedAbstractly ( getIEntityName(ent),
719 Cell data = unap(I_DATA,ent);
720 data = z5ble ( zsel15(data), zsel25(data), zsel35(data),
721 zsel45(data), NIL /* the constr list */ );
722 hd(es) = ap(I_DATA,data);
723 fprintf(stderr, "abstractify data %s\n", textToStr(textOf(getIEntityName(ent))) );
725 else if (whatIs(ent)==I_NEWTYPE
726 && isExportedAbstractly ( getIEntityName(ent),
728 Cell data = unap(I_NEWTYPE,ent);
729 data = z5ble ( zsel15(data), zsel25(data), zsel35(data),
730 zsel45(data), NIL /* the constr-type pair */ );
731 hd(es) = ap(I_NEWTYPE,data);
732 fprintf(stderr, "abstractify newtype %s\n", textToStr(textOf(getIEntityName(ent))) );
736 /* We've finally finished mashing this iface. Update the iface list. */
737 hd(xs) = ap(I_INTERFACE,iface);
741 /* At this point, the interfaces are cleaned up so that no type, data or
742 newtype defn refers to a non-existant type. However, there still may
743 be value defns, classes and instances which refer to unknown types.
744 Delete iteratively until a fixed point is reached.
748 num_known_types = 999999999;
752 /* Construct a list of all known tycons. This is a list of QualIds.
753 Unfortunately it also has to contain all known class names, since
754 allTypesKnown cannot distinguish between tycons and classes -- a
755 deficiency of the iface abs syntax.
757 all_known_types = getAllKnownTyconsAndClasses();
758 for (xs = ifaces; nonNull(xs); xs=tl(xs))
759 all_known_types = addTyconsAndClassesFromIFace ( hd(xs), all_known_types );
761 /* Have we reached a fixed point? */
762 i = length(all_known_types);
763 printf ( "\n------------- %d known types -------------\n", i );
764 if (num_known_types == i) break;
767 /* Delete all entities which refer to unknown tycons. */
768 for (xs = ifaces; nonNull(xs); xs = tl(xs)) {
769 ConId mod = zfst(unap(I_INTERFACE,hd(xs)));
770 assert(nonNull(mod));
772 hd(xs) = filterInterface ( hd(xs),
773 ifentityAllTypesKnown,
774 zpair(all_known_types,mod),
775 ifentityAllTypesKnown_dumpmsg );
780 /* Allocate module table entries and read in object code. */
783 xs=tl(xs), iface_sizes=tl(iface_sizes), iface_onames=tl(iface_onames)) {
784 startGHCModule ( textOf(zfst(unap(I_INTERFACE,hd(xs)))),
785 intOf(hd(iface_sizes)),
788 assert (isNull(iface_sizes));
789 assert (isNull(iface_onames));
792 /* Now work through the decl lists of the modules, and call the
793 startGHC* functions on the entities. This creates names in
794 various tables but doesn't bind them to anything.
797 for (xs = ifaces; nonNull(xs); xs = tl(xs)) {
798 iface = unap(I_INTERFACE,hd(xs));
799 mname = textOf(zfst(iface));
800 mod = findModule(mname);
801 if (isNull(mod)) internal("processInterfaces(4)");
803 ppModule ( module(mod).text );
805 for (decls = zsnd(iface); nonNull(decls); decls = tl(decls)) {
806 Cell decl = hd(decls);
807 switch(whatIs(decl)) {
809 Cell exdecl = unap(I_EXPORT,decl);
810 startGHCExports ( zfst(exdecl), zsnd(exdecl) );
814 Cell imdecl = unap(I_IMPORT,decl);
815 startGHCImports ( zfst(imdecl), zsnd(imdecl) );
822 /* Trying to find the instance table location allocated by
823 startGHCInstance in subsequent processing is a nightmare, so
824 cache it on the tree.
826 Cell instance = unap(I_INSTANCE,decl);
827 Inst in = startGHCInstance ( zsel15(instance), zsel25(instance),
828 zsel35(instance), zsel45(instance) );
829 hd(decls) = ap(I_INSTANCE,
830 z5ble( zsel15(instance), zsel25(instance),
831 zsel35(instance), zsel45(instance), in ));
835 Cell tydecl = unap(I_TYPE,decl);
836 startGHCSynonym ( zsel14(tydecl), zsel24(tydecl),
837 zsel34(tydecl), zsel44(tydecl) );
841 Cell ddecl = unap(I_DATA,decl);
842 startGHCDataDecl ( zsel15(ddecl), zsel25(ddecl),
843 zsel35(ddecl), zsel45(ddecl), zsel55(ddecl) );
847 Cell ntdecl = unap(I_NEWTYPE,decl);
848 startGHCNewType ( zsel15(ntdecl), zsel25(ntdecl),
849 zsel35(ntdecl), zsel45(ntdecl),
854 Cell klass = unap(I_CLASS,decl);
855 startGHCClass ( zsel15(klass), zsel25(klass),
856 zsel35(klass), zsel45(klass),
861 Cell value = unap(I_VALUE,decl);
862 startGHCValue ( zfst3(value), zsnd3(value), zthd3(value) );
866 internal("processInterfaces(1)");
871 fprintf(stderr, "\n=========================================================\n");
872 fprintf(stderr, "=========================================================\n");
874 /* Traverse again the decl lists of the modules, this time
875 calling the finishGHC* functions. But don't process
876 the export lists; those must wait for later.
878 for (xs = ifaces; nonNull(xs); xs = tl(xs)) {
879 iface = unap(I_INTERFACE,hd(xs));
880 mname = textOf(zfst(iface));
881 mod = findModule(mname);
882 if (isNull(mod)) internal("processInterfaces(3)");
884 ppModule ( module(mod).text );
886 for (decls = zsnd(iface); nonNull(decls); decls = tl(decls)) {
887 Cell decl = hd(decls);
888 switch(whatIs(decl)) {
899 Cell instance = unap(I_INSTANCE,decl);
900 finishGHCInstance ( zsel55(instance) );
904 Cell tydecl = unap(I_TYPE,decl);
905 finishGHCSynonym ( zsel24(tydecl) );
909 Cell ddecl = unap(I_DATA,decl);
910 finishGHCDataDecl ( zsel35(ddecl) );
914 Cell ntdecl = unap(I_NEWTYPE,decl);
915 finishGHCNewType ( zsel35(ntdecl) );
919 Cell klass = unap(I_CLASS,decl);
920 finishGHCClass ( zsel35(klass) );
924 Cell value = unap(I_VALUE,decl);
925 finishGHCValue ( zsnd3(value) );
929 internal("processInterfaces(2)");
934 fprintf(stderr, "\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
935 fprintf(stderr, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
936 /* Build the module(m).export lists for each module, by running
937 through the export lists in the iface. Also, do the implicit
938 'import Prelude' thing. And finally, do the object code
941 for (xs = ifaces; nonNull(xs); xs = tl(xs))
942 finishGHCModule(hd(xs));
945 ifaces_outstanding = NIL;
949 /* --------------------------------------------------------------------------
951 * ------------------------------------------------------------------------*/
953 void startGHCModule_errMsg ( char* msg )
955 fprintf ( stderr, "object error: %s\n", msg );
958 void* startGHCModule_clientLookup ( char* sym )
960 /* fprintf ( stderr, "CLIENTLOOKUP %s\n", sym ); */
961 return lookupObjName ( sym );
964 ObjectCode* startGHCModule_partial_load ( String objNm, Int objSz )
967 = ocNew ( startGHCModule_errMsg,
968 startGHCModule_clientLookup,
972 ERRMSG(0) "Storage allocation for object file \"%s\" failed", objNm
975 if (!ocLoadImage(oc,VERBOSE)) {
976 ERRMSG(0) "Reading of object file \"%s\" failed", objNm
979 if (!ocVerifyImage(oc,VERBOSE)) {
980 ERRMSG(0) "Validation of object file \"%s\" failed", objNm
983 if (!ocGetNames(oc,0||VERBOSE)) {
984 ERRMSG(0) "Reading of symbol names in object file \"%s\" failed", objNm
990 Void startGHCModule ( Text mname, Int sizeObj, Text nameObj )
993 Module m = findModule(mname);
996 m = newModule(mname);
997 fprintf ( stderr, "startGHCIface: name %16s objsize %d\n",
998 textToStr(mname), sizeObj );
1000 if (module(m).fake) {
1001 module(m).fake = FALSE;
1003 ERRMSG(0) "Module \"%s\" already loaded", textToStr(mname)
1008 /* Get hold of the primary object for the module. */
1010 = startGHCModule_partial_load ( textToStr(nameObj), sizeObj );
1012 /* and any extras ... */
1013 for (xts = module(m).objectExtraNames; nonNull(xts); xts=tl(xts)) {
1017 String nm = getExtraObjectInfo ( textToStr(nameObj),
1021 ERRMSG(0) "Can't find extra object file \"%s\"", nm
1024 oc = startGHCModule_partial_load ( nm, size );
1025 oc->next = module(m).objectExtras;
1026 module(m).objectExtras = oc;
1031 /* For the module mod, augment both the export environment (.exports)
1032 and the eval environment (.names, .tycons, .classes)
1033 with the symbols mentioned in exlist. We don't actually need
1034 to modify the names, tycons, classes or instances in the eval
1035 environment, since previous processing of the
1036 top-level decls in the iface should have done this already.
1038 mn is the module mentioned in the export list; it is the "original"
1039 module for the symbols in the export list. We should also record
1040 this info with the symbols, since references to object code need to
1041 refer to the original module in which a symbol was defined, rather
1042 than to some module it has been imported into and then re-exported.
1044 We take the policy that if something mentioned in an export list
1045 can't be found in the symbol tables, it is simply ignored. After all,
1046 previous processing of the iface syntax trees has already removed
1047 everything which Hugs can't handle, so if there is mention of these
1048 things still lurking in export lists somewhere, about the only thing
1049 to do is to ignore it.
1051 Also do an implicit 'import Prelude' thingy for the module,
1056 Void finishGHCModule ( Cell root )
1058 /* root :: I_INTERFACE */
1059 Cell iface = unap(I_INTERFACE,root);
1060 ConId iname = zfst(iface);
1061 Module mod = findModule(textOf(iname));
1062 List exlist_list = NIL;
1066 fprintf(stderr, "begin finishGHCModule %s\n", textToStr(textOf(iname)));
1068 if (isNull(mod)) internal("finishExports(1)");
1071 exlist_list = getExportDeclsInIFace ( root );
1072 /* exlist_list :: [I_EXPORT] */
1074 for (; nonNull(exlist_list); exlist_list=tl(exlist_list)) {
1075 ZPair exdecl = unap(I_EXPORT,hd(exlist_list));
1076 ConId exmod = zfst(exdecl);
1077 List exlist = zsnd(exdecl);
1078 /* exlist :: [ ConVarId | ((ConId, [ConVarId])) ] */
1080 for (; nonNull(exlist); exlist=tl(exlist)) {
1085 Cell ex = hd(exlist);
1087 switch (whatIs(ex)) {
1089 case VARIDCELL: /* variable */
1090 q = mkQualId(exmod,ex);
1091 c = findQualNameWithoutConsultingExportList ( q );
1092 if (isNull(c)) goto notfound;
1093 fprintf(stderr, " var %s\n", textToStr(textOf(ex)) );
1094 module(mod).exports = cons(c, module(mod).exports);
1097 case CONIDCELL: /* non data tycon */
1098 q = mkQualId(exmod,ex);
1099 c = findQualTyconWithoutConsultingExportList ( q );
1100 if (isNull(c)) goto notfound;
1101 fprintf(stderr, " type %s\n", textToStr(textOf(ex)) );
1102 module(mod).exports = cons(c, module(mod).exports);
1105 case ZTUP2: /* data T = C1 ... Cn or class C where f1 ... fn */
1106 subents = zsnd(ex); /* :: [ConVarId] */
1107 ex = zfst(ex); /* :: ConId */
1108 q = mkQualId(exmod,ex);
1109 c = findQualTyconWithoutConsultingExportList ( q );
1111 if (nonNull(c)) { /* data */
1112 fprintf(stderr, " data/newtype %s = { ", textToStr(textOf(ex)) );
1113 assert(tycon(c).what == DATATYPE || tycon(c).what==NEWTYPE);
1114 abstract = isNull(tycon(c).defn);
1115 /* This data/newtype could be abstract even tho the export list
1116 says to export it non-abstractly. That happens if it was
1117 imported from some other module and is now being re-exported,
1118 and previous cleanup phases have abstractified it in the
1119 original (defining) module.
1122 module(mod).exports = cons ( ex, module(mod).exports );
1123 fprintf ( stderr, "(abstract) ");
1125 module(mod).exports = cons(pair(c,DOTDOT), module(mod).exports);
1126 for (; nonNull(subents); subents = tl(subents)) {
1127 Cell ent2 = hd(subents);
1128 assert(isCon(ent2) || isVar(ent2));
1129 /* isVar since could be a field name */
1130 q = mkQualId(exmod,ent2);
1131 c = findQualNameWithoutConsultingExportList ( q );
1132 fprintf(stderr, "%s ", textToStr(name(c).text));
1134 module(mod).exports = cons(c, module(mod).exports);
1137 fprintf(stderr, "}\n" );
1138 } else { /* class */
1139 q = mkQualId(exmod,ex);
1140 c = findQualClassWithoutConsultingExportList ( q );
1141 if (isNull(c)) goto notfound;
1142 fprintf(stderr, " class %s { ", textToStr(textOf(ex)) );
1143 module(mod).exports = cons(pair(c,DOTDOT), module(mod).exports);
1144 for (; nonNull(subents); subents = tl(subents)) {
1145 Cell ent2 = hd(subents);
1146 assert(isVar(ent2));
1147 q = mkQualId(exmod,ent2);
1148 c = findQualNameWithoutConsultingExportList ( q );
1149 fprintf(stderr, "%s ", textToStr(name(c).text));
1150 if (isNull(c)) goto notfound;
1151 module(mod).exports = cons(c, module(mod).exports);
1153 fprintf(stderr, "}\n" );
1158 internal("finishExports(2)");
1161 continue; /* so notfound: can be placed after this */
1164 /* q holds what ain't found */
1165 assert(whatIs(q)==QUALIDENT);
1166 fprintf( stderr, " ------ IGNORED: %s.%s\n",
1167 textToStr(qmodOf(q)), textToStr(qtextOf(q)) );
1172 if (preludeLoaded) {
1173 /* do the implicit 'import Prelude' thing */
1174 List pxs = module(modulePrelude).exports;
1175 for (; nonNull(pxs); pxs=tl(pxs)) {
1178 switch (whatIs(px)) {
1183 module(mod).names = cons ( px, module(mod).names );
1186 module(mod).tycons = cons ( px, module(mod).tycons );
1189 module(mod).classes = cons ( px, module(mod).classes );
1192 fprintf(stderr, "finishGHCModule: unknown tag %d\n", whatIs(px));
1193 internal("finishGHCModule -- implicit import Prelude");
1199 /* Last, but by no means least ... */
1200 if (!ocResolve(module(mod).object,0||VERBOSE))
1201 internal("finishGHCModule: object resolution failed");
1203 for (oc=module(mod).objectExtras; oc; oc=oc->next) {
1204 if (!ocResolve(oc, 0||VERBOSE))
1205 internal("finishGHCModule: extra object resolution failed");
1210 /* --------------------------------------------------------------------------
1212 * ------------------------------------------------------------------------*/
1214 Void startGHCExports ( ConId mn, List exlist )
1217 printf("startGHCExports %s\n", textToStr(textOf(mn)) );
1219 /* Nothing to do. */
1222 Void finishGHCExports ( ConId mn, List exlist )
1225 printf("finishGHCExports %s\n", textToStr(textOf(mn)) );
1227 /* Nothing to do. */
1231 /* --------------------------------------------------------------------------
1233 * ------------------------------------------------------------------------*/
1235 Void startGHCImports ( ConId mn, List syms )
1236 /* nm the module to import from */
1237 /* syms [ConId | VarId] -- the names to import */
1240 printf("startGHCImports %s\n", textToStr(textOf(mn)) );
1242 /* Nothing to do. */
1246 Void finishGHCImports ( ConId nm, List syms )
1247 /* nm the module to import from */
1248 /* syms [ConId | VarId] -- the names to import */
1251 printf("finishGHCImports %s\n", textToStr(textOf(nm)) );
1253 /* Nothing to do. */
1257 /* --------------------------------------------------------------------------
1259 * ------------------------------------------------------------------------*/
1261 void startGHCValue ( Int line, VarId vid, Type ty )
1265 Text v = textOf(vid);
1268 printf("begin startGHCValue %s\n", textToStr(v));
1273 ERRMSG(0) "Attempt to redefine variable \"%s\"", textToStr(v)
1278 tvs = ifTyvarsIn(ty);
1279 for (tmp=tvs; nonNull(tmp); tmp=tl(tmp))
1280 hd(tmp) = zpair(hd(tmp),STAR);
1282 ty = mkPolyType(tvsToKind(tvs),ty);
1284 ty = tvsToOffsets(line,ty,tvs);
1286 name(n).arity = arityInclDictParams(ty);
1287 name(n).line = line;
1291 void finishGHCValue ( VarId vid )
1293 Name n = findName ( textOf(vid) );
1294 Int line = name(n).line;
1296 fprintf(stderr, "begin finishGHCValue %s\n", textToStr(name(n).text) );
1298 assert(currentModule == name(n).mod);
1299 name(n).type = conidcellsToTycons(line,name(n).type);
1303 /* --------------------------------------------------------------------------
1305 * ------------------------------------------------------------------------*/
1307 Void startGHCSynonym ( Int line, ConId tycon, List tvs, Type ty )
1309 /* tycon :: ConId */
1310 /* tvs :: [((VarId,Kind))] */
1312 Text t = textOf(tycon);
1314 fprintf(stderr, "begin startGHCSynonym %s\n", textToStr(t) );
1316 if (nonNull(findTycon(t))) {
1317 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
1321 Tycon tc = newTycon(t);
1322 tycon(tc).line = line;
1323 tycon(tc).arity = length(tvs);
1324 tycon(tc).what = SYNONYM;
1325 tycon(tc).kind = tvsToKind(tvs);
1327 /* prepare for finishGHCSynonym */
1328 tycon(tc).defn = tvsToOffsets(line,ty,tvs);
1333 static Void finishGHCSynonym ( ConId tyc )
1335 Tycon tc = findTycon(textOf(tyc));
1336 Int line = tycon(tc).line;
1338 fprintf(stderr, "begin finishGHCSynonym %s\n", textToStr(textOf(tyc)) );
1341 assert (currentModule == tycon(tc).mod);
1342 // setCurrModule(tycon(tc).mod);
1343 tycon(tc).defn = conidcellsToTycons(line,tycon(tc).defn);
1345 /* (ADR) ToDo: can't really do this until I've done all synonyms
1346 * and then I have to do them in order
1347 * tycon(tc).defn = fullExpand(ty);
1348 * (JRS) What?!?! i don't understand
1353 /* --------------------------------------------------------------------------
1355 * ------------------------------------------------------------------------*/
1357 Void startGHCDataDecl(line,ctx0,tycon,ktyvars,constrs0)
1359 List ctx0; /* [((QConId,VarId))] */
1360 Cell tycon; /* ConId */
1361 List ktyvars; /* [((VarId,Kind))] */
1362 List constrs0; /* [((ConId,[((Type,VarId,Int))]))] */
1363 /* The Text is an optional field name
1364 The Int indicates strictness */
1365 /* ToDo: worry about being given a decl for (->) ?
1366 * and worry about qualidents for ()
1369 Type ty, resTy, selTy, conArgTy;
1370 List tmp, conArgs, sels, constrs, fields, tyvarsMentioned;
1374 Pair conArg, ctxElem;
1376 Int conArgStrictness;
1378 Text t = textOf(tycon);
1380 fprintf(stderr, "begin startGHCDataDecl %s\n",textToStr(t));
1383 if (nonNull(findTycon(t))) {
1384 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
1388 Tycon tc = newTycon(t);
1390 tycon(tc).line = line;
1391 tycon(tc).arity = length(ktyvars);
1392 tycon(tc).kind = tvsToKind(ktyvars);
1393 tycon(tc).what = DATATYPE;
1395 /* a list to accumulate selectors in :: [((VarId,Type))] */
1398 /* make resTy the result type of the constr, T v1 ... vn */
1400 for (tmp=ktyvars; nonNull(tmp); tmp=tl(tmp))
1401 resTy = ap(resTy,fst(hd(tmp)));
1403 /* for each constructor ... */
1404 for (constrs=constrs0; nonNull(constrs); constrs=tl(constrs)) {
1405 constr = hd(constrs);
1406 conid = zfst(constr);
1407 fields = zsnd(constr);
1409 /* Build type of constr and handle any selectors found.
1410 Also collect up tyvars occurring in the constr's arg
1411 types, so we can throw away irrelevant parts of the
1415 tyvarsMentioned = NIL;
1416 /* tyvarsMentioned :: [VarId] */
1418 conArgs = reverse(fields);
1419 for (; nonNull(conArgs); conArgs=tl(conArgs)) {
1420 conArg = hd(conArgs); /* (Type,Text) */
1421 conArgTy = zfst3(conArg);
1422 conArgNm = zsnd3(conArg);
1423 conArgStrictness = intOf(zthd3(conArg));
1424 tyvarsMentioned = dupListOnto(ifTyvarsIn(conArgTy),
1426 if (conArgStrictness > 0) conArgTy = bang(conArgTy);
1427 ty = fn(conArgTy,ty);
1428 if (nonNull(conArgNm)) {
1429 /* a field name is mentioned too */
1430 selTy = fn(resTy,conArgTy);
1431 if (whatIs(tycon(tc).kind) != STAR)
1432 selTy = pair(POLYTYPE,pair(tycon(tc).kind, selTy));
1433 selTy = tvsToOffsets(line,selTy, ktyvars);
1434 sels = cons( zpair(conArgNm,selTy), sels);
1438 /* Now ty is the constructor's type, not including context.
1439 Throw away any parts of the context not mentioned in
1440 tyvarsMentioned, and use it to qualify ty.
1443 for (ctx=ctx0; nonNull(ctx); ctx=tl(ctx)) {
1445 /* ctxElem :: ((QConId,VarId)) */
1446 if (nonNull(cellIsMember(textOf(zsnd(ctxElem)),tyvarsMentioned)))
1447 ctx2 = cons(ctxElem, ctx2);
1450 ty = ap(QUAL,pair(ctx2,ty));
1452 /* stick the tycon's kind on, if not simply STAR */
1453 if (whatIs(tycon(tc).kind) != STAR)
1454 ty = pair(POLYTYPE,pair(tycon(tc).kind, ty));
1456 ty = tvsToOffsets(line,ty, ktyvars);
1458 /* Finally, stick the constructor's type onto it. */
1459 hd(constrs) = ztriple(conid,fields,ty);
1462 /* Final result is that
1463 constrs :: [((ConId,[((Type,Text))],Type))]
1464 lists the constructors and their types
1465 sels :: [((VarId,Type))]
1466 lists the selectors and their types
1468 tycon(tc).defn = startGHCConstrs(line,constrs0,sels);
1473 static List startGHCConstrs ( Int line, List cons, List sels )
1475 /* cons :: [((ConId,[((Type,Text,Int))],Type))] */
1476 /* sels :: [((VarId,Type))] */
1477 /* returns [Name] */
1479 Int conNo = length(cons)>1 ? 1 : 0;
1480 for(cs=cons; nonNull(cs); cs=tl(cs), conNo++) {
1481 Name c = startGHCConstr(line,conNo,hd(cs));
1484 /* cons :: [Name] */
1486 for(ss=sels; nonNull(ss); ss=tl(ss)) {
1487 hd(ss) = startGHCSel(line,hd(ss));
1489 /* sels :: [Name] */
1490 return appendOnto(cons,sels);
1494 static Name startGHCSel ( Int line, ZPair sel )
1496 /* sel :: ((VarId, Type)) */
1497 Text t = textOf(zfst(sel));
1498 Type type = zsnd(sel);
1500 Name n = findName(t);
1502 ERRMSG(line) "Repeated definition for selector \"%s\"",
1508 name(n).line = line;
1509 name(n).number = SELNAME;
1512 name(n).type = type;
1517 static Name startGHCConstr ( Int line, Int conNo, ZTriple constr )
1519 /* constr :: ((ConId,[((Type,Text,Int))],Type)) */
1520 /* (ADR) ToDo: add rank2 annotation and existential annotation
1521 * these affect how constr can be used.
1523 Text con = textOf(zfst3(constr));
1524 Type type = zthd3(constr);
1525 Int arity = arityFromType(type);
1526 Name n = findName(con); /* Allocate constructor fun name */
1528 n = newName(con,NIL);
1529 } else if (name(n).defn!=PREDEFINED) {
1530 ERRMSG(line) "Repeated definition for constructor \"%s\"",
1534 name(n).arity = arity; /* Save constructor fun details */
1535 name(n).line = line;
1536 name(n).number = cfunNo(conNo);
1537 name(n).type = type;
1542 static Void finishGHCDataDecl ( ConId tyc )
1545 Tycon tc = findTycon(textOf(tyc));
1547 printf ( "begin finishGHCDataDecl %s\n", textToStr(textOf(tyc)) );
1549 if (isNull(tc)) internal("finishGHCDataDecl");
1551 for (nms=tycon(tc).defn; nonNull(nms); nms=tl(nms)) {
1553 Int line = name(n).line;
1554 assert(currentModule == name(n).mod);
1555 name(n).type = conidcellsToTycons(line,name(n).type);
1560 /* --------------------------------------------------------------------------
1562 * ------------------------------------------------------------------------*/
1564 Void startGHCNewType ( Int line, List ctx0,
1565 ConId tycon, List tvs, Cell constr )
1567 /* ctx0 :: [((QConId,VarId))] */
1568 /* tycon :: ConId */
1569 /* tvs :: [((VarId,Kind))] */
1570 /* constr :: ((ConId,Type)) or NIL if abstract */
1573 Text t = textOf(tycon);
1575 fprintf(stderr, "begin startGHCNewType %s\n", textToStr(t) );
1577 if (nonNull(findTycon(t))) {
1578 ERRMSG(line) "Repeated definition of type constructor \"%s\"",
1582 Tycon tc = newTycon(t);
1583 tycon(tc).line = line;
1584 tycon(tc).arity = length(tvs);
1585 tycon(tc).what = NEWTYPE;
1586 tycon(tc).kind = tvsToKind(tvs);
1587 /* can't really do this until I've read in all synonyms */
1589 if (isNull(constr)) {
1590 tycon(tc).defn = NIL;
1592 /* constr :: ((ConId,Type)) */
1593 Text con = textOf(zfst(constr));
1594 Type type = zsnd(constr);
1595 Name n = findName(con); /* Allocate constructor fun name */
1597 n = newName(con,NIL);
1598 } else if (name(n).defn!=PREDEFINED) {
1599 ERRMSG(line) "Repeated definition for constructor \"%s\"",
1603 name(n).arity = 1; /* Save constructor fun details */
1604 name(n).line = line;
1605 name(n).number = cfunNo(0);
1606 name(n).defn = nameId;
1607 tycon(tc).defn = singleton(n);
1609 /* make resTy the result type of the constr, T v1 ... vn */
1611 for (tmp=tvs; nonNull(tmp); tmp=tl(tmp))
1612 resTy = ap(resTy,zfst(hd(tmp)));
1613 type = fn(type,resTy);
1615 type = ap(QUAL,pair(ctx0,type));
1616 type = tvsToOffsets(line,type,tvs);
1617 name(n).type = type;
1623 static Void finishGHCNewType ( ConId tyc )
1625 Tycon tc = findTycon(textOf(tyc));
1627 printf ( "begin finishGHCNewType %s\n", textToStr(textOf(tyc)) );
1630 if (isNull(tc)) internal("finishGHCNewType");
1632 if (isNull(tycon(tc).defn)) {
1633 /* it's an abstract type */
1635 else if (length(tycon(tc).defn) == 1) {
1636 /* As we expect, has a single constructor */
1637 Name n = hd(tycon(tc).defn);
1638 Int line = name(n).line;
1639 assert(currentModule == name(n).mod);
1640 name(n).type = conidcellsToTycons(line,name(n).type);
1642 internal("finishGHCNewType(2)");
1647 /* --------------------------------------------------------------------------
1648 * Class declarations
1649 * ------------------------------------------------------------------------*/
1651 Void startGHCClass(line,ctxt,tc_name,kinded_tvs,mems0)
1653 List ctxt; /* [((QConId, VarId))] */
1654 ConId tc_name; /* ConId */
1655 List kinded_tvs; /* [((VarId, Kind))] */
1656 List mems0; { /* [((VarId, Type))] */
1658 List mems; /* [((VarId, Type))] */
1659 List tvsInT; /* [VarId] and then [((VarId,Kind))] */
1660 List tvs; /* [((VarId,Kind))] */
1662 ZPair kinded_tv = hd(kinded_tvs);
1663 Text ct = textOf(tc_name);
1664 Pair newCtx = pair(tc_name, zfst(kinded_tv));
1666 printf ( "begin startGHCClass %s\n", textToStr(ct) );
1669 if (length(kinded_tvs) != 1) {
1670 ERRMSG(line) "Cannot presently handle multiparam type classes in ifaces"
1674 if (nonNull(findClass(ct))) {
1675 ERRMSG(line) "Repeated definition of class \"%s\"",
1678 } else if (nonNull(findTycon(ct))) {
1679 ERRMSG(line) "\"%s\" used as both class and type constructor",
1683 Class nw = newClass(ct);
1684 cclass(nw).text = ct;
1685 cclass(nw).line = line;
1686 cclass(nw).arity = 1;
1687 cclass(nw).head = ap(nw,mkOffset(0));
1688 cclass(nw).kinds = singleton(STAR); /* absolutely no idea at all */
1689 cclass(nw).instances = NIL; /* what the kind should be */
1690 cclass(nw).numSupers = length(ctxt);
1692 /* Kludge to map the single tyvar in the context to Offset 0.
1693 Need to do something better for multiparam type classes.
1695 cclass(nw).supers = tvsToOffsets(line,ctxt,
1696 singleton(pair(tv,STAR)));
1698 cclass(nw).supers = tvsToOffsets(line,ctxt,
1699 singleton(kinded_tv));
1702 for (mems=mems0; nonNull(mems); mems=tl(mems)) {
1703 ZPair mem = hd(mems);
1704 Type memT = zsnd(mem);
1705 Text mnt = textOf(zfst(mem));
1708 /* Stick the new context on the member type */
1709 if (whatIs(memT)==POLYTYPE) internal("startGHCClass");
1710 if (whatIs(memT)==QUAL) {
1712 pair(cons(newCtx,fst(snd(memT))),snd(snd(memT))));
1715 pair(singleton(newCtx),memT));
1718 /* Cook up a kind for the type. */
1719 tvsInT = ifTyvarsIn(memT);
1720 /* tvsInT :: [VarId] */
1722 /* ToDo: maximally bogus */
1723 for (tvs=tvsInT; nonNull(tvs); tvs=tl(tvs))
1724 hd(tvs) = zpair(hd(tvs),STAR);
1725 /* tvsIntT :: [((VarId,STAR))] */
1727 memT = mkPolyType(tvsToKind(tvsInT),memT);
1728 memT = tvsToOffsets(line,memT,tvsInT);
1730 /* Park the type back on the member */
1731 mem = zpair(zfst(mem),memT);
1733 /* Bind code to the member */
1737 "Repeated definition for class method \"%s\"",
1741 mn = newName(mnt,NIL);
1746 cclass(nw).members = mems0;
1747 cclass(nw).numMembers = length(mems0);
1750 * cclass(nw).dsels = ?;
1751 * cclass(nw).dbuild = ?;
1752 * cclass(nm).dcon = ?;
1753 * cclass(nm).defaults = ?;
1759 static Void finishGHCClass ( Tycon cls_tyc )
1764 Class nw = findClass ( textOf(cls_tyc) );
1766 printf ( "begin finishGHCClass %s\n", textToStr(cclass(nw).text) );
1768 if (isNull(nw)) internal("finishGHCClass");
1770 line = cclass(nw).line;
1771 ctr = - length(cclass(nw).members);
1772 assert (currentModule == cclass(nw).mod);
1774 cclass(nw).level = 0; /* (ADR) ToDo: 1 + max (map level supers) */
1775 cclass(nw).head = conidcellsToTycons(line,cclass(nw).head);
1776 cclass(nw).supers = conidcellsToTycons(line,cclass(nw).supers);
1777 cclass(nw).members = conidcellsToTycons(line,cclass(nw).members);
1779 for (mems=cclass(nw).members; nonNull(mems); mems=tl(mems)) {
1780 Pair mem = hd(mems); /* (VarId, Type) */
1781 Text txt = textOf(fst(mem));
1783 Name n = findName(txt);
1785 name(n).line = cclass(nw).line;
1787 name(n).number = ctr++;
1793 /* --------------------------------------------------------------------------
1795 * ------------------------------------------------------------------------*/
1797 Inst startGHCInstance (line,ctxt0,cls,var)
1799 List ctxt0; /* [((QConId, VarId))] */
1800 Type cls; /* Type */
1801 VarId var; { /* VarId */
1803 Inst in = newInst();
1805 printf ( "begin startGHCInstance\n" );
1808 /* Make tvs into a list of tyvars with bogus kinds. */
1809 tvs = ifTyvarsIn(cls);
1810 /* tvs :: [VarId] */
1813 for (tmp = tvs; nonNull(tmp); tmp=tl(tmp)) {
1814 hd(tmp) = zpair(hd(tmp),STAR);
1817 /* tvs :: [((VarId,STAR))] */
1818 inst(in).line = line;
1819 inst(in).implements = NIL;
1820 inst(in).kinds = ks;
1821 inst(in).specifics = tvsToOffsets(line,ctxt0,tvs);
1822 inst(in).numSpecifics = length(ctxt0);
1823 inst(in).head = tvsToOffsets(line,cls,tvs);
1825 /* Figure out the name of the class being instanced, and store it
1826 at inst(in).c. finishGHCInstance will resolve it to a real Class. */
1828 Cell cl = inst(in).head;
1829 while (isAp(cl)) cl = arg(cl);
1830 assert(whatIs(cl)==DICTAP);
1831 cl = unap(DICTAP,cl);
1833 assert ( isQCon(cl) );
1838 Is this still needed?
1840 Name b = newName(inventText(),NIL);
1841 name(b).line = line;
1842 name(b).arity = length(ctxt); /* unused? */
1843 name(b).number = DFUNNAME;
1844 inst(in).builder = b;
1845 bindNameToClosure(b, lookupGHCClosure(inst(in).mod,var));
1852 static Void finishGHCInstance ( Inst in )
1859 printf ( "begin finishGHCInstance\n" );
1862 assert (nonNull(in));
1863 line = inst(in).line;
1864 assert (currentModule==inst(in).mod);
1866 /* inst(in).c is, prior to finishGHCInstance, a ConId or Tuple,
1867 since startGHCInstance couldn't possibly have resolved it to
1868 a Class at that point. We convert it to a Class now.
1872 c = findQualClassWithoutConsultingExportList(c);
1876 inst(in).head = conidcellsToTycons(line,inst(in).head);
1877 inst(in).specifics = conidcellsToTycons(line,inst(in).specifics);
1878 cclass(c).instances = cons(in,cclass(c).instances);
1882 /* --------------------------------------------------------------------------
1884 * ------------------------------------------------------------------------*/
1886 /* This is called from the startGHC* functions. It traverses a structure
1887 and converts varidcells, ie, type variables parsed by the interface
1888 parser, into Offsets, which is how Hugs wants to see them internally.
1889 The Offset for a type variable is determined by its place in the list
1890 passed as the second arg; the associated kinds are irrelevant.
1892 ((t1,t2)) denotes the typed (z-)pair of t1 and t2.
1895 /* tvsToOffsets :: LineNo -> Type -> [((VarId,Kind))] -> Type */
1896 static Type tvsToOffsets(line,type,ktyvars)
1899 List ktyvars; { /* [((VarId,Kind))] */
1900 switch (whatIs(type)) {
1907 case ZTUP2: /* convert to the untyped representation */
1908 return ap( tvsToOffsets(line,zfst(type),ktyvars),
1909 tvsToOffsets(line,zsnd(type),ktyvars) );
1911 return ap( tvsToOffsets(line,fun(type),ktyvars),
1912 tvsToOffsets(line,arg(type),ktyvars) );
1916 tvsToOffsets(line,monotypeOf(type),ktyvars)
1920 return pair(QUAL,pair(tvsToOffsets(line,fst(snd(type)),ktyvars),
1921 tvsToOffsets(line,snd(snd(type)),ktyvars)));
1922 case DICTAP: /* bogus ?? */
1923 return ap(DICTAP, tvsToOffsets(line,snd(type),ktyvars));
1924 case UNBOXEDTUP: /* bogus?? */
1925 return ap(UNBOXEDTUP, tvsToOffsets(line,snd(type),ktyvars));
1926 case BANG: /* bogus?? */
1927 return ap(BANG, tvsToOffsets(line,snd(type),ktyvars));
1928 case VARIDCELL: /* Ha! some real work to do! */
1930 Text tv = textOf(type);
1931 for (; nonNull(ktyvars); i++,ktyvars=tl(ktyvars)) {
1934 assert(isZPair(hd(ktyvars)));
1935 varid = zfst(hd(ktyvars));
1937 if (tv == tt) return mkOffset(i);
1939 ERRMSG(line) "Undefined type variable \"%s\"", textToStr(tv)
1944 fprintf(stderr, "tvsToOffsets: unknown stuff %d\n", whatIs(type));
1946 fprintf(stderr,"\n");
1950 return NIL; /* NOTREACHED */
1954 /* This is called from the finishGHC* functions. It traverses a structure
1955 and converts conidcells, ie, type constructors parsed by the interface
1956 parser, into Tycons (or Classes), which is how Hugs wants to see them
1957 internally. Calls to this fn have to be deferred to the second phase
1958 of interface loading (finishGHC* rather than startGHC*) so that all relevant
1959 Tycons or Classes have been loaded into the symbol tables and can be
1962 static Type conidcellsToTycons ( Int line, Type type )
1964 switch (whatIs(type)) {
1974 { Cell t; /* Tycon or Class */
1975 Text m = qmodOf(type);
1976 Module mod = findModule(m);
1979 "Undefined module in qualified name \"%s\"",
1984 t = findQualTyconWithoutConsultingExportList(type);
1985 if (nonNull(t)) return t;
1986 t = findQualClassWithoutConsultingExportList(type);
1987 if (nonNull(t)) return t;
1989 "Undefined qualified class or type \"%s\"",
1997 cl = findQualClass(type);
1998 if (nonNull(cl)) return cl;
1999 if (textOf(type)==findText("[]"))
2000 /* a hack; magically qualify [] into PrelBase.[] */
2001 return conidcellsToTycons(line,
2002 mkQualId(mkCon(findText("PrelBase")),type));
2003 tc = findQualTycon(type);
2004 if (nonNull(tc)) return tc;
2006 "Undefined class or type constructor \"%s\"",
2012 return ap( conidcellsToTycons(line,fun(type)),
2013 conidcellsToTycons(line,arg(type)) );
2014 case ZTUP2: /* convert to std pair */
2015 return ap( conidcellsToTycons(line,zfst(type)),
2016 conidcellsToTycons(line,zsnd(type)) );
2021 conidcellsToTycons(line,monotypeOf(type))
2025 return pair(QUAL,pair(conidcellsToTycons(line,fst(snd(type))),
2026 conidcellsToTycons(line,snd(snd(type)))));
2027 case DICTAP: /* bogus?? */
2028 return ap(DICTAP, conidcellsToTycons(line, snd(type)));
2030 return ap(UNBOXEDTUP, conidcellsToTycons(line, snd(type)));
2032 return ap(BANG, conidcellsToTycons(line, snd(type)));
2034 fprintf(stderr, "conidcellsToTycons: unknown stuff %d\n",
2037 fprintf(stderr,"\n");
2041 return NIL; /* NOTREACHED */
2045 /* Find out if a type mentions a type constructor not present in
2046 the supplied list of qualified tycons.
2048 static Bool allTypesKnown ( Type type,
2049 List aktys /* [QualId] */,
2052 switch (whatIs(type)) {
2059 return allTypesKnown(fun(type),aktys,thisMod)
2060 && allTypesKnown(arg(type),aktys,thisMod);
2062 return allTypesKnown(zfst(type),aktys,thisMod)
2063 && allTypesKnown(zsnd(type),aktys,thisMod);
2065 return allTypesKnown(unap(DICTAP,type),aktys,thisMod);
2068 if (textOf(type)==findText("[]"))
2069 /* a hack; magically qualify [] into PrelBase.[] */
2070 type = mkQualId(mkCon(findText("PrelBase")),type); else
2071 type = mkQualId(thisMod,type);
2074 if (isNull(qualidIsMember(type,aktys))) goto missing;
2078 fprintf(stderr, "allTypesKnown: unknown stuff %d\n", whatIs(type));
2079 print(type,10);printf("\n");
2080 internal("allTypesKnown");
2081 return TRUE; /*notreached*/
2084 printf ( "allTypesKnown: unknown " ); print(type,10); printf("\n");
2089 /* --------------------------------------------------------------------------
2092 * None of these do lookups or require that lookups have been resolved
2093 * so they can be performed while reading interfaces.
2094 * ------------------------------------------------------------------------*/
2096 /* tvsToKind :: [((VarId,Kind))] -> Kinds */
2097 static Kinds tvsToKind(tvs)
2098 List tvs; { /* [((VarId,Kind))] */
2101 for (rs=reverse(tvs); nonNull(rs); rs=tl(rs)) {
2102 if (whatIs(hd(rs)) != ZTUP2) internal("tvsToKind(1)");
2103 if (whatIs(zfst(hd(rs))) != VARIDCELL) internal("tvsToKind(2)");
2104 r = ap(zsnd(hd(rs)),r);
2110 static Int arityInclDictParams ( Type type )
2113 if (isPolyType(type)) type = monotypeOf(type);
2115 if (whatIs(type) == QUAL)
2117 arity += length ( fst(snd(type)) );
2118 type = snd(snd(type));
2120 while (isAp(type) && getHead(type)==typeArrow) {
2127 /* arity of a constructor with this type */
2128 static Int arityFromType(type)
2131 if (isPolyType(type)) {
2132 type = monotypeOf(type);
2134 if (whatIs(type) == QUAL) {
2135 type = snd(snd(type));
2137 if (whatIs(type) == EXIST) {
2138 type = snd(snd(type));
2140 if (whatIs(type)==RANK2) {
2141 type = snd(snd(type));
2143 while (isAp(type) && getHead(type)==typeArrow) {
2151 /* ifTyvarsIn :: Type -> [VarId]
2152 The returned list has no duplicates -- is a set.
2154 static List ifTyvarsIn(type)
2156 List vs = typeVarsIn(type,NIL,NIL,NIL);
2158 for (; nonNull(vs2); vs2=tl(vs2))
2159 if (whatIs(hd(vs2)) != VARIDCELL)
2160 internal("ifTyvarsIn");
2166 /* --------------------------------------------------------------------------
2167 * General object symbol query stuff
2168 * ------------------------------------------------------------------------*/
2170 #define EXTERN_SYMS \
2171 Sym(stg_gc_enter_1) \
2172 Sym(stg_gc_noregs) \
2179 Sym(stg_update_PAP) \
2180 Sym(stg_error_entry) \
2181 Sym(__ap_2_upd_info) \
2182 Sym(__ap_3_upd_info) \
2183 Sym(__ap_4_upd_info) \
2184 Sym(__ap_5_upd_info) \
2185 Sym(__ap_6_upd_info) \
2186 Sym(__sel_0_upd_info) \
2187 Sym(__sel_1_upd_info) \
2188 Sym(__sel_2_upd_info) \
2189 Sym(__sel_3_upd_info) \
2190 Sym(__sel_4_upd_info) \
2191 Sym(__sel_5_upd_info) \
2192 Sym(__sel_6_upd_info) \
2193 Sym(__sel_7_upd_info) \
2194 Sym(__sel_8_upd_info) \
2195 Sym(__sel_9_upd_info) \
2196 Sym(__sel_10_upd_info) \
2197 Sym(__sel_11_upd_info) \
2198 Sym(__sel_12_upd_info) \
2200 Sym(Upd_frame_info) \
2201 Sym(seq_frame_info) \
2202 Sym(CAF_BLACKHOLE_info) \
2203 Sym(IND_STATIC_info) \
2204 Sym(EMPTY_MVAR_info) \
2205 Sym(MUT_ARR_PTRS_FROZEN_info) \
2207 Sym(putMVarzh_fast) \
2208 Sym(newMVarzh_fast) \
2209 Sym(takeMVarzh_fast) \
2214 Sym(killThreadzh_fast) \
2215 Sym(waitReadzh_fast) \
2216 Sym(waitWritezh_fast) \
2217 Sym(CHARLIKE_closure) \
2218 Sym(suspendThread) \
2220 Sym(stackOverflow) \
2221 Sym(int2Integerzh_fast) \
2222 Sym(stg_gc_unbx_r1) \
2224 Sym(makeForeignObjzh_fast) \
2225 Sym(__encodeDouble) \
2226 Sym(decodeDoublezh_fast) \
2228 Sym(isDoubleInfinite) \
2229 Sym(isDoubleDenormalized) \
2230 Sym(isDoubleNegativeZero) \
2231 Sym(__encodeFloat) \
2232 Sym(decodeFloatzh_fast) \
2234 Sym(isFloatInfinite) \
2235 Sym(isFloatDenormalized) \
2236 Sym(isFloatNegativeZero) \
2237 Sym(__int_encodeFloat) \
2238 Sym(__int_encodeDouble) \
2241 Sym(newArrayzh_fast) \
2242 Sym(unsafeThawArrayzh_fast) \
2243 Sym(newDoubleArrayzh_fast) \
2244 Sym(newFloatArrayzh_fast) \
2245 Sym(newAddrArrayzh_fast) \
2246 Sym(newWordArrayzh_fast) \
2247 Sym(newIntArrayzh_fast) \
2248 Sym(newCharArrayzh_fast) \
2249 Sym(newMutVarzh_fast) \
2250 Sym(quotRemIntegerzh_fast) \
2251 Sym(divModIntegerzh_fast) \
2252 Sym(timesIntegerzh_fast) \
2253 Sym(minusIntegerzh_fast) \
2254 Sym(plusIntegerzh_fast) \
2255 Sym(addr2Integerzh_fast) \
2256 Sym(mkWeakzh_fast) \
2259 Sym(resetNonBlockingFd) \
2261 /* needed by libHS_cbits */ \
2263 Sym(__errno_location) \
2309 /* entirely bogus claims about types of these symbols */
2310 #define Sym(vvv) extern int vvv;
2311 #define SymX(vvv) /* nothing */
2316 #define Sym(vvv) { #vvv, &vvv },
2317 #define SymX(vvv) { #vvv, &vvv },
2326 void* lookupObjName ( char* nm )
2336 strncpy(nm2,nm,200);
2338 /* first see if it's an RTS name */
2339 for (k = 0; rtsTab[k].nm; k++)
2340 if (0==strcmp(nm2,rtsTab[k].nm))
2341 return rtsTab[k].ad;
2343 /* perhaps an extra-symbol ? */
2344 a = lookupOExtraTabName ( nm );
2347 /* if not an RTS name, look in the
2348 relevant module's object symbol table
2350 pp = strchr(nm2, '_');
2351 if (!pp || !isupper(nm2[0])) goto not_found;
2353 t = unZcodeThenFindText(nm2);
2355 if (isNull(m)) goto not_found;
2357 a = lookupOTabName ( m, nm ); /* RATIONALISE */
2362 "lookupObjName: can't resolve name `%s'\n",
2369 int is_dynamically_loaded_code_or_rodata_ptr ( char* p )
2371 OSectionKind sk = lookupSection(p);
2372 assert (sk != HUGS_SECTIONKIND_NOINFOAVAIL);
2373 return (sk == HUGS_SECTIONKIND_CODE_OR_RODATA);
2377 int is_dynamically_loaded_rwdata_ptr ( char* p )
2379 OSectionKind sk = lookupSection(p);
2380 assert (sk != HUGS_SECTIONKIND_NOINFOAVAIL);
2381 return (sk == HUGS_SECTIONKIND_RWDATA);
2385 int is_not_dynamically_loaded_ptr ( char* p )
2387 OSectionKind sk = lookupSection(p);
2388 assert (sk != HUGS_SECTIONKIND_NOINFOAVAIL);
2389 return (sk == HUGS_SECTIONKIND_OTHER);
2393 /* --------------------------------------------------------------------------
2395 * ------------------------------------------------------------------------*/
2397 Void interface(what)
2400 case POSTPREL: break;
2404 ifaces_outstanding = NIL;
2407 mark(ifaces_outstanding);
2412 /*-------------------------------------------------------------------------*/