0 | module Compiler.Common
  1 |
  2 |
  3 | import Compiler.ANF
  4 | import Compiler.CompileExpr
  5 | import Compiler.Inline
  6 | import Compiler.LambdaLift
  7 | import Compiler.Opts.Constructor
  8 | import Compiler.Opts.CSE
  9 | import Compiler.VMCode
 10 |
 11 | import Core.Binary.Prims
 12 | import Core.Directory
 13 | import Core.TTC
 14 |
 15 | import Data.IOArray
 16 | import Data.String as String
 17 | import Data.SortedSet
 18 | import Libraries.Data.NameMap
 19 | import Libraries.Data.NatSet
 20 | import Libraries.Data.WithDefault
 21 | import Libraries.Utils.Scheme
 22 |
 23 | import Idris.Syntax
 24 |
 25 | import System.File
 26 | import System.Info
 27 |
 28 | %default covering
 29 |
 30 | ||| Tag to indicate if the compiler needs to stop execution immediately
 31 | public export
 32 | data ControlFlow = Continue | Abort
 33 |
 34 | ||| Generic interface to some code generator
 35 | public export
 36 | record Codegen where
 37 |   constructor MkCG
 38 |   ||| Compile an Idris 2 expression, saving it to a file.
 39 |   compileExpr : Ref Ctxt Defs -> Ref Syn SyntaxInfo ->
 40 |                 (tmpDir : String) -> (outputDir : String) ->
 41 |                 ClosedTerm -> (outfile : String) -> Core (Maybe String)
 42 |   ||| Execute an Idris 2 expression directly.
 43 |   executeExpr : Ref Ctxt Defs -> Ref Syn SyntaxInfo ->
 44 |                 (tmpDir : String) -> ClosedTerm -> Core ()
 45 |   ||| Incrementally compile definitions in the current module (toIR defs)
 46 |   ||| if supported
 47 |   ||| Takes a source file name, returns the name of the generated object
 48 |   ||| file, if successful, plus any other backend specific data in a list
 49 |   ||| of strings. The generated object file should be placed in the same
 50 |   ||| directory as the associated TTC.
 51 |   incCompileFile : Maybe (Ref Ctxt Defs -> Ref Syn SyntaxInfo ->
 52 |                           (sourcefile : String) ->
 53 |                           Core (Maybe (String, List String)))
 54 |   ||| If incremental compilation is supported, get the output file extension
 55 |   incExt : Maybe String
 56 |
 57 | -- Say which phase of compilation is the last one to use - it saves time if
 58 | -- you only ask for what you need.
 59 | public export
 60 | data UsePhase = Cases | Lifted | ANF | VMCode
 61 |
 62 | Eq UsePhase where
 63 |   (==) Cases Cases = True
 64 |   (==) Lifted Lifted = True
 65 |   (==) ANF ANF = True
 66 |   (==) VMCode VMCode = True
 67 |   (==) _ _ = False
 68 |
 69 | Ord UsePhase where
 70 |   compare x y = compare (tag x) (tag y)
 71 |     where
 72 |       tag : UsePhase -> Int
 73 |       tag Cases = 0
 74 |       tag Lifted = 1
 75 |       tag ANF = 2
 76 |       tag VMCode = 3
 77 |
 78 | public export
 79 | record CompileData where
 80 |   constructor MkCompileData
 81 |   mainExpr : ClosedCExp -- main expression to execute. This also appears in
 82 |                      -- the definitions below as MN "__mainExpression" 0
 83 |                      -- For incremental compilation and for compiling exported
 84 |                      -- names only, this can be set to 'erased'.
 85 |   exported : List (Name, String) -- names to be made accessible to the foreign
 86 |                      -- and what they should be called in that language
 87 |   namedDefs : List (Name, FC, NamedDef)
 88 |   lambdaLifted : List (Name, LiftedDef)
 89 |        -- ^ lambda lifted definitions, if required. Only the top level names
 90 |        -- will be in the context, and (for the moment...) I don't expect to
 91 |        -- need to look anything up, so it's just an alist.
 92 |   anf : List (Name, ANFDef)
 93 |        -- ^ lambda lifted and converted to ANF (all arguments to functions
 94 |        -- and constructors transformed to either variables or Null if erased)
 95 |   vmcode : List (Name, VMDef)
 96 |        -- ^ A much simplified virtual machine code, suitable for passing
 97 |        -- to a more low level target such as C
 98 |
 99 | ||| compile
100 | ||| Given a value of type Codegen, produce a standalone function
101 | ||| that executes the `compileExpr` method of the Codegen
102 | export
103 | compile : {auto c : Ref Ctxt Defs} ->
104 |           {auto s : Ref Syn SyntaxInfo} ->
105 |           Codegen ->
106 |           ClosedTerm -> (outfile : String) -> Core (Maybe String)
107 | compile {c} {s} cg tm out
108 |     = do d <- getDirs
109 |          let tmpDir = execBuildDir d
110 |          let outputDir = outputDirWithDefault d
111 |          ensureDirectoryExists tmpDir
112 |          ensureDirectoryExists outputDir
113 |          logTime 1 "Code generation overall" $
114 |              compileExpr cg c s tmpDir outputDir tm out
115 |
116 | ||| execute
117 | ||| As with `compile`, produce a functon that executes
118 | ||| the `executeExpr` method of the given Codegen
119 | export
120 | execute : {auto c : Ref Ctxt Defs} ->
121 |           {auto s : Ref Syn SyntaxInfo} ->
122 |           Codegen -> ClosedTerm -> Core ()
123 | execute {c} {s} cg tm
124 |     = do d <- getDirs
125 |          let tmpDir = execBuildDir d
126 |          ensureDirectoryExists tmpDir
127 |          executeExpr cg c s tmpDir tm
128 |
129 | export
130 | incCompile : {auto c : Ref Ctxt Defs} ->
131 |              {auto s : Ref Syn SyntaxInfo} ->
132 |              Codegen -> String -> Core (Maybe (String, List String))
133 | incCompile {c} {s} cg src
134 |     = do let Just inc = incCompileFile cg
135 |              | Nothing => pure Nothing
136 |          inc c s src
137 |
138 | -- If an entry isn't already decoded, get the minimal entry we need for
139 | -- compilation, and record the Binary so that we can put it back when we're
140 | -- done (so that we don't obliterate the definition)
141 | getMinimalDef : ContextEntry -> Core (GlobalDef, Maybe (Namespace, Binary))
142 | getMinimalDef (Decoded def) = pure (def, Nothing)
143 | getMinimalDef (Coded ns bin)
144 |     = do b <- newRef Bin bin
145 |          cdef <- fromBuf
146 |          refsRList <- fromBuf
147 |          let refsR = map fromList refsRList
148 |          fc <- fromBuf
149 |          mul <- fromBuf
150 |          name <- fromBuf
151 |          let def
152 |              = MkGlobalDef fc name (Erased fc Placeholder) NatSet.empty NatSet.empty NatSet.empty NatSet.empty mul
153 |                            Scope.empty (specified Public) (MkTotality Unchecked IsCovering) False
154 |                            [] Nothing refsR False False True
155 |                            None cdef Nothing [] Nothing
156 |          pure (def, Just (ns, bin))
157 |
158 | -- ||| Recursively get all calls in a function definition
159 | -- ||| Note: this only checks resolved names
160 | getAllDesc : {auto c : Ref Ctxt Defs} ->
161 |              List Name -> -- calls to check
162 |              IOArray (Int, Maybe (Namespace, Binary)) ->
163 |                             -- which nodes have been visited. If the entry is
164 |                             -- present, it's visited. Keep the binary entry, if
165 |                             -- we partially decoded it, so that we can put back
166 |                             -- the full definition later.
167 |                             -- (We only need to decode the case tree IR, and
168 |                             -- it's expensive to decode the whole thing)
169 |              Defs -> Core ()
170 | getAllDesc [] arr defs = pure ()
171 | getAllDesc (n@(Resolved i) :: rest) arr defs
172 |   = do Nothing <- coreLift $ readArray arr i
173 |            | Just _ => getAllDesc rest arr defs
174 |        case !(lookupContextEntry n (gamma defs)) of
175 |             Nothing => do log "compile.execute" 20 $ "Couldn't find " ++ show n
176 |                           getAllDesc rest arr defs
177 |             Just (_, entry) =>
178 |               do (def, bin) <- getMinimalDef entry
179 |                  ignore $ addDef n def
180 |                  let refs = refersToRuntime def
181 |                  if multiplicity def /= erased
182 |                     then do coreLift_ $ writeArray arr i (i, bin)
183 |                             let refs = refersToRuntime def
184 |                             refs' <- traverse toResolvedNames (keys refs)
185 |                             getAllDesc (refs' ++ rest) arr defs
186 |                     else do log "compile.execute" 20
187 |                                $ "Dropping " ++ show n ++ " because it's erased"
188 |                             getAllDesc rest arr defs
189 | getAllDesc (n :: rest) arr defs
190 |   = do log "compile.execute" 20 $
191 |          "Ignoring " ++ show n ++ " because it's not a Resolved name"
192 |        getAllDesc rest arr defs
193 |
194 | warnIfHole : Name -> NamedDef -> Core ()
195 | warnIfHole n (MkNmError _)
196 |     = coreLift $ putStrLn $ "Warning: compiling hole " ++ show n
197 | warnIfHole n _ = pure ()
198 |
199 | getNamedDef :  {auto c : Ref Ctxt Defs}
200 |             -> (Name,FC,CDef)
201 |             -> Core (Name, FC, NamedDef)
202 | getNamedDef (n,fc,cdef) =
203 |   let ndef = forgetDef cdef
204 |    in warnIfHole n ndef >> pure (n,fc,ndef)
205 |
206 | replaceEntry : {auto c : Ref Ctxt Defs} ->
207 |                (Int, Maybe (Namespace, Binary)) -> Core ()
208 | replaceEntry (i, Nothing) = pure ()
209 | replaceEntry (i, Just (ns, b))
210 |     = ignore $ addContextEntry ns (Resolved i) b
211 |
212 | natHackNames : List Name
213 | natHackNames =
214 |     [ UN (Basic "prim__sub_Integer")
215 |     , NS typesNS (UN $ Basic "prim__integerToNat")
216 |     , NS eqOrdNS (UN $ Basic "compareInteger")
217 |     ]
218 |
219 | dumpIR : Show def => String -> List (Name, def) -> Core ()
220 | dumpIR fn lns
221 |     = do let cstrs = map dumpDef lns
222 |          Right () <- coreLift $ writeFile fn (fastConcat cstrs)
223 |                | Left err => throw (FileErr fn err)
224 |          pure ()
225 |   where
226 |     fullShow : Name -> String
227 |     fullShow (DN _ n) = show n
228 |     fullShow n = show n
229 |
230 |     dumpDef : (Name, def) -> String
231 |     dumpDef (n, d) = fullShow n ++ " = " ++ show d ++ "\n"
232 |
233 |
234 | export
235 | nonErased : {auto c : Ref Ctxt Defs} ->
236 |             Name -> Core Bool
237 | nonErased n
238 |     = do defs <- get Ctxt
239 |          Just gdef <- lookupCtxtExact n (gamma defs)
240 |               | Nothing => pure True
241 |          pure (multiplicity gdef /= erased)
242 |
243 | export
244 | addForeignImpl : {auto c : Ref Ctxt Defs} ->
245 |              Name -> Core ()
246 | addForeignImpl n
247 |     = do defs <- get Ctxt
248 |          Just def <- lookupCtxtExact n (gamma defs)        | Nothing => pure ()
249 |          let Just (MkForeign cs atys retty) = compexpr def | _ => pure ()
250 |          let xs = map snd $ filter (\x => fst x == n) $ Prelude.toList defs.options.foreignImpl
251 |          setCompiled n (MkForeign (xs ++ cs) atys retty)
252 |
253 | -- Get the names of the functions we're exporting to the given back end, and
254 | -- the corresponding name it will have when exported.
255 | getExported : String -> NameMap (List (String, String)) -> List (Name, String)
256 | getExported backend all
257 |     = mapMaybe isExp (toList all)
258 |   where
259 |     -- If the name/convention pair matches the backend, keep the name
260 |     isExp : (Name, List (String, String)) -> Maybe (Name, String)
261 |     isExp (n, cs)
262 |         = do fn <- lookup backend cs
263 |              pure (n, fn)
264 |
265 | -- Find all the names which need compiling, from a given expression, and compile
266 | -- them to CExp form (and update that in the Defs).
267 | -- Return the names, the type tags, and a compiled version of the expression
268 | export
269 | getCompileDataWith : {auto c : Ref Ctxt Defs} ->
270 |                      List String -> -- which FFI(s), if compiling foreign exports
271 |                      (doLazyAnnots : Bool) ->
272 |                      UsePhase -> ClosedTerm -> Core CompileData
273 | getCompileDataWith exports doLazyAnnots phase_in tm_in
274 |     = do log "compile.execute" 10 $ "Getting compiled data for: " ++ show tm_in
275 |          sopts <- getSession
276 |          let phase = foldl {t=List} (flip $ maybe id max) phase_in $
277 |                        [ Cases <$ dumpcases sopts
278 |                        , Lifted <$ dumplifted sopts
279 |                        , ANF <$ dumpanf sopts
280 |                        , VMCode <$ dumpvmcode sopts
281 |                        ]
282 |
283 |          -- When we compile a REPL expression, there may be leftovers holes in it.
284 |          -- Turn these into runtime errors.
285 |          let metas = addMetas True empty tm_in
286 |          for_ (keys metas) $ \ metanm =>
287 |              do defs <- get Ctxt
288 |                 Just gdef <- lookupCtxtExact metanm (gamma defs)
289 |                   | Nothing => log "compile.execute" 50 $ unwords
290 |                                     [ "Couldn't find"
291 |                                     , show metanm
292 |                                     , "(probably impossible)"]
293 |                 let Hole _ _ = definition gdef
294 |                   | _ => pure ()
295 |                 let fulln = fullname gdef
296 |                 let cexp = MkError $ CCrash emptyFC
297 |                          $ "Encountered unimplemented hole " ++ show fulln
298 |                 ignore $ addDef metanm ({ compexpr := Just cexp
299 |                                         , namedcompexpr := Just (forgetDef cexp)
300 |                                         } gdef)
301 |
302 |          defs <- get Ctxt
303 |          let refs  = getRefs (Resolved (-1)) tm_in
304 |          exported <- if isNil exports
305 |                  then pure []
306 |                  else getExports defs
307 |          log "compile.export" 25 "exporting: \{show $ map fst exported}"
308 |          let ns = keys (mergeWith const metas refs) ++ map fst exported
309 |          log "compile.execute" 70 $
310 |            "Found names: " ++ concat (intersperse ", " $ map show $ ns)
311 |          tm <- toFullNames tm_in
312 |          natHackNames' <- traverse toResolvedNames natHackNames
313 |          -- make an array of Bools to hold which names we've found (quicker
314 |          -- to check than a NameMap!)
315 |          asize <- getNextEntry
316 |          arr <- coreLift $ newArray asize
317 |
318 |          defs <- get Ctxt
319 |          logTime 2 "Get names" $ getAllDesc (natHackNames' ++ ns) arr defs
320 |
321 |          let entries = catMaybes !(coreLift (toList arr))
322 |          let allNs = map (Resolved . fst) entries
323 |          cns <- traverse toFullNames allNs
324 |          log "compile.execute" 30 $
325 |            "All names: " ++ concat (intersperse ", " $ map show $ zip allNs cns)
326 |
327 |          -- Do a round of merging/arity fixing for any names which were
328 |          -- unknown due to cyclic modules (i.e. declared in one, defined in
329 |          -- another)
330 |          rcns <- filterM nonErased cns
331 |          log "compile.execute" 40 $
332 |            "Kept: " ++ concat (intersperse ", " $ map show rcns)
333 |
334 |          logTime 2 "Merge lambda" $ traverse_ mergeLamDef rcns
335 |          logTime 2 "Fix arity" $ traverse_ fixArityDef rcns
336 |          logTime 2 "Fix foreign bindings" $ traverse_ addForeignImpl rcns
337 |          compiledtm <- fixArityExp !(compileExp tm)
338 |
339 |          (cseDefs, csetm) <- logTime 2 "CSE" $ cse rcns compiledtm
340 |
341 |          -- Add intrinsic constructors (see Compiler.Opts.Constructor)
342 |          let cseDefs = intrinsicCons ++ cseDefs
343 |
344 |          namedDefs <- logTime 2 "Forget names" $
345 |            traverse getNamedDef cseDefs
346 |
347 |          let mainname = MN "__mainExpression" 0
348 |          (liftedtm, ldefs) <- liftBody {doLazyAnnots} mainname csetm
349 |
350 |          lifted_in <- if phase >= Lifted
351 |                          then logTime 2 "Lambda lift" $
352 |                               traverse (lambdaLift doLazyAnnots) cseDefs
353 |                          else pure []
354 |
355 |          let lifted = (mainname, MkLFun Scope.empty Scope.empty liftedtm) ::
356 |                       (ldefs ++ concat lifted_in)
357 |
358 |          anf <- if phase >= ANF
359 |                    then logTime 2 "Get ANF" $ traverse (\ (n, d) => pure (n, !(toANF d))) lifted
360 |                    else pure []
361 |          vmcode <- if phase >= VMCode
362 |                       then logTime 2 "Get VM Code" $ pure (allDefs anf)
363 |                       else pure []
364 |
365 |          defs <- get Ctxt
366 |          whenJust (dumpcases sopts) $ \ f =>
367 |             do coreLift $ putStrLn $ "Dumping case trees to " ++ f
368 |                dumpIR f (map (\(n, _, def) => (n, def)) namedDefs)
369 |
370 |          whenJust (dumplifted sopts) $ \ f =>
371 |             do coreLift $ putStrLn $ "Dumping lambda lifted defs to " ++ f
372 |                dumpIR f lifted
373 |
374 |          whenJust (dumpanf sopts) $ \ f =>
375 |             do coreLift $ putStrLn $ "Dumping ANF defs to " ++ f
376 |                dumpIR f anf
377 |
378 |          whenJust (dumpvmcode sopts) $ \ f =>
379 |             do coreLift $ putStrLn $ "Dumping VM defs to " ++ f
380 |                dumpIR f vmcode
381 |
382 |          -- We're done with our minimal context now, so put it back the way
383 |          -- it was. Back ends shouldn't look at the global context, because
384 |          -- it'll have to decode the definitions again.
385 |          traverse_ replaceEntry entries
386 |          pure (MkCompileData csetm exported namedDefs lifted anf vmcode)
387 |   where
388 |     lookupBackend :
389 |         List String ->
390 |         (Name, List (String, String)) ->
391 |         Maybe (Name, String)
392 |     lookupBackend [] _ = Nothing
393 |     lookupBackend (b :: bs) (n, exps) = case find (\(b', _) => b == b') exps of
394 |         Just (_, exp) => Just (n, exp)
395 |         Nothing => lookupBackend bs (n, exps)
396 |
397 |     getExports : Defs -> Core (List (Name, String))
398 |     getExports defs = traverse (\(n, exp) => pure (!(resolved defs.gamma n), exp)) $
399 |         mapMaybe (lookupBackend exports) (toList defs.foreignExports)
400 |
401 | -- Find all the names which need compiling, from a given expression, and compile
402 | -- them to CExp form (and update that in the Defs).
403 | -- Return the names, the type tags, and a compiled version of the expression
404 | export
405 | getCompileData : {auto c : Ref Ctxt Defs} ->
406 |                  (doLazyAnnots : Bool) ->
407 |                  UsePhase -> ClosedTerm -> Core CompileData
408 | getCompileData = getCompileDataWith []
409 |
410 | export
411 | compileTerm : {auto c : Ref Ctxt Defs} ->
412 |               ClosedTerm -> Core ClosedCExp
413 | compileTerm tm_in
414 |     = do tm <- toFullNames tm_in
415 |          fixArityExp !(compileExp tm)
416 |
417 | compDef : {auto c : Ref Ctxt Defs} -> Name -> Core (Maybe (Name, FC, CDef))
418 | compDef n = do
419 |   defs <- get Ctxt
420 |   Just def <- lookupCtxtExact n (gamma defs) | Nothing => pure Nothing
421 |   let Just cexpr =  compexpr def             | Nothing => pure Nothing
422 |   pure $ Just (n, location def, cexpr)
423 |
424 | export
425 | getIncCompileData : {auto c : Ref Ctxt Defs} ->
426 |                     (doLazyAnnots : Bool) ->
427 |                     UsePhase -> Core CompileData
428 | getIncCompileData doLazyAnnots phase
429 |     = do defs <- get Ctxt
430 |          -- Compile all the names in 'toIR', since those are the ones defined
431 |          -- in the current source file
432 |          let ns = keys (toIR defs)
433 |          cns <- traverse toFullNames ns
434 |          rcns <- filterM nonErased cns
435 |          cseDefs <- catMaybes <$> traverse compDef rcns
436 |
437 |          namedDefs <- traverse getNamedDef cseDefs
438 |
439 |          lifted_in <- if phase >= Lifted
440 |                          then logTime 2 "Lambda lift" $
441 |                               traverse (lambdaLift doLazyAnnots) cseDefs
442 |                          else pure []
443 |          let lifted = concat lifted_in
444 |          anf <- if phase >= ANF
445 |                    then logTime 2 "Get ANF" $ traverse (\ (n, d) => pure (n, !(toANF d))) lifted
446 |                    else pure []
447 |          vmcode <- if phase >= VMCode
448 |                       then logTime 2 "Get VM Code" $ pure (allDefs anf)
449 |                       else pure []
450 |          pure (MkCompileData (CErased emptyFC) [] namedDefs lifted anf vmcode)
451 |
452 | -- Some things missing from Prelude.File
453 |
454 |
455 | ||| check to see if a given file exists
456 | export
457 | exists : String -> IO Bool
458 | exists f
459 |     = do Right ok <- openFile f Read
460 |              | Left err => pure False
461 |          closeFile ok
462 |          pure True
463 | -- Select the most preferred target from an ordered list of choices and
464 | -- parse the calling convention into a backend/target for the call, and
465 | -- a comma separated list of any other location data. For example
466 | -- the chez backend would supply ["scheme,chez", "scheme", "C"]. For a function with
467 | -- more than one string, a string with "scheme" would be preferred over one
468 | -- with "C" and "scheme,chez" would be preferred to both.
469 | -- e.g. "scheme:display" - call the scheme function 'display'
470 | --      "C:puts,libc,stdio.h" - call the C function 'puts' which is in
471 | --      the library libc and the header stdio.h
472 | -- Returns Nothing if there is no match.
473 | export
474 | parseCC : List String -> List String -> Maybe (String, List String)
475 | parseCC [] _ = Nothing
476 | parseCC (target::ts) strs = findTarget target strs <|> parseCC ts strs
477 |   where
478 |     getOpts : String -> List String
479 |     getOpts "" = []
480 |     getOpts str
481 |         = case span (/= ',') str of
482 |                (opt, "") => [opt]
483 |                (opt, rest) => opt :: getOpts (assert_total (strTail rest))
484 |     hasTarget : String -> String -> Bool
485 |     hasTarget target str = case span (/= ':') str of
486 |                             (targetSpec, _) => targetSpec == target
487 |     findTarget : String -> List String -> Maybe (String, List String)
488 |     findTarget target [] = Nothing
489 |     findTarget target (s::xs) = if hasTarget target s
490 |                                   then case span (/= ':') s of
491 |                                         (t, "") => Just (trim t, [])
492 |                                         (t, opts) => Just (trim t, map trim (getOpts
493 |                                                                   (assert_total (strTail opts))))
494 |                                   else findTarget target xs
495 |
496 | export
497 | dylib_suffix : String
498 | dylib_suffix
499 |     = cond [(elem os $ the (List String) ["windows", "mingw32", "cygwin32"], "dll"),
500 |             (os == "darwin", "dylib")]
501 |            "so"
502 |
503 | export
504 | locate : {auto c : Ref Ctxt Defs} ->
505 |          String -> Core (String, String)
506 | locate libspec
507 |     = do -- Attempt to turn libspec into an appropriate filename for the system
508 |          let fname
509 |               = case words libspec of
510 |                      [] => ""
511 |                      [fn] => if '.' `elem` unpack fn
512 |                                 then fn -- full filename given
513 |                                 else -- add system extension
514 |                                      fn ++ "." ++ dylib_suffix
515 |                      (fn :: ver :: _) =>
516 |                           -- library and version given, build path name as
517 |                           -- appropriate for the system
518 |                           cond [(dylib_suffix == "dll",
519 |                                       fn ++ "-" ++ ver ++ ".dll"),
520 |                                 (dylib_suffix == "dylib",
521 |                                       fn ++ "." ++ ver ++ ".dylib")]
522 |                                 (fn ++ "." ++ dylib_suffix ++ "." ++ ver)
523 |
524 |          fullname <- catch (findLibraryFile fname)
525 |                            (\err => -- assume a system library so not
526 |                                     -- in our library path
527 |                                     pure fname)
528 |          pure (fname, fullname)
529 |
530 | export
531 | copyLib : (String, String) -> Core ()
532 | copyLib (lib, fullname)
533 |     = if lib == fullname
534 |          then pure ()
535 |          else do Right bin <- coreLift $ readFromFile fullname
536 |                     | Left err => pure () -- assume a system library installed globally
537 |                  Right _ <- coreLift $ writeToFile lib bin
538 |                     | Left err => throw (FileErr lib err)
539 |                  pure ()
540 |
541 |
542 | -- parses `--directive extraRuntime=/path/to/defs.scm` options for textual inclusion in generated
543 | -- source. Use with `%foreign "scheme:..."` declarations to write runtime-specific scheme calls.
544 | export
545 | getExtraRuntime : List String -> Core String
546 | getExtraRuntime directives
547 |     = do fileContents <- traverse Core.readFile paths
548 |          pure $ concat $ intersperse "\n" fileContents
549 |   where
550 |     getArg : String -> Maybe String
551 |     getArg directive =
552 |       let (k,v) = break (== '=') directive
553 |       in
554 |         if (trim k) == "extraRuntime"
555 |           then Just $ trim $ substr 1 (length v) v
556 |           else Nothing
557 |
558 |     paths : List String
559 |     paths = nub $ mapMaybe getArg $ reverse directives
560 |
561 | -- parses `--directive lazy=weakMemo` option for turning on weak memoisation of lazy values
562 | -- (if supported by a backend).
563 | -- This particular form of the directive string is chosen to be able to pass different variants
564 | -- in the future (say, for strong memoisation, or turning laziness off).
565 | export
566 | getWeakMemoLazy : List String -> Bool
567 | getWeakMemoLazy = elem "lazy=weakMemo"
568 |
569 | ||| Cast implementations. Values of `ConstantPrimitives` can
570 | ||| be used in a call to `castInt`, which then determines
571 | ||| the cast implementation based on the given pair of
572 | ||| constants.
573 | public export
574 | record ConstantPrimitives' str where
575 |   constructor MkConstantPrimitives
576 |   charToInt    : IntKind -> str -> Core str
577 |   intToChar    : IntKind -> str -> Core str
578 |   stringToInt  : IntKind -> str -> Core str
579 |   intToString  : IntKind -> str -> Core str
580 |   doubleToInt  : IntKind -> str -> Core str
581 |   intToDouble  : IntKind -> str -> Core str
582 |   intToInt     : IntKind -> IntKind -> str -> Core str
583 |
584 | public export
585 | ConstantPrimitives : Type
586 | ConstantPrimitives = ConstantPrimitives' String
587 |
588 | ||| Implements casts from and to integral types by using
589 | ||| the implementations from the provided `ConstantPrimitives`.
590 | export
591 | castInt :  ConstantPrimitives' str
592 |         -> PrimType
593 |         -> PrimType
594 |         -> str
595 |         -> Core str
596 | castInt p from to x =
597 |   case ((from, intKind from), (to, intKind to)) of
598 |        ((CharType, _)  , (_, Just k)) => p.charToInt k x
599 |        ((StringType, _), (_, Just k)) => p.stringToInt k x
600 |        ((DoubleType, _), (_, Just k)) => p.doubleToInt k x
601 |        ((_, Just k), (CharType, _))   => p.intToChar k x
602 |        ((_, Just k), (StringType, _)) => p.intToString k x
603 |        ((_, Just k), (DoubleType, _)) => p.intToDouble k x
604 |        ((_, Just k1), (_, Just k2))   => p.intToInt k1 k2 x
605 |        _ => throw $ InternalError $ "invalid cast: + " ++ show from ++ " + ' -> ' + " ++ show to
606 |