Debian Codegraph @

folkwisdom.md

raw symbols SCIP
1 The purpose of this document is to document which design heuristics have
2 resulted in tolerable code, and which patterns might be indicative of a dead
3 end. The intent is to document experience (imperical results), not comprehensive
4 truth. For each guideline here, there probably exists some situation where it is
5 best to deviate from the said guideline. Yet incomplete wisdom is better than no
6 wisdom, so let's note down the trade-offs we have faced and how we have resolved
7 them.
8
9 # Data representations
10
11 ## Validity
12
13 ### Obvious validity
14
15 For some data, the obvious simple type can only take meaningful values --
16 a natural number is either zero or the successor of another natural number, and
17 that is all there is to it. This section covers the cases when the choice of
18 correct representation is not obvious.
19
20 ### Validity by a well-engineered simple type structure
21
22 If using a representation where the type only admits semantically valid values
23 would not make the functions that operate that type look horrendous, use that
24 representation. For example, the Coq standard library represents a rational
25 number as a pair of a integer numerator and `positive` denominator, and it works
26 out okay. Fractions with 0 denominator can not be represented because there is
27 no value of type `positive` that would be interpreted as zero.
28
29 On the other hand, an elliptic curve point in Edwards coordinates is informally
30 defined as a pair `(x, y)` s.t. `x^2 + y^2 = 1 + d*x^2*y^2`. It is no longer
31 obvious how one would hack up a simple type that only represents valid points.
32 A solution that gets quite close would be to use "point compression": store `y`
33 and the sign bit of `x`; solve for `x` each time it is needed. Yet this
34 representation is not unique (there are two ways to represent a point with
35 `x=0`), and solving for `x` would clutter all functions that operate on `x` and
36 `y`. Uniqueness can still be restored at the cost of cluttering the functions
37 even more: one could make a type that has three cases `Xpositive`, that takes
38 a `y`, `Xnegative` that takes a `y`, and `Xzero` that represents the point `(0,
39 1)` but does not allow a superfluous y to be specified.
40
41 The alternative is to first write down a type that can represent all valid
42 values and some invalid ones, and then disallow the invalid ones. Sometimes
43 disallowing the invalid values can be circumvented by redefining validity: it
44 may be possible to extend an algorithm that only operates on positive numbers to
45 work with all natural numbers or even all integers. Sometimes the validity
46 condition is crucial: the group law for combining two Edwards curve points is
47 only proven to be associative for points that are on the curve, not for all
48 pairs of numbers.
49
50 ### Validity using dependent types
51
52 If nontrivial data validity invariants are required, the intuitive "value such
53 that" definition can be encoded as a sigma type: `Definition point := { P | let
54 '(x,y) := P in a*x^2 + y^2 = 1 + d*x^2*y^2 }`. In this encoding, every time
55 a value of type `point` is constructed out of the `x` and `y` coordinates,
56 a proof that the point is valid will need to be provided. Code that manipulates
57 point using functions that are already known to return points does not need to
58 deal with the invariant: a value that comes out of a function that returns
59 `point` is valid because wherever it was that the value was constructed from
60 coordinates, a validity proof must have been provided. Using sigma types this
61 way moves proof obligations from one place in the code to another, hopefully
62 more convenient place.
63
64 Dependent types are not a free lunch, we have encountered three types of issues
65 when dealing with them.
66
67 #### Rewriting
68
69 The `rewrite` tactic does not work in equations that construct a point from
70 its coordinates and a proof. This is because after rewriting just the
71 coordinates, the proof would still refer to the old coordinates, and thus the
72 construction would not be valid. It might be possible to make rewriting work by
73 showing an equivalence relation on values such that the invariant does not
74 become invalidated when replacing one equivalent value with another, and the
75 rewrite only changes the value within an equivalence class. It might even be
76 possible to hook this argument with the `setoid_rewrite` tactic to automate it.
77 However, a more lightweight rule has been successful enough to keep us from
78 pursuing that strategy: when non-trivial equational reasoning on the value is
79 required, it can be done separately from the invariant preservation proof. For
80 example, when aiming to implement an optimized `add : point -> point -> point`,
81 first define `add_coordinates : F*F -> F*F -> F*F` that operates on arbitrary
82 pairs of coordinates, do all the rewriting you want, and then define `add` in
83 terms of `add_coordinates`. In analogy to Java's `public` and `private`
84 annotations, users of the Edwards curve `point`s never operate on the
85 coordinates alone, while the implementation of point addition operates on
86 coordinates and proves invariant preservation separately.
87
88 #### Computation inside Coq
89
90 Computing values of a proof-carrying type inside Coq often runs unreasonably
91 long or uses unreasonably much memory. However, computing the coordinates of the
92 same point that itself would take too long to compute seems to work fine. In
93 cases were the evaluation heuristics do not manage to make this okay, rewriting
94 the expression before evaluating it has not been too difficult.
95
96 #### Equality and Equivalence
97
98 Equality and invariant preservation proofs do not play nice by default. Under
99 Leibniz equality, showing that two points with equal coordinates are equal
100 requires showing that the invariant preservation proofs are equal. This can be
101 done using the `UIP_dec` lemma if the invariant itself is an equality and that
102 for all values of coordinates it is decidable to compute whether the invariant
103 holds on them or or not. A principled way of representing an invariant `P : T ->
104 Prop` as an equality is to define `check_P : T -> bool` s.t. `check_P x = true
105 <-> P x` and use `{x | is_true (check_P x) }` as the type of valid values^[This
106 technique is used extensively in `ssreflect`.]. Alternatively, two points can be
107 defined to be equivalent (not equal) if they have the same coordinates (working
108 with custom equivalence relations involves nontrivial considerations of its
109 own).
110
111 #### Note on defining values
112
113 The most reliable way to make a value of a sigma type is to start the
114 `Definition` in proof mode (ending the first line with a dot like `Definition
115 zero : point.`) and then do `refine (exist _ value _); abstract
116 (tacticThatProvesInvariant)`. Another way of doing this is to first do
117 `Obligation Tactic := tacticThatProvesInvariant.` and then `Program Definition
118 zero : point := exist _ value _.` which will call the tactic to fill in the
119 holes that implicit argument inference does not fill. By default, `Program
120 Definition` rewrites all match statements using the convoy pattern, and this can
121 clutter definitions quite badly. Neatness of resulting definitions takes
122 priority over neatness of source code. To prevent `Program Definition` to
123 rewriting a match statement, specify an explicit return clause: `match x return
124 _ with ... end.`
125
126 ## Equivalence
127
128 Terms can be equivalent in different ways. In this list, each kind of equality
129 is stricter than the one right after it.
130
131 - syntactic: they are literally the same expression. Proof automation is
132 sensitive to syntactic changes.
133 - definitional: one term can be transformed into the other by applying rules of
134 computation only. Proof checking considers two syntactically different
135 expressions interchangeable as long as they are definitionally equal.
136 - propositional: as established by a proof (which can use lemmas in addition to
137 rules of computation), these two terms would compute to the exact same vale. It
138 is always possible to rewrite using a propositional equality
139 - custom equivalence relations: for example, two fractions `a/b` and `c/d` can
140 be defined equivalent iff `a*d = b*c`. Given `x == y`, it is possible to rewrite
141 `f(g(x))` to `f(g(y))` if there is some equivalence relation `===` such that the
142 output of `f` does not change when one `===`-equivalent thing is replaced with
143 another, and the output of `g` only changes within a `===`-equivalence class
144 when the input changes within a `==`-equivalence class. This is what `Proper`
145 instances are about; the last statement can be written `Proper((==)=>(===))g`.
146
147 ### Which equivalence to use?
148
149 When defining a datatype from scratch, try to define it in a way that makes
150 propositional equality coincide with the desired notion of equivalence. However,
151 as with sigma types, it is not worth garbling the code itself to use the
152 propositional equality
153
154 When defining a datatype that has a field of a type that is used with a custom
155 equivalence, it is probably a good idea to define the obvious custom equivalence
156 relation for the new type right away (and make an `Equivalence` instance for
157 the relation and `Proper` instances for constructors and projections). When
158 defining a type parametrized over some other type, and it is likely that some
159 use of the parametric type will set the parameter to a type with a custom
160 equivalence relation, define an equivalence relation for the new type,
161 parametrized over an equivalence relation for the parameter type.
162
163 When writing a module that is parametric over a type, require the weakest
164 sufficient equivalence. In particular, if there is a chance that the module will
165 be instantiated with a type whose propositional equivalence makes little sense,
166 it is well worth requiring additional parameters for `Proper` and `Equivalence`
167 (and maybe `Decidable`) instances. See the Algebra library for an example.
168
169 When writing a tactic, specify the form of the input goal format with syntactic
170 precision -- trying to be insensitive to syntactic changes and only require
171 definitional equality can lead to arbitrary amounts of computation and is
172 usually not worth it. One possible exception is the reification-by-typeclasses
173 pattern which has not yet had issues even when it works up to definitional
174 equivalence to the extent typeclass resolution does.
175
176 ### Custom Equivalence Relations and Tactics
177
178 The primary reason for avoiding custom equivalence relations is that the tactic
179 support for them is incomplete and sometimes brittle. This does not mean that
180 custom equivalence relations are useless: battling with a buggy tactic can be
181 bad; reformulating a proof to bypass using custom equivalence relations is often
182 worse. Here are some suggestions.
183
184 1. The number one reason for hitting issues with custom equivalence relations is
185 that either the goal or the givens contain a typo that switched one equivalence
186 relation with another. In particular, `<>` refers to negation of propositional
187 equality by default. This can be avoided with good conventions: when introducing
188 a type that will be used with a custom equivalence relation, introduce the
189 equivalence relation (and its `Equivalence` instance) right away. When
190 introducing a function involving a such type, introduce a `Proper` instance
191 right away. Define local notations for the equivalences used in the file. Note
192 that while introducing the tooling may clutters the source code, section
193 parameters introduced using `Context {x:type}` are required for the definitions
194 in the section only if the definition actually refers to them.
195 2. Use normal `rewrite` by default -- it can deal with custom equivalence
196 relations and `Proper` instances.
197 3. To rewrite under a binder (e.g. `E` in `Let_In x (fun x => E)` or `E` in `map
198 (fun x => E) xs`) use `setoid_rewrite`. However, `setoid_rewrite` tries to be
199 oblivious to definitional equality -- and in doing so, it sometimes goes on
200 a wild goose chase trying to unfold definitions to find something that can be
201 rewritten deep down in the structure. This can cause arbitrary slowdowns and
202 unexpected behavior. To dodge the issues, mark the definitions as `Local Opaque`
203 before the `setoid_rewrite` and re-set to `Local Transparent` after.
204 4. When a `rewrite` fails (probably with an inexplicable error message),
205 double-check that the conventions from (1) are followed correctly. If this does
206 not reveal the issue, try `setoid_rewrite` instead for troubleshooting (it
207 sometimes even gives sensible error messages in Coq 8.5) but revert to `rewrite`
208 once the issue has been found and fixed. If rewriting picks the wrong
209 `Equivalence` or `Proper` instance for some type or function (or fails to find
210 one altogether), troubleshoot that separately: check that `pose proof
211 (_:@Equivalence T equiv)` or `pose proof (_:Proper (equiv1==>equiv2) f)` give
212 the right answer, and if not, `Set Typeclasses Debug` and read the log (which is
213 in the hidden `*coq*` buffer in Proof General). A useful heuristic for reading
214 that log is to look for the first place where the resolution backtracks and then
215 read backwards from there.
216 5. To perform multiple rewrites at once, make rewrite hint database and call
217 `(rewrite_strat topdown hints dbname).` where `topdown` can be replaced
218 with `bottomup` for different behavior. This does not seem to unfold
219 definitions, so it may be a reasonable alternative to using `Local Opaque` to
220 protect definitions from `setoid_rewrite`.
221
222 # Generality and Abstraction
223
224 Coq has ample facilities for abstraction and generality. The main issue we have
225 faced is that undisciplined use of them can clutter definitions even when only
226 the properties of the definitions are to be abstracted. We are not sure that the
227 strategy we are currently working with is optimal (in particular, it results in
228 verbose code), but it definitely dodges some issues other approaches do not. In
229 particular, we want to relate a specific set of types and operations to an
230 abstract structure (e.g., a group) without changing the definitions of any of
231 the type or operations involved. This reduces the interlock between concrete
232 definitions and abstractions and also enables relating the same definitions to
233 an abstract structure in multiple ways (e.g., integers can be a semiring under
234 `+` and `*` or under `max` and `+`). Furthermore, we require that it be possible
235 to manipulate abstractions using tactics.
236
237 To define an abstraction, first open a module with no parameters to make a new
238 namespace for the abstraction (even if the entire file is dedicated to one
239 abstraction). Then open a new section and add to the context parameters for all
240 definitions. The requirements which need to be satisfied by the definitions to
241 fit the structure can be defined using a typeclass record. When a one of the
242 requirements is a typeclass, mark the field name as a `Global Existing Instance`
243 right after declaring the new record. To prove lemmas about everything of that
244 structure, introduce an instance of that typeclass to the context (in additions
245 to the parameters). To relate a specific set of definitions to an abstract
246 structure, create a `Global Instance` of the parametric typeclass for that
247 structure, with the specific definitions filled in. To use a lemma proven about
248 an abstract structure in a specific context, just apply or rewrite using it --
249 typeclass resolution will most likely determine that the specific definitions
250 indeed fit the structure. If not, specify the parameters to lemma manually (a
251 definitive description of what parameters are required and in what form can be
252 seen using `About lemma_name.`).
253
254 Compared to other means of abstraction, this one does not create common notation
255 for all instances of the same structure. We define notations for each specific
256 definition, and separate them using notation scopes (which are often named after
257 datatypes). It would be possible to add a typeclass field that aliases the
258 specific definition and define a global notation for it, but definitions that
259 use that notation would then gain an extra layer of definitions: each underlying
260 operator would be wrapped in the abstract one for which the notation was
261 defined. Furthermore, this interferes with having one definition satisfy the
262 same structure in multiple ways.
263
264 Another alternative is to use the Coq module system (which can be understood by
265 reading the documentation of the Ocaml module system documentation), and when
266 applicable, this is usually a good idea. When parameters are set once and used
267 very many times, the module system can be quite convenient. However, if the
268 number of parameters and the number of places where the values of them are
269 determined are comparable to the number of uses of abstractly proven lemmas, the
270 module system can be cumbersome. Modules cannot be instantiated automatically.
271
272 # Omissions
273
274 Considerations not (yet) covered in this document include the following:
275
276 - structuring proofs: bullets, braces, `Focus` (a la http://poleiro.info/posts/2013-06-27-structuring-proofs-with-bullets.html)
277 - conflicts in notation levels (as resolved by having files import `Util/Notations.v`)
278 - tactic engineering
279 - tactic expression evaluation vs tactic running
280 - how to write tactics that are debuggable
281 - how to write tactics that are robust against small changes
282 - reification: ltac, typeclasses, canonical structures (maybe reference an existing document)
283 - how `intuition` should never be used because it calls `auto with *`, which
284 leads to fragile documents, and `intuition auto` should be used instead
285 - performance of proofs and proof checking
286 - `simpl`, `cbn`, `cbv`
287 - `Qed slowness, `change` vs `rewrite`
288 - which things fail in what ways as terms get big
289 - how to migrate across versions of Coq