on c7efd0a help sign in
Idris-dev/docs/reference/elaborator-reflection.rst
161 lines 8.7 kB history raw
1.. _elaborator-reflection:
3*********************
4Elaborator Reflection
5*********************
7The Idris elaborator is responsible for converting high-level Idris code into the core language.
8It is implemented as a kind of embedded tactic language in Haskell, where tactic scripts are written in an *elaboration monad* that provides error handling and a proof state.
9For details, see Edwin Brady's 2013 paper in the Journal of Functional Programming.
11Elaborator reflection makes the elaboration type as well as a selection of its tactics available to Idris code.
12This means that metaprograms written in Idris can have complete control over the elaboration process, generating arbitrary code, and they have access to all of the facilities available in the elaborator, such as higher-order unification, type checking, and emitting auxiliary definitions.
14The Elaborator State
15====================
17The elaborator state contains information about the ongoing elaboration process.
18In particular, it contains a *goal type*, which is to be filled by an under-construction *proof term*.
19The proof term can contain *holes*, each of which has a scope in which it is valid and a type.
20Some holes may additionally contain *guesses*, which can be substituted in the scope of the hole.
21The holes are tracked in a *hole queue*, and one of them is *focused*.
22In addition to the goal type, proof term, and holes, the elaborator state contains a collection of unsolved unification problems that can affect elaboration.
24The elaborator state is not directly available to Idris programs.
25Instead, it is modified through the use of *tactics*, which are operations that affect the elaborator state.
26A tactic that returns a value of type ``a``, potentially modifying the elaborator state, has type ``Elab a``.
27The default tactics are all in the namespace ``Language.Reflection.Elab.Tactics``.
30Running Elaborator Scripts
31==========================
33On their own, tactics have no effect.
34The meta-operation ``%runElab script`` runs ``script`` in the current elaboration context.
35For example, the following script constructs the identity function at type ``Nat``:
37.. code-block:: idris
39 idNat : Nat -> Nat
40 idNat = %runElab (do intro (Just (UN "x"))
41 fill (Var (UN "x"))
42 solve)
45On the right-hand side, the Idris elaborator has the goal ``Nat -> Nat``.
46When it encounters the ``%runElab`` directive, it fulfills this goal by running the provided script.
47The first tactic, ``intro``, constructs a lambda that binds the name ``x``.
48The name argument is optional because a default name can be taken from the function type.
49Now, the proof term is of the form ``\x : Nat => {hole}``.
50The second tactic, ``fill``, fills this hole with a guess, giving the term ``\x : Nat => {hole≈x}``.
51Finally, the ``solve`` tactic instantiates the guess, giving the result ``\x : Nat => x``.
53Because elaborator scripts are ordinary Idris expressions, it is also possible to use them in multiple contexts.
54Note that there is nothing ``Nat``-specific about the above script.
55We can generate identity functions at any concrete type using the same script:
57.. code-block:: idris
59 mkId : Elab ()
60 mkId = do intro (Just (UN "x"))
61 fill (Var (UN "x"))
62 solve
64 idNat : Nat -> Nat
65 idNat = %runElab mkId
67 idUnit : () -> ()
68 idUnit = %runElab mkId
70 idString : String -> String
71 idString = %runElab mkId
74Interactively Building Elab Scripts
75===================================
77To build an ``Elab`` script interactively, use the ``:elab`` command at the REPL.
78It takes the name of a hole as an argument.
79To list all available holes, use the command ``:m``.
81In interactive elaboration shell, the following commands are available:
82- ``:q`` - Quits the elaboration shell (gives up on proving current lemma).
83- ``:abandon`` - Same as :q
84- ``:state`` - Displays the current state of the term being constructed.
85- ``:term`` - Displays the current proof term complete with its yet-to-be-filled holes.
86- ``:undo`` - Undoes the last tactic.
87- ``:qed`` - Once the elaboration shell tells you "No more goals," you get to type this in celebration! (Completes the construction and exits the shell)
90Failure
91=======
93Some tactics may *fail*.
94For example, ``intro`` will fail if the focused hole does not have a function type, ``solve`` will fail if the current hole does not contain a guess, and ``fill`` will fail if the term to be filled in has the wrong type.
95Scripts can also fail explicitly using the ``fail`` tactic.
97To account for failure, there is an ``Alternative`` instance for ``Elab``.
98The ``<|>`` operator first tries the script to its left.
99If that script fails, any changes that it made to the state are undone and the right argument is executed.
100If the first argument succeeds, then the second argument is not executed.
102Querying the Elaboration State
103==============================
105``Elab`` includes operations to query the elaboration state, allowing scripts to use information about their environment to steer the elaboration process.
106The ordinary Idris bind syntax can be used to propagate this information.
107For example, a tactic that solves the current goal when it is the unit type might look like this:
109.. code-block:: idris
111 triv : Elab ()
112 triv = do compute
113 g <- getGoal
114 case (snd g) of
115 `(() : Type) => do fill `(() : ())
116 solve
117 otherGoal => fail [ TermPart otherGoal
118 , TextPart "is not trivial"
119 ]
122The tactic ``compute`` normalises the type of its goal with respect to the current context.
123While not strictly necessary, this allows ``triv`` to be used in contexts where the triviality of the goal is not immediately apparent.
124Then, ``getGoal`` is used, and its result is bound to ``g``.
125Because it returns a pair consisting of the current goal's name and type, we case-split on its second projection.
126If the goal type turns out to have been the unit type, we fill using the unit constructor and solve the goal.
127Otherwise, we fail with an error message informing the user that the current goal is not trivial.
129Additionally, the elaboration state can be dumped into an error message with the ``debug`` tactic.
130A variant, ``debugMessage``, allows arbitrary messages to be included with the state, allowing for a kind of "``printf`` debuggging" of elaboration scripts.
131The message format used by ``debugMessage`` is the same for errors produced by the error reflection mechanism, allowing the re-use of the Idris pretty-printer when rendering messages.
133Changing the Global Context
134===========================
136``Elab`` scripts can modify the global context during execution.
137Just as the Idris elaborator produces auxiliary definitions to implement features such as ``where``-blocks and ``case`` expressions, user elaboration scripts may need to define functions.
138Furthermore, this allows ``Elab`` reflection to be used to implement features such as type class deriving.
139The operations ``declareType``, ``defineFunction``, and ``addInstance`` allow ``Elab`` scripts to modify the global context.
141Using Idris's Features
142======================
144The Idris compiler has a number of ways to automate the construction of terms.
145On its own, the ``Elab`` state and its interactions with the unifier allow implicits to be solved using unification.
146Additional operations use further features of Idris.
147In particular, ``resolveTC`` solves the current goal using type class resolution, ``search`` invokes the proof search mechanism, and ``sourceLocation`` finds the context in the original file at which the elaboration script is invoked.
150Recursive Elaboration
151=====================
153The elaboration mechanism can be invoked recursively using the ``runElab`` tactic.
154This tactic takes a goal type and an elaboration script as arguments and runs the script in a fresh lexical environment to create an inhabitant of the provided goal type.
155This is primarily useful for code generation, particularly for generating pattern-matching clauses, where variable scope needs to be one that isn't the present local context.
157Learn More
158==========
159While this documentation is still incomplete, elaboration reflection works in Idris today.
160As you wait for the completion of the documentation, the list of built-in tactics can be obtained using the ``:browse`` command in an Idris REPL or the corresponding feature in one of the graphical IDE clients to explore the ``Language.Reflection.Elab.Tactics`` namespace.
161All of the built-in tactics contain documentation strings.