0 | module System
  1 |
  2 | import public Data.So
  3 | import Data.String
  4 |
  5 | import public System.Escape
  6 | import System.File
  7 |
  8 | %default total
  9 |
 10 | ||| Shorthand for referring to the C support library
 11 | |||
 12 | ||| @ fn the function name to refer to in the C support library
 13 | supportC : (fn : String) -> String
 14 | supportC fn = "C:\{fn}, libidris2_support, idris_support.h"
 15 |
 16 | ||| Shorthand for referring to the Node system support library
 17 | |||
 18 | ||| @ fn the function name to refer to in the js/system_support.js file
 19 | supportNode : (fn : String) -> String
 20 | supportNode fn = "node:support:\{fn},support_system"
 21 |
 22 | ||| Shorthand for referring to libc 6
 23 | |||
 24 | ||| @ fn the function name to refer to in libc 6
 25 | libc : (fn : String) -> String
 26 | libc fn = "C:" ++ fn ++ ", libc 6"
 27 |
 28 | -- `sleep` and `usleep` need to be tied to `blodwen-[u]sleep` for threading
 29 | -- reasons: on Racket a blocking C call stops all threads (see
 30 | -- support/racket/support.rkt), and on Chez it stops every other thread at its
 31 | -- next garbage collection (see support/chez/support.ss).
 32 |
 33 | %foreign "scheme,racket:blodwen-sleep"
 34 |          "scheme,chez:blodwen-sleep"
 35 |          supportC "idris2_sleep"
 36 | prim__sleep : Int -> PrimIO ()
 37 |
 38 | %foreign "scheme,racket:blodwen-usleep"
 39 |          "scheme,chez:blodwen-usleep"
 40 |          supportC "idris2_usleep"
 41 | prim__usleep : Int -> PrimIO ()
 42 |
 43 | ||| Sleep for the specified number of seconds or, if signals are supported,
 44 | ||| until an un-ignored signal arrives.
 45 | ||| The exact wall-clock time slept might slightly differ depending on how busy
 46 | ||| the system is and the resolution of the system's clock.
 47 | |||
 48 | ||| @ sec the number of seconds to sleep for
 49 | export
 50 | sleep : HasIO io => (sec : Int) -> io ()
 51 | sleep sec = primIO (prim__sleep sec)
 52 |
 53 | ||| Sleep for the specified number of microseconds or, if signals are supported,
 54 | ||| until an un-ignored signal arrives.
 55 | ||| The exact wall-clock time slept might slighly differ depending on how busy
 56 | ||| the system is and the resolution of the system's clock.
 57 | |||
 58 | ||| @ usec the number of microseconds to sleep for
 59 | export
 60 | usleep : HasIO io => (usec : Int) -> So (usec >= 0) => io ()
 61 | usleep usec = primIO (prim__usleep usec)
 62 |
 63 | -- Get the number of arguments
 64 | -- Note: node prefixes the list of command line arguments
 65 | --       with the path to the `node` executable. This is
 66 | --       inconsistent with other backends, which only list
 67 | --       the path to the running program. For reasons of
 68 | --       consistency across backends, this first argument ist
 69 | --       dropped on the node backend.
 70 | %foreign "scheme:blodwen-arg-count"
 71 |          supportC "idris2_getArgCount"
 72 |          "node:lambda:() => process.argv.length - 1"
 73 | prim__getArgCount : PrimIO Int
 74 |
 75 | -- Get argument number `n`. See also `prim__getArgCount`
 76 | -- about the special treatment of the node backend.
 77 | %foreign "scheme:blodwen-arg"
 78 |          supportC "idris2_getArg"
 79 |          "node:lambda:n => process.argv[n + 1]"
 80 | prim__getArg : Int -> PrimIO String
 81 |
 82 | ||| Retrieve the arguments to the program call, if there were any.
 83 | export
 84 | getArgs : HasIO io => io (List String)
 85 | getArgs = do
 86 |             n <- primIO prim__getArgCount
 87 |             if n > 0
 88 |               then for [0..n-1] $ primIO . prim__getArg
 89 |               else pure []
 90 |
 91 | %foreign libc "getenv"
 92 |          "node:lambda: n => process.env[n]"
 93 | prim__getEnv : String -> PrimIO (Ptr String)
 94 |
 95 | %foreign supportC "idris2_getEnvPair"
 96 | prim__getEnvPair : Int -> PrimIO (Ptr String)
 97 | %foreign supportC "idris2_setenv"
 98 |          supportNode "setEnv"
 99 | prim__setEnv : String -> String -> Int -> PrimIO Int
100 | %foreign supportC "idris2_unsetenv"
101 |          supportNode "unsetEnv"
102 | prim__unsetEnv : String -> PrimIO Int
103 |
104 | %foreign "C:idris2_enableRawMode, libidris2_support, idris_support.h"
105 | prim__enableRawMode : (1 x : %World) -> IORes Int
106 |
107 | %foreign "C:idris2_resetRawMode, libidris2_support, idris_support.h"
108 | prim__resetRawMode : (1 x : %World) -> IORes ()
109 |
110 | ||| `enableRawMode` enables raw mode for stdin, allowing characters
111 | ||| to be read one at a time, without buffering or echoing.
112 | ||| If `enableRawMode` is used, the program should call `resetRawMode` before
113 | ||| exiting. Consider using `withRawMode` instead to ensure the tty is reset.
114 | |||
115 | ||| This is not supported on windows.
116 | export
117 | enableRawMode : HasIO io => io (Either FileError ())
118 | enableRawMode =
119 |   case !(primIO prim__enableRawMode) of
120 |     0 => pure $ Right ()
121 |     _ => returnError
122 |
123 | ||| `resetRawMode` resets stdin raw mode to original state if
124 | ||| `enableRawMode` had been previously called.
125 | export
126 | resetRawMode : HasIO io => io ()
127 | resetRawMode = primIO prim__resetRawMode
128 |
129 | ||| `withRawMode` performs a given operation after setting stdin to raw mode
130 | ||| and ensure that stdin is reset to its original state afterwards.
131 | |||
132 | ||| This is not supported on windows.
133 | export
134 | withRawMode : HasIO io =>
135 |               (onError   : FileError -> io a) ->
136 |               (onSuccess : () -> io a) ->
137 |               io a
138 | withRawMode onError onSuccess = do
139 |   Right () <- enableRawMode
140 |     | Left err => onError err
141 |   result <- onSuccess ()
142 |   resetRawMode
143 |   pure result
144 |
145 | ||| Retrieve the specified environment variable's value string, or `Nothing` if
146 | ||| there is no such environment variable.
147 | |||
148 | ||| @ var the name of the environment variable to look up
149 | export
150 | getEnv : HasIO io => (var : String) -> io (Maybe String)
151 | getEnv var
152 |    = do env <- primIO $ prim__getEnv var
153 |         if prim__nullPtr env /= 0
154 |            then pure Nothing
155 |            else pure (Just (prim__getString env))
156 |
157 | ||| Retrieve all the key-value pairs of the environment variables, and return a
158 | ||| list containing them.
159 | export
160 | covering
161 | getEnvironment : HasIO io => io (List (String, String))
162 | getEnvironment = getAllPairs 0 []
163 |   where
164 |     splitEq : String -> (String, String)
165 |     splitEq str
166 |         = let (k, v)  = break (== '=') str
167 |               (_, v') = break (/= '=') v in
168 |               (k, v')
169 |
170 |     getAllPairs : Int -> List String -> io (List (String, String))
171 |     getAllPairs n acc = do
172 |       envPair <- primIO $ prim__getEnvPair n
173 |       if prim__nullPtr envPair /= 0
174 |          then pure $ reverse $ map splitEq acc
175 |          else getAllPairs (n + 1) (prim__getString envPair :: acc)
176 |
177 | ||| Add the specified variable with the given value string to the environment,
178 | ||| optionally overwriting any existing environment variable with the same name.
179 | ||| Returns True whether the value is set, overwritten, or not overwritten because
180 | ||| overwrite was False. Returns False if a system error occurred. You can `getErrno`
181 | ||| to check the error.
182 | |||
183 | ||| @ var       the name of the environment variable to set
184 | ||| @ val       the value string to set the environment variable to
185 | ||| @ overwrite whether to overwrite the existing value if an environment
186 | |||             variable with the specified name already exists
187 | export
188 | setEnv : HasIO io => (var : String) -> (val : String) -> (overwrite : Bool) ->
189 |                      io Bool
190 | setEnv var val overwrite
191 |    = do ok <- primIO $ prim__setEnv var val (if overwrite then 1 else 0)
192 |         pure $ ok == 0
193 |
194 | ||| Delete the specified environment variable. Returns `True` either if the
195 | ||| value was deleted or if the value was not defined/didn't exist. Returns
196 | ||| `False` if a system error occurred. You can `getErrno` to check the error.
197 | export
198 | unsetEnv : HasIO io => (var : String) -> io Bool
199 | unsetEnv var
200 |    = do ok <- primIO $ prim__unsetEnv var
201 |         pure $ ok == 0
202 |
203 | -- On Chez, `blodwen-system` lets other threads keep running while the command
204 | -- runs (see `sleep` above).
205 | %foreign "scheme,chez:blodwen-system"
206 |          "C:idris2_system, libidris2_support, idris_system.h"
207 |          supportNode "spawnSync"
208 | prim__system : String -> PrimIO Int
209 |
210 | ||| Execute a shell command, returning its termination status or -1 if an error
211 | ||| occurred.
212 | export
213 | system : HasIO io => String -> io Int
214 | system cmd = primIO (prim__system cmd)
215 |
216 | namespace Escaped
217 |   export
218 |   system : HasIO io => List String -> io Int
219 |   system = system . escapeCmd
220 |
221 | ||| Run a shell command, returning its stdout, and exit code.
222 | export
223 | covering
224 | run : HasIO io => (cmd : String) -> io (String, Int)
225 | run cmd = do
226 |     Right f <- popen cmd Read
227 |         | Left err => pure ("", 1)
228 |     Right resp <- fRead f
229 |         | Left err => pure ("", 1)
230 |     exitCode <- pclose f
231 |     pure (resp, exitCode)
232 |
233 | namespace Escaped
234 |   export
235 |   covering
236 |   run : HasIO io => (cmd : List String) -> io (String, Int)
237 |   run = run . escapeCmd
238 |
239 | ||| Run a shell command, allowing processing its stdout line by line.
240 | |||
241 | ||| Notice that is the line of the command ends with a newline character,
242 | ||| it will be present in the string passed to the processing function.
243 | |||
244 | ||| This function returns an exit code which value should be consistent with the `run` function.
245 | export
246 | covering
247 | runProcessingOutput : HasIO io => (String -> io ()) -> (cmd : String) -> io Int
248 | runProcessingOutput pr cmd = do
249 |   Right f <- popen cmd Read
250 |     | Left err => pure 1
251 |   True <- process f
252 |     | False => pure 1 -- we do not close `f` in case of reading error, like `run` does
253 |   pclose f
254 |
255 |   where
256 |     process : File -> io Bool
257 |     process h = if !(fEOF h) then pure True else do
258 |       Right line <- fGetLine h
259 |         | Left err => pure False
260 |       pr line
261 |       process h
262 |
263 | namespace Escaped
264 |   export
265 |   covering
266 |   runProcessingOutput : HasIO io => (String -> io ()) -> (cmd : List String) -> io Int
267 |   runProcessingOutput pr = runProcessingOutput pr . escapeCmd
268 |
269 | %foreign supportC "idris2_time"
270 |          "javascript:lambda:() => Math.floor(new Date().getTime() / 1000)"
271 | prim__time : PrimIO Int
272 |
273 | ||| Return the number of seconds since epoch.
274 | export
275 | time : HasIO io => io Integer
276 | time = pure $ cast !(primIO prim__time)
277 |
278 | %foreign supportC "idris2_getPID"
279 |          "node:lambda:() => process.pid"
280 | prim__getPID : PrimIO Int
281 |
282 | ||| Get the ID of the currently running process.
283 | export
284 | getPID : HasIO io => io Int
285 | getPID = primIO prim__getPID
286 |
287 | %foreign libc "exit"
288 |          "node:lambda:c => process.exit(c)"
289 | prim__exit : Int -> PrimIO ()
290 |
291 | ||| Programs can either terminate successfully, or end in a caught
292 | ||| failure.
293 | public export
294 | data ExitCode : Type where
295 |   ||| Terminate successfully.
296 |   ExitSuccess : ExitCode
297 |   ||| Program terminated for some prescribed reason.
298 |   |||
299 |   ||| @errNo A non-zero numerical value indicating failure.
300 |   ||| @prf   Proof that the int value is non-zero.
301 |   ExitFailure : (errNo    : Int) -> (So (not $ errNo == 0)) => ExitCode
302 |
303 | export
304 | Cast Int ExitCode where
305 |   cast 0 = ExitSuccess
306 |   cast code = ExitFailure code @{believe_me Oh}
307 |
308 | export
309 | Cast ExitCode Int where
310 |   cast ExitSuccess = 0
311 |   cast (ExitFailure code) = code
312 |
313 | ||| Exit the program normally, with the specified status.
314 | export
315 | exitWith : HasIO io => ExitCode -> io a
316 | exitWith = primIO . believe_me . prim__exit . cast
317 |
318 | ||| Exit the program with status value 1, indicating failure.
319 | ||| If you want to specify a custom status value, see `exitWith`.
320 | export
321 | exitFailure : HasIO io => io a
322 | exitFailure = exitWith (ExitFailure 1)
323 |
324 | ||| Exit the program after a successful run.
325 | export
326 | exitSuccess : HasIO io => io a
327 | exitSuccess = exitWith ExitSuccess
328 |
329 | ||| Print the error message and call exitFailure
330 | export
331 | die : HasIO io => String -> io a
332 | die str
333 |   = do ignore $ fPutStrLn stderr str
334 |        exitFailure
335 |