1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
|
module REPL.Main where
import Control.Monad ( when, unless )
import Curry.Compiler.Distribution ( installDir )
import Data.Char ( toLower, toUpper )
import Data.List ( intercalate, intersperse, isInfixOf, isPrefixOf
, maximum, nub, partition, sort, sortBy )
import System.Environment ( getArgs, getEnv )
import System.FilePath ( (</>), (<.>) )
import System.IO ( hClose, hFlush, hPutStrLn, isEOF, stdout )
import AbstractCurry.Types hiding (preludeName)
import AbstractCurry.Files
import AbstractCurry.Build ( ioType, stringType, unitType )
import AbstractCurry.Select
import System.CurryPath ( inCurrySubdir, lookupModuleSource, modNameToPath
, stripCurrySuffix )
import System.Directory ( doesDirectoryExist, doesFileExist, getAbsolutePath
, getDirectoryContents, getHomeDirectory
, renameFile, setCurrentDirectory )
import System.FilePath ( searchPathSeparator, splitExtension
, splitFileName, splitSearchPath )
import System.FrontendExec
import System.IOExts ( connectToCommand )
import System.Process ( exitWith, getPID, system )
import REPL.Compiler
import REPL.RCFile
import REPL.State
import REPL.Utils ( showMonoTypeExpr, showMonoQualTypeExpr
, getTimeCmd, getTimeoutCmd, moduleNameToPath
, validModuleName, notNull, removeFileIfExists
, strip, writeErrorMsg )
mainREPL :: CCDescription -> IO ()
mainREPL cd = do
rcFileDefs <- readRC cd
args <- getArgs
let (nodefargs,defargs) = extractRCArgs args
(mainargs,rtargs) = break (=="--") nodefargs
rcDefs = updateRCDefs rcFileDefs defargs
furtherRcDefs = filter (\da -> fst da `notElem` map fst rcFileDefs)
defargs
rst <- initReplState cd
ipath <- defaultImportPaths rst
let rst1 = rst { importPaths = ipath
, rcVars = rcDefs
, rtsArgs = if null rtargs then "" else unwords (tail rtargs)
}
if null furtherRcDefs
then processArgsAndStart
rst1
(map strip (words (rcValue (rcVars rst1) "defaultparams")) ++
mainargs)
else putStrLn $ "Error: rc property name '" ++ fst (head furtherRcDefs) ++
"' not found in rc file!"
processArgsAndStart :: ReplState -> [String] -> IO ()
processArgsAndStart rst []
| quit rst = cleanUpAndExitRepl rst
| otherwise = do
writeVerboseInfo rst 1 (ccBanner (compiler rst))
writeVerboseInfo rst 1 $
"Type \":h\" for help (contact: " ++ ccEmail (compiler rst) ++ ")"
when (currMod rst == "Prelude") $ do
writeVerboseInfo rst 1 $ "Compiling Prelude..."
processCompile (reduceVerbose rst) "Prelude" >> return ()
repLoop rst
processArgsAndStart rst (arg:args)
| null arg
= processArgsAndStart rst args
| arg `elem` ["-n", "--nocypm", "--noreadline"]
= processArgsAndStart rst args
| arg == "-h" || arg == "--help" || arg == "-?"
= printHelp >> cleanUpAndExitRepl rst
| arg == "-q" || arg == "--quiet"
= processArgsAndStart rst { verbose = 0 } args
| arg == "-V" || arg == "--version"
= do putStrLn (ccBanner (compiler rst))
processArgsAndStart rst { quit = True} args
| arg `elem` versionOpts
= do let (vopts,mopts) = partition (`elem` versionOpts) args
if null mopts
then do system $ unwords (ccExec (compiler rst) : arg : vopts)
cleanUpAndExitRepl rst
else writeErrorMsg ("illegal options: " ++ unwords mopts)
| isCommand arg = do
let (cmdargs, more) = break isCommand args
mbrst <- processCommand rst (tail (unwords (arg:cmdargs)))
maybe printHelp (\rst' -> processArgsAndStart rst' more) mbrst
| otherwise
= writeErrorMsg ("unknown command: " ++ unwords (arg:args)) >> printHelp
where
versionOpts = ["--compiler-name", "--numeric-version", "--base-version"]
isCommand :: String -> Bool
isCommand s = case s of
':' : _ -> True
_ -> False
printHelp :: IO ()
printHelp = putStrLn $ unlines
[ "Invoke interactive environment:"
, ""
, " <repl> <options> [ -- <run-time arguments>]"
, ""
, "with options:"
, ""
, "-h|--help|-? : show this message and quit"
, "-V|--version : show version and quit"
, "--compiler-name : show the compiler name and quit"
, "--numeric-version : show the compiler version number and quit"
, "--base-version : show the version of the base libraries and quit"
, "-q|--quiet : work silently"
, "-n|--nocypm : do not invoke `cypm' to compute package load path"
, "--noreadline : do not use input line editing via command `rlwrap'"
, "-Dprop=val : define rc property `prop' as `val'"
, ":<cmd> <args> : commands of the interactive environment"
, ""
]
repLoop :: ReplState -> IO ()
repLoop rst = do
putStr prompt >> hFlush stdout
eof <- isEOF
if eof then cleanUpAndExitRepl rst
else mGetLine >>= maybe (cleanUpAndExitRepl rst) (checkInput . strip)
where
prompt = calcPrompt rst
checkInput inp
| null inp
= repLoop rst
| ord (head inp) == 0
= cleanUpAndExitRepl rst
| otherwise
= do when (withEcho rst) $ putStrLn $ prompt ++ inp
processInput rst inp
mGetLine :: IO (Maybe String)
mGetLine = do
eof <- isEOF
if eof
then return Nothing
else do
c <- getChar
if ord c == 0
then return Nothing
else if c == '\n'
then return $ Just []
else do mGetLine >>= maybe (return Nothing)
(\cs -> return $ Just (c:cs))
calcPrompt :: ReplState -> String
calcPrompt rst =
substS (unwords (currMod rst : addMods rst)) (prompt rst)
substS :: String -> String -> String
substS replacement = sub
where
sub [] = []
sub [c] = [c]
sub (c:d:cs) = case c of
'%' -> case d of
'%' -> '%' : cs
's' -> replacement ++ sub cs
_ -> c : d : sub cs
_ -> c : sub (d:cs)
cleanUpAndExitRepl :: ReplState -> IO ()
cleanUpAndExitRepl rst = do
terminateSourceProgGUIs rst
exitWith (exitStatus rst)
processInput :: ReplState -> String -> IO ()
processInput rst g
| null g = repLoop rst
| isCommand g = do mbrst <- processCommand rst (strip (tail g))
maybe (repLoop (rst { exitStatus = 1 }))
(\rst' -> if quit rst' then cleanUpAndExitRepl rst'
else repLoop rst')
mbrst
| otherwise = evalExpression rst g >>= repLoop
evalExpression :: ReplState -> String -> IO ReplState
evalExpression rst expr = do
exst <- compileMainExpression rst expr True
return rst { exitStatus = exst }
importUnsafeModule :: ReplState -> IO Bool
importUnsafeModule rst =
if containsUnsafe (addMods rst)
then return True
else do
let acyMainModFile = acyFileName rst (currMod rst)
frontendParams = currentFrontendParams rst (verbose rst <= 1)
catch (do verbCallFrontendWithParams rst ACY frontendParams (currMod rst)
p <- readAbstractCurryFile acyMainModFile
return $ containsUnsafe (imports p))
(\_ -> return (currMod rst /= "Prelude"))
where
containsUnsafe = any ("Unsafe" `isInfixOf`)
currentFrontendParams :: ReplState -> Bool -> FrontendParams
currentFrontendParams rst quiet =
setQuiet quiet
$ setFrontendPath (ccFrontend cc)
$ setFullPath (loadPaths rst)
$ setExtended (rcValue (rcVars rst) "curryextensions" /= "no")
$ setOverlapWarn (rcValue (rcVars rst) "warnoverlapping" /= "no")
$ setSpecials (parseOpts rst)
$ setDefinitions [("__" ++ map toUpper (ccName cc) ++ "__", maj*100 + min)]
$ setOutDir (compilerOutDir rst)
defaultParams
where
cc = compiler rst
(maj,min,_) = ccVersion cc
compilerOutDir :: ReplState -> String
compilerOutDir rst =
".curry" </> map toLower (ccName cc) ++ "-" ++
intercalate "." (map show [maj,min,rev])
where
cc = compiler rst
(maj,min,rev) = ccVersion cc
acyFileName :: ReplState -> String -> String
acyFileName rst prog = compilerOutDir rst </> modNameToPath prog <.> "acy"
verbCallFrontendWithParams :: ReplState -> FrontendTarget -> FrontendParams
-> String -> IO ()
verbCallFrontendWithParams rst target params modpath = do
when (verbose rst > 1) $ do
parsecmd <- getFrontendCall target params modpath
writeVerboseInfo rst 2 $ "Executing: " ++ parsecmd
callFrontendWithParams target params modpath
writeSimpleMainExpFile :: ReplState -> String -> IO ()
writeSimpleMainExpFile rst exp = writeMainExpFile rst [] Nothing exp
writeMainExpFile :: ReplState -> [String] -> Maybe String -> String -> IO ()
writeMainExpFile rst imports mtype exp =
writeFile (mainExpFile rst) $ unlines $
[noMissingSigs, "module " ++ mainExpMod rst ++ " where"] ++
map ("import " ++) allImports ++
maybe [] (\ts -> ["main :: " ++ ts]) mtype ++
["main = " ++ qualifyMain (strip exp)]
where
allImports = filter (/="Prelude") . nub $ currMod rst : addMods rst ++ imports
noMissingSigs = "{-# OPTIONS_FRONTEND -W no-missing-signatures #-}"
qualifyMain s
| "main" `isPrefixOf` s = currMod rst ++ ".main" ++ drop 4 s
| "(" `isPrefixOf` s = '(' : qualifyMain (tail s)
| otherwise = s
getAcyOfMainExpMod :: ReplState -> IO (Maybe CurryProg)
getAcyOfMainExpMod rst = do
let acyMainExpFile = acyFileName rst (mainExpMod rst)
frontendParams = currentFrontendParams rst (verbose rst <= 1)
prog <- catch (verbCallFrontendWithParams rst ACY frontendParams
(mainExpMod rst) >>
tryReadACYFile acyMainExpFile)
(\_ -> return Nothing)
unlessKeepFiles rst $ removeFileIfExists acyMainExpFile
return prog
getAcyOfExpr :: ReplState -> String -> IO (Maybe CurryProg)
getAcyOfExpr rst expr = do
writeSimpleMainExpFile rst expr
mbProg <- getAcyOfMainExpMod rst
unlessKeepFiles rst $ removeFileIfExists (mainExpFile rst)
return mbProg
printTypeOfExp :: ReplState -> String -> IO Bool
printTypeOfExp rst exp = do
mbProg <- getAcyOfExpr rst exp
maybe (do writeVerboseInfo rst 3 "Cannot read AbstractCurry file"
return False)
(\ (CurryProg _ _ _ _ _ _ [CFunc _ _ _ qty _] _) -> do
putStrLn $ exp ++ " :: " ++ showMonoQualTypeExpr False qty
return True)
mbProg
getModuleOfFunction :: ReplState -> String -> IO String
getModuleOfFunction rst funname = do
mbprog <- getAcyOfExpr rst $
if isAlpha (head funname) then funname else '(' : funname ++ ")"
return $ maybe ""
(\ (CurryProg _ _ _ _ _ _ [CFunc _ _ _ _ mainrules] _) ->
modOfMain mainrules)
mbprog
where modOfMain r = case r of
[CRule [] (CSimpleRhs (CSymbol (m, _)) [])] -> m
[CRule [] (CGuardedRhs [(_, CSymbol (m, _))] [])] -> m
_ -> ""
processCommand :: ReplState -> String -> IO (Maybe ReplState)
processCommand rst cmds
| null cmds = skipCommand "unknown command"
| head cmds == '!' = unsafeExec rst $ processSysCall rst (strip $ tail cmds)
| otherwise = case matchedCmds of
[] -> skipCommand $ "unknown command: ':" ++ cmds ++ "'"
[(fcmd, act)] -> if fcmd `elem` ["eval","load","quit","reload"]
then act rst (strip args)
else unsafeExec rst $ act rst (strip args)
(_:_:_) -> skipCommand $ "ambiguous command: ':" ++ cmds ++ "'"
where (cmd, args) = break (==' ') cmds
matchedCmds = filter (isPrefixOf (map toLower cmd) . fst) replCommands
unsafeExec :: ReplState -> IO (Maybe ReplState) -> IO (Maybe ReplState)
unsafeExec rst act =
if safeExec rst
then skipCommand "Operation not allowed in safe mode!"
else act
replCommands :: [(String, ReplState -> String -> IO (Maybe ReplState))]
replCommands =
[ ("?" , processHelp )
, ("add" , processAdd )
, ("browse" , processBrowse )
, ("cd" , processCd )
, ("compile" , processCompile )
, ("edit" , processEdit )
, ("eval" , processEval )
, ("fork" , processFork )
, ("help" , processHelp )
, ("interface" , processInterface )
, ("load" , processLoad )
, ("modules" , processModules )
, ("programs" , processPrograms )
, ("reload" , processReload )
, ("quit" , processQuit )
, ("save" , processSave )
, ("set" , processSetOption )
, ("source" , processSource )
, ("show" , processShow )
, ("type" , processType )
, ("usedimports", processUsedImports )
]
skipCommand :: String -> IO (Maybe ReplState)
skipCommand msg = writeErrorMsg msg >> return Nothing
processSysCall :: ReplState -> String -> IO (Maybe ReplState)
processSysCall rst cmd
| null cmd = skipCommand "missing system command"
| otherwise = system cmd >> return (Just rst)
processAdd :: ReplState -> String -> IO (Maybe ReplState)
processAdd rst args
| null args = skipCommand "Missing module name"
| otherwise = Just `fmap` foldIO add rst (words args)
where
add rst' m = let mdl = stripCurrySuffix m in
if validModuleName mdl
then do
mbf <- lookupModuleSource (loadPaths rst') mdl
case mbf of
Nothing -> do
writeErrorMsg $ "Source file of module '" ++ mdl ++ "' not found"
return rst'
Just _ -> return rst' { addMods = insert mdl (addMods rst') }
else do writeErrorMsg $ "Illegal module name (ignored): " ++ mdl
return rst'
insert m [] = [m]
insert m ms@(n:ns)
| m < n = m : ms
| m == n = ms
| otherwise = n : insert m ns
foldIO _ a [] = return a
foldIO f a (x:xs) = f a x >>= \fax -> foldIO f fax xs
processBrowse :: ReplState -> String -> IO (Maybe ReplState)
processBrowse rst args
| notNull $ stripCurrySuffix args = skipCommand "superfluous argument"
| otherwise = checkForWish $ do
writeVerboseInfo rst 1 "Starting Curry Browser in separate window..."
checkAndCallCpmTool "curry-browse" "currybrowse"
(\toolexec -> execCommandWithPath rst toolexec [currMod rst])
processCd :: ReplState -> String -> IO (Maybe ReplState)
processCd rst args = do
dirname <- getAbsolutePath args
exists <- doesDirectoryExist dirname
if exists then setCurrentDirectory dirname >> return (Just rst)
else skipCommand $ "directory does not exist"
processCompile :: ReplState -> String -> IO (Maybe ReplState)
processCompile rst args = do
let modname = stripCurrySuffix args
if null modname
then skipCommand "missing module name"
else compileCurryProgram rst modname
processEdit :: ReplState -> String -> IO (Maybe ReplState)
processEdit rst args = do
modname <- getModuleName rst args
mbf <- lookupModuleSource (loadPaths rst) modname
editenv <- getEnv "EDITOR"
let editcmd = rcValue (rcVars rst) "editcommand"
editprog = if null editcmd then editenv else editcmd
if null editenv && null editcmd
then skipCommand "no editor defined"
else maybe (skipCommand "source file not found")
(\ (_,fn) -> do system (editprog ++ " " ++ fn ++ "& ")
return (Just rst))
mbf
processEval :: ReplState -> String -> IO (Maybe ReplState)
processEval rst args = evalExpression rst args >>= return . Just
processFork :: ReplState -> String -> IO (Maybe ReplState)
processFork rst args
| currMod rst == preludeName rst
= skipCommand "no program loaded"
| otherwise
= do exst <- compileMainExpression rst (if null args then "main" else args)
False
if exst == 0
then do
pid <- getPID
let execname = "." </> "MAINFORK" ++ show pid
renameFile ("." </> mainExpMod rst) execname
writeVerboseInfo rst 3 $
"Starting executable '" ++ execname ++ "'..."
system $ "( " ++ execname ++ " && rm -f " ++ execname ++ ") " ++
"> /dev/null 2> /dev/null &"
return $ Just rst
else return Nothing
processHelp :: ReplState -> String -> IO (Maybe ReplState)
processHelp rst _ = do
printHelpOnCommands
putStrLn "... or type any <expression> to evaluate\n"
return (Just rst)
processInterface :: ReplState -> String -> IO (Maybe ReplState)
processInterface rst args = do
modname <- getModuleName rst args
checkAndCallCpmTool "curry-showflat" "showflatcurry"
(\toolexec -> execCommandWithPath rst toolexec ["-int", modname])
processLoad :: ReplState -> String -> IO (Maybe ReplState)
processLoad rst args = do
rst' <- terminateSourceProgGUIs rst
let dirmodname = stripCurrySuffix args
if null dirmodname
then skipCommand "missing module name"
else do
let (dirname, modname) = splitFileName dirmodname
mbrst <- if (dirname == "./") then return (Just rst')
else do putStrLn $ "Changing working directory to " ++ dirname
processCd rst' dirname
maybe (return Nothing)
(\rst2 ->
lookupModuleSource (loadPaths rst2) modname >>=
maybe (skipCommand $
"source file of module '" ++ dirmodname ++ "' not found")
(\_ -> loadCurryProgram rst2 { currMod = modname, addMods = [] }
modname)
)
mbrst
processReload :: ReplState -> String -> IO (Maybe ReplState)
processReload rst args
| currMod rst == preludeName rst
= skipCommand "no program loaded!"
| null (stripCurrySuffix args)
= loadCurryProgram rst (currMod rst)
| otherwise
= skipCommand "superfluous argument"
processModules :: ReplState -> String -> IO (Maybe ReplState)
processModules rst _ = printAllLoadedModules rst >> return (Just rst)
processPrograms :: ReplState -> String -> IO (Maybe ReplState)
processPrograms rst _ = printAllLoadPathPrograms rst >> return (Just rst)
processQuit :: ReplState -> String -> IO (Maybe ReplState)
processQuit rst _ = return (Just rst { quit = True })
processSave :: ReplState -> String -> IO (Maybe ReplState)
processSave rst args
| currMod rst == preludeName rst
= skipCommand "no program loaded"
| otherwise
= do exst <- compileMainExpression rst (if null args then "main" else args)
False
if exst == 0
then do renameFile ("." </> mainExpMod rst) (currMod rst)
writeVerboseInfo rst 1 $
"Executable saved in '" ++ currMod rst ++ "'"
return $ Just rst
else return Nothing
processShow :: ReplState -> String -> IO (Maybe ReplState)
processShow rst args = do
modname <- getModuleName rst args
mbf <- lookupModuleSource (loadPaths rst) modname
case mbf of
Nothing -> skipCommand "source file not found"
Just (_,fn) -> do
pager <- getEnv "PAGER"
let rcshowcmd = rcValue (rcVars rst) "showcommand"
showprog = if not (null rcshowcmd)
then rcshowcmd
else (if null pager then "cat" else pager)
system $ showprog ++ ' ' : fn
putStrLn ""
return (Just rst)
processSource :: ReplState -> String -> IO (Maybe ReplState)
processSource rst args
| null args = skipCommand "missing function name"
| null dotfun = do m <- getModuleOfFunction rst args
if null m
then skipCommand "function not found"
else showFunctionInModule rst m args
| otherwise = showFunctionInModule rst mod (tail dotfun)
where (mod, dotfun) = break (== '.') args
processType :: ReplState -> String -> IO (Maybe ReplState)
processType rst args = do
typeok <- printTypeOfExp rst args
return (if typeok then Just rst else Nothing)
processUsedImports :: ReplState -> String -> IO (Maybe ReplState)
processUsedImports rst args = do
let modname = if null args then currMod rst else stripCurrySuffix args
checkAndCallCpmTool "curry-usedimports" "importusage"
(\toolexec -> execCommandWithPath rst toolexec [modname])
printHelpOnCommands :: IO ()
printHelpOnCommands = putStrLn $ unlines $
[ "Basic commands (commands can be abbreviated to a prefix if unique):\n" ] ++
formatVarVals " - "
[ (":load <prog>", "load program '<prog>.[l]curry' as main module")
, (":reload" , "recompile currently loaded modules")
, (":add <m1> .. <mn>",
"add modules <m1>,...,<mn> to currently loaded modules")
, (":eval <expr>", "evaluate expression <expr>")
, (":save <expr>", "save executable with main expression <expr>")
, (":save" , "save executable with main expression 'main'")
, (":type <expr>", "show type of expression <expr>")
, (":quit" , "leave the system") ] ++
[ "\nFurther commands:\n" ] ++
formatVarVals " - "
[ (":!<command>" , "execute <command> in shell")
, (":browse" , "browse program and its imported modules")
, (":compile <m>" , "compile module <m> (but do not load it)")
, (":cd <dir>" , "change current directory to <dir>")
, (":edit" , "load source of currently loaded module into editor")
, (":edit <m>" , "load source of module <m> into editor")
, (":fork <expr>" , "fork new process evaluating <expr>")
, (":help" , "show this message")
, (":interface" , "show interface of currently loaded module")
, (":interface <m>", "show interface of module <m>")
, (":modules" ,
"show currently loaded modules with source information")
, (":programs" , "show names of Curry modules available in load path")
, (":set <option>" , "set an option")
, (":set" , "see help on options and current options")
, (":show" , "show currently loaded source program")
, (":show <m>" , "show source of module <m>")
, (":source <f>" , "show source of (visible!) function <f>")
, (":source <m>.<f> ", "show source of function <f> in module <m>")
, (":usedimports" , "show all used imported functions/constructors") ]
printAllLoadedModules :: ReplState -> IO ()
printAllLoadedModules rst = do
putStrLn "Currently loaded modules:"
let mods = currMod rst : addMods rst
mapM getSrc mods >>= putStr . unlines . map fmtSrc
where
getSrc m = lookupModuleSource (loadPaths rst) m >>=
return . maybe (m,"???") (\ (_,s) -> (m, s))
fmtSrc (m,s) = m ++ take (20 - length m) (repeat ' ') ++ " (from " ++ s ++ ")"
printAllLoadPathPrograms :: ReplState -> IO ()
printAllLoadPathPrograms rst = mapM_ printDirPrograms (loadPaths rst)
where
depthLimit = 10
printDirPrograms dir = do
putStrLn $ "Curry programs in directory '" ++ dir ++ "':"
progs <- getDirPrograms depthLimit "" dir
putStrLn $ unwords $ sort $ progs
putStrLn ""
getDirPrograms dlimit prefix dir = do
exdir <- doesDirectoryExist dir
files <- if exdir && dlimit > 0 then getDirectoryContents dir
else return []
subprogs <- mapM (\d -> getDirPrograms (dlimit - 1) (prefix ++ d ++ ".")
(dir </> d))
(filter (\f -> let c = head f in c>='A' && c<='Z') files)
return $ concat subprogs ++
concatMap (\f -> let (base, sfx) = splitExtension f
in if sfx `elem` [".curry", ".lcurry"] && notNull base
then [prefix ++ base]
else [])
files
processSetOption :: ReplState -> String -> IO (Maybe ReplState)
processSetOption rst option
| null (strip option)
= printOptions rst >> return (Just rst)
| otherwise
= case matched of
[] -> skipCommand $ "unknown option: '" ++ option ++ "'"
[(_,act)] -> act rst (strip args)
_ -> skipCommand $ "ambiguous option: ':" ++ option ++ "'"
where
(opt, args) = break (==' ') option
matched = filter (isPrefixOf (map toLower opt) . fst)
(replOptions rst)
replOptions :: ReplState
-> [(String, ReplState -> String -> IO (Maybe ReplState))]
replOptions rst =
[ ("v0" , \r _ -> return (Just r { verbose = 0 }))
, ("v1" , \r _ -> return (Just r { verbose = 1 }))
, ("v2" , \r _ -> return (Just r { verbose = 2 }))
, ("v3" , \r _ -> return (Just r { verbose = 3 }))
, ("v4" , \r _ -> return (Just r { verbose = 4 }))
, ("path" , setOptionPath )
, ("prompt" , setPrompt )
, ("safe" , \r _ -> return (Just r { safeExec = True }))
, ("parser" , \r a -> return (Just r { parseOpts = a }))
, ("timeout" , setTimeout )
, ("args" , \r a -> return (Just r { rtsArgs = a }))
, ("+bindings" , \r _ -> return (Just r { showBindings = True }))
, ("-bindings" , \r _ -> return (Just r { showBindings = False }))
, ("+echo" , \r _ -> return (Just r { withEcho = True }))
, ("-echo" , \r _ -> return (Just r { withEcho = False }))
, ("+show" , \r _ -> return (Just r { withShow = True }))
, ("-show" , \r _ -> return (Just r { withShow = False }))
, ("+time" , \r _ -> return (Just r { showTime = True }))
, ("-time" , \r _ -> return (Just r { showTime = False }))
] ++
concatMap setCmpOpt (ccOpts (compiler rst))
where
setCmpOpt (CCOption _ _ tags) = map (setOptTag tags) tags
setOptTag alltags (tag,co) =
(tag,
\r _ -> return (Just r { cmpOpts = (tag,co) :
filter (`notElem` alltags) (cmpOpts r) }))
setPrompt :: ReplState -> String -> IO (Maybe ReplState)
setPrompt rst p
| null rawPrompt = skipCommand "no prompt specified"
| otherwise = case head rawPrompt of
'"' -> case reads rawPrompt of
[(strPrompt, [])] -> return (Just rst { prompt = strPrompt })
_ -> skipCommand "could not parse prompt"
_ -> return (Just rst { prompt = rawPrompt })
where rawPrompt = strip p
setTimeout :: ReplState -> String -> IO (Maybe ReplState)
setTimeout rst rawopt
| null opts = skipCommand "no value for timeout given"
| otherwise = case reads opts of
[(n, [])] -> return (Just rst { timeOut = if n<0 then 0 else n })
_ -> skipCommand "illegal timeout parameter (no integer)"
where opts = strip rawopt
printOptions :: ReplState -> IO ()
printOptions rst = putStrLn $ unlines $ filter notNull
[ "Options for ':set' command:" ] ++
formatVarVals " - "
([ ("v<n>", "verbosity level\n" ++
"0: quiet (errors and warnings only)\n" ++
"1: show status messages (default)\n" ++
"2: show commands\n" ++
"3: show intermediate infos\n" ++
"4: show all details")
, ("path <paths>" , "set additional search paths for imported modules")
, ("prompt <prompt>", "set the user prompt")
, ("safe" , "safe execution mode without I/O actions")
, ("parser <opts>" , "additional options passed to parser (front end)")
, ("timeout <n>" ,
"timeout (in seconds) for main evaluation (0 = unlimited)")
, ("args <args>" , "run-time arguments passed to main program") ] ++
sort
([ ("+/-time" , "show compilation and execution time")
, ("+/-echo" , "turn on/off echoing of commands")
, ("+/-show" , "use 'Prelude.show' to show evaluation results")
, ("+/-bindings", "show bindings of free variables in initial goal")
] ++ showCompilerOptions (ccOpts (compiler rst)))) ++
[ showCurrentOptions rst ]
showCurrentOptions :: ReplState -> String
showCurrentOptions rst = intercalate "\n" $ filter notNull
[ "\nCurrent settings:" ] ++
formatVarVals ": "
[ ("import paths ", intercalate [searchPathSeparator] (loadPaths rst))
, ("parser options ", parseOpts rst)
, ("timeout ", show (timeOut rst))
, ("run-time arguments", rtsArgs rst)
, ("verbosity ", show (verbose rst))
, ("prompt ", show (prompt rst))
, ("...............and"
, unwordsOpts $ sortBy (\f1 f2 -> setFlag f1 <= setFlag f2) $
[ showOnOff (showBindings rst) ++ "bindings"
, showOnOff (withEcho rst) ++ "echo"
, showOnOff (withShow rst) ++ "show"
, showOnOff (showTime rst) ++ "time"
] ++ map fst (cmpOpts rst)) ] ++
(if verbose rst > 2
then [ "\nProperties from rc file:" ] ++
formatVarVals " = " (rcVars rst) ++
[ "\nREPL configuration:" ] ++
formatVarVals ": "
[ ("prelude name" , preludeName rst)
, ("main exp module" , mainExpMod rst)
, ("parser executable" , ccFrontend ccdesc)
, ("parser option" , ccParseOpt ccdesc "OPTS")
, ("compiler home dir" , ccHome ccdesc)
, ("compiler executable", ccExec ccdesc)
, ("verbosity option" , ccVerbOpt ccdesc "VERB")
, ("compile option" , ccCmplOpt ccdesc "MOD")
, ("executable option" , ccExecOpt ccdesc "MOD")
, ("clean command" , ccCleanCmd ccdesc "MOD") ]
else [])
where
ccdesc = compiler rst
unwordsOpts xs = let s = unwords xs
in if length s >= 60 then unlines (unwordsN 5 xs)
else s
unwordsN n xs = let (ns,ms) = splitAt n xs
in unwords ns : if null ms then [] else unwordsN n ms
setFlag [] = []
setFlag (c:cs) = if c `elem` "+-" then '~':cs else c:cs
showOnOff b = if b then "+" else "-"
formatVarVals :: String -> [(String,String)] -> [String]
formatVarVals sep vvs =
map (\ (var,val) -> var ++ blanks (maxvar - length var) ++ sep ++
intercalate ('\n' : blanks (maxvar + length sep)) (lines val))
vvs
where
blanks n = take n (repeat ' ')
maxvar = maximum (map (length . fst) vvs)
defaultImportPaths :: ReplState -> IO [String]
defaultImportPaths rst = do
currypath <- getEnv "CURRYPATH"
let rclibs = rcValue (rcVars rst) "libraries"
return $ filter (/= ".") $ splitSearchPath currypath ++ splitSearchPath rclibs
defaultImportPathsWith :: ReplState -> String -> IO [String]
defaultImportPathsWith rst dirs = do
defipath <- defaultImportPaths rst
adirs <- mapM getAbsolutePath (splitSearchPath dirs)
return (adirs ++ defipath)
setOptionPath :: ReplState -> String -> IO (Maybe ReplState)
setOptionPath rst args = do
ipath <- if null args then defaultImportPaths rst
else defaultImportPathsWith rst args
return (Just rst { importPaths = ipath })
compileMainExpression :: ReplState -> String -> Bool -> IO Int
compileMainExpression rst exp runrmexec = do
if safeExec rst
then do
unsafeused <- importUnsafeModule rst
if unsafeused
then do writeErrorMsg "Import of 'Unsafe' not allowed in safe mode!"
return 1
else compileProgExp
else compileProgExp
where
compileProgExp = do
ecg <- generateMainExpFile
if ecg /= 0
then return ecg
else do
when (verbose rst > 3) $ do
putStrLn "GENERATED MAIN MODULE:"
readFile (mainExpFile rst) >>= putStrLn
let mainexpmod = mainExpMod rst
compilecmd = curryCompilerCommand (reduceVerbose rst) ++ " " ++
(ccExecOpt (compiler rst)) mainexpmod
timecompilecmd <- getTimeCmd rst "Compilation" compilecmd
if ccCurryPath (compiler rst)
then execCommandWithPath rst timecompilecmd [] >> return ()
else do writeVerboseInfo rst 2 $ "Executing: " ++ timecompilecmd
system timecompilecmd >> return ()
cleanModule rst mainexpmod
if runrmexec
then do
timecmd <- getTimeCmd rst "Execution"
(unwords ["./" ++ mainexpmod, rtsArgs rst])
execcmd <- getTimeoutCmd rst timecmd
writeVerboseInfo rst 2 $ "Executing: " ++ execcmd
ecx <- system execcmd
unless (ecx == 0) $ writeVerboseInfo rst 1 $
"Execution terminated with exit status: " ++ show ecx
unlessKeepFiles rst $
removeFileIfExists mainexpmod
return ecx
else return 0
generateMainExpFile = do
unlessKeepFiles rst $ removeFileIfExists $ acyFileName rst (mainExpMod rst)
writeSimpleMainExpFile rst exp
getAcyOfMainExpMod rst >>=
maybe (return 1)
(\cprog -> insertFreeVarsInMainExp rst cprog exp >>=
maybe (return 1)
(\ (mprog,mexp) ->
makeMainExpMonomorphic rst mprog mexp >>=
maybe (return 1) (const (return 0))))
cleanModule :: ReplState -> String -> IO ()
cleanModule rst mainmod = unlessKeepFiles rst $ do
writeVerboseInfo rst 2 $ "Executing: " ++ cleancmd
system cleancmd
return ()
where
cleancmd = ccCleanCmd (compiler rst) mainmod
unlessKeepFiles :: ReplState -> IO () -> IO ()
unlessKeepFiles rst act = unless keepfiles act
where
keepfiles = rcValue (rcVars rst) "keepfiles" == "yes"
insertFreeVarsInMainExp :: ReplState -> CurryProg -> String
-> IO (Maybe (CurryProg, String))
insertFreeVarsInMainExp rst cprog@(CurryProg _ _ _ _ _ _ fdecls _) mainexp = do
let [mfunc@(CFunc _ _ _ (CQualType _ ty) _)] = fdecls
let freevars = freeVarsInFuncRule mfunc
(exp, whereclause) = breakWhereFreeClause mainexp
if (safeExec rst) && isIOType ty
then do writeErrorMsg "Operation not allowed in safe mode!"
return Nothing
else
if null freevars
|| not (showBindings rst)
|| isIOType ty
|| (not (withShow rst) && length freevars > 10)
|| null whereclause
then return $ Just (cprog,mainexp)
else do
let freevarexp = addFreeShow exp freevars whereclause
writeVerboseInfo rst 2 $
"Adding printing of bindings for free variables: " ++
intercalate "," freevars
writeVerboseInfo rst 3 $ "New expression: " ++ freevarexp
writeSimpleMainExpFile rst freevarexp
getAcyOfMainExpMod rst >>=
maybe (return Nothing)
(\p -> return $ Just (p,freevarexp))
where
addFreeShow exp freevars whereclause = unwords $
if withShow rst
then ["((\"{\""] ++
intersperse ("++ \", \" ")
(map (\v-> "++ \"" ++ v ++ " = \" ++ show " ++ v) freevars) ++
["++ \"} \") ++) $!! (show (", exp, "))"] ++ [whereclause]
else ["(", exp] ++
map (\v-> ", \"" ++ v ++ ":\", " ++ v) freevars ++
[")"] ++ [whereclause]
freeVarsInFuncRule f = case f of
CFunc _ _ _ _ (CRule _ rhs : _) -> freeVarsInRhs rhs
_ -> error "REPL.insertFreeVarsInMainGoal.freeVarsInFuncRule"
freeVarsInRhs rhs = case rhs of
CSimpleRhs _ ldecls -> concatMap lvarName ldecls
CGuardedRhs _ ldecls -> concatMap lvarName ldecls
lvarName ldecl = case ldecl of CLocalVars vs -> map snd vs
_ -> []
breakWhereFreeClause :: String -> (String,String)
breakWhereFreeClause exp =
let revexp = reverse exp
in if take 4 revexp == "eerf"
then let woWhere = findWhere (drop 4 revexp)
in if null woWhere
then (exp,"")
else (reverse woWhere, drop (length woWhere) exp)
else (exp,"")
where
findWhere [] = []
findWhere (c:cs) | isSpace c && take 6 cs == "erehw " = drop 6 cs
| otherwise = findWhere cs
makeMainExpMonomorphic :: ReplState -> CurryProg -> String
-> IO (Maybe (CurryProg, String))
makeMainExpMonomorphic rst prog exp = case prog of
CurryProg _ _ _ _ _ _ [CFunc _ _ _ qty _] _ -> makeMonoType qty
_ -> error "REPL.makeMainExpMonomorphic"
where
makeMonoType qty@(CQualType _ ty)
| isFunctionalType ty
= do writeErrorMsg "expression is of functional type"
return Nothing
| isPolyType ty
= case defaultQualTypeExpr qty of
CQualType (CContext []) defTy -> do
when (defTy /= ty) $ writeVerboseInfo rst 2 $
"Defaulted type of main expression: " ++
showMonoTypeExpr False defTy
let (nwexp, whereclause) = breakWhereFreeClause exp
(nwexpS, defTyS) = if null whereclause || not (showBindings rst)
then addShow nwexp defTy
else (nwexp, defTy)
mtype = showMonoTypeExpr True defTyS
mexp = "(" ++ nwexpS ++ " :: " ++ mtype ++ ") " ++ whereclause
writeMainExpFile rst (modsOfType defTy) (Just mtype) mexp
when (isPolyType defTy) $ writeVerboseInfo rst 2 $
"Type of main expression \"" ++ showMonoTypeExpr False defTy
++ "\" made monomorphic by replacing type variables by \"()\""
getAcyOfMainExpMod rst >>=
maybe (return Nothing)
(\p -> return $ Just (p,mexp))
_ -> do writeErrorMsg $
"cannot handle overloaded top-level expression of type: " ++
showMonoQualTypeExpr False qty
return Nothing
| otherwise
= if newexp == exp
then return $ Just (prog,exp)
else do writeSimpleMainExpFile rst newexp
getAcyOfMainExpMod rst >>=
maybe (return Nothing)
(\p -> return $ Just (p,newexp))
where
newexp = let (nwexp, whereclause) = breakWhereFreeClause exp
in if null whereclause || not (showBindings rst)
then fst (addShow nwexp ty) ++ whereclause
else nwexp ++ whereclause
addShow e te = if isIOReturnType te && withShow rst
then ('(' : e ++ ") Prelude.>>= Prelude.print",
ioType unitType)
else if isIOType te || not (withShow rst)
then (e,te)
else ("Prelude.show (" ++ e ++ ")", stringType)
defaultQualTypeExpr :: CQualTypeExpr -> CQualTypeExpr
defaultQualTypeExpr (CQualType (CContext ctxt) cty) =
defaultMonad $ defaultData $ defaultTExp ctxt (CQualType (CContext []) cty)
where
defaultData qty@(CQualType (CContext dctxt) dcty) = case dctxt of
[] -> qty
(qtcons, CTVar tv) : cs | qtcons == ("Prelude","Data")
-> defaultData (CQualType (CContext cs)
(substTypeVar tv (CTCons ("Prelude","Bool")) dcty))
_ -> qty
defaultMonad qty@(CQualType (CContext dctxt) dcty) = case dctxt of
[] -> qty
(qtcons, CTVar tv) : cs | qtcons == ("Prelude","Monad")
-> defaultMonad (CQualType (CContext cs)
(substTypeVar tv (CTCons ("Prelude","IO")) dcty))
_ -> qty
defaultTExp :: [CConstraint] -> CQualTypeExpr -> CQualTypeExpr
defaultTExp [] qty = qty
defaultTExp (c:cs) (CQualType (CContext cs2) ty) = case c of
(("Prelude", ptype), CTVar tv) ->
if ptype `elem` ["Num", "Integral", "Fractional"]
then let defptype = if ptype == "Fractional" then "Float" else "Int"
in defaultTExp
(removeConstraints tv defptype cs)
(CQualType (CContext (removeConstraints tv defptype cs2))
(substTypeVar tv (CTCons ("Prelude", defptype)) ty))
else defaultTExp cs (CQualType (CContext (cs2 ++ [c])) ty)
_ -> defaultTExp cs (CQualType (CContext (cs2 ++ [c])) ty)
removeConstraints _ _ [] = []
removeConstraints tv dflttype (c3:cs3) = case c3 of
(("Prelude", cls), CTVar tv2)
| tv == tv2 && cls `elem` ["Data", "Eq", "Ord", "Read", "Show"]
-> removeConstraints tv dflttype cs3
| tv == tv2 && dflttype == "Int" && cls == "Enum"
-> removeConstraints tv dflttype cs3
_ -> c3 : removeConstraints tv dflttype cs3
substTypeVar :: CTVarIName -> CTypeExpr -> CTypeExpr -> CTypeExpr
substTypeVar tv def te@(CTVar tv2) = if tv == tv2 then def else te
substTypeVar _ _ te@(CTCons _) = te
substTypeVar tv def (CFuncType te1 te2) =
CFuncType (substTypeVar tv def te1) (substTypeVar tv def te2)
substTypeVar tv def (CTApply te1 te2) =
CTApply (substTypeVar tv def te1) (substTypeVar tv def te2)
parseCurryProgram :: ReplState -> String -> Bool -> IO (Maybe ReplState)
parseCurryProgram rst curryprog tfcy = do
let frontendparams = currentFrontendParams rst (verbose rst == 0)
target = if tfcy then TFCY else FCY
catch (verbCallFrontendWithParams rst target frontendparams curryprog
>> return (Just rst))
(\_ -> return Nothing)
loadCurryProgram :: ReplState -> String -> IO (Maybe ReplState)
loadCurryProgram rst curryprog =
maybe (compileCurryProgram rst curryprog)
(parseCurryProgram rst curryprog)
(ccTypedFC (compiler rst))
compileCurryProgram :: ReplState -> String -> IO (Maybe ReplState)
compileCurryProgram rst curryprog = do
let compilecmd = curryCompilerCommand rst ++ " " ++
(ccCmplOpt (compiler rst)) curryprog
timecompilecmd <- getTimeCmd rst "Compilation" compilecmd
if ccCurryPath (compiler rst)
then execCommandWithPath rst timecompilecmd []
else do writeVerboseInfo rst 2 $ "Executing: " ++ timecompilecmd
es <- system timecompilecmd
return $ if es == 0 then Just rst else Nothing
curryCompilerCommand :: ReplState -> String
curryCompilerCommand rst = unwords [ccExec (compiler rst), cmpopts]
where
cmpopts = unwords $
[
(ccVerbOpt (compiler rst)) (show (verbose rst))
] ++
(if ccCurryPath (compiler rst)
then []
else map ("-i" ++) (loadPaths rst)) ++
filter notNull (map snd (cmpOpts rst)) ++
(if null (parseOpts rst)
then []
else [(ccParseOpt (compiler rst)) (parseOpts rst)])
getModuleName :: ReplState -> String -> IO String
getModuleName rst args =
if null args
then return (currMod rst)
else let (dirname, mname) = splitFileName (stripCurrySuffix args)
in if dirname == "./"
then return mname
else getAbsolutePath (stripCurrySuffix args)
reduceVerbose :: ReplState -> ReplState
reduceVerbose rst = rst { verbose = redVerb (verbose rst) }
where
redVerb n | n == 0 = 0
| otherwise = n - 1
showFunctionInModule :: ReplState -> String -> String -> IO (Maybe ReplState)
showFunctionInModule rst mod fun =
checkForWish $
checkAndCallCpmTool "curry-showsource" "sourceproggui" $ \spgui -> do
writeVerboseInfo rst 1 $
"Showing source code of function '" ++ mod ++ "." ++ fun ++
"' in separate window..."
let spguicmd = "CURRYPATH=" ++
intercalate [searchPathSeparator] (loadPaths rst) ++
" && export CURRYPATH && " ++ spgui ++ " " ++ mod
writeVerboseInfo rst 2 $ "Executing: " ++ spguicmd
(rst',h') <- maybe (do h <- connectToCommand spguicmd
return (rst {sourceguis = (mod,(fun,h))
: sourceguis rst }, h))
(\ (f,h) -> do
hPutStrLn h ('-':f)
hFlush h
return (rst {sourceguis = updateFun (sourceguis rst)
mod fun }, h))
(lookup mod (sourceguis rst))
hPutStrLn h' ('+':fun)
hFlush h'
return (Just rst')
where
updateFun [] _ _ = []
updateFun ((m,(f,h)):sguis) md fn =
if m==md then (m,(fn,h)):sguis
else (m,(f,h)) : updateFun sguis md fn
checkAndCallCpmTool :: String -> String -> (String -> IO (Maybe ReplState))
-> IO (Maybe ReplState)
checkAndCallCpmTool tool package continue = do
excmd <- system $ "which " ++ tool ++ " > /dev/null"
if excmd == 0
then continue tool
else do homedir <- getHomeDirectory
let cpmtoolfile = homedir </> ".cpm" </> "bin" </> tool
excpm <- doesFileExist cpmtoolfile
if excpm
then continue cpmtoolfile
else skipCommand errmsg
where
errmsg = "'" ++ tool ++ "' not found. Install it by: 'cypm install " ++
package ++ "'!"
execCommandWithPath :: ReplState -> String -> [String]
-> IO (Maybe ReplState)
execCommandWithPath rst cmd args = do
let setpath = "CURRYPATH=" ++
intercalate [searchPathSeparator] (loadPaths rst) ++
" && export CURRYPATH && "
syscmd = setpath ++ cmd ++ ' ' : unwords args
writeVerboseInfo rst 2 $ "Executing: " ++ syscmd
system syscmd >> return (Just rst)
checkForCommand :: String -> String -> IO (Maybe ReplState)
-> IO (Maybe ReplState)
checkForCommand cmd errmsg continue = do
excmd <- system $ "which " ++ cmd ++ " > /dev/null"
if (excmd>0) then skipCommand errmsg
else continue
checkForWish :: IO (Maybe ReplState) -> IO (Maybe ReplState)
checkForWish =
checkForCommand "wish"
"Windowing shell `wish' not found. Please install package `tk'!"
terminateSourceProgGUIs :: ReplState -> IO ReplState
terminateSourceProgGUIs rst
| null sguis = return rst
| otherwise = do
writeVerboseInfo rst 1 "Terminating source program GUIs..."
catch (mapM_ (\ (_,(_,h)) -> hPutStrLn h "q" >> hFlush h >> hClose h)
sguis)
(\_ -> return ())
return rst { sourceguis = [] }
where sguis = sourceguis rst
|