reflection.lagda.rst 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  1. ..
  2. ::
  3. module language.reflection where
  4. open import Agda.Builtin.Sigma
  5. open import Agda.Builtin.Unit
  6. open import Agda.Builtin.Nat
  7. open import Agda.Builtin.List
  8. open import Agda.Builtin.Float
  9. open import Agda.Builtin.Bool
  10. open import Agda.Builtin.Char
  11. open import Agda.Builtin.String
  12. open import Agda.Builtin.Word
  13. open import Agda.Builtin.Equality
  14. open import Agda.Primitive
  15. data ⊥ : Set where
  16. pattern [_] x = x ∷ []
  17. ¬_ : ∀ {u} → Set u → Set u
  18. ¬ x = x → ⊥
  19. infixl 2 ¬_
  20. data Associativity : Set where
  21. left-assoc : Associativity
  22. right-assoc : Associativity
  23. non-assoc : Associativity
  24. data Precedence : Set where
  25. related : Float → Precedence
  26. unrelated : Precedence
  27. data Fixity : Set where
  28. fixity : Associativity → Precedence → Fixity
  29. {-# BUILTIN ASSOC Associativity #-}
  30. {-# BUILTIN ASSOCLEFT left-assoc #-}
  31. {-# BUILTIN ASSOCRIGHT right-assoc #-}
  32. {-# BUILTIN ASSOCNON non-assoc #-}
  33. {-# BUILTIN PRECEDENCE Precedence #-}
  34. {-# BUILTIN PRECRELATED related #-}
  35. {-# BUILTIN PRECUNRELATED unrelated #-}
  36. {-# BUILTIN FIXITY Fixity #-}
  37. {-# BUILTIN FIXITYFIXITY fixity #-}
  38. .. _reflection:
  39. **********
  40. Reflection
  41. **********
  42. Builtin types
  43. -------------
  44. Names
  45. ~~~~~
  46. The built-in ``QNAME`` type represents quoted names and comes equipped with
  47. equality, ordering, and a show function.
  48. ::
  49. postulate Name : Set
  50. {-# BUILTIN QNAME Name #-}
  51. primitive
  52. primQNameEquality : Name → Name → Bool
  53. primQNameLess : Name → Name → Bool
  54. primShowQName : Name → String
  55. The fixity of a name can also be retrived.
  56. ::
  57. primitive
  58. primQNameFixity : Name → Fixity
  59. To define a decidable propositional equality with the option
  60. :option:`--safe`, one can use the conversion to a pair of built-in
  61. 64-bit machine words
  62. ::
  63. primitive
  64. primQNameToWord64s : Name → Σ Word64 (λ _ → Word64)
  65. with the injectivity proof in the ``Properties`` module.::
  66. primitive
  67. primQNameToWord64sInjective : ∀ a b → primQNameToWord64s a ≡ primQNameToWord64s b → a ≡ b
  68. Name literals are created using the ``quote`` keyword and can appear both in
  69. terms and in patterns
  70. ::
  71. nameOfNat : Name
  72. nameOfNat = quote Nat
  73. isNat : Name → Bool
  74. isNat (quote Nat) = true
  75. isNat _ = false
  76. Note that the name being quoted must be in scope.
  77. Metavariables
  78. ~~~~~~~~~~~~~
  79. Metavariables are represented by the built-in ``AGDAMETA`` type. They have
  80. primitive equality, ordering, show, and conversion to Nat::
  81. postulate Meta : Set
  82. {-# BUILTIN AGDAMETA Meta #-}
  83. primitive
  84. primMetaEquality : Meta → Meta → Bool
  85. primMetaLess : Meta → Meta → Bool
  86. primShowMeta : Meta → String
  87. primMetaToNat : Meta → Nat
  88. Builtin metavariables show up in reflected terms. In ``Properties``, there is a proof of injectivity
  89. of ``primMetaToNat``
  90. ::
  91. primitive
  92. primMetaToNatInjective : ∀ a b → primMetaToNat a ≡ primMetaToNat b → a ≡ b
  93. which can be used to define a decidable propositional equality with
  94. the option :option:`--safe`.
  95. Literals
  96. ~~~~~~~~
  97. Literals are mapped to the built-in ``AGDALITERAL`` datatype. Given the appropriate
  98. built-in binding for the types ``Nat``, ``Float``, etc, the ``AGDALITERAL`` datatype
  99. has the following shape::
  100. data Literal : Set where
  101. nat : (n : Nat) → Literal
  102. word64 : (n : Word64) → Literal
  103. float : (x : Float) → Literal
  104. char : (c : Char) → Literal
  105. string : (s : String) → Literal
  106. name : (x : Name) → Literal
  107. meta : (x : Meta) → Literal
  108. {-# BUILTIN AGDALITERAL Literal #-}
  109. {-# BUILTIN AGDALITNAT nat #-}
  110. {-# BUILTIN AGDALITWORD64 word64 #-}
  111. {-# BUILTIN AGDALITFLOAT float #-}
  112. {-# BUILTIN AGDALITCHAR char #-}
  113. {-# BUILTIN AGDALITSTRING string #-}
  114. {-# BUILTIN AGDALITQNAME name #-}
  115. {-# BUILTIN AGDALITMETA meta #-}
  116. Arguments
  117. ~~~~~~~~~
  118. Arguments can be (visible), {hidden}, or {{instance}}::
  119. data Visibility : Set where
  120. visible hidden instance′ : Visibility
  121. {-# BUILTIN HIDING Visibility #-}
  122. {-# BUILTIN VISIBLE visible #-}
  123. {-# BUILTIN HIDDEN hidden #-}
  124. {-# BUILTIN INSTANCE instance′ #-}
  125. Arguments can be relevant or irrelevant::
  126. data Relevance : Set where
  127. relevant irrelevant : Relevance
  128. {-# BUILTIN RELEVANCE Relevance #-}
  129. {-# BUILTIN RELEVANT relevant #-}
  130. {-# BUILTIN IRRELEVANT irrelevant #-}
  131. Arguments also have a quantity::
  132. data Quantity : Set where
  133. quantity-0 quantity-ω : Quantity
  134. {-# BUILTIN QUANTITY Quantity #-}
  135. {-# BUILTIN QUANTITY-0 quantity-0 #-}
  136. {-# BUILTIN QUANTITY-ω quantity-ω #-}
  137. Relevance and quantity are combined into a modality::
  138. data Modality : Set where
  139. modality : (r : Relevance) (q : Quantity) → Modality
  140. {-# BUILTIN MODALITY Modality #-}
  141. {-# BUILTIN MODALITY-CONSTRUCTOR modality #-}
  142. The visibility and the modality characterise the behaviour of an
  143. argument::
  144. data ArgInfo : Set where
  145. arg-info : (v : Visibility) (m : Modality) → ArgInfo
  146. data Arg (A : Set) : Set where
  147. arg : (i : ArgInfo) (x : A) → Arg A
  148. {-# BUILTIN ARGINFO ArgInfo #-}
  149. {-# BUILTIN ARGARGINFO arg-info #-}
  150. {-# BUILTIN ARG Arg #-}
  151. {-# BUILTIN ARGARG arg #-}
  152. Name abstraction
  153. ~~~~~~~~~~~~~~~~
  154. ::
  155. data Abs (A : Set) : Set where
  156. abs : (s : String) (x : A) → Abs A
  157. {-# BUILTIN ABS Abs #-}
  158. {-# BUILTIN ABSABS abs #-}
  159. Terms
  160. ~~~~~
  161. Terms, sorts, patterns, and clauses are mutually recursive and mapped
  162. to the ``AGDATERM``, ``AGDASORT``, ``AGDAPATTERN`` and ``AGDACLAUSE``
  163. built-ins respectively. Types are simply terms. Terms and patterns use
  164. de Bruijn indices to represent variables.
  165. ::
  166. data Term : Set
  167. data Sort : Set
  168. data Pattern : Set
  169. data Clause : Set
  170. Type = Term
  171. Telescope = List (Σ String λ _ → Arg Type)
  172. data Term where
  173. var : (x : Nat) (args : List (Arg Term)) → Term
  174. con : (c : Name) (args : List (Arg Term)) → Term
  175. def : (f : Name) (args : List (Arg Term)) → Term
  176. lam : (v : Visibility) (t : Abs Term) → Term
  177. pat-lam : (cs : List Clause) (args : List (Arg Term)) → Term
  178. pi : (a : Arg Type) (b : Abs Type) → Term
  179. agda-sort : (s : Sort) → Term
  180. lit : (l : Literal) → Term
  181. meta : (x : Meta) → List (Arg Term) → Term
  182. unknown : Term -- Treated as '_' when unquoting.
  183. data Sort where
  184. set : (t : Term) → Sort -- A Set of a given (possibly neutral) level.
  185. lit : (n : Nat) → Sort -- A Set of a given concrete level.
  186. prop : (t : Term) → Sort -- A Prop of a given (possibly neutral) level.
  187. propLit : (n : Nat) → Sort -- A Prop of a given concrete level.
  188. inf : (n : Nat) → Sort -- Setωi of a given concrete level i.
  189. unknown : Sort
  190. data Pattern where
  191. con : (c : Name) (ps : List (Arg Pattern)) → Pattern
  192. dot : (t : Term) → Pattern
  193. var : (x : Nat ) → Pattern
  194. lit : (l : Literal) → Pattern
  195. proj : (f : Name) → Pattern
  196. absurd : (x : Nat) → Pattern -- Absurd patterns have de Bruijn indices
  197. data Clause where
  198. clause : (tel : Telescope) (ps : List (Arg Pattern)) (t : Term) → Clause
  199. absurd-clause : (tel : Telescope) (ps : List (Arg Pattern)) → Clause
  200. {-# BUILTIN AGDATERM Term #-}
  201. {-# BUILTIN AGDASORT Sort #-}
  202. {-# BUILTIN AGDAPATTERN Pattern #-}
  203. {-# BUILTIN AGDACLAUSE Clause #-}
  204. {-# BUILTIN AGDATERMVAR var #-}
  205. {-# BUILTIN AGDATERMCON con #-}
  206. {-# BUILTIN AGDATERMDEF def #-}
  207. {-# BUILTIN AGDATERMMETA meta #-}
  208. {-# BUILTIN AGDATERMLAM lam #-}
  209. {-# BUILTIN AGDATERMEXTLAM pat-lam #-}
  210. {-# BUILTIN AGDATERMPI pi #-}
  211. {-# BUILTIN AGDATERMSORT agda-sort #-}
  212. {-# BUILTIN AGDATERMLIT lit #-}
  213. {-# BUILTIN AGDATERMUNSUPPORTED unknown #-}
  214. {-# BUILTIN AGDASORTSET set #-}
  215. {-# BUILTIN AGDASORTLIT lit #-}
  216. {-# BUILTIN AGDASORTPROP prop #-}
  217. {-# BUILTIN AGDASORTPROPLIT propLit #-}
  218. {-# BUILTIN AGDASORTINF inf #-}
  219. {-# BUILTIN AGDASORTUNSUPPORTED unknown #-}
  220. {-# BUILTIN AGDAPATCON con #-}
  221. {-# BUILTIN AGDAPATDOT dot #-}
  222. {-# BUILTIN AGDAPATVAR var #-}
  223. {-# BUILTIN AGDAPATLIT lit #-}
  224. {-# BUILTIN AGDAPATPROJ proj #-}
  225. {-# BUILTIN AGDAPATABSURD absurd #-}
  226. {-# BUILTIN AGDACLAUSECLAUSE clause #-}
  227. {-# BUILTIN AGDACLAUSEABSURD absurd-clause #-}
  228. Absurd lambdas ``λ ()`` are quoted to extended lambdas with an absurd clause.
  229. The built-in constructors ``AGDATERMUNSUPPORTED`` and ``AGDASORTUNSUPPORTED``
  230. are translated to meta variables when unquoting.
  231. Declarations
  232. ~~~~~~~~~~~~
  233. There is a built-in type ``AGDADEFINITION`` representing definitions. Values of
  234. this type is returned by the ``AGDATCMGETDEFINITION`` built-in :ref:`described
  235. below <reflection-tc-monad>`.
  236. ::
  237. data Definition : Set where
  238. function : (cs : List Clause) → Definition
  239. data-type : (pars : Nat) (cs : List Name) → Definition -- parameters and constructors
  240. record-type : (c : Name) (fs : List (Arg Name)) → -- c: name of record constructor
  241. Definition -- fs: fields
  242. data-cons : (d : Name) → Definition -- d: name of data type
  243. axiom : Definition
  244. prim-fun : Definition
  245. {-# BUILTIN AGDADEFINITION Definition #-}
  246. {-# BUILTIN AGDADEFINITIONFUNDEF function #-}
  247. {-# BUILTIN AGDADEFINITIONDATADEF data-type #-}
  248. {-# BUILTIN AGDADEFINITIONRECORDDEF record-type #-}
  249. {-# BUILTIN AGDADEFINITIONDATACONSTRUCTOR data-cons #-}
  250. {-# BUILTIN AGDADEFINITIONPOSTULATE axiom #-}
  251. {-# BUILTIN AGDADEFINITIONPRIMITIVE prim-fun #-}
  252. Type errors
  253. ~~~~~~~~~~~
  254. Type checking computations (see :ref:`below <reflection-tc-monad>`)
  255. can fail with an error, which is a list of ``ErrorPart``\s. This
  256. allows metaprograms to generate nice errors without having to
  257. implement pretty printing for reflected terms.
  258. ::
  259. -- Error messages can contain embedded names and terms.
  260. data ErrorPart : Set where
  261. strErr : String → ErrorPart
  262. termErr : Term → ErrorPart
  263. pattErr : Pattern → ErrorPart
  264. nameErr : Name → ErrorPart
  265. {-# BUILTIN AGDAERRORPART ErrorPart #-}
  266. {-# BUILTIN AGDAERRORPARTSTRING strErr #-}
  267. {-# BUILTIN AGDAERRORPARTTERM termErr #-}
  268. {-# BUILTIN AGDAERRORPARTNAME nameErr #-}
  269. .. _reflection-tc-monad:
  270. Type checking computations
  271. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  272. Metaprograms, i.e. programs that create other programs, run in a built-in type
  273. checking monad ``TC``::
  274. postulate
  275. TC : ∀ {a} → Set a → Set a
  276. returnTC : ∀ {a} {A : Set a} → A → TC A
  277. bindTC : ∀ {a b} {A : Set a} {B : Set b} → TC A → (A → TC B) → TC B
  278. {-# BUILTIN AGDATCM TC #-}
  279. {-# BUILTIN AGDATCMRETURN returnTC #-}
  280. {-# BUILTIN AGDATCMBIND bindTC #-}
  281. The ``TC`` monad provides an interface to the Agda type checker using the
  282. following primitive operations::
  283. postulate
  284. -- Unify two terms, potentially solving metavariables in the process.
  285. unify : Term → Term → TC ⊤
  286. -- Throw a type error. Can be caught by catchTC.
  287. typeError : ∀ {a} {A : Set a} → List ErrorPart → TC A
  288. -- Block a type checking computation on a metavariable. This will abort
  289. -- the computation and restart it (from the beginning) when the
  290. -- metavariable is solved.
  291. blockOnMeta : ∀ {a} {A : Set a} → Meta → TC A
  292. -- Prevent current solutions of metavariables from being rolled back in
  293. -- case 'blockOnMeta' is called.
  294. commitTC : TC ⊤
  295. -- Backtrack and try the second argument if the first argument throws a
  296. -- type error.
  297. catchTC : ∀ {a} {A : Set a} → TC A → TC A → TC A
  298. -- Infer the type of a given term
  299. inferType : Term → TC Type
  300. -- Check a term against a given type. This may resolve implicit arguments
  301. -- in the term, so a new refined term is returned. Can be used to create
  302. -- new metavariables: newMeta t = checkType unknown t
  303. checkType : Term → Type → TC Term
  304. -- Compute the normal form of a term.
  305. normalise : Term → TC Term
  306. -- Compute the weak head normal form of a term.
  307. reduce : Term → TC Term
  308. -- Get the current context. Returns the context in reverse order, so that
  309. -- it is indexable by deBruijn index. Note that the types in the context are
  310. -- valid in the rest of the context. To use in the current context they need
  311. -- to be weakened by 1 + their position in the list.
  312. getContext : TC Telescope
  313. -- Extend the current context with a variable of the given type and its name.
  314. extendContext : ∀ {a} {A : Set a} → String → Arg Type → TC A → TC A
  315. -- Set the current context. Takes a context telescope entries in
  316. -- reverse order, as given by `getContext`. Each type should be valid
  317. -- in the context formed by the remaining elements in the list.
  318. inContext : ∀ {a} {A : Set a} → Telescope → TC A → TC A
  319. -- Quote a value, returning the corresponding Term.
  320. quoteTC : ∀ {a} {A : Set a} → A → TC Term
  321. -- Unquote a Term, returning the corresponding value.
  322. unquoteTC : ∀ {a} {A : Set a} → Term → TC A
  323. -- Quote a value in Setω, returning the corresponding Term
  324. quoteωTC : ∀ {A : Setω} → A → TC Term
  325. -- Create a fresh name.
  326. freshName : String → TC Name
  327. -- Declare a new function of the given type. The function must be defined
  328. -- later using 'defineFun'. Takes an Arg Name to allow declaring instances
  329. -- and irrelevant functions. The Visibility of the Arg must not be hidden.
  330. declareDef : Arg Name → Type → TC ⊤
  331. -- Declare a new postulate of the given type. The Visibility of the Arg
  332. -- must not be hidden. It fails when executed from command-line with --safe
  333. -- option.
  334. declarePostulate : Arg Name → Type → TC ⊤
  335. -- Define a declared function. The function may have been declared using
  336. -- 'declareDef' or with an explicit type signature in the program.
  337. defineFun : Name → List Clause → TC ⊤
  338. -- Get the type of a defined name. Replaces 'primNameType'.
  339. getType : Name → TC Type
  340. -- Get the definition of a defined name. Replaces 'primNameDefinition'.
  341. getDefinition : Name → TC Definition
  342. -- Check if a name refers to a macro
  343. isMacro : Name → TC Bool
  344. -- Change the behaviour of inferType, checkType, quoteTC, getContext
  345. -- to normalise (or not) their results. The default behaviour is no
  346. -- normalisation.
  347. withNormalisation : ∀ {a} {A : Set a} → Bool → TC A → TC A
  348. -- Prints the third argument to the debug buffer in Emacs
  349. -- if the verbosity level (set by the -v flag to Agda)
  350. -- is higher than the second argument. Note that Level 0 and 1 are printed
  351. -- to the info buffer instead. For instance, giving -v a.b.c:10 enables
  352. -- printing from debugPrint "a.b.c.d" 10 msg.
  353. debugPrint : String → Nat → List ErrorPart → TC ⊤
  354. -- Return the formatted string of the argument using the internal pretty printer.
  355. formatErrorParts : List ErrorPart → TC String
  356. -- Only allow reduction of specific definitions while executing the TC computation
  357. onlyReduceDefs : ∀ {a} {A : Set a} → List Name → TC A → TC A
  358. -- Don't allow reduction of specific definitions while executing the TC computation
  359. dontReduceDefs : ∀ {a} {A : Set a} → List Name → TC A → TC A
  360. -- Makes the following primitives to reconstruct hidden parameters:
  361. -- getDefinition, normalise, reduce, inferType, checkType and getContext
  362. withReconstructed : ∀ {a} {A : Set a} → TC A → TC A
  363. -- Fail if the given computation gives rise to new, unsolved
  364. -- "blocking" constraints.
  365. noConstraints : ∀ {a} {A : Set a} → TC A → TC A
  366. -- Run the given TC action and return the first component. Resets to
  367. -- the old TC state if the second component is 'false', or keep the
  368. -- new TC state if it is 'true'.
  369. runSpeculative : ∀ {a} {A : Set a} → TC (Σ A λ _ → Bool) → TC A
  370. -- Get a list of all possible instance candidates for the given meta
  371. -- variable (it does not have to be an instance meta).
  372. getInstances : Meta → TC (List Term)
  373. {-# BUILTIN AGDATCMUNIFY unify #-}
  374. {-# BUILTIN AGDATCMTYPEERROR typeError #-}
  375. {-# BUILTIN AGDATCMBLOCKONMETA blockOnMeta #-}
  376. {-# BUILTIN AGDATCMCATCHERROR catchTC #-}
  377. {-# BUILTIN AGDATCMINFERTYPE inferType #-}
  378. {-# BUILTIN AGDATCMCHECKTYPE checkType #-}
  379. {-# BUILTIN AGDATCMNORMALISE normalise #-}
  380. {-# BUILTIN AGDATCMREDUCE reduce #-}
  381. {-# BUILTIN AGDATCMGETCONTEXT getContext #-}
  382. {-# BUILTIN AGDATCMEXTENDCONTEXT extendContext #-}
  383. {-# BUILTIN AGDATCMINCONTEXT inContext #-}
  384. {-# BUILTIN AGDATCMQUOTETERM quoteTC #-}
  385. {-# BUILTIN AGDATCMUNQUOTETERM unquoteTC #-}
  386. {-# BUILTIN AGDATCMQUOTEOMEGATERM quoteωTC #-}
  387. {-# BUILTIN AGDATCMFRESHNAME freshName #-}
  388. {-# BUILTIN AGDATCMDECLAREDEF declareDef #-}
  389. {-# BUILTIN AGDATCMDECLAREPOSTULATE declarePostulate #-}
  390. {-# BUILTIN AGDATCMDEFINEFUN defineFun #-}
  391. {-# BUILTIN AGDATCMGETTYPE getType #-}
  392. {-# BUILTIN AGDATCMGETDEFINITION getDefinition #-}
  393. {-# BUILTIN AGDATCMCOMMIT commitTC #-}
  394. {-# BUILTIN AGDATCMISMACRO isMacro #-}
  395. {-# BUILTIN AGDATCMWITHNORMALISATION withNormalisation #-}
  396. {-# BUILTIN AGDATCMDEBUGPRINT debugPrint #-}
  397. {-# BUILTIN AGDATCMONLYREDUCEDEFS onlyReduceDefs #-}
  398. {-# BUILTIN AGDATCMDONTREDUCEDEFS dontReduceDefs #-}
  399. {-# BUILTIN AGDATCMNOCONSTRAINTS noConstraints #-}
  400. {-# BUILTIN AGDATCMRUNSPECULATIVE runSpeculative #-}
  401. {-# BUILTIN AGDATCMGETINSTANCES getInstances #-}
  402. Metaprogramming
  403. ---------------
  404. There are three ways to run a metaprogram (``TC`` computation). To run
  405. a metaprogram in a term position you use a :ref:`macro <macros>`. To
  406. run metaprograms to create top-level definitions you can use the
  407. ``unquoteDecl`` and ``unquoteDef`` primitives (see `Unquoting
  408. Declarations`_).
  409. .. _macros:
  410. Macros
  411. ~~~~~~
  412. Macros are functions of type ``t₁ → t₂ → .. → Term → TC ⊤`` that are defined in
  413. a ``macro`` block. The last argument is supplied by the type checker and will
  414. be the representation of a metavariable that should be instantiated with the
  415. result of the macro.
  416. Macro application is guided by the type of the macro, where ``Term`` and
  417. ``Name`` arguments are quoted before passed to the macro. Arguments of any
  418. other type are preserved as-is.
  419. For example, the macro application ``f u v w`` where
  420. ``f : Term → Name → Bool → Term → TC ⊤`` desugars into:
  421. .. code-block:: agda
  422. unquote (f (quoteTerm u) (quote v) w)
  423. where ``quoteTerm u`` takes a ``u`` of arbitrary type and returns its
  424. representation in the ``Term`` data type, and ``unquote m`` runs a computation
  425. in the ``TC`` monad. Specifically, when checking ``unquote m : A`` for some
  426. type ``A`` the type checker proceeds as follows:
  427. - Check ``m : Term → TC ⊤``.
  428. - Create a fresh metavariable ``hole : A``.
  429. - Let ``qhole : Term`` be the quoted representation of ``hole``.
  430. - Execute ``m qhole``.
  431. - Return (the now hopefully instantiated) ``hole``.
  432. Reflected macro calls are constructed using the ``def`` constructor, so given a
  433. macro ``g : Term → TC ⊤`` the term ``def (quote g) []`` unquotes to a macro
  434. call to ``g``.
  435. .. note::
  436. The ``quoteTerm`` and ``unquote`` primitives are available in the language,
  437. but it is recommended to avoid using them in favour of macros.
  438. Limitations:
  439. - Macros cannot be recursive. This can be worked around by defining the
  440. recursive function outside the macro block and have the macro call the
  441. recursive function.
  442. Silly example:
  443. ..
  444. ::
  445. module example₁ where
  446. ::
  447. macro
  448. plus-to-times : Term → Term → TC ⊤
  449. plus-to-times (def (quote _+_) (a ∷ b ∷ [])) hole =
  450. unify hole (def (quote _*_) (a ∷ b ∷ []))
  451. plus-to-times v hole = unify hole v
  452. thm : (a b : Nat) → plus-to-times (a + b) ≡ a * b
  453. thm a b = refl
  454. Macros lets you write tactics that can be applied without any syntactic
  455. overhead. For instance, suppose you have a solver::
  456. magic : Type → Term
  457. ..
  458. ::
  459. postulate God : (A : Set) → A
  460. magic t =
  461. def (quote God)
  462. (arg (arg-info visible (modality relevant quantity-ω)) t ∷ [])
  463. that takes a reflected goal and outputs a proof (when successful). You can then
  464. define the following macro::
  465. macro
  466. by-magic : Term → TC ⊤
  467. by-magic hole =
  468. bindTC (inferType hole) λ goal →
  469. unify hole (magic goal)
  470. This lets you apply the magic tactic as a normal function:
  471. ..
  472. ::
  473. module P≠NP where
  474. postulate T : Set
  475. postulate P NP : T
  476. ::
  477. thm : ¬ P ≡ NP
  478. thm = by-magic
  479. .. _unquoting-declarations:
  480. Tactic Arguments
  481. ~~~~~~~~~~~~~~~~
  482. You can declare tactics to be used to solve a particular implicit argument
  483. using a ``@(tactic t)`` annotation. The provided tactic should be a term
  484. ``t : Term → TC ⊤``. For instance,
  485. ::
  486. defaultTo : {A : Set} (x : A) → Term → TC ⊤
  487. defaultTo x hole = bindTC (quoteTC x) (unify hole)
  488. f : {@(tactic defaultTo true) x : Bool} → Bool
  489. f {x} = x
  490. test-f : f ≡ true
  491. test-f = refl
  492. At calls to `f`, `defaultTo true` is called on the
  493. metavariable inserted for `x` if it is not given explicitly.
  494. The tactic can depend on previous arguments to the function.
  495. For instance,
  496. ::
  497. g : (x : Nat) {@(tactic defaultTo x) y : Nat} → Nat
  498. g x {y} = x + y
  499. test-g : g 4 ≡ 8
  500. test-g = refl
  501. Record fields can also be annotated with a tactic, allowing them to be
  502. omitted in constructor applications, record constructions and co-pattern
  503. matches::
  504. record Bools : Set where
  505. constructor mkBools
  506. field fst : Bool
  507. @(tactic defaultTo fst) {snd} : Bool
  508. open Bools
  509. tt₀ tt₁ tt₂ tt₃ : Bools
  510. tt₀ = mkBools true {true}
  511. tt₁ = mkBools true
  512. tt₂ = record{ fst = true }
  513. tt₃ .fst = true
  514. test-tt : tt₁ ∷ tt₂ ∷ tt₃ ∷ [] ≡ tt₀ ∷ tt₀ ∷ tt₀ ∷ []
  515. test-tt = refl
  516. Unquoting Declarations
  517. ~~~~~~~~~~~~~~~~~~~~~~
  518. While macros let you write metaprograms to create terms, it is also useful to
  519. be able to create top-level definitions. You can do this from a macro using the
  520. ``declareDef`` and ``defineFun`` primitives, but there is no way to bring such
  521. definitions into scope. For this purpose there are two top-level primitives
  522. ``unquoteDecl`` and ``unquoteDef`` that runs a ``TC`` computation in a
  523. declaration position. They both have the same form:
  524. .. code-block:: agda
  525. unquoteDecl x₁ .. xₙ = m
  526. unquoteDef x₁ .. xₙ = m
  527. except that the list of names can be empty for ``unquoteDecl``, but not for
  528. ``unquoteDef``. In both cases ``m`` should have type ``TC ⊤``. The main
  529. difference between the two is that ``unquoteDecl`` requires ``m`` to both
  530. declare (with ``declareDef``) and define (with ``defineFun``) the ``xᵢ``
  531. whereas ``unquoteDef`` expects the ``xᵢ`` to be already declared. In other
  532. words, ``unquoteDecl`` brings the ``xᵢ`` into scope, but ``unquoteDef``
  533. requires them to already be in scope.
  534. In ``m`` the ``xᵢ`` stand for the names of the functions being defined (i.e.
  535. ``xᵢ : Name``) rather than the actual functions.
  536. One advantage of ``unquoteDef`` over ``unquoteDecl`` is that
  537. ``unquoteDef`` is allowed in mutual blocks, allowing mutually
  538. recursion between generated definitions and hand-written definitions.
  539. Example usage:
  540. ..
  541. ::
  542. module unquote-id where
  543. _>>=_ = bindTC
  544. _>>_ : ∀ {ℓ} {A : Set ℓ} → TC ⊤ → TC A → TC A
  545. a >> b = a >>= λ { tt → b }
  546. ::
  547. arg′ : {A : Set} → Visibility → A → Arg A
  548. arg′ v = arg (arg-info v (modality relevant quantity-ω))
  549. -- Defining: id-name {A} x = x
  550. defId : (id-name : Name) → TC ⊤
  551. defId id-name = do
  552. defineFun id-name
  553. [ clause
  554. ( ("A" , arg′ visible (agda-sort (lit 0)))
  555. ∷ ("x" , arg′ visible (var 0 []))
  556. ∷ [])
  557. ( arg′ hidden (var 1)
  558. ∷ arg′ visible (var 0)
  559. ∷ [] )
  560. (var 0 [])
  561. ]
  562. id : {A : Set} (x : A) → A
  563. unquoteDef id = defId id
  564. mkId : (id-name : Name) → TC ⊤
  565. mkId id-name = do
  566. ty ← quoteTC ({A : Set} (x : A) → A)
  567. declareDef (arg′ visible id-name) ty
  568. defId id-name
  569. unquoteDecl id′ = mkId id′
  570. System Calls
  571. ~~~~~~~~~~~~
  572. It is possible to run system calls as part of a metaprogram, using the ``execTC`` builtin. You can use this feature to implement type providers, or to call external solvers. For instance, the following example calls ``/bin/echo`` from Agda:
  573. .. code-block:: agda
  574. postulate
  575. execTC : (exe : String) (args : List String) (stdIn : String)
  576. → TC (Σ Nat (λ _ → Σ String (λ _ → String)))
  577. {-# BUILTIN AGDATCMEXEC execTC #-}
  578. macro
  579. echo : List String → Term → TC ⊤
  580. echo args hole = do
  581. (exitCode , (stdOut , stdErr)) ← execTC "echo" args ""
  582. unify hole (lit (string stdOut))
  583. _ : echo ("hello" ∷ "world" ∷ []) ≡ "hello world\n"
  584. _ = refl
  585. The ``execTC`` builtin takes three arguments: the basename of the executable (e.g., ``"echo"``), a list of arguments, and the contents of the standard input. It returns a triple, consisting of the exit code (as a natural number), the contents of the standard output, and the contents of the standard error.
  586. It would be ill-advised to allow Agda to make arbitrary system calls. Hence, the feature must be activated by passing the ``--allow-exec`` option, either on the command-line or using a pragma. (Note that ``--allow-exec`` is incompatible with ``--safe``.) Furthermore, Agda can only call executables which are listed in the list of trusted executables, ``~/.agda/executables``. For instance, to run the example above, you must add ``/bin/echo`` to this file:
  587. .. code-block:: text
  588. # contents of ~/.agda/executables
  589. /bin/echo
  590. The executable can then be called by passing its basename to ``execTC``, subtracting the ``.exe`` on Windows.