/
iomonad.c
1904 lines (1675 loc) · 48.7 KB
/
iomonad.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* --------------------------------------------------------------------------
* Implementation of the Haskell IO monad.
*
* The primitives below implement the standard IO monad for Haskell 1.3
* using a continuation passing monad for sequencing. The primitives are
* believed to give a reasonably good implementation of the semantics
* specified by the Haskell 1.3 report. There are also some additional
* primitives, particularly for dealing with IOError and Handle values
* that are not included in the prelude, but are used by standard libraries.
*
* The Hugs 98 system is Copyright (c) Mark P Jones, Alastair Reid, the
* Yale Haskell Group, and the OGI School of Science & Engineering at OHSU,
* 1994-2003, All rights reserved. It is distributed as free software under
* the license in the file "License", which is included in the distribution.
*
* $RCSfile: iomonad.c,v $
* $Revision: 1.101 $
* $Date: 2006/05/03 09:10:40 $
* ------------------------------------------------------------------------*/
Name nameIORun; /* run IO code */
Name nameIOBind; /* bind IO code */
Name namePutStr; /* Prelude.putStr */
static Name namePass; /* auxiliary:: \f b a -> f a b */
#if IO_HANDLES
static Name nameHreader; /* auxiliary function */
#endif
static Cell hugsProgName; /* value of getProgName */
static Cell hugsArgs; /* value of getArgs */
#if IO_HANDLES
static Void local throwErrno Args((String,Bool,Int,Cell *));
static String local toIOErrorDescr Args((int,Bool));
static Name local toIOError Args((int));
static Int local newHandle Args((Cell *,String));
static String local modeString Args((Int,Bool));
static Cell local openHandle Args((StackPtr,Cell *,Int,Bool,String));
static Cell local openFdHandle Args((StackPtr,Int,Int,Bool,String));
static Char local hGetChar Args((Int,String));
static Void local hPutChar Args((Char,Int,String));
static Void local setRWState Args((Int,Int));
static Void local checkOpen Args((Int,String));
static Void local checkReadable Args((Int,String));
static Void local checkWritable Args((Int,String));
#endif
#if IO_HANDLES
# if WANT_FIXED_SIZE_TABLES
# define MAX_HANDLES NUM_HANDLES
# else
# define MAX_HANDLES num_handles
# endif
#endif
extern Void local pushString Args((String));
/* --------------------------------------------------------------------------
* IO monad control:
* ------------------------------------------------------------------------*/
static Void iomonadControl Args((Int));
static Void iomonadControl(what)
Int what; {
switch (what) {
case INSTALL :
setCurrModule(modulePrelude);
#define pFun(n,s,t) addPrim(0,n=newName(findText(s),NIL),t,modulePrelude,NIL)
pFun(namePass, "_pass", "passIO");
#if IO_HANDLES
pFun(nameHreader, "_hreader", "hreader");
#endif
#undef pFun
#define predef(nm,str) nm=newName(findText(str),NIL); name(nm).defn=PREDEFINED
predef(nameIORun, "hugsIORun");
predef(nameIOBind, "primbindIO");
predef(namePutStr, "putStr");
#undef predef
break;
case MARK : mark(hugsProgName);
mark(hugsArgs);
break;
}
}
PROTO_PRIM(primReturnIO);
PROTO_PRIM(primBindIO);
PROTO_PRIM(primPass);
PROTO_PRIM(primGC);
PROTO_PRIM(primGetEnv);
PROTO_PRIM(primSystem);
PROTO_PRIM(primGetRandomSeed);
PROTO_PRIM(primGetProgName);
PROTO_PRIM(primGetArgs);
PROTO_PRIM(primSetProgName);
PROTO_PRIM(primSetArgs);
#if IO_HANDLES
static Void local fopenPrim Args((StackPtr,Bool,String));
static int local getIOMode Args((Cell));
PROTO_PRIM(primHGetChar);
PROTO_PRIM(primHPutChar);
PROTO_PRIM(primHPutStr);
PROTO_PRIM(primHreader);
PROTO_PRIM(primHContents);
PROTO_PRIM(primOpenFile);
PROTO_PRIM(primOpenBinaryFile);
PROTO_PRIM(primStdin);
PROTO_PRIM(primStdout);
PROTO_PRIM(primStderr);
PROTO_PRIM(primOpenFd);
PROTO_PRIM(primHandleToFd);
PROTO_PRIM(primHIsEOF);
PROTO_PRIM(primHFlush);
PROTO_PRIM(primHClose);
PROTO_PRIM(primHGetPosn);
PROTO_PRIM(primHSetPosn);
PROTO_PRIM(primHSetBuffering);
PROTO_PRIM(primHGetBuffering);
PROTO_PRIM(primHSeek);
PROTO_PRIM(primHLookAhead);
PROTO_PRIM(primHIsOpen);
PROTO_PRIM(primHIsClosed);
PROTO_PRIM(primHIsReadable);
PROTO_PRIM(primHIsWritable);
PROTO_PRIM(primHIsSeekable);
PROTO_PRIM(primHFileSize);
PROTO_PRIM(primHWaitForInput);
PROTO_PRIM(primEqHandle);
PROTO_PRIM(primGetHandleNumber);
PROTO_PRIM(primHSetBinaryMode);
PROTO_PRIM(primHPutBuf);
PROTO_PRIM(primHGetBuf);
PROTO_PRIM(primHIsTerminalDevice);
PROTO_PRIM(primHGetEcho);
PROTO_PRIM(primHSetEcho);
PROTO_PRIM(primIOEql);
PROTO_PRIM(primIOHash);
#endif
#if IO_REFS
PROTO_PRIM(primNewRef);
PROTO_PRIM(primDerefRef);
PROTO_PRIM(primAssignRef);
PROTO_PRIM(primEqRef);
#endif
PROTO_PRIM(primMakeSP);
PROTO_PRIM(primDerefSP);
PROTO_PRIM(primFreeSP);
PROTO_PRIM(primCastSPToP);
PROTO_PRIM(primCastPToSP);
PROTO_PRIM(primNewFP);
PROTO_PRIM(primAddFPF);
PROTO_PRIM(primAddFPFEnv);
PROTO_PRIM(primWriteFP);
PROTO_PRIM(primEqFP);
PROTO_PRIM(primTouchFP);
PROTO_PRIM(primFPToP);
#if GC_WEAKPTRS
PROTO_PRIM(primWeakPtrEq);
PROTO_PRIM(primMkWeak);
PROTO_PRIM(primDeRefWeak);
PROTO_PRIM(primReplaceFinalizer);
PROTO_PRIM(primFinalize);
PROTO_PRIM(primRunFinalizer);
PROTO_PRIM(primFinalizerWaiting);
#endif
#if STABLE_NAMES
PROTO_PRIM(primMakeSN);
PROTO_PRIM(primDerefSN);
PROTO_PRIM(primHashSN);
PROTO_PRIM(primEqSN);
#endif
#ifdef HSCRIPT
PROTO_PRIM(primGetCurrentScript);
#endif
#ifdef DOTNET
/* These primops are remnants from the first attempt at
* providing .NET interop for Haskell / Hugs. They've been
* mostly superceeded by the integration of .NET interop
* with the Haskell FFI, but we'll keep these primops around
* for a little bit longer.
*/
EXT_PROTO_PRIM(primCreateObject);
EXT_PROTO_PRIM(primInvokeMethod);
EXT_PROTO_PRIM(primInvokeStaticMethod);
EXT_PROTO_PRIM(primNewString);
EXT_PROTO_PRIM(primToHsString);
EXT_PROTO_PRIM(primNewArgArray);
EXT_PROTO_PRIM(primSetArg);
EXT_PROTO_PRIM(primGetArg);
EXT_PROTO_PRIM(primGetField);
EXT_PROTO_PRIM(primSetField);
EXT_PROTO_PRIM(primGetStaticField);
EXT_PROTO_PRIM(primSetStaticField);
EXT_PROTO_PRIM(primIsNullPtr);
EXT_PROTO_PRIM(primMkPrimVector);
#endif
static struct primitive iomonadPrimTable[] = {
{"primretIO", 1+IOArity, primReturnIO},
{"primbindIO", 2+IOArity, primBindIO},
{"passIO", 2+IOArity, primPass},
{"primGC", 0+IOArity, primGC},
{"getEnv", 1+IOArity, primGetEnv},
{"primSystem", 1+IOArity, primSystem},
{"getRandomSeed", 0+IOArity, primGetRandomSeed},
{"primGetProgName", 0+IOArity, primGetProgName},
{"primGetArgs", 0+IOArity, primGetArgs},
{"primSetProgName", 1+IOArity, primSetProgName},
{"primSetArgs", 1+IOArity, primSetArgs},
#if IO_HANDLES
{"hGetChar", 1+IOArity, primHGetChar},
{"hPutChar", 2+IOArity, primHPutChar},
{"hPutStr", 2+IOArity, primHPutStr},
{"hreader", 1, primHreader},
{"hGetContents", 1+IOArity, primHContents},
{"openFile", 2+IOArity, primOpenFile},
{"openBinaryFile", 2+IOArity, primOpenBinaryFile},
{"openFd", 4+IOArity, primOpenFd},
{"handleToFd", 1+IOArity, primHandleToFd},
{"stdin", 0, primStdin},
{"stdout", 0, primStdout},
{"stderr", 0, primStderr},
{"hIsEOF", 1+IOArity, primHIsEOF},
{"hFlush", 1+IOArity, primHFlush},
{"hClose", 1+IOArity, primHClose},
{"hGetPosnPrim", 1+IOArity, primHGetPosn},
{"hSetPosnPrim", 2+IOArity, primHSetPosn},
{"hSetBuff", 3+IOArity, primHSetBuffering},
{"hGetBuff", 1+IOArity, primHGetBuffering},
{"hSeekPrim", 3+IOArity, primHSeek},
{"hLookAhead", 1+IOArity, primHLookAhead},
{"hIsOpen", 1+IOArity, primHIsOpen},
{"hIsClosed", 1+IOArity, primHIsClosed},
{"hIsReadable", 1+IOArity, primHIsReadable},
{"hIsWritable", 1+IOArity, primHIsWritable},
{"hIsSeekable", 1+IOArity, primHIsSeekable},
{"hFileSize", 1+IOArity, primHFileSize},
{"hWaitForInput", 2+IOArity, primHWaitForInput},
{"primEqHandle", 2, primEqHandle},
{"primGetHandleNumber", 1, primGetHandleNumber},
{"hSetBinaryMode", 2+IOArity, primHSetBinaryMode},
{"hPutBuf", 3+IOArity, primHPutBuf},
{"hGetBuf", 3+IOArity, primHGetBuf},
{"hIsTerminalDevice", 1+IOArity, primHIsTerminalDevice},
{"hGetEcho", 1+IOArity, primHGetEcho},
{"hSetEcho", 2+IOArity, primHSetEcho},
#endif
#if IO_REFS
{"newRef", 1+IOArity, primNewRef},
{"getRef", 1+IOArity, primDerefRef},
{"setRef", 2+IOArity, primAssignRef},
{"eqRef", 2, primEqRef},
#endif
{"makeStablePtr", 1+IOArity, primMakeSP},
{"deRefStablePtr", 1+IOArity, primDerefSP},
{"freeStablePtr", 1+IOArity, primFreeSP},
{"castStablePtrToPtr",1, primCastSPToP},
{"castPtrToStablePtr",1, primCastPToSP},
{"writeForeignObj", 2+IOArity, primWriteFP},
{"eqForeignObj", 2, primEqFP},
{"newForeignPtr_", 1+IOArity, primNewFP},
{"addForeignPtrFinalizer", 2+IOArity, primAddFPF},
{"addForeignPtrFinalizerEnv", 3+IOArity, primAddFPFEnv},
{"touchForeignPtr", 1+IOArity, primTouchFP},
{"unsafeForeignPtrToPtr", 1, primFPToP},
#if GC_WEAKPTRS
{"weakPtrEq", 2, primWeakPtrEq},
{"mkWeak", 3+IOArity, primMkWeak},
{"deRefWeak", 1+IOArity, primDeRefWeak},
{"replaceFinalizer", 2+IOArity, primReplaceFinalizer},
{"finalize", 1+IOArity, primFinalize},
{"runFinalizer", 0+IOArity, primRunFinalizer},
{"finalizerWaiting", 0+IOArity, primFinalizerWaiting},
#endif
#if STABLE_NAMES
{"makeStableName", 1+IOArity, primMakeSN},
{"deRefStableName", 1, primDerefSN},
{"hashStableName", 1, primHashSN},
{"eqStableName", 2, primEqSN},
#endif
#ifdef HSCRIPT
{"getCurrentScript", 0+IOArity, primGetCurrentScript},
#endif
#ifdef DOTNET
{"createObject", 2+IOArity, primCreateObject},
{"invokeMethod", 3+IOArity, primInvokeMethod},
{"invokeStaticMethod", 2+IOArity, primInvokeStaticMethod},
{"newString", 1+IOArity, primNewString},
{"toString", 1+IOArity, primToHsString},
{"newArgArray", 1+IOArity, primNewArgArray},
{"setArrayArg", 3+IOArity, primSetArg},
{"getArrayArg", 2+IOArity, primGetArg},
{"getField", 2+IOArity, primGetField},
{"setField", 3+IOArity, primSetField},
{"getStaticField", 2+IOArity, primGetStaticField},
{"setStaticField", 3+IOArity, primSetStaticField},
{"isNullPtr", 1+IOArity, primIsNullPtr},
{"mkPrimVector", 2+IOArity, primMkPrimVector},
#endif
{"IOEql", 2+IOArity, primIOEql},
{"IOHash", 1+IOArity, primIOHash},
{0, 0, 0}
};
static struct primInfo iomonadPrims = { iomonadControl, iomonadPrimTable, 0 };
/* --------------------------------------------------------------------------
* The monad combinators:
* ------------------------------------------------------------------------*/
primFun(primReturnIO) { /* IO monad unit */
IOReturn(IOArg(1));
}
primFun(primBindIO) { /* IO monad bind */
push(ap(namePass,primArg(2))); /* bind 3 2 1 = 3 (pass 2 1) */
toparg(primArg(1));
updapRoot(primArg(3),top());
}
primFun(primPass) { /* Auxiliary function */
push(ap(primArg(3),primArg(1))); /* pass 3 2 1 = 3 1 2 */
updapRoot(top(),primArg(2));
}
/* --------------------------------------------------------------------------
* Handle operations:
* ------------------------------------------------------------------------*/
#if IO_HANDLES
static
Int local newHandle(sCell,loc) /* return a free Handle or throw an IOError */
Cell *sCell;
String loc; {
Int i;
for (i=0; i<(Int)MAX_HANDLES && nonNull(handles[i].hcell); ++i)
; /* Search for unused handle*/
if (i>=(Int)MAX_HANDLES) { /* If at first we don't */
garbageCollect(); /* succeed, garbage collect*/
for (i=0; i<(Int)MAX_HANDLES && nonNull(handles[i].hcell); ++i)
; /* and try again ... */
#if !WANT_FIXED_SIZE_TABLES
if (i >= (Int)MAX_HANDLES) {
Int j;
growDynTable(dynTabHandles);
handles = (struct strHandle*)(dynTabHandles->data);
num_handles = dynTabHandles->maxIdx;
/* Nil out the new entries in the table */
for (j=i; j < (Int)num_handles; j++) {
handles[j].hcell = NIL;
}
}
#endif
}
if (i>=(Int)MAX_HANDLES) { /* ... before we give up */
IOFail(mkIOError(NULL,
nameIllegal,
loc,
"too many handles open",
sCell));
}
return i;
}
static
String local modeString(hmode,binary) /* return mode string for f(d)open */
Int hmode;
Bool binary; {
if (binary) {
return (hmode&HAPPEND) ? "ab" :
(hmode&HWRITE) ? "wb" :
(hmode&HREADWRITE) ? "rb+" :
(hmode&HREAD) ? "rb" : (String)0;
} else {
return (hmode&HAPPEND) ? "a" :
(hmode&HWRITE) ? "w" :
(hmode&HREADWRITE) ? "r+" :
(hmode&HREAD) ? "r" : (String)0;
}
}
static
Cell local openHandle(root,sCell,hmode,binary,loc) /* open handle to file named s in */
StackPtr root;
Cell *sCell; /* the specified hmode */
Int hmode;
Bool binary;
String loc; {
Int i;
String s = evalName(*sCell);
String stmode = modeString(hmode,binary);
/* openHandle() either returns a Handle or throws an IOError. */
if (!s) { /* check for valid name */
IOFail(mkIOError(NULL,
nameIllegal,
loc,
"illegal file name",
NULL));
}
i = newHandle(sCell,loc);
if (!stmode) {
IOFail(mkIOError(NULL,
nameIllegal,
loc,
"illegal mode",
NULL));
}
/* prepare to open file */
handles[i].hfp = fopen(s,stmode);
if (hmode==HREADWRITE && handles[i].hfp==NULL) /* try to create it */
handles[i].hfp = fopen(s, binary ? "wb+" : "w+");
if (!handles[i].hfp)
throwErrno(loc, TRUE, NO_HANDLE, sCell);
handles[i].hmode = hmode;
handles[i].hbufMode = HUNKNOWN_BUFFERING;
handles[i].hbufSize = (-1);
setRWState(i, RW_NEUTRAL);
#if CHAR_ENCODING
handles[i].hBinaryMode = binary;
handles[i].hLookAhead = -1;
#endif
return (handles[i].hcell = ap(HANDCELL,i));
}
static
Cell local openFdHandle(root,fd,hmode,binary,loc) /* open handle to file desc fd in */
StackPtr root;
Int fd; /* the specified hmode */
Int hmode;
Bool binary;
String loc; {
Int i = newHandle(NIL,loc);
String stmode = modeString(hmode,binary);
/* openFdHandle() either returns a Handle or throws an IOError. */
if (!stmode) {
IOFail(mkIOError(NULL,
nameIllegal,
loc,
"illegal mode",
NULL));
}
if (!(handles[i].hfp=fdopen(fd,stmode)))
throwErrno(loc, TRUE, NO_HANDLE, NULL);
handles[i].hmode = hmode;
handles[i].hbufMode = HANDLE_NOTBUFFERED;
handles[i].hbufSize = 0;
setRWState(i, RW_NEUTRAL);
#if CHAR_ENCODING
handles[i].hBinaryMode = binary;
handles[i].hLookAhead = -1;
#endif
return (handles[i].hcell = ap(HANDCELL,i));
}
static Char local hGetChar(Int h, String fname) {
Int c;
#if CHAR_ENCODING
if (handles[h].hLookAhead>=0) {
c = handles[h].hLookAhead;
handles[h].hLookAhead = -1;
} else if (handles[h].hBinaryMode) {
c = getc(handles[h].hfp);
} else {
c = FGetChar(handles[h].hfp);
}
#else /* !CHAR_ENCODING */
c = FGetChar(handles[h].hfp);
#endif
if (c==EOF && !feof(handles[h].hfp))
throwErrno(fname, TRUE, h, NULL);
#if CHAR_ENCODING
else if (c==BAD_CHAR) {
IOFail(mkIOError(&handles[h].hcell,
nameProtocolError,
fname,
"input contains non-character data - use binary I/O for binary data",
NULL));
}
#endif /* CHAR_ENCODING */
return c;
}
static Void local hPutChar(Char c, Int h, String fname) {
Int retval;
#if CHAR_ENCODING
retval = handles[h].hBinaryMode ? putc(c, handles[h].hfp) :
FPutChar(c, handles[h].hfp);
#else
retval = FPutChar(c, handles[h].hfp);
#endif
if (retval == EOF)
throwErrno(fname, TRUE, h, NULL);
#if FLUSHEVERY
if (h <= 2) { /* Only flush the standard handles */
fflush(handles[h].hfp);
}
#endif
}
/* If the stream is read-write, set the state, otherwise do nothing */
static Void local setRWState(Int h, Int newState) {
if (handles[h].hmode&HREADWRITE) {
/* ANSI C requires repositioning between writes and reads */
if (newState==RW_READING) {
if (handles[h].hRWState==RW_WRITING) {
fflush(handles[h].hfp);
fseek(handles[h].hfp, 0L, SEEK_CUR);
}
} else if (newState==RW_WRITING) {
if (handles[h].hRWState==RW_READING)
fseek(handles[h].hfp, 0L, SEEK_CUR);
}
handles[h].hRWState = newState;
}
}
/* ensure that the handle is neither closed nor semi-closed */
static Void local checkOpen(Int h, String fname) {
Int mode = handles[h].hmode;
if (mode==HCLOSED)
IOFail(mkIOError(&handles[h].hcell,
nameIllegal,
fname,
"handle is closed",
NULL));
if (mode==HSEMICLOSED)
IOFail(mkIOError(&handles[h].hcell,
nameIllegal,
fname,
"handle is semi-closed",
NULL));
}
/* ensure that the handle is readable */
static Void local checkReadable(Int h, String fname) {
checkOpen(h, fname);
if (!(handles[h].hmode&(HREAD|HREADWRITE)))
IOFail(mkIOError(&handles[h].hcell,
nameIllegal,
fname,
"handle is not readable",
NULL));
}
/* ensure that the handle is writable */
static Void local checkWritable(Int h, String fname) {
checkOpen(h, fname);
if (!(handles[h].hmode&(HWRITE|HAPPEND|HREADWRITE)))
IOFail(mkIOError(&handles[h].hcell,
nameIllegal,
fname,
"handle is not writeable",
NULL));
}
/* --------------------------------------------------------------------------
* Building strings:
* ------------------------------------------------------------------------*/
Void pushString(s) /* push pointer to string onto stack */
String s; {
if (*s == '\0')
push(nameNil);
else {
Cell l = ap(consChar(ExtractChar(s)),NIL);
push(l);
while (*s) {
snd(l) = ap(consChar(ExtractChar(s)),NIL);
l = snd(l);
}
snd(l) = nameNil;
}
}
/* Helper function for constructing IOErrors (see Prelude defn of
* IOError for explanation of what the the individual arguments
* do.
*/
Cell
mkIOError(mbH, kind, loc, desc, mbF)
Cell *mbH; /* a Handle or NULL */
Name kind; /* an IOErrorType */
String loc;
String desc;
Cell *mbF; /* a FilePath or NULL */
{
Cell str;
push(nameIOError);
toparg(mbH==NULL ? nameNothing : ap(nameJust,*mbH));
toparg(kind);
pushString(loc); str = pop(); toparg(str);
pushString(desc); str = pop(); toparg(str);
toparg(mbF==NULL ? nameNothing : ap(nameJust,*mbF));
return pop();
}
#endif
/* --------------------------------------------------------------------------
* IO Errors (more defined for file ops)
* ------------------------------------------------------------------------*/
static Void local throwErrno(String fname, Bool isFile, Int h, Cell *mbF)
{
IOFail(mkIOError(h == NO_HANDLE ? NULL : &handles[h].hcell,
toIOError(errno),
fname,
toIOErrorDescr(errno, isFile),
mbF));
}
/*
* Map a libc error code to an IOError
*/
static Name local toIOError(errc)
int errc;
{
#if HAVE_ERRNO_H && !(__MWERKS__ && macintosh)
switch(errc) {
case EEXIST:
return nameAlreadyExists;
case ENOENT:
case ENOTDIR:
return nameDoesNotExist;
case EPERM:
case EACCES:
return namePermDenied;
case ENOSPC:
case EFBIG:
return nameIsFull;
default:
return nameIllegal;
}
#else
return nameIllegal;
#endif
}
/*
* Map a libc error code to an IOError descriptive string
*/
static String local toIOErrorDescr(errc,isFile)
int errc;
Bool isFile;
{
#if HAVE_ERRNO_H && !(__MWERKS__ && macintosh)
switch(errc) {
case EEXIST:
return (isFile ? "file already exists" : "directory already exists");
case ENOENT:
case ENOTDIR:
return (isFile ? "file does not exist" : "directory does not exist");
case EPERM:
case EACCES:
return ""; /* No need to replicate the info conveyed by the IOErrorKind */
case ENOSPC:
case EFBIG:
return "device is full";
default:
return "";
}
#else
return "";
#endif
}
/* --------------------------------------------------------------------------
* Misc.
* ------------------------------------------------------------------------*/
primFun(primGC) { /* force a GC right now */
garbageCollect();
IOReturn(nameUnit);
}
#if BIGNUMS && defined HAVE_TIME_H
#include <time.h>
primFun(primGetRandomSeed) { /* generate a random seed */
IOReturn(bigInt(clock()));
}
#else
primFun(primGetRandomSeed) { /* generate a random seed */
ERRMSG(0) "getRandomSeed is not implemented on this architecture"
EEND;
}
#endif
primFun(primGetEnv) { /* primGetEnv :: String -> IO String */
String s = evalName(IOArg(1)); /* Eval name */
String r;
if (!s) { /* check for valid name */
IOFail(mkIOError(NULL,
nameIllegal,
"System.getEnv",
"illegal environment variable name",
&IOArg(1)));
}
if ((r = getenv(s))==0) {
IOFail(mkIOError(NULL,
nameDoesNotExist,
"System.getEnv",
"environment variable not found",
&IOArg(1)));
}
pushString(r);
IOReturn(pop());
}
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#if HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#ifndef WEXITSTATUS
/* If it's not defined, return it verbatim. */
# define WEXITSTATUS(stat_val) (stat_val)
#endif
primFun(primSystem) { /* primSystem :: String -> IO Int */
String s = evalName(IOArg(1)); /* Eval name */
Int r;
if (!s) { /* check for valid string */
IOFail(mkIOError(NULL,
nameIllegal,
"System.system",
"illegal system command string",
&IOArg(1)));
}
r = shellEsc(s, TRUE/*synchronous*/, TRUE/*use shell*/);
IOReturn(mkInt(WEXITSTATUS(r)));
}
Void setHugsArgs(argc,argv)
Int argc;
String argv[]; {
int i;
Cell str;
hugsArgs = nameNil;
pushString(argv[0]);
hugsProgName = pop();
for (i=argc-1; i>0; i--) {
pushString(argv[i]);
str = pop();
hugsArgs = ap2(nameCons, str, hugsArgs);
}
}
primFun(primGetProgName) { /* primGetProgName :: IO String */
IOReturn(hugsProgName);
}
primFun(primGetArgs) { /* primGetArgs :: IO [String] */
IOReturn(hugsArgs);
}
primFun(primSetProgName) { /* primSetProgName :: String -> IO () */
hugsProgName = IOArg(1);
IOReturn(nameUnit);
}
primFun(primSetArgs) { /* primSetArgs :: [String] -> IO () */
hugsArgs = IOArg(1);
IOReturn(nameUnit);
}
/* --------------------------------------------------------------------------
* File IO
* ------------------------------------------------------------------------*/
#if IO_HANDLES
#define HandleArg(nm,offset) \
eval(primArg(offset)); \
nm = intValOf(whnfHead)
#define IOBoolResult(e) \
IOReturn((e)?nameTrue:nameFalse)
primFun(primHGetChar) { /* Read character from handle */
Int h;
Int c;
HandleArg(h,1+IOArity);
checkReadable(h, "IO.hGetChar");
setRWState(h, RW_READING);
c = hGetChar(h, "IO.hGetChar");
if (c==EOF) {
setRWState(h, RW_NEUTRAL);
IOFail(mkIOError(&handles[h].hcell,
nameEOFErr,
"IO.hGetChar",
"end of file",
NULL));
}
IOReturn(mkChar(c));
}
primFun(primHPutChar) { /* print character on handle */
Char c = 0;
Int h;
HandleArg(h,2+IOArity);
CharArg(c,1+IOArity);
checkWritable(h, "IO.hPutChar");
setRWState(h, RW_WRITING);
hPutChar(c, h, "IO.hPutChar");
IOReturn(nameUnit);
}
primFun(primHPutStr) { /* print string on handle */
Int h;
HandleArg(h,2+IOArity);
push(primArg(1+IOArity));
primArg(1+IOArity) = NIL;
checkWritable(h, "IO.hPutStr");
setRWState(h, RW_WRITING);
blackHoleRoot();
eval(pop());
while (whnfHead==nameCons) {
eval(pop());
hPutChar(charOf(whnfHead),h,"IO.hPutStr");
eval(pop());
}
#if !FLUSHEVERY
if (h <= 2) { /* Only flush the standard handles */
fflush(handles[h].hfp);
}
#endif
IOReturn(nameUnit);
}
primFun(primHreader) { /* read String from a handle */
Int h; /* Handle -> String */
HandleArg(h,1);
if (handles[h].hmode&HSEMICLOSED) { /* read requires semi-closed handle*/
Int c = hGetChar(h, "IO.getContents");
if (c!=EOF && c>=0 && c<=MAXCHARVAL) {
updapRoot(consChar(c),ap(nameHreader,primArg(1)));
return;
}
clearerr(handles[h].hfp);
}
updateRoot(nameNil);
}
primFun(primHContents) { /* hGetContents :: Handle -> IO Str*/
Int h;
HandleArg(h,1+IOArity);
checkReadable(h, "IO.hGetContents"); /* must have readable handle */
setRWState(h, RW_READING);
handles[h].hmode = HSEMICLOSED; /* semi-close handle */
IOReturn(ap(nameHreader,IOArg(1)));
}
static int local getIOMode(mode) /* From IOMode to internal form */
Cell mode; {
Int m = HCLOSED;
eval(mode); /* Eval IOMode */
if (isName(whnfHead) && isCfun(whnfHead))
switch (cfunOf(whnfHead)) { /* we have to use numeric consts */
case 1 : m = HREAD; /* here to avoid the need to put */
break; /* IOMode in startup environment */
case 2 : m = HWRITE;
break;
case 3 : m = HAPPEND;
break;
case 4 : m = HREADWRITE;
break;
}
return m;
}
static Void local fopenPrim(root,binary,loc)/* Auxiliary function for */
StackPtr root; /* opening a file */
Bool binary;
String loc; {
Int m;
m = getIOMode(IOArg(1));
if (m==HCLOSED) { /* Only accept legal modes */
IOFail(mkIOError(NULL,
nameIllegal,
loc,
"unknown handle mode",
&IOArg(2)));
}
IOReturn(openHandle(root,&IOArg(2),m,binary,loc));
}
primFun(primOpenFile) { /* open handle to a text file */
fopenPrim(root,FALSE,"IO.openFile");
}
primFun(primOpenBinaryFile) { /* open handle to a binary file */
fopenPrim(root,TRUE,"System.IO.openBinaryFile");
}
primFun(primStdin) { /* Standard input handle */
push(handles[HSTDIN].hcell);
}
primFun(primStdout) { /* Standard output handle */
push(handles[HSTDOUT].hcell);
}
primFun(primStderr) { /* Standard error handle */
push(handles[HSTDERR].hcell);
}
primFun(primOpenFd) { /* open handle to file descriptor. */
Int m; /* :: Int{-Fd-} -> Bool -> IOMode -> Bool -> IO Handle */
Int fd;
Bool binary;
Bool isSock;
IntArg(fd,4+IOArity);
BoolArg(isSock,3+IOArity);
BoolArg(binary,1+IOArity);
m = getIOMode(IOArg(2));
if (m==HCLOSED) { /* Only accept legal modes */
IOFail(mkIOError(NULL,
nameIllegal,
"openFd",
"unknown handle mode",
NULL));
}
#if defined(_WIN32) && !cygwin32_HOST_OS
if (isSock) {
/* fd is a SOCKET, convert it to an FD.
* Note: _open_osfhandle() will fail under
* Win9x. ToDo: better on those plats.
*/
fd = _open_osfhandle(fd,
(m & HREAD ? O_RDONLY : 0) |
(m & HWRITE ? O_WRONLY : 0) |
(m & HREADWRITE ? O_RDWR : 0) |
(m & HAPPEND ? O_APPEND : 0) |
(binary ? O_BINARY : O_TEXT)
);
}
#endif
IOReturn(openFdHandle(root,fd,m,binary,"openFd"));
}
/* Extract the file descriptor from a Handle, discarding the Handle */
primFun(primHandleToFd) {