| 1 |
------------------------------------------------------------------------ |
| 2 |
-- The Agda standard library |
| 3 |
-- |
| 4 |
-- How to use reflection to call external functions. |
| 5 |
-- |
| 6 |
-- IMPORTANT: In order for this file to type-check you will need to add |
| 7 |
-- a line `/usr/bin/expr` to your `~/.agda/executables` file. See the |
| 8 |
-- section on Reflection in the Agda user manual for more details. |
| 9 |
------------------------------------------------------------------------ |
| 10 |
|
| 11 |
{-# OPTIONS --cubical-compatible --allow-exec #-} |
| 12 |
|
| 13 |
module README.Reflection.External where |
| 14 |
|
| 15 |
open import Data.List.Base using ([]; _∷_) |
| 16 |
open import Data.String.Base using (String; _++_) |
| 17 |
open import Relation.Binary.PropositionalEquality |
| 18 |
|
| 19 |
-- All the commands needed to make an external system call are included |
| 20 |
-- in `Reflection.External`. |
| 21 |
|
| 22 |
open import Reflection.External |
| 23 |
using (CmdSpec; runCmd) |
| 24 |
|
| 25 |
-- The most important one is `CmdSpec` ("command specification") |
| 26 |
-- which allows ones to specify the external command being called, its |
| 27 |
-- arguments and the contents of stdin. |
| 28 |
|
| 29 |
-- Here we define a simple command spec that takes two numbers and |
| 30 |
-- uses the Unix `expr` command to add the two together. |
| 31 |
|
| 32 |
add : String → String → CmdSpec |
| 33 |
add x y = record |
| 34 |
{ name = "expr" |
| 35 |
; args = x ∷ "+" ∷ y ∷ [] |
| 36 |
; input = "" |
| 37 |
} |
| 38 |
|
| 39 |
-- The command can then be run using the `runCmd` macro. If no error |
| 40 |
-- occured then by default the macro returns the result of `stdout`. |
| 41 |
-- Otherwise the macro will terminate with a type error. |
| 42 |
|
| 43 |
test : runCmd (add "1" "2") ≡ "3\n" |
| 44 |
test = refl |
| 45 |
|
| 46 |
-- If you are running a command that you know might be ill-formed |
| 47 |
-- and result in an error then can use `unsafeRunCmd` instead that |
| 48 |
-- returns a `Result` object containing the exit code and the contents |
| 49 |
-- of both `stdout` and `stderr`. |
| 50 |
|
| 51 |
open import Reflection.External |
| 52 |
using (unsafeRunCmd; result; exitFailure) |
| 53 |
|
| 54 |
error = "/usr/bin/expr: non-integer argument\n" |
| 55 |
|
| 56 |
test2 : unsafeRunCmd (add "a" "b") ≡ result (exitFailure 2) "" error |
| 57 |
test2 = refl |
| 58 |
|
| 59 |
-- For a more advanced use-case where SMT solvers are invoked from |
| 60 |
-- Agda, see Schmitty (https://github.com/wenkokke/schmitty) |