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
|
module CPM.Query.Main
( main, askCurryInfoServer, askCurryInfoCmd)
where
import Control.Monad ( unless, when, replicateM, replicateM_ )
import Curry.Compiler.Distribution ( baseVersion )
import Data.Char ( isDigit )
import Data.List ( init, last, split )
import System.Environment ( getArgs, getEnv, setEnv )
import System.IO ( hFlush, stderr, hClose, hGetLine, hPutStrLn )
import FlatCurry.Types ( QName )
import Network.Socket ( connectToSocket, close )
import System.CurryPath ( lookupModuleSourceInLoadPath, setCurryPath
, sysLibPath )
import System.Directory ( doesFileExist, getCurrentDirectory
, getModificationTime )
import System.FilePath ( (</>), joinPath, splitDirectories )
import System.IOExts ( evalCmd, execCmd, readCompleteFile )
import System.Path ( fileInPath )
import System.Process ( exitWith, system )
import CPM.Query.Options
banner :: String
banner = unlines [bannerLine, bannerText, bannerLine]
where
bannerText = "CPM Query Tool (Version of 17/12/24)"
bannerLine = take (length bannerText) (repeat '=')
main :: IO ()
main = do
checkExecutable
(opts,args) <- getArgs >>= processOptions banner
when (optEntity opts == Unknown) $ do
printWhenStatus opts $
"No information for entity of kind '" ++ optCLS opts ++ "'"
exitWith 0
case args of
[pkg,vsn,mn] | optGenerate opts -> generateForModule opts pkg vsn mn
[mn,fn] -> if optGenerate opts then generateForPackage opts mn fn
else startQueryTool opts mn fn
_ -> do putStrLn $ "Illegal arguments: " ++ unwords args ++ "\n\n" ++
usageText
exitWith 1
where
checkExecutable = do
hascurryinfo <- fileInPath "curry-info"
unless hascurryinfo $ do
putStrLn $ "Binary 'curry-info' not found in PATH!\n" ++
"Install it by the the following commands:\n\n" ++
"> git clone https://github.com/curry-language/curry-info-system.git\n" ++
"> cd curry-info-system\n" ++
"> cypm install\n"
exitWith 1
generateForPackage:: Options -> String -> String -> IO ()
generateForPackage opts pkg vsn = do
printWhenStatus opts $
"Generating infos for package '" ++ pkg ++ "-" ++ vsn ++ "' for " ++
show (optEntity opts) ++ " entities..."
when (optEntity opts == Unknown) $ exitWith 0
mods <- getPackageInfos opts pkg vsn ["modules"]
mapM_ (generateForModule opts pkg vsn) mods
generateForModule :: Options -> String -> String -> String -> IO ()
generateForModule opts pkg vsn mn = do
genInfo ""
let cicmd = [ curryInfoVerb opts, "-f2", "-p", pkg, "-x"
, escapeShellString vsn, "-m", mn]
let tcreq = "--allclasses" : defaultRequest ( opts {optEntity = Class })
genInfo (unwords tcreq)
runCommand opts $ unwords $ cicmd ++ tcreq
let treq = "--alltypes": defaultRequest ( opts { optEntity = Type } )
genInfo (unwords treq)
runCommand opts $ unwords $ cicmd ++ treq
ops <- getPackageInfos opts pkg vsn ["-m", mn, "operations"]
unless (null ops) $ do
mapM_ (\r -> do genInfo ("alloperations " ++ r)
runCommand opts $ unwords $ cicmd ++ ["--alloperations", r])
["signature", "definition"]
let opreqs = defaultRequest (opts { optEntity = Operation })
mapM_ (\r -> do genInfo ("alloperations " ++ r)
runCommand opts $ unwords $
cicmd ++ ["-o", escapeShellString (head ops), r])
(opreqs)
where
genInfo req = printWhenStatus opts $
"Generating infos for module '" ++ mn ++
(if null req then "" else "' and request '" ++ req) ++ "'..."
getPackageInfos :: Read a => Options -> String -> String -> [String] -> IO a
getPackageInfos opts pkg vsn requests = do
printWhenStatus opts $ "Generating infos for package '" ++ pkg ++ "-" ++ vsn
++ "' for requests: " ++ unwords requests
let cmdopts = ["-v0", "--format=CurryTerm", "-p", pkg, "-x", vsn] ++ requests
printWhenAll opts $ unwords $ ["Executing:", curryInfoBin] ++ cmdopts
(ec,sout,serr) <- evalCmd curryInfoBin cmdopts ""
printWhenAll opts $ "Exit code: " ++ show ec ++ "\nSTDOUT:\n" ++ sout ++
"\nSTDERR:\n" ++ serr
when (ec > 0) $ putStrLn "ERROR OCCURRED" >> exitWith 1
resterm <- case reads sout of
[(ms,_)] -> return (ms :: [(String,String)])
_ -> putStrLn ("Parse error for: " ++ sout) >> exitWith 1
let infos = snd (head resterm)
infolist <- case reads infos of
[(ms,_)] -> return (ms :: [(String,String)])
_ -> putStrLn ("Parse error for: " ++ infos) >> exitWith 1
let infostring = snd (head infolist)
case reads infostring of
[(ms,_)] -> return ms
_ -> putStrLn ("Parse error for: " ++ infostring) >> exitWith 1
curryInfoBin :: String
curryInfoBin = "curry-info"
curryInfoVerb :: Options -> String
curryInfoVerb opts = unwords [curryInfoBin, "-v" ++ show (optVerb opts)]
runCommand :: Options -> String -> IO ()
runCommand opts cmd = do
when (optVerb opts > 2 || optDryRun opts) $ putStrLn $ "Executing: " ++ cmd
unless (optDryRun opts) $ system cmd >> return ()
startQueryTool :: Options -> String -> String -> IO ()
startQueryTool opts mname ename = do
setCurryPathIfNecessary
mbsrc <- lookupModuleSourceInLoadPath mname
case mbsrc of
Nothing -> error $ "Module '" ++ mname ++ "' not found!"
Just (dirname,filename) -> do
getPackageId dirname >>= maybe
(printWhenStatus opts $
"Module '" ++ mname ++ "' " ++
(if optVerb opts > 1
then "stored in file\n " ++ filename ++
"\nbut this does not belong to the sources of a "
else "does not belong to a ") ++
"registered CPM package!")
(\(pname,vers) -> do
let edescr = if optVerb opts > 1
then unlines [ "Package name : " ++ pname
, "Package version: " ++ vers
, "Module name : " ++ mname
, "Entity name : " ++ ename ]
else show (optEntity opts) ++ " " ++
mname ++ "." ++ ename ++
" (package " ++ pname ++ "-" ++ vers ++ ")"
putStrLn edescr
let request = if null (optRequest opts) then defaultRequest opts
else optRequest opts
icmd = unwords $
[ curryInfoVerb opts ] ++
[ "--format=" ++ optOutFormat opts ] ++
(if optForce opts then ["-f1"] else ["-f0"]) ++
[ "-p", pname, "-x", escapeShellString vers
, "-m", mname] ++ entityParam ++ request
runCommand opts icmd
)
where
entityParam = case optEntity opts of
Operation -> [ "-o", escapeShellString ename ]
Type -> [ "-t", escapeShellString ename ]
Class -> [ "-c", escapeShellString ename ]
Unknown -> []
escapeShellString :: String -> String
escapeShellString s = '\'' : concatMap escapeSingleQuote s ++ "'"
where
escapeSingleQuote c | c == '\'' = "'\\''"
| otherwise = [c]
defaultRequest :: Options -> [String]
defaultRequest opts = case optEntity opts of
Operation -> [ "cass-deterministic", "cass-total"
, "cass-terminating", "cass-demand", "failfree" ]
Type -> [ "definition" ]
Class -> [ "definition" ]
Unknown -> []
getPackageIdOfModule :: String -> IO (Maybe (String,String))
getPackageIdOfModule mname = do
mbsrc <- lookupModuleSourceInLoadPath mname
case mbsrc of
Nothing -> error $ "Module '" ++ mname ++ "' not found in load path!"
Just (dirname,_) -> getPackageId dirname
getPackageId :: String -> IO (Maybe (String,String))
getPackageId path =
if sysLibPath == [path]
then return (Just ("base",baseVersion))
else getPackageSpecPath (splitDirectories path) >>=
maybe (return Nothing)
(\dirnames -> return (splitPkgId "" (last dirnames)))
where
splitPkgId oldpn s =
let (pname,hvers) = break (=='-') s
newpn = if null oldpn then pname else oldpn ++ "-" ++ pname
in if null hvers
then Nothing
else let vers = tail hvers
in if isVersionId vers then Just (newpn,vers)
else splitPkgId newpn vers
isVersionId vs = case split (=='.') vs of
(maj:min:patch:_) -> all (all isDigit) [maj, min, take 1 patch]
_ -> False
getPackageSpecPath :: [String] -> IO (Maybe [String])
getPackageSpecPath [] = return Nothing
getPackageSpecPath dirnames@(_:_) = do
expkg <- doesFileExist (joinPath (dirnames ++ [packageSpecFile]))
if expkg
then return (Just dirnames)
else getPackageSpecPath (init dirnames)
setCurryPathIfNecessary :: IO ()
setCurryPathIfNecessary = do
cp <- getEnv "CURRYPATH"
when (null cp) $ do
cdir <- getCurrentDirectory
getPackageSpecPath (splitDirectories cdir) >>=
maybe setCurryPathByCPM (loadCurryPathFromCache . joinPath)
where
loadCurryPathFromCache specdir = do
let cachefile = specdir </> ".cpm" </> "CURRYPATH_CACHE"
excache <- doesFileExist cachefile
if excache
then do
cftime <- getModificationTime cachefile
pftime <- getModificationTime (specdir </> packageSpecFile)
if cftime > pftime
then do cnt <- readCompleteFile cachefile
let cpath = head (lines cnt)
setEnv "CURRYPATH" cpath
else setCurryPathByCPM
else setCurryPathByCPM
setCurryPathByCPM = setCurryPath True ""
packageSpecFile :: String
packageSpecFile = "package.json"
askCurryInfoServer :: String -> CurryEntity -> String
-> IO (Maybe [(QName, String)])
askCurryInfoServer modname entkind req
| entkind == Unknown = return Nothing
| otherwise = do
mres <- getPackageIdOfModule modname
case mres of
Nothing -> return Nothing
Just (pkg, vsn) -> do
(srvin, srvout, srverr) <- execCmd "curry-info --quiet -f0 --server &"
port <- fmap readPort (hGetLine srvout)
hPutStrLn stderr $ "Connecting to port " ++ port
handle <- connectToSocket "localhost" (read port)
let srvcmd = case entkind of
Type -> "RequestAllTypesInformation"
Class -> "RequestAllClassesInformation"
_ -> "RequestAllOperationsInformation"
let msg = srvcmd ++ " curryterm 0 " ++ pkg ++ " " ++ vsn ++ " " ++
modname ++ " " ++ req
hPutStrLn handle msg
hFlush handle
resultMsg <- hGetLine handle
result <- case words resultMsg of
["ok", numberOfLines] -> do
ls <- replicateM (read numberOfLines) (hGetLine handle)
let results = read (unlines ls) :: [(String, String)]
fmap Just (mapM readResult results)
("error":errmsg) -> do
hPutStrLn stderr $ "Error message: " ++ unwords errmsg
return Nothing
_ -> do hPutStrLn stderr $ "Unexpected message: " ++ resultMsg
return Nothing
hPutStrLn handle "StopServer"
hFlush handle
hClose srvin
hClose srvout
hClose srverr
return result
where
readPort s = words s !! 2
readResult :: (String, String) -> IO (QName, String)
readResult (obj, res) = do
let (m, o) = read obj :: (String, String)
[(_, result)] = read res :: [(String, String)]
return ((m, o), result)
askCurryInfoCmd :: String -> CurryEntity -> String
-> IO (Maybe [(QName, String)])
askCurryInfoCmd modname entkind req
| entkind == Unknown = return Nothing
| otherwise = do
mres <- getPackageIdOfModule modname
case mres of
Nothing -> return Nothing
Just (pkg, vsn) -> do
let alloption = case entkind of Type -> "--alltypes"
Class -> "--allclasses"
_ -> "--alloperations"
cmdopts = [ "--quiet", "-f0", "-p", pkg, "-x", vsn, "-m", modname
, alloption, "--format=CurryTerm", req]
(ec, out, err) <- evalCmd "curry-info" cmdopts ""
if ec > 0
then do putStrLn "Execution error. Output:"
unless (null out) $ putStrLn out
unless (null err) $ putStrLn err
return Nothing
else do let results = read out :: [(String, String)]
fmap Just (mapM readResult results)
where
readResult :: (String, String) -> IO (QName, String)
readResult (obj, res) = do
let (m, o) = read obj :: (String, String)
[(_, result)] = read res :: [(String, String)]
return ((m, o), result)
|