2 /* --------------------------------------------------------------------------
5 * The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
6 * Yale Haskell Group, and the Oregon Graduate Institute of Science and
7 * Technology, 1994-1999, All rights reserved. It is distributed as
8 * free software under the license in the file "License", which is
9 * included in the distribution.
11 * $RCSfile: hugs.c,v $
13 * $Date: 1999/11/12 17:50:01 $
14 * ------------------------------------------------------------------------*/
34 Bool haskell98 = TRUE; /* TRUE => Haskell 98 compatibility*/
36 #if EXPLAIN_INSTANCE_RESOLUTION
37 Bool showInstRes = FALSE;
40 Bool multiInstRes = FALSE;
43 /* --------------------------------------------------------------------------
44 * Local function prototypes:
45 * ------------------------------------------------------------------------*/
47 static Void local initialize Args((Int,String []));
48 static Void local promptForInput Args((String));
49 static Void local interpreter Args((Int,String []));
50 static Void local menu Args((Void));
51 static Void local guidance Args((Void));
52 static Void local forHelp Args((Void));
53 static Void local set Args((Void));
54 static Void local changeDir Args((Void));
55 static Void local load Args((Void));
56 static Void local project Args((Void));
57 static Void local readScripts Args((Int));
58 static Void local whatScripts Args((Void));
59 static Void local editor Args((Void));
60 static Void local find Args((Void));
61 static Bool local startEdit Args((Int,String));
62 static Void local runEditor Args((Void));
63 static Void local setModule Args((Void));
64 static Module local findEvalModule Args((Void));
65 static Void local evaluator Args((Void));
66 static Void local stopAnyPrinting Args((Void));
67 static Void local showtype Args((Void));
68 static String local objToStr Args((Module, Cell));
69 static Void local info Args((Void));
70 static Void local printSyntax Args((Name));
71 static Void local showInst Args((Inst));
72 static Void local describe Args((Text));
73 static Void local listNames Args((Void));
75 static Void local toggleSet Args((Char,Bool));
76 static Void local togglesIn Args((Bool));
77 static Void local optionInfo Args((Void));
78 #if USE_REGISTRY || HUGS_FOR_WINDOWS
79 static String local optionsToStr Args((Void));
81 static Void local readOptions Args((String));
82 static Bool local processOption Args((String));
83 static Void local setHeapSize Args((String));
84 static Int local argToInt Args((String));
86 static Void local loadProject Args((String));
87 static Void local clearProject Args((Void));
88 static Bool local addScript Args((Int));
89 static Void local forgetScriptsFrom Args((Script));
90 static Void local setLastEdit Args((String,Int));
91 static Void local failed Args((Void));
92 static String local strCopy Args((String));
93 static Void local browseit Args((Module,String));
94 static Void local browse Args((Void));
96 /* --------------------------------------------------------------------------
97 * Machine dependent code for Hugs interpreter:
98 * ------------------------------------------------------------------------*/
105 /* --------------------------------------------------------------------------
107 * ------------------------------------------------------------------------*/
109 static Bool printing = FALSE; /* TRUE => currently printing value*/
110 static Bool showStats = FALSE; /* TRUE => print stats after eval */
111 static Bool listScripts = TRUE; /* TRUE => list scripts after loading*/
112 static Bool addType = FALSE; /* TRUE => print type with value */
113 static Bool useDots = RISCOS; /* TRUE => use dots in progress */
114 static Bool quiet = FALSE; /* TRUE => don't show progress */
115 static Bool lastWasObject = FALSE;
116 Bool preludeLoaded = FALSE;
120 String modName; /* Module name */
121 Bool details; /* FALSE => remaining fields are invalid */
122 String path; /* Path to module */
123 String srcExt; /* ".hs" or ".lhs" if fromSource */
124 Time lastChange; /* Time of last change to script */
125 Bool fromSource; /* FALSE => load object code */
126 Bool postponed; /* Indicates postponed load */
133 static Void local makeStackEntry Args((ScriptInfo*,String));
134 static Void local addStackEntry Args((String));
136 static ScriptInfo scriptInfo[NUM_SCRIPTS];
138 static Int numScripts; /* Number of scripts loaded */
139 static Int nextNumScripts;
140 static Int namesUpto; /* Number of script names set */
141 static Bool needsImports; /* set to TRUE if imports required */
142 String scriptFile; /* Name of current script (if any) */
146 static Text evalModule = 0; /* Name of module we eval exprs in */
147 static String currProject = 0; /* Name of current project file */
148 static Bool projectLoaded = FALSE; /* TRUE => project file loaded */
150 static Bool autoMain = FALSE;
151 static String lastEdit = 0; /* Name of script to edit (if any) */
152 static Int lastEdLine = 0; /* Editor line number (if possible)*/
153 static String prompt = 0; /* Prompt string */
154 static Int hpSize = DEFAULTHEAP; /* Desired heap size */
155 String hugsEdit = 0; /* String for editor command */
156 String hugsPath = 0; /* String for file search path */
159 static Bool disableOutput = FALSE; /* redirect output to buffer? */
162 String bool2str ( Bool b )
164 if (b) return "Yes"; else return "No ";
167 void ppSmStack ( String who )
171 fflush(stdout);fflush(stderr);
173 printf ( "ppSmStack %s: numScripts = %d namesUpto = %d needsImports = %s\n",
174 who, numScripts, namesUpto, bool2str(needsImports) );
175 assert (namesUpto >= numScripts);
176 printf ( " Det FrS Pst ObL Module Ext Size ModTime Path\n" );
177 for (i = namesUpto-1; i >= 0; i--) {
178 printf ( "%c%2d: %3s %3s %3s %3s %16s %-4s %5ld %8lx %s\n",
179 (i==numScripts ? '*' : ' '),
180 i, bool2str(scriptInfo[i].details),
181 bool2str(scriptInfo[i].fromSource),
182 bool2str(scriptInfo[i].postponed),
183 bool2str(scriptInfo[i].objLoaded),
184 scriptInfo[i].modName,
185 scriptInfo[i].fromSource ? scriptInfo[i].srcExt : "",
187 scriptInfo[i].lastChange,
191 fflush(stdout);fflush(stderr);
197 /* --------------------------------------------------------------------------
199 * ------------------------------------------------------------------------*/
201 #ifndef NO_MAIN /* we omit main when building the "Hugs server" */
203 Main main Args((Int, String [])); /* now every func has a prototype */
208 #ifdef HAVE_CONSOLE_H /* Macintosh port */
210 _fcreator = 'R*ch'; /* // 'KAHL'; //'*TEX'; //'ttxt'; */
212 console_options.top = 50;
213 console_options.left = 20;
215 console_options.nrows = 32;
216 console_options.ncols = 80;
218 console_options.pause_atexit = 1;
219 console_options.title = "\pHugs";
221 console_options.procID = 5;
222 argc = ccommand(&argv);
225 CStackBase = &argc; /* Save stack base for use in gc */
227 /* Try and figure out an absolute path to the executable, so
228 we can make a reasonable guess about where the default
229 libraries (Prelude etc) are.
231 setDefaultLibDir ( argv[0] );
233 /* If first arg is +Q or -Q, be entirely silent, and automatically run
234 main after loading scripts. Useful for running the nofib suite. */
235 if (argc > 1 && (strcmp(argv[1],"+Q") == 0 || strcmp(argv[1],"-Q")==0)) {
240 Printf("__ __ __ __ ____ ___ _________________________________________\n");
241 Printf("|| || || || || || ||__ Hugs 98: Based on the Haskell 98 standard\n");
242 Printf("||___|| ||__|| ||__|| __|| Copyright (c) 1994-1999\n");
243 Printf("||---|| ___|| World Wide Web: http://haskell.org/hugs\n");
244 Printf("|| || Report bugs to: hugs-bugs@haskell.org\n");
245 Printf("|| || Version: %s _________________________________________\n\n",HUGS_VERSION);
248 Printf(" Ported to Macintosh by Hans Aberg, compiled " __DATE__ ".\n\n");
251 interpreter(argc,argv);
252 Printf("[Leaving Hugs]\n");
263 /* --------------------------------------------------------------------------
264 * Initialization, interpret command line args and read prelude:
265 * ------------------------------------------------------------------------*/
267 static Void local initialize(argc,argv)/* Interpreter initialization */
272 char argv_0_orig[1000];
274 setLastEdit((String)0,0);
281 hugsEdit = strCopy(fromEnv("EDITOR","c:\\windows\\notepad.exe"));
285 hugsEdit = strCopy(fromEnv("EDITOR",NULL));
287 hugsPath = strCopy(HUGSPATH);
288 readOptions("-p\"%s> \" -r$$");
290 projectPath = strCopy(readRegChildStrings(HKEY_LOCAL_MACHINE,ProjectRoot,
291 "HUGSPATH", PATHSEP, ""));
292 readOptions(readRegString(HKEY_LOCAL_MACHINE,HugsRoot,"Options",""));
293 readOptions(readRegString(HKEY_CURRENT_USER, HugsRoot,"Options",""));
294 #endif /* USE_REGISTRY */
295 readOptions(fromEnv("STGHUGSFLAGS",""));
297 strncpy(argv_0_orig,argv[0],1000); /* startupHaskell mangles argv[0] */
298 startupHaskell (argc,argv);
299 argc = prog_argc; argv = prog_argv;
301 namesUpto = numScripts = 0;
302 addStackEntry("Prelude");
304 for (i=1; i<argc; ++i) { /* process command line arguments */
305 if (strcmp(argv[i], "--")==0) break;
306 if (strcmp(argv[i],"+")==0 && i+1<argc) {
308 ERRMSG(0) "Multiple project filenames on command line"
313 } else if (argv[i] && argv[i][0]/* workaround for /bin/sh silliness*/
314 && !processOption(argv[i])) {
315 addStackEntry(argv[i]);
320 DEBUG_LoadSymbols(argv_0_orig);
325 if (!scriptName[0]) {
326 Printf("Prelude not found on current path: \"%s\"\n",
327 hugsPath ? hugsPath : "");
328 fatal("Unable to load prelude");
333 Printf("Haskell 98 mode: Restart with command line option -98 to enable extensions\n\n");
335 Printf("Hugs mode: Restart with command line option +98 for Haskell 98 mode\n\n");
339 evalModule = findText(""); /* evaluate wrt last module by default */
343 "\nUsing project file, ignoring additional filenames\n");
345 loadProject(strCopy(proj));
350 /* --------------------------------------------------------------------------
351 * Command line options:
352 * ------------------------------------------------------------------------*/
354 struct options { /* command line option toggles */
355 char c; /* table defined in main app. */
360 extern struct options toggle[];
362 static Void local toggleSet(c,state) /* Set command line toggle */
366 for (i=0; toggle[i].c; ++i)
367 if (toggle[i].c == c) {
368 *toggle[i].flag = state;
371 ERRMSG(0) "Unknown toggle `%c'", c
375 static Void local togglesIn(state) /* Print current list of toggles in*/
376 Bool state; { /* given state */
379 for (i=0; toggle[i].c; ++i)
380 if (*toggle[i].flag == state && (!haskell98 || toggle[i].h98)) {
382 Putchar((char)(state ? '+' : '-'));
383 Putchar(toggle[i].c);
390 static Void local optionInfo() { /* Print information about command */
391 static String fmts = "%-5s%s\n"; /* line settings */
392 static String fmtc = "%-5c%s\n";
395 Printf("TOGGLES: groups begin with +/- to turn options on/off resp.\n");
396 for (i=0; toggle[i].c; ++i) {
397 if (!haskell98 || toggle[i].h98) {
398 Printf(fmtc,toggle[i].c,toggle[i].description);
402 Printf("\nOTHER OPTIONS: (leading + or - makes no difference)\n");
403 Printf(fmts,"hnum","Set heap size (cannot be changed within Hugs)");
404 Printf(fmts,"pstr","Set prompt string to str");
405 Printf(fmts,"rstr","Set repeat last expression string to str");
406 Printf(fmts,"Pstr","Set search path for modules to str");
407 Printf(fmts,"Estr","Use editor setting given by str");
408 Printf(fmts,"cnum","Set constraint cutoff limit");
409 #if USE_PREPROCESSOR && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
410 Printf(fmts,"Fstr","Set preprocessor filter to str");
413 Printf("\nCurrent settings: ");
416 Printf("-h%d",heapSize);
420 printString(repeatStr);
421 Printf(" -c%d",cutoff);
422 Printf("\nSearch path : -P");
423 printString(hugsPath);
426 if (projectPath!=NULL) {
427 Printf("\nProject Path : %s",projectPath);
430 Printf("\nEditor setting : -E");
431 printString(hugsEdit);
432 #if USE_PREPROCESSOR && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
433 Printf("\nPreprocessor : -F");
434 printString(preprocessor);
436 Printf("\nCompatibility : %s", haskell98 ? "Haskell 98 (+98)"
437 : "Hugs Extensions (-98)");
441 #if USE_REGISTRY || HUGS_FOR_WINDOWS
449 #define PUTInt(optc,i) \
450 sprintf(next,"-%c%d",optc,i); \
453 #define PUTStr(c,s) \
454 next=PUTStr_aux(next,c,s)
456 static String local PUTStr_aux Args((String,Char, String));
458 static String local PUTStr_aux(next,c,s)
464 sprintf(next,"-%c\"",c);
467 PUTS(unlexChar(*t,'"'));
475 static String local optionsToStr() { /* convert options to string */
476 static char buffer[2000];
477 String next = buffer;
480 for (i=0; toggle[i].c; ++i) {
481 PUTC(*toggle[i].flag ? '+' : '-');
485 PUTS(haskell98 ? "+98 " : "-98 ");
486 PUTInt('h',hpSize); PUTC(' ');
488 PUTStr('r',repeatStr);
489 PUTStr('P',hugsPath);
490 PUTStr('E',hugsEdit);
491 PUTInt('c',cutoff); PUTC(' ');
492 #if USE_PREPROCESSOR && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
493 PUTStr('F',preprocessor);
498 #endif /* USE_REGISTRY */
505 static Void local readOptions(options) /* read options from string */
509 stringInput(options);
510 while ((s=readFilename())!=0) {
511 if (*s && !processOption(s)) {
512 ERRMSG(0) "Option string must begin with `+' or `-'"
519 static Bool local processOption(s) /* process string s for options, */
520 String s; { /* return FALSE if none found. */
532 case 'Q' : break; /* already handled */
534 case 'p' : if (s[1]) {
535 if (prompt) free(prompt);
536 prompt = strCopy(s+1);
540 case 'r' : if (s[1]) {
541 if (repeatStr) free(repeatStr);
542 repeatStr = strCopy(s+1);
547 String p = substPath(s+1,hugsPath ? hugsPath : "");
548 if (hugsPath) free(hugsPath);
553 case 'E' : if (hugsEdit) free(hugsEdit);
554 hugsEdit = strCopy(s+1);
557 #if USE_PREPROCESSOR && (defined(HAVE_POPEN) || defined(HAVE__POPEN))
558 case 'F' : if (preprocessor) free(preprocessor);
559 preprocessor = strCopy(s+1);
563 case 'h' : setHeapSize(s+1);
566 case 'D' : /* hack */
568 extern void setRtsFlags( int x );
569 setRtsFlags(argToInt(s+1));
573 default : if (strcmp("98",s)==0) {
574 if (heapBuilt() && ((state && !haskell98) ||
575 (!state && haskell98))) {
577 "Haskell 98 compatibility cannot be changed"
578 " while the interpreter is running\n");
591 static Void local setHeapSize(s)
594 hpSize = argToInt(s);
595 if (hpSize < MINIMUMHEAP)
596 hpSize = MINIMUMHEAP;
597 else if (MAXIMUMHEAP && hpSize > MAXIMUMHEAP)
598 hpSize = MAXIMUMHEAP;
599 if (heapBuilt() && hpSize != heapSize) {
600 /* ToDo: should this use a message box in winhugs? */
602 FPrintf(stderr,"Change to heap size will not take effect until you rerun Hugs\n");
604 FPrintf(stderr,"Cannot change heap size\n");
612 static Int local argToInt(s) /* read integer from argument str */
617 if (*s=='\0' || !isascii((int)(*s)) || !isdigit((int)(*s))) {
618 ERRMSG(0) "Missing integer in option setting \"%s\"", t
623 Int d = (*s++) - '0';
624 if (n > ((MAXPOSINT - d)/10)) {
625 ERRMSG(0) "Option setting \"%s\" is too large", t
629 } while (isascii((int)(*s)) && isdigit((int)(*s)));
631 if (*s=='K' || *s=='k') {
632 if (n > (MAXPOSINT/1000)) {
633 ERRMSG(0) "Option setting \"%s\" is too large", t
640 #if MAXPOSINT > 1000000 /* waste of time on 16 bit systems */
641 if (*s=='M' || *s=='m') {
642 if (n > (MAXPOSINT/1000000)) {
643 ERRMSG(0) "Option setting \"%s\" is too large", t
651 #if MAXPOSINT > 1000000000
652 if (*s=='G' || *s=='g') {
653 if (n > (MAXPOSINT/1000000000)) {
654 ERRMSG(0) "Option setting \"%s\" is too large", t
663 ERRMSG(0) "Unwanted characters after option setting \"%s\"", t
670 /* --------------------------------------------------------------------------
671 * Print Menu of list of commands:
672 * ------------------------------------------------------------------------*/
674 static struct cmd cmds[] = {
675 {":?", HELP}, {":cd", CHGDIR}, {":also", ALSO},
676 {":type", TYPEOF}, {":!", SYSTEM}, {":load", LOAD},
677 {":reload", RELOAD}, {":gc", COLLECT}, {":edit", EDIT},
678 {":quit", QUIT}, {":set", SET}, {":find", FIND},
679 {":names", NAMES}, {":info", INFO}, {":project", PROJECT},
680 {":dump", DUMP}, {":ztats", STATS},
681 {":module",SETMODULE},
683 #if EXPLAIN_INSTANCE_RESOLUTION
686 {":version", PNTVER},
691 static Void local menu() {
692 Printf("LIST OF COMMANDS: Any command may be abbreviated to :c where\n");
693 Printf("c is the first character in the full name.\n\n");
694 Printf(":load <filenames> load modules from specified files\n");
695 Printf(":load clear all files except prelude\n");
696 Printf(":also <filenames> read additional modules\n");
697 Printf(":reload repeat last load command\n");
698 Printf(":project <filename> use project file\n");
699 Printf(":edit <filename> edit file\n");
700 Printf(":edit edit last module\n");
701 Printf(":module <module> set module for evaluating expressions\n");
702 Printf("<expr> evaluate expression\n");
703 Printf(":type <expr> print type of expression\n");
704 Printf(":? display this list of commands\n");
705 Printf(":set <options> set command line options\n");
706 Printf(":set help on command line options\n");
707 Printf(":names [pat] list names currently in scope\n");
708 Printf(":info <names> describe named objects\n");
709 Printf(":browse <modules> browse names defined in <modules>\n");
710 #if EXPLAIN_INSTANCE_RESOLUTION
711 Printf(":xplain <context> explain instance resolution for <context>\n");
713 Printf(":find <name> edit module containing definition of name\n");
714 Printf(":!command shell escape\n");
715 Printf(":cd dir change directory\n");
716 Printf(":gc force garbage collection\n");
717 Printf(":version print Hugs version\n");
718 Printf(":dump <name> print STG code for named fn\n");
719 #ifdef CRUDE_PROFILING
720 Printf(":ztats <name> print reduction stats\n");
722 Printf(":quit exit Hugs interpreter\n");
725 static Void local guidance() {
726 Printf("Command not recognised. ");
730 static Void local forHelp() {
731 Printf("Type :? for help\n");
734 /* --------------------------------------------------------------------------
735 * Setting of command line options:
736 * ------------------------------------------------------------------------*/
738 struct options toggle[] = { /* List of command line toggles */
739 {'s', 1, "Print no. reductions/cells after eval", &showStats},
740 {'t', 1, "Print type after evaluation", &addType},
741 {'g', 1, "Print no. cells recovered after gc", &gcMessages},
742 {'l', 1, "Literate modules as default", &literateScripts},
743 {'e', 1, "Warn about errors in literate modules", &literateErrors},
744 {'.', 1, "Print dots to show progress", &useDots},
745 {'q', 1, "Print nothing to show progress", &quiet},
746 {'w', 1, "Always show which modules are loaded", &listScripts},
747 {'k', 1, "Show kind errors in full", &kindExpert},
748 {'o', 0, "Allow overlapping instances", &allowOverlap},
752 {'D', 1, "Debug: show generated code", &debugCode},
754 #if EXPLAIN_INSTANCE_RESOLUTION
755 {'x', 1, "Explain instance resolution", &showInstRes},
758 {'m', 0, "Use multi instance resolution", &multiInstRes},
761 {'D', 1, "Debug: show generated G code", &debugCode},
764 {'S', 1, "Debug: show generated SC code", &debugSC},
767 {'f', 1, "Terminate evaluation on first error", &failOnError},
768 {'u', 1, "Use \"show\" to display results", &useShow},
769 {'i', 1, "Chase imports while loading modules", &chaseImports},
774 static Void local set() { /* change command line options from*/
775 String s; /* Hugs command line */
777 if ((s=readFilename())!=0) {
779 if (!processOption(s)) {
780 ERRMSG(0) "Option string must begin with `+' or `-'"
783 } while ((s=readFilename())!=0);
785 writeRegString("Options", optionsToStr());
792 /* --------------------------------------------------------------------------
793 * Change directory command:
794 * ------------------------------------------------------------------------*/
796 static Void local changeDir() { /* change directory */
797 String s = readFilename();
799 ERRMSG(0) "Unable to change to directory \"%s\"", s
804 /* --------------------------------------------------------------------------
805 * Loading project and script files:
806 * ------------------------------------------------------------------------*/
808 static Void local loadProject(s) /* Load project file */
812 projInput(currProject);
813 scriptFile = currProject;
814 forgetScriptsFrom(1);
815 while ((s=readFilename())!=0)
818 ERRMSG(0) "Empty project file"
822 projectLoaded = TRUE;
825 static Void local clearProject() { /* clear name for current project */
829 projectLoaded = FALSE;
831 setLastEdit((String)0,0);
837 static Void local makeStackEntry ( ScriptInfo* ent, String iname )
840 Bool sAvail, iAvail, oAvail;
841 Time sTime, iTime, oTime;
842 Long sSize, iSize, oSize;
845 ok = findFilesForModule (
849 &sAvail, &sTime, &sSize,
850 &iAvail, &iTime, &iSize,
851 &oAvail, &oTime, &oSize
855 /* "Can't file source or object+interface for module \"%s\"", */
856 "Can't file source for module \"%s\"",
860 /* findFilesForModule should enforce this */
861 if (!(sAvail || (oAvail && iAvail)))
863 /* Load objects in preference to sources if both are available */
864 /* 11 Oct 99: disable object loading in the interim.
865 Will probably only reinstate when HEP becomes available.
867 ? (oAvail && iAvail && timeEarlier(sTime,oTime))
872 /* ToDo: namesUpto overflow */
873 ent->modName = strCopy(iname);
876 ent->fromSource = !fromObj;
878 ent->postponed = FALSE;
879 ent->lastChange = sTime; /* ToDo: is this right? */
880 ent->size = fromObj ? iSize : sSize;
881 ent->oSize = fromObj ? oSize : 0;
882 ent->objLoaded = FALSE;
887 static Void nukeEnding( String s )
890 if (l > 2 && strncmp(s+l-2,".o" ,3)==0) s[l-2] = 0; else
891 if (l > 3 && strncmp(s+l-3,".hi" ,3)==0) s[l-3] = 0; else
892 if (l > 3 && strncmp(s+l-3,".hs" ,3)==0) s[l-3] = 0; else
893 if (l > 4 && strncmp(s+l-4,".lhs",4)==0) s[l-4] = 0; else
894 if (l > 4 && strncmp(s+l-4,".dll",4)==0) s[l-4] = 0; else
895 if (l > 4 && strncmp(s+l-4,".DLL",4)==0) s[l-4] = 0;
898 static Void local addStackEntry(s) /* Add script to list of scripts */
899 String s; { /* to be read in ... */
904 if (namesUpto>=NUM_SCRIPTS) {
905 ERRMSG(0) "Too many module files (maximum of %d allowed)",
912 for (s2 = s; *s2; s2++)
913 if (*s2 == SLASH && *(s2+1)) s = s2+1;
916 for (i = 0; i < namesUpto; i++)
917 if (strcmp(scriptInfo[i].modName,s)==0)
921 makeStackEntry ( &scriptInfo[namesUpto], strCopy(s) );
927 /* Return TRUE if no imports were needed; FALSE otherwise. */
928 static Bool local addScript(stacknum) /* read single file */
930 static char name[FILENAME_MAX+1];
931 Int len = scriptInfo[stacknum].size;
933 #if HUGS_FOR_WINDOWS /* Set clock cursor while loading */
935 SetCursor(LoadCursor(NULL, IDC_WAIT));
938 // setLastEdit(name,0);
941 strcpy(name, scriptInfo[stacknum].path);
942 strcat(name, scriptInfo[stacknum].modName);
943 if (scriptInfo[stacknum].fromSource)
944 strcat(name, scriptInfo[stacknum].srcExt); else
949 if (scriptInfo[stacknum].fromSource) {
950 if (lastWasObject) finishInterfaces();
951 lastWasObject = FALSE;
952 Printf("Reading script \"%s\":\n",name);
953 needsImports = FALSE;
954 parseScript(name,len);
955 if (needsImports) return FALSE;
960 Printf("Reading iface \"%s\":\n", name);
962 needsImports = FALSE;
964 // set nameObj for the benefit of openGHCIface
965 strcpy(nameObj, scriptInfo[stacknum].path);
966 strcat(nameObj, scriptInfo[stacknum].modName);
967 strcat(nameObj, DLL_ENDING);
968 sizeObj = scriptInfo[stacknum].oSize;
970 loadInterface(name,len);
972 lastWasObject = TRUE;
973 if (needsImports) return FALSE;
977 preludeLoaded = TRUE;
982 Bool chase(imps) /* Process list of import requests */
986 Int origPos = numScripts; /* keep track of original position */
987 String origName = scriptInfo[origPos].modName;
988 for (; nonNull(imps); imps=tl(imps)) {
989 String iname = textToStr(textOf(hd(imps)));
991 for (; i<namesUpto; i++)
992 if (strcmp(scriptInfo[i].modName,iname)==0)
994 //fprintf(stderr, "import name = %s num = %d\n", iname, i );
997 /* We should have filled in the details of each module
998 the first time we hear about it.
1000 assert(scriptInfo[i].details);
1003 if (i>=origPos) { /* Neither loaded or queued */
1009 needsImports = TRUE;
1010 if (scriptInfo[origPos].fromSource)
1011 scriptInfo[origPos].postponed = TRUE;
1013 if (i==namesUpto) { /* Name not found (i==namesUpto) */
1014 /* Find out where it lives, whether source or object, etc */
1015 makeStackEntry ( &scriptInfo[i], iname );
1019 if (scriptInfo[i].postponed && scriptInfo[i].fromSource) {
1020 /* Check for recursive dependency */
1022 "Recursive import dependency between \"%s\" and \"%s\"",
1023 scriptInfo[origPos].modName, iname
1026 /* Move stack entry i to somewhere below origPos. If i denotes
1027 * an object, destination is immediately below origPos.
1028 * Otherwise, it's underneath the queue of objects below origPos.
1030 dstPosn = origPos-1;
1031 if (scriptInfo[i].fromSource)
1032 while (!scriptInfo[dstPosn].fromSource && dstPosn > 0)
1036 tmp = scriptInfo[i];
1037 for (; i > dstPosn; i--) scriptInfo[i] = scriptInfo[i-1];
1038 scriptInfo[dstPosn] = tmp;
1039 if (dstPosn < nextNumScripts) nextNumScripts = dstPosn;
1043 return needsImports;
1046 static Void local forgetScriptsFrom(scno)/* remove scripts from system */
1050 for (i=scno; i<namesUpto; ++i)
1052 free(scriptName[i]);
1054 dropScriptsFrom(scno-1);
1056 if (numScripts>namesUpto)
1060 /* --------------------------------------------------------------------------
1061 * Commands for loading and removing script files:
1062 * ------------------------------------------------------------------------*/
1064 static Void local load() { /* read filenames from command line */
1065 String s; /* and add to list of scripts waiting */
1067 while ((s=readFilename())!=0)
1072 static Void local project() { /* read list of script names from */
1073 String s; /* project file */
1075 if ((s=readFilename()) || currProject) {
1077 s = strCopy(currProject);
1078 else if (readFilename()) {
1079 ERRMSG(0) "Too many project files"
1086 ERRMSG(0) "No project filename specified"
1093 static Void local readScripts(n) /* Reread current list of scripts, */
1094 Int n; { /* loading everything after and */
1095 Time timeStamp; /* including the first script which*/
1096 Long fileSize; /* has been either changed or added*/
1097 static char name[FILENAME_MAX+1];
1099 lastWasObject = FALSE;
1100 ppSmStack("readscripts-begin");
1101 #if HUGS_FOR_WINDOWS
1102 SetCursor(LoadCursor(NULL, IDC_WAIT));
1106 for (; n<numScripts; n++) { /* Scan previously loaded scripts */
1107 ppSmStack("readscripts-loop1");
1108 getFileInfo(scriptName[n], &timeStamp, &fileSize);
1109 if (timeChanged(timeStamp,lastChange[n])) {
1110 dropScriptsFrom(n-1);
1115 for (; n<NUM_SCRIPTS; n++) /* No scripts have been postponed */
1116 postponed[n] = FALSE; /* at this stage */
1119 while (numScripts<namesUpto) { /* Process any remaining scripts */
1120 ppSmStack("readscripts-loop2");
1121 getFileInfo(scriptName[numScripts], &timeStamp, &fileSize);
1122 timeSet(lastChange[numScripts],timeStamp);
1123 if (numScripts>0) /* no new script for prelude */
1124 startNewScript(scriptName[numScripts]);
1125 if (addScript(scriptName[numScripts],fileSize))
1128 dropScriptsFrom(numScripts-1);
1134 for (; n<numScripts; n++) {
1135 ppSmStack("readscripts-loop2");
1136 strcpy(name, scriptInfo[n].path);
1137 strcat(name, scriptInfo[n].modName);
1138 if (scriptInfo[n].fromSource)
1139 strcat(name, scriptInfo[n].srcExt); else
1140 strcat(name, ".hi"); //ToDo: should be .o
1141 getFileInfo(name,&timeStamp, &fileSize);
1142 if (timeChanged(timeStamp,scriptInfo[n].lastChange)) {
1143 dropScriptsFrom(n-1);
1148 for (; n<NUM_SCRIPTS; n++)
1149 scriptInfo[n].postponed = FALSE;
1153 while (numScripts < namesUpto) {
1154 ppSmStack ( "readscripts-loop2" );
1156 if (scriptInfo[numScripts].fromSource) {
1159 startNewScript(scriptInfo[numScripts].modName);
1160 nextNumScripts = NUM_SCRIPTS; //bogus initialisation
1161 if (addScript(numScripts)) {
1163 assert(nextNumScripts==NUM_SCRIPTS);
1166 dropScriptsFrom(numScripts-1);
1170 if (scriptInfo[numScripts].objLoaded) {
1173 scriptInfo[numScripts].objLoaded = TRUE;
1176 startNewScript(scriptInfo[numScripts].modName);
1178 nextNumScripts = NUM_SCRIPTS;
1179 if (addScript(numScripts)) {
1181 assert(nextNumScripts==NUM_SCRIPTS);
1183 //while (!scriptInfo[numScripts].fromSource && numScripts > 0)
1185 //if (scriptInfo[numScripts].fromSource)
1187 numScripts = nextNumScripts;
1188 assert(nextNumScripts<NUM_SCRIPTS);
1192 if (numScripts==namesUpto) ppSmStack( "readscripts-final") ;
1197 { Int m = namesUpto-1;
1198 Text mtext = findText(scriptInfo[m].modName);
1199 /* Commented out till we understand what
1200 * this is trying to do.
1201 * Problem, you cant find a module till later.
1204 setCurrModule(findModule(mtext));
1214 setLastEdit((String)0, 0);
1215 ppSmStack("readscripts-end ");
1218 static Void local whatScripts() { /* list scripts in current session */
1220 Printf("\nHugs session for:");
1222 Printf(" (project: %s)",currProject);
1223 for (i=0; i<numScripts; ++i)
1224 Printf("\n%s%s",scriptInfo[i].path, scriptInfo[i].modName);
1228 /* --------------------------------------------------------------------------
1229 * Access to external editor:
1230 * ------------------------------------------------------------------------*/
1232 static Void local editor() { /* interpreter-editor interface */
1233 String newFile = readFilename();
1235 setLastEdit(newFile,0);
1236 if (readFilename()) {
1237 ERRMSG(0) "Multiple filenames not permitted"
1244 static Void local find() { /* edit file containing definition */
1246 This just plain wont work no more.
1248 String nm = readFilename(); /* of specified name */
1250 ERRMSG(0) "No name specified"
1253 else if (readFilename()) {
1254 ERRMSG(0) "Multiple names not permitted"
1260 setCurrModule(findEvalModule());
1262 if (nonNull(c=findTycon(t=findText(nm)))) {
1263 if (startEdit(tycon(c).line,scriptName[scriptThisTycon(c)])) {
1266 } else if (nonNull(c=findName(t))) {
1267 if (startEdit(name(c).line,scriptName[scriptThisName(c)])) {
1271 ERRMSG(0) "No current definition for name \"%s\"", nm
1278 static Void local runEditor() { /* run editor on script lastEdit */
1279 if (startEdit(lastEdLine,lastEdit)) /* at line lastEdLine */
1283 static Void local setLastEdit(fname,line)/* keep name of last file to edit */
1288 lastEdit = strCopy(fname);
1290 #if HUGS_FOR_WINDOWS
1291 DrawStatusLine(hWndMain); /* Redo status line */
1295 /* --------------------------------------------------------------------------
1296 * Read and evaluate an expression:
1297 * ------------------------------------------------------------------------*/
1299 static Void local setModule(){/*set module in which to evaluate expressions*/
1300 String s = readFilename();
1301 if (!s) s = ""; /* :m clears the current module selection */
1302 evalModule = findText(s);
1303 setLastEdit(fileOfModule(findEvalModule()),0);
1306 static Module local findEvalModule() { /*Module in which to eval expressions*/
1307 Module m = findModule(evalModule);
1313 static Void local evaluator() { /* evaluate expr and print value */
1317 setCurrModule(findEvalModule());
1319 startNewScript(0); /* Enables recovery of storage */
1320 /* allocated during evaluation */
1323 defaultDefns = evalDefaults;
1324 type = typeCheckExp(TRUE);
1325 if (isPolyType(type)) {
1326 ks = polySigOf(type);
1327 bd = monotypeOf(type);
1332 if (whatIs(bd)==QUAL) {
1333 ERRMSG(0) "Unresolved overloading" ETHEN
1334 ERRTEXT "\n*** Type : " ETHEN ERRTYPE(type);
1335 ERRTEXT "\n*** Expression : " ETHEN ERREXPR(inputExpr);
1345 if (typeMatches(type,ap(typeIO,typeUnit))) {
1346 inputExpr = ap(nameRunIO,inputExpr);
1350 Cell d = provePred(ks,NIL,ap(classShow,bd));
1352 ERRMSG(0) "Cannot find \"show\" function for:" ETHEN
1353 ERRTEXT "\n*** expression : " ETHEN ERREXPR(inputExpr);
1354 ERRTEXT "\n*** of type : " ETHEN ERRTYPE(type);
1358 inputExpr = ap2(findName(findText("show")),d,inputExpr);
1359 inputExpr = ap(findName(findText("putStr")), inputExpr);
1360 inputExpr = ap(nameRunIO, inputExpr);
1362 evalExp(); printf("\n");
1365 printType(stdout,type);
1372 printf ( "result type is " );
1373 printType ( stdout, type );
1382 static Void local stopAnyPrinting() { /* terminate printing of expression,*/
1383 if (printing) { /* after successful termination or */
1384 printing = FALSE; /* runtime error (e.g. interrupt) */
1387 #define plural(v) v, (v==1?"":"s")
1388 Printf("%lu cell%s",plural(numCells));
1390 Printf(", %u garbage collection%s",plural(numGcs));
1399 /* --------------------------------------------------------------------------
1400 * Print type of input expression:
1401 * ------------------------------------------------------------------------*/
1403 static Void local showtype() { /* print type of expression (if any)*/
1406 setCurrModule(findEvalModule());
1407 startNewScript(0); /* Enables recovery of storage */
1408 /* allocated during evaluation */
1411 defaultDefns = evalDefaults;
1412 type = typeCheckExp(FALSE);
1413 printExp(stdout,inputExpr);
1415 printType(stdout,type);
1420 static Void local browseit(mod,t)
1425 Printf("module %s where\n",textToStr(module(mod).text));
1426 for (cs = module(mod).names; nonNull(cs); cs=tl(cs)) {
1428 /* only look at things defined in this module */
1429 if (name(nm).mod == mod) {
1430 /* unwanted artifacts, like lambda lifted values,
1431 are in the list of names, but have no types */
1432 if (nonNull(name(nm).type)) {
1433 printExp(stdout,nm);
1435 printType(stdout,name(nm).type);
1437 Printf(" -- data constructor");
1438 } else if (isMfun(nm)) {
1439 Printf(" -- class member");
1440 } else if (isSfun(nm)) {
1441 Printf(" -- selector function");
1449 Printf("Unknown module %s\n",t);
1454 static Void local browse() { /* browse modules */
1455 Int count = 0; /* or give menu of commands */
1458 setCurrModule(findEvalModule());
1459 startNewScript(0); /* for recovery of storage */
1460 for (; (s=readFilename())!=0; count++) {
1461 browseit(findModule(findText(s)),s);
1468 #if EXPLAIN_INSTANCE_RESOLUTION
1469 static Void local xplain() { /* print type of expression (if any)*/
1472 Bool sir = showInstRes;
1474 setCurrModule(findEvalModule());
1475 startNewScript(0); /* Enables recovery of storage */
1476 /* allocated during evaluation */
1480 d = provePred(NIL,NIL,hd(inputContext));
1482 fprintf(stdout, "not Sat\n");
1484 fprintf(stdout, "Sat\n");
1490 /* --------------------------------------------------------------------------
1491 * Enhanced help system: print current list of scripts or give information
1493 * ------------------------------------------------------------------------*/
1495 static String local objToStr(m,c)
1498 #if 1 || DISPLAY_QUANTIFIERS
1499 static char newVar[60];
1500 switch (whatIs(c)) {
1501 case NAME : if (m == name(c).mod) {
1502 sprintf(newVar,"%s", textToStr(name(c).text));
1504 sprintf(newVar,"%s.%s",
1505 textToStr(module(name(c).mod).text),
1506 textToStr(name(c).text));
1510 case TYCON : if (m == tycon(c).mod) {
1511 sprintf(newVar,"%s", textToStr(tycon(c).text));
1513 sprintf(newVar,"%s.%s",
1514 textToStr(module(tycon(c).mod).text),
1515 textToStr(tycon(c).text));
1519 case CLASS : if (m == cclass(c).mod) {
1520 sprintf(newVar,"%s", textToStr(cclass(c).text));
1522 sprintf(newVar,"%s.%s",
1523 textToStr(module(cclass(c).mod).text),
1524 textToStr(cclass(c).text));
1528 default : internal("objToStr");
1532 static char newVar[33];
1533 switch (whatIs(c)) {
1534 case NAME : sprintf(newVar,"%s", textToStr(name(c).text));
1537 case TYCON : sprintf(newVar,"%s", textToStr(tycon(c).text));
1540 case CLASS : sprintf(newVar,"%s", textToStr(cclass(c).text));
1543 default : internal("objToStr");
1551 static Void local dumpStg( void ) { /* print STG stuff */
1556 Cell v; /* really StgVar */
1557 setCurrModule(findEvalModule());
1559 for (; (s=readFilename())!=0;) {
1562 /* find the name while ignoring module scopes */
1563 for (i=NAMEMIN; i<nameHw; i++)
1564 if (name(i).text == t) n = i;
1566 /* perhaps it's an "idNNNNNN" thing? */
1569 s[0]=='i' && s[1]=='d' && isdigit(s[2])) {
1572 while (isdigit(s[i])) {
1573 v = v * 10 + (s[i]-'0');
1577 n = nameFromStgVar(v);
1580 if (isNull(n) && whatIs(v)==STGVAR) {
1581 Printf ( "\n{- `%s' has no nametable entry -}\n", s );
1582 printStg(stderr, v );
1585 Printf ( "Unknown reference `%s'\n", s );
1588 Printf ( "Not a Name: `%s'\n", s );
1590 if (isNull(name(n).stgVar)) {
1591 Printf ( "Doesn't have a STG tree: %s\n", s );
1593 Printf ( "\n{- stgVar of `%s' is id%d -}\n", s, -name(n).stgVar);
1594 printStg(stderr, name(n).stgVar);
1599 static Void local info() { /* describe objects */
1600 Int count = 0; /* or give menu of commands */
1603 setCurrModule(findEvalModule());
1604 startNewScript(0); /* for recovery of storage */
1605 for (; (s=readFilename())!=0; count++) {
1606 describe(findText(s));
1614 static Void local describe(t) /* describe an object */
1616 Tycon tc = findTycon(t);
1617 Class cl = findClass(t);
1618 Name nm = findName(t);
1620 if (nonNull(tc)) { /* as a type constructor */
1624 for (i=0; i<tycon(tc).arity; ++i) {
1625 t = ap(t,mkOffset(i));
1627 Printf("-- type constructor");
1629 Printf(" with kind ");
1630 printKind(stdout,tycon(tc).kind);
1633 switch (tycon(tc).what) {
1634 case SYNONYM : Printf("type ");
1635 printType(stdout,t);
1637 printType(stdout,tycon(tc).defn);
1641 case DATATYPE : { List cs = tycon(tc).defn;
1642 if (tycon(tc).what==DATATYPE) {
1647 printType(stdout,t);
1649 mapProc(printSyntax,cs);
1651 Printf("\n-- constructors:");
1653 for (; hasCfun(cs); cs=tl(cs)) {
1655 printExp(stdout,hd(cs));
1657 printType(stdout,name(hd(cs)).type);
1660 Printf("\n-- selectors:");
1662 for (; nonNull(cs); cs=tl(cs)) {
1664 printExp(stdout,hd(cs));
1666 printType(stdout,name(hd(cs)).type);
1671 case RESTRICTSYN : Printf("type ");
1672 printType(stdout,t);
1673 Printf(" = <restricted>");
1677 if (nonNull(in=findFirstInst(tc))) {
1678 Printf("\n-- instances:\n");
1681 in = findNextInst(tc,in);
1682 } while (nonNull(in));
1687 if (nonNull(cl)) { /* as a class */
1688 List ins = cclass(cl).instances;
1689 Kinds ks = cclass(cl).kinds;
1690 if (nonNull(ks) && isNull(tl(ks)) && hd(ks)==STAR) {
1691 Printf("-- type class");
1693 Printf("-- constructor class");
1695 Printf(" with arity ");
1696 printKinds(stdout,ks);
1700 mapProc(printSyntax,cclass(cl).members);
1702 if (nonNull(cclass(cl).supers)) {
1703 printContext(stdout,cclass(cl).supers);
1706 printPred(stdout,cclass(cl).head);
1708 if (nonNull(cclass(cl).fds)) {
1709 List fds = cclass(cl).fds;
1711 for (; nonNull(fds); fds=tl(fds)) {
1713 printFD(stdout,hd(fds));
1718 if (nonNull(cclass(cl).members)) {
1719 List ms = cclass(cl).members;
1722 Type t = name(hd(ms)).type;
1723 if (isPolyType(t)) {
1727 printExp(stdout,hd(ms));
1729 if (isNull(tl(fst(snd(t))))) {
1732 t = ap(QUAL,pair(tl(fst(snd(t))),snd(snd(t))));
1734 printType(stdout,t);
1736 } while (nonNull(ms));
1740 Printf("\n-- instances:\n");
1744 } while (nonNull(ins));
1749 if (nonNull(nm)) { /* as a function/name */
1751 printExp(stdout,nm);
1753 if (nonNull(name(nm).type)) {
1754 printType(stdout,name(nm).type);
1756 Printf("<unknown type>");
1760 Printf(" -- data constructor");
1761 } else if (isMfun(nm)) {
1762 Printf(" -- class member");
1763 } else if (isSfun(nm)) {
1764 Printf(" -- selector function");
1770 if (isNull(tc) && isNull(cl) && isNull(nm)) {
1771 Printf("Unknown reference `%s'\n",textToStr(t));
1775 static Void local printSyntax(nm)
1777 Syntax sy = syntaxOf(nm);
1778 Text t = name(nm).text;
1779 String s = textToStr(t);
1780 if (sy != defaultSyntax(t)) {
1782 switch (assocOf(sy)) {
1783 case LEFT_ASS : Putchar('l'); break;
1784 case RIGHT_ASS : Putchar('r'); break;
1785 case NON_ASS : break;
1787 Printf(" %i ",precOf(sy));
1788 if (isascii((int)(*s)) && isalpha((int)(*s))) {
1797 static Void local showInst(in) /* Display instance decl header */
1799 Printf("instance ");
1800 if (nonNull(inst(in).specifics)) {
1801 printContext(stdout,inst(in).specifics);
1804 printPred(stdout,inst(in).head);
1808 /* --------------------------------------------------------------------------
1809 * List all names currently in scope:
1810 * ------------------------------------------------------------------------*/
1812 static Void local listNames() { /* list names matching optional pat*/
1813 String pat = readFilename();
1815 Int width = getTerminalWidth() - 1;
1818 Module mod = findEvalModule();
1820 if (pat) { /* First gather names to list */
1822 names = addNamesMatching(pat,names);
1823 } while ((pat=readFilename())!=0);
1825 names = addNamesMatching((String)0,names);
1827 if (isNull(names)) { /* Then print them out */
1828 ERRMSG(0) "No names selected"
1831 for (termPos=0; nonNull(names); names=tl(names)) {
1832 String s = objToStr(mod,hd(names));
1834 if (termPos+1+l>width) {
1837 } else if (termPos>0) {
1845 Printf("\n(%d names listed)\n", count);
1848 /* --------------------------------------------------------------------------
1849 * print a prompt and read a line of input:
1850 * ------------------------------------------------------------------------*/
1852 static Void local promptForInput(moduleName)
1853 String moduleName; {
1854 char promptBuffer[1000];
1856 /* This is portable but could overflow buffer */
1857 sprintf(promptBuffer,prompt,moduleName);
1859 /* Works on ANSI C - but pre-ANSI compilers return a pointer to
1860 * promptBuffer instead.
1862 if (sprintf(promptBuffer,prompt,moduleName) >= 1000) {
1863 /* Reset prompt to a safe default to avoid an infinite loop */
1865 prompt = strCopy("? ");
1866 internal("Combined prompt and evaluation module name too long");
1870 stringInput("main\0"); else
1871 consoleInput(promptBuffer);
1874 /* --------------------------------------------------------------------------
1875 * main read-eval-print loop, with error trapping:
1876 * ------------------------------------------------------------------------*/
1878 static jmp_buf catch_error; /* jump buffer for error trapping */
1880 static Void local interpreter(argc,argv)/* main interpreter loop */
1883 Int errorNumber = setjmp(catch_error);
1885 if (errorNumber && autoMain) {
1886 fprintf(stderr, "hugs +Q: compilation failed -- can't run `main'\n" );
1890 breakOn(TRUE); /* enable break trapping */
1891 if (numScripts==0) { /* only succeeds on first time, */
1892 if (errorNumber) /* before prelude has been loaded */
1893 fatal("Unable to load prelude");
1894 initialize(argc,argv);
1898 /* initialize calls startupHaskell, which trashes our signal handlers */
1903 everybody(RESET); /* reset to sensible initial state */
1904 dropScriptsFrom(numScripts-1); /* remove partially loaded scripts */
1905 /* not counting prelude as a script*/
1907 promptForInput(textToStr(module(findEvalModule()).text));
1909 cmd = readCommand(cmds, (Char)':', (Char)'!');
1914 case EDIT : editor();
1918 case LOAD : clearProject();
1919 forgetScriptsFrom(1);
1922 case ALSO : clearProject();
1923 forgetScriptsFrom(numScripts);
1926 case RELOAD : readScripts(1);
1928 case PROJECT: project();
1933 case EVAL : evaluator();
1935 case TYPEOF : showtype();
1937 case BROWSE : browse();
1939 #if EXPLAIN_INSTANCE_RESOLUTION
1940 case XPLAIN : xplain();
1943 case NAMES : listNames();
1947 case BADCMD : guidance();
1952 #ifdef CRUDE_PROFILING
1956 case SYSTEM : if (shellEsc(readLine()))
1957 Printf("Warning: Shell escape terminated abnormally\n");
1959 case CHGDIR : changeDir();
1963 case PNTVER: Printf("-- Hugs Version %s\n",
1966 case DUMP : dumpStg();
1969 case COLLECT: consGC = FALSE;
1972 Printf("Garbage collection recovered %d cells\n",
1979 Printf("Elapsed time (ms): %ld (user), %ld (system)\n",
1980 millisecs(userElapsed), millisecs(systElapsed));
1982 if (autoMain) break;
1987 /* --------------------------------------------------------------------------
1988 * Display progress towards goal:
1989 * ------------------------------------------------------------------------*/
1991 static Target currTarget;
1992 static Bool aiming = FALSE;
1995 static Int charCount;
1997 Void setGoal(what, t) /* Set goal for what to be t */
2001 currTarget = (t?t:1);
2004 currPos = strlen(what);
2005 maxPos = getTerminalWidth() - 1;
2009 for (charCount=0; *what; charCount++)
2014 Void soFar(t) /* Indicate progress towards goal */
2015 Target t; { /* has now reached t */
2018 Int newPos = (Int)((maxPos * ((long)t))/currTarget);
2023 if (newPos>currPos) {
2026 while (newPos>++currPos);
2033 Void done() { /* Goal has now been achieved */
2036 while (maxPos>currPos++)
2041 for (; charCount>0; charCount--) {
2050 static Void local failed() { /* Goal cannot be reached due to */
2051 if (aiming) { /* errors */
2058 /* --------------------------------------------------------------------------
2060 * ------------------------------------------------------------------------*/
2062 Void errHead(l) /* print start of error message */
2064 failed(); /* failed to reach target ... */
2066 FPrintf(errorStream,"ERROR");
2069 FPrintf(errorStream," \"%s\"", scriptFile);
2070 setLastEdit(scriptFile,l);
2071 if (l) FPrintf(errorStream," (line %d)",l);
2074 FPrintf(errorStream,": ");
2075 FFlush(errorStream);
2078 Void errFail() { /* terminate error message and */
2079 Putc('\n',errorStream); /* produce exception to return to */
2080 FFlush(errorStream); /* main command loop */
2081 longjmp(catch_error,1);
2084 Void errAbort() { /* altern. form of error handling */
2085 failed(); /* used when suitable error message*/
2086 stopAnyPrinting(); /* has already been printed */
2090 Void internal(msg) /* handle internal error */
2092 #if HUGS_FOR_WINDOWS
2094 wsprintf(buf,"INTERNAL ERROR: %s",msg);
2095 MessageBox(hWndMain, buf, appName, MB_ICONHAND | MB_OK);
2099 Printf("INTERNAL ERROR: %s\n",msg);
2101 longjmp(catch_error,1);
2104 Void fatal(msg) /* handle fatal error */
2106 #if HUGS_FOR_WINDOWS
2108 wsprintf(buf,"FATAL ERROR: %s",msg);
2109 MessageBox(hWndMain, buf, appName, MB_ICONHAND | MB_OK);
2112 Printf("\nFATAL ERROR: %s\n",msg);
2117 sigHandler(breakHandler) { /* respond to break interrupt */
2118 #if HUGS_FOR_WINDOWS
2119 MessageBox(GetFocus(), "Interrupted!", appName, MB_ICONSTOP | MB_OK);
2122 Printf("{Interrupted!}\n");
2124 breakOn(TRUE); /* reinstall signal handler - redundant on BSD systems */
2125 /* but essential on POSIX (and other?) systems */
2131 longjmp(catch_error,1);
2132 sigResume;/*NOTREACHED*/
2135 /* --------------------------------------------------------------------------
2136 * Read value from environment variable or registry:
2137 * ------------------------------------------------------------------------*/
2139 String fromEnv(var,def) /* return value of: */
2140 String var; /* environment variable named by var */
2141 String def; { /* or: default value given by def */
2142 String s = getenv(var);
2143 return (s ? s : def);
2146 /* --------------------------------------------------------------------------
2147 * String manipulation routines:
2148 * ------------------------------------------------------------------------*/
2150 static String local strCopy(s) /* make malloced copy of a string */
2154 if ((t=(char *)malloc(strlen(s)+1))==0) {
2155 ERRMSG(0) "String storage space exhausted"
2158 for (r=t; (*r++ = *s++)!=0; ) {
2165 /* --------------------------------------------------------------------------
2167 * We can redirect compiler output (prompts, error messages, etc) by
2168 * tweaking these functions.
2169 * ------------------------------------------------------------------------*/
2171 #if REDIRECT_OUTPUT && !HUGS_FOR_WINDOWS
2173 #ifdef HAVE_STDARG_H
2176 #include <varargs.h>
2179 /* ----------------------------------------------------------------------- */
2181 #define BufferSize 10000 /* size of redirected output buffer */
2183 typedef struct _HugsStream {
2184 char buffer[BufferSize]; /* buffer for redirected output */
2185 Int next; /* next space in buffer */
2188 static Void local vBufferedPrintf Args((HugsStream*, const char*, va_list));
2189 static Void local bufferedPutchar Args((HugsStream*, Char));
2190 static String local bufferClear Args((HugsStream *stream));
2192 static Void local vBufferedPrintf(stream, fmt, ap)
2196 Int spaceLeft = BufferSize - stream->next;
2197 char* p = &stream->buffer[stream->next];
2198 Int charsAdded = vsnprintf(p, spaceLeft, fmt, ap);
2199 if (0 <= charsAdded && charsAdded < spaceLeft)
2200 stream->next += charsAdded;
2201 #if 1 /* we can either buffer the first n chars or buffer the last n chars */
2207 static Void local bufferedPutchar(stream, c)
2210 if (BufferSize - stream->next >= 2) {
2211 stream->buffer[stream->next++] = c;
2212 stream->buffer[stream->next] = '\0';
2216 static String local bufferClear(stream)
2217 HugsStream *stream; {
2218 if (stream->next == 0) {
2222 return stream->buffer;
2226 /* ----------------------------------------------------------------------- */
2228 static HugsStream outputStreamH;
2230 * We rely on standard C semantics to initialise outputStreamH.next to 0.
2233 Void hugsEnableOutput(f)
2238 String hugsClearOutputBuffer() {
2239 return bufferClear(&outputStreamH);
2242 #ifdef HAVE_STDARG_H
2243 Void hugsPrintf(const char *fmt, ...) {
2244 va_list ap; /* pointer into argument list */
2245 va_start(ap, fmt); /* make ap point to first arg after fmt */
2246 if (!disableOutput) {
2249 vBufferedPrintf(&outputStreamH, fmt, ap);
2251 va_end(ap); /* clean up */
2254 Void hugsPrintf(fmt, va_alist)
2257 va_list ap; /* pointer into argument list */
2258 va_start(ap); /* make ap point to first arg after fmt */
2259 if (!disableOutput) {
2262 vBufferedPrintf(&outputStreamH, fmt, ap);
2264 va_end(ap); /* clean up */
2270 if (!disableOutput) {
2273 bufferedPutchar(&outputStreamH, c);
2277 Void hugsFlushStdout() {
2278 if (!disableOutput) {
2285 if (!disableOutput) {
2290 #ifdef HAVE_STDARG_H
2291 Void hugsFPrintf(FILE *fp, const char* fmt, ...) {
2294 if (!disableOutput) {
2295 vfprintf(fp, fmt, ap);
2297 vBufferedPrintf(&outputStreamH, fmt, ap);
2302 Void hugsFPrintf(FILE *fp, const char* fmt, va_list)
2308 if (!disableOutput) {
2309 vfprintf(fp, fmt, ap);
2311 vBufferedPrintf(&outputStreamH, fmt, ap);
2317 Void hugsPutc(c, fp)
2320 if (!disableOutput) {
2323 bufferedPutchar(&outputStreamH, c);
2327 #endif /* REDIRECT_OUTPUT && !HUGS_FOR_WINDOWS */
2328 /* --------------------------------------------------------------------------
2329 * Send message to each component of system:
2330 * ------------------------------------------------------------------------*/
2332 Void everybody(what) /* send command `what' to each component of*/
2333 Int what; { /* system to respond as appropriate ... */
2334 machdep(what); /* The order of calling each component is */
2335 storage(what); /* important for the INSTALL command */
2338 translateControl(what);
2340 staticAnalysis(what);
2341 deriveControl(what);
2347 /* --------------------------------------------------------------------------
2348 * Hugs for Windows code (WinMain and related functions)
2349 * ------------------------------------------------------------------------*/
2351 #if HUGS_FOR_WINDOWS
2352 #include "winhugs.c"