]> matita.cs.unibo.it Git - helm.git/blob - helm/papers/matita/matita2.tex
e1d283d6973dff977c54f2e2970c18f7b5cf53e0
[helm.git] / helm / papers / matita / matita2.tex
1 \documentclass[]{kluwer}
2 \usepackage{color}
3 \usepackage{graphicx}
4 \usepackage{hyperref}
5 \usepackage{color}
6 \usepackage{fancyvrb}
7 \usepackage[show]{ed}
8
9 \newcommand{\component}{component}
10 \newcommand{\components}{components}
11
12 \newcommand{\AUTO}{\textsc{Auto}}
13 \newcommand{\BOXML}{BoxML}
14 \newcommand{\COQ}{Coq}
15 \newcommand{\COQIDE}{CoqIde}
16 \newcommand{\ELIM}{\textsc{Elim}}
17 \newcommand{\GDOME}{Gdome}
18 \newcommand{\GTKMATHVIEW}{\textsc{GtkMathView}}
19 \newcommand{\HELM}{Helm}
20 \newcommand{\HINT}{\textsc{Hint}}
21 \newcommand{\IN}{\ensuremath{\dN}}
22 \newcommand{\INSTANCE}{\textsc{Instance}}
23 \newcommand{\IR}{\ensuremath{\dR}}
24 \newcommand{\IZ}{\ensuremath{\dZ}}
25 \newcommand{\LIBXSLT}{LibXSLT}
26 \newcommand{\LOCATE}{\textsc{Locate}}
27 \newcommand{\MATCH}{\textsc{Match}}
28 \newcommand{\MATHML}{MathML}
29 \newcommand{\MATITA}{Matita}
30 \newcommand{\MATITAC}{\texttt{matitac}}
31 \newcommand{\MATITADEP}{\texttt{matitadep}}
32 \newcommand{\MOWGLI}{MoWGLI}
33 \newcommand{\NAT}{\ensuremath{\mathit{nat}}}
34 \newcommand{\NATIND}{\mathit{nat\_ind}}
35 \newcommand{\NUPRL}{NuPRL}
36 \newcommand{\OCAML}{OCaml}
37 \newcommand{\PROP}{\mathit{Prop}}
38 \newcommand{\REF}[3]{\ensuremath{\mathit{Ref}_{#1}(#2,#3)}}
39 \newcommand{\REWRITEHINT}{\textsc{RewriteHint}}
40 \newcommand{\TEXMACRO}[1]{\texttt{\char92 #1}}
41 \newcommand{\UWOBO}{UWOBO}
42 \newcommand{\GETTER}{Getter}
43 \newcommand{\WHELP}{Whelp}
44
45 \newcommand{\DOT}{\ensuremath{\mbox{\textbf{.}}}}
46 \newcommand{\SEMICOLON}{\ensuremath{\mbox{\textbf{;}}}}
47 \newcommand{\BRANCH}{\ensuremath{\mbox{\textbf{[}}}}
48 \newcommand{\SHIFT}{\ensuremath{\mbox{\textbf{\textbar}}}}
49 \newcommand{\POS}[1]{\ensuremath{#1\mbox{\textbf{:}}}}
50 \newcommand{\MERGE}{\ensuremath{\mbox{\textbf{]}}}}
51 \newcommand{\FOCUS}[1]{\ensuremath{\mathtt{focus}~#1}}
52 \newcommand{\UNFOCUS}{\ensuremath{\mathtt{unfocus}}}
53 \newcommand{\SKIP}{\MATHTT{skip}}
54 \newcommand{\TACTIC}[1]{\ensuremath{\mathtt{tactic}~#1}}
55
56 \newcommand{\NT}[1]{\ensuremath{\langle\mathit{#1}\rangle}}
57 \newcommand{\URI}[1]{\texttt{#1}}
58 \newcommand{\OP}[1]{``\texttt{#1}''}
59 \newcommand{\FILE}[1]{\texttt{#1}}
60 \newcommand{\NOTE}[1]{\ednote{#1}{}}
61 \newcommand{\TODO}[1]{\textbf{TODO: #1}}
62
63 \definecolor{gray}{gray}{0.85} % 1 -> white; 0 -> black
64
65 \newenvironment{grafite}{\VerbatimEnvironment
66  \begin{SaveVerbatim}{boxtmp}}%
67  {\end{SaveVerbatim}\setlength{\fboxsep}{3mm}%
68   \begin{center}
69    \fcolorbox{black}{gray}{\BUseVerbatim[boxwidth=0.9\linewidth]{boxtmp}}
70   \end{center}}
71
72 \newcounter{pass}
73 \newcommand{\PASS}{\stepcounter{pass}\arabic{pass}}
74
75 \newsavebox{\tmpxyz}
76 \newcommand{\sequent}[2]{
77   \savebox{\tmpxyz}[0.9\linewidth]{
78     \begin{minipage}{0.9\linewidth}
79       \ensuremath{#1} \\
80       \rule{3cm}{0.03cm}\\
81       \ensuremath{#2}
82     \end{minipage}}\setlength{\fboxsep}{3mm}%
83   \begin{center}
84    \fcolorbox{black}{gray}{\usebox{\tmpxyz}}
85   \end{center}}
86
87 \bibliographystyle{alpha}
88
89 \begin{document}
90
91 \begin{opening}
92  \title{The \MATITA{} Proof Assistant}
93
94  \author{Andrea \surname{Asperti} \email{asperti@cs.unibo.it}}
95  \author{Claudio \surname{Sacerdoti Coen} \email{sacerdot@cs.unibo.it}}
96  \author{Enrico \surname{Tassi} \email{tassi@cs.unibo.it}}
97  \author{Stefano \surname{Zacchiroli} \email{zacchiro@cs.unibo.it}}
98
99  \institute{Department of Computer Science, University of Bologna\\
100  Mura Anteo Zamboni, 7 --- 40127 Bologna, ITALY}
101
102  \runningtitle{The \MATITA{} proof assistant}
103  \runningauthor{Asperti, Sacerdoti Coen, Tassi, Zacchiroli}
104
105  \begin{motto}
106   ``We are nearly bug-free'' -- \emph{CSC, Oct 2005}
107  \end{motto}
108
109  \begin{abstract}
110   \TODO{scrivere abstract}
111  \end{abstract}
112
113  \keywords{Proof Assistant, Mathematical Knowledge Management, XML, Authoring,
114  Digital Libraries}
115 \end{opening}
116
117 % toc & co: to be removed in the final paper version
118 \tableofcontents
119 \listoffigures
120 \listoftables
121
122 \section{Introduction}
123 \label{sec:intro}
124
125 \MATITA{} is the Proof Assistant under development by the \HELM{}
126 team~\cite{mkm-helm} at the University of Bologna, under the direction of
127 Prof.~Asperti. The paper describes the overall architecture of
128 the system, focusing on its most distinctive and innovative 
129 features.
130
131 \subsection{Historical perspective}
132 The origins of \MATITA{} go back to 1999. At the time we were mostly 
133 interested to develop tools and techniques to enhance the accessibility
134 via Web of formal libraries of mathematics. Due to its dimension, the
135 library of the \COQ~\cite{CoqManual} proof assistant (of the order of 35'000 theorems) 
136 was chosen as a privileged test bench for our work, although experiments
137 have been also conducted with other systems, and notably 
138 with \NUPRL~\cite{nuprl-book}.
139 The work, mostly performed in the framework of the recently concluded 
140 European project IST-33562 \MOWGLI~\cite{pechino}, mainly consisted in the 
141 following steps:
142 \begin{itemize}
143 \item exporting the information from the internal representation of
144  \COQ{} to a system and platform independent format. Since XML was at the 
145 time an emerging standard, we naturally adopted this technology, fostering
146 a content-centric architecture~\cite{content-centric} where the documents
147 of the library were the the main components around which everything else 
148 has to be build;
149 \item developing indexing and searching techniques supporting semantic
150  queries to the library; 
151 \item developing languages and tools for a high-quality notational 
152 rendering of mathematical information\footnote{We have been 
153 active in the \MATHML{} Working group since 1999.}; 
154 \end{itemize}
155
156 According to our content-centric commitment, the library exported from
157 \COQ{} was conceived as being distributed and most of the tools were developed
158 as Web services. The user could interact with the library and the tools by
159 means of a Web interface that orchestrates the Web services.
160
161 The Web services and the other tools have been implemented as front-ends
162 to a set of software components, collectively called the \HELM{} components.
163 At the end of the \MOWGLI{} project we already disposed of the following
164 tools and software components:
165 \begin{itemize}
166 \item XML specifications for the Calculus of Inductive Constructions,
167 with components for parsing and saving mathematical objects in such a
168 format~\cite{exportation-module};
169 \item metadata specifications with components for indexing and querying the
170 XML knowledge base;
171 \item a proof checker library (i.e. the {\em kernel} of a proof assistant), 
172 implemented to check that we exported from the \COQ{} library all the 
173 logically relevant content;
174 \item a sophisticated parser (used by the search engine), able to deal 
175 with potentially ambiguous and incomplete information, typical of the 
176 mathematical notation~\cite{disambiguation};
177 \item a {\em refiner} library, i.e. a type inference system, based on
178 partially specified terms, used by the disambiguating parser;
179 \item complex transformation algorithms for proof rendering in natural
180 language~\cite{remathematization};
181 \item an innovative, \MATHML-compliant rendering widget for the GTK 
182 graphical environment~\cite{padovani}, supporting 
183 high-quality bidimensional
184 rendering, and semantic selection, i.e. the possibility to select semantically
185 meaningful rendering expressions, and to paste the respective content into
186 a different text area.
187 \end{itemize}
188 Starting from all this, developing our own proof assistant was not
189 too far away: essentially, we ``just'' had to
190 add an authoring interface, and a set of functionalities for the
191 overall management of the library, integrating everything into a
192 single system. \MATITA{} is the result of this effort. 
193
194 \subsection{The system}
195
196 \MATITA{} is a proof assistant (also called interactive theorem prover).
197 It is based on the Calculus of (Co)Inductive Constructions
198 (CIC)~\cite{Werner} that is a dependently typed lambda-calculus \`a la
199 Church enriched with primitive inductive and co-inductive data types.
200 Via the Curry-Howard isomorphism, the calculus can be seen as a very
201 rich higher order logic and proofs can be simply represented and
202 stored as lambda-terms. \COQ{} and Lego are other systems that adopt
203 (variations of) CIC as their foundation.
204
205 The proof language of \MATITA{} is procedural, in the tradition of the LCF
206 theorem prover. \COQ, \NUPRL, PVS, Isabelle are all examples of others systems
207 whose proof language is procedural. Traditionally, in a procedural system
208 the user interacts only with the \emph{script}, while proof terms are internal
209 records kept by the system. On the contrary, in \MATITA{} proof terms are
210 praised as declarative versions of the proof. With this role, they are the
211 primary mean of communication of proofs (once rendered to natural language
212 for human audiences).
213
214 The user interfaces now adopted by all the proof assistants based on a
215 procedural proof language have been inspired by the CtCoq pioneering
216 system~\cite{ctcoq1}. One successful incarnation of the ideas introduced
217 by CtCoq is the Proof General generic interface~\cite{proofgeneral},
218 that has set a sort of
219 standard way to interact with the system. Several procedural proof assistants
220 have either adopted or cloned Proof General as their main user interface.
221 The authoring interface of \MATITA{} is a clone of the Proof General interface.
222
223 \TODO{item che seguono:}
224 \begin{itemize}
225  \item sistema indipendente (da \COQ)
226  \item compatibilit\`a con sistemi legacy
227 \end{itemize}
228
229 \subsection{Relationship with \COQ{}}
230
231 At first sight, \MATITA{} looks as (and partly is) a \COQ{} clone. This is
232 more the effect of the circumstances of its creation described 
233 above than the result of a deliberate design. In particular, we
234 (essentially) share the same foundational dialect of \COQ{} (the
235 Calculus of (Co)Inductive Constructions), the same implementation
236 language (\OCAML{}), and the same (script based) authoring philosophy.
237 However, the analogy essentially stops here and no code is shared by the
238 two systems.
239
240 In a sense, we like to think of \MATITA{} as the way \COQ{} would 
241 look like if entirely rewritten from scratch: just to give an
242 idea, although \MATITA{} currently supports almost all functionalities of
243 \COQ{}, it links 60'000 lines of \OCAML{} code, against the 166'000 lines linked
244 by \COQ{} (and we are convinced that, starting from scratch again,
245 we could reduce our code even further in sensible way).
246
247 Moreover, the complexity of the code of \MATITA{} is greatly reduced with
248 respect to \COQ. For instance, the API of the components of \MATITA{} comprise
249 989 functions, to be compared with the 4'286 functions of \COQ.
250
251 Finally, \MATITA{} has several innovative features over \COQ{} that derive
252 from the integration of Mathematical Knowledge Management tools with proof
253 assistants. Among them, the advanced indexing tools over the library and
254 the parser for ambiguous mathematical notation.
255
256 The size and complexity improvements over \COQ{} must be understood
257 historically. \COQ{} is a quite old
258 system whose development started 20 years ago. Since then
259 several developers have took over the code and several new research ideas
260 that were not considered in the original architecture have been experimented
261 and integrated in the system. Moreover, there exists a lot of developments
262 for \COQ{} that require backward compatibility between each pair of releases;
263 since many central functionalities of a proof assistant are based on heuristics
264 or arbitrary choices to overcome undecidability (e.g. for higher order
265 unification), changing these functionalities maintaining backward compatibility
266 is very difficult. Finally, the code of \COQ{} has been greatly optimized
267 over the years; optimization reduces maintainability and rises the complexity
268 of the code.
269
270 In writing \MATITA{} we have not been hindered by backward compatibility and
271 we have took advantage of the research results and experiences previously
272 developed by others, comprising the authors of \COQ. Moreover, starting from
273 scratch, we have designed in advance the architecture and we have split
274 the code in coherent minimally coupled components.
275
276 In the future we plan to exploit \MATITA{} as a test bench for new ideas and
277 extensions. Keeping the single components and the whole architecture as
278 simple as possible is thus crucial to foster future experiments and to
279 allow other developers to quickly understand our code and contribute.
280
281 %For direct experience of the authors, the learning curve to understand and
282 %be able to contribute to \COQ{}'s code is quite steep and requires direct
283 %and frequent interactions with \COQ{} developers.
284
285 \section{Architecture}
286 \label{architettura}
287
288 \begin{figure}[!ht]
289  \begin{center}
290   \includegraphics[width=0.9\textwidth,height=0.8\textheight]{pics/libraries-clusters}
291   \caption[\MATITA{} components and related applications]{\MATITA{}
292    components and related applications, with thousands of line of
293    codes (klocs)\strut}
294   \label{fig:libraries}
295  \end{center}
296 \end{figure}
297
298 Fig.~\ref{fig:libraries} shows the architecture of the \emph{\components}
299 (circle nodes) and \emph{applications} (squared nodes) developed in the HELM
300 project. Each node is annotated with the number of lines of source code
301 (comprising comments).
302
303 Applications and \components{} depend over other \components{} forming a
304 directed acyclic graph (DAG). Each \component{} can be decomposed in
305 a a set of \emph{modules} also forming a DAG.
306
307 Modules and \components{} provide coherent sets of functionalities
308 at different scales. Applications that require only a few functionalities
309 depend on a restricted set of \components{}.
310
311 Only the proof assistant \MATITA{} and the \WHELP{} search engine are
312 applications meant to be used directly by the user. All the other applications
313 are Web services developed in the HELM and MoWGLI projects and already described
314 elsewhere. In particular:
315 \begin{itemize}
316  \item The \emph{\GETTER} is a Web service to retrieve an (XML) document
317    from a physical location (URL) given its logical name (URI). The Getter is
318    responsible of updating a table that maps URIs to URLs. Thanks to the Getter
319    it is possible to work on a logically monolithic library that is physically
320    distributed on the network. More information on the Getter can be found
321    in~\cite{zack-master}.
322  \item \emph{\WHELP} is a search engine to index and locate mathematical
323    notions (axioms, theorems, definitions) in the logical library managed
324    by the Getter. Typical examples of a query to Whelp are queries that search
325    for a theorem that generalize or instantiate a given formula, or that
326    can be immediately applied to prove a given goal. The output of Whelp is
327    an XML document that lists the URIs of a complete set of candidates that
328    are likely to satisfy the given query. The set is complete in the sense
329    that no notion that actually satisfies the query is thrown away. However,
330    the query is only approximated in the sense that false matches can be
331    returned. Whelp has been described in~\cite{whelp}.
332  \item \emph{\UWOBO} is a Web service that, given the URI of a mathematical
333    notion in the distributed library, renders it according to the user provided
334    two dimensional mathematical notation. \UWOBO{} may also embed the rendering
335    of mathematical notions into arbitrary documents before returning them.
336    The Getter is used by \UWOBO{} to retrieve the document to be rendered.
337    \UWOBO{} has been described in~\cite{zack-master}.
338  \item The \emph{Proof Checker} is a Web service that, given the URI of
339    notion in the distributed library, checks its correctness. Since the notion
340    is likely to depend in an acyclic way over other notions, the proof checker
341    is also responsible of building in a top-down way the DAG of all
342    dependencies, checking in turn every notion for correctness.
343    The proof checker has been described in~\cite{zack-master}.
344  \item The \emph{Dependency Analyzer} is a Web service that can produce
345    a textual or graphical representation of the dependencies of an object.
346    The dependency analyzer has been described in~\cite{zack-master}.
347 \end{itemize}
348
349 The dependency of a \component{} or application over another \component{} can
350 be satisfied by linking the \component{} in the same executable.
351 For those \components{} whose functionalities are also provided by the
352 aforementioned Web services, it is also possible to link stub code that
353 forwards the request to a remote Web service. For instance, the Getter
354 is just a wrapper to the \GETTER{} \component{} that allows the
355 \component{} to be used as a Web service. \MATITA{} can directly link the code
356 of the \GETTER{} \component, or it can use a stub library with the same
357 API that forwards every request to the Getter.
358
359 To better understand the architecture of \MATITA{} and the role of each
360 \component, we can focus on the representation of the mathematical information.
361 \MATITA{} is based on (a variant of) the Calculus of (Co)Inductive
362 Constructions (CIC). In CIC terms are used to represent mathematical
363 formulae, types and proofs. \MATITA{} is able to handle terms at
364 four different levels of specification. On each level it is possible to provide
365 a different set of functionalities. The four different levels are:
366 fully specified terms; partially specified terms; 
367 content level terms; presentation level terms.
368
369 \subsection{Fully specified terms}
370 \label{sec:fullyintro}
371
372  \emph{Fully specified terms} are CIC terms where no information is
373    missing or left implicit. A fully specified term should be well-typed.
374    The mathematical notions (axioms, definitions, theorems) that are stored
375    in our mathematical library are fully specified and well-typed terms.
376    Fully specified terms are extremely verbose (to make type-checking
377    decidable). Their syntax is fixed and does not resemble the usual
378    extendible mathematical notation. They are not meant for direct user
379    consumption.
380
381    The \texttt{cic} \component{} defines the data type that represents CIC terms
382    and provides a parser for terms stored in an XML format.
383
384    The most important \component{} that deals with fully specified terms is
385    \texttt{cic\_proof\_checking}. It implements the procedure that verifies
386    if a fully specified term is well-typed. It also implements the
387    \emph{conversion} judgement that verifies if two given terms are
388    computationally equivalent (i.e. they share the same normal form).
389
390    Terms may reference other mathematical notions in the library.
391    One commitment of our project is that the library should be physically
392    distributed. The \GETTER{} \component{} manages the distribution,
393    providing a mapping from logical names (URIs) to the physical location
394    of a notion (an URL). The \texttt{urimanager} \component{} provides the URI
395    data type and several utility functions over URIs. The
396    \texttt{cic\_proof\_checking} \component{} calls the \GETTER{}
397    \component{} every time it needs to retrieve the definition of a mathematical
398    notion referenced by a term that is being type-checked. 
399
400    The Proof Checker is the Web service that provides an interface
401    to the \texttt{cic\_proof\_checking} \component.
402
403    We use metadata and a sort of crawler to index the mathematical notions
404    in the distributed library. We are interested in retrieving a notion
405    by matching, instantiation or generalization of a user or system provided
406    mathematical formula. Thus we need to collect metadata over the fully
407    specified terms and to store the metadata in some kind of (relational)
408    database for later usage. The \texttt{hmysql} \component{} provides
409    a simplified
410    interface to a (possibly remote) MySql database system used to store the
411    metadata. The \texttt{metadata} \component{} defines the data type of the
412    metadata
413    we are collecting and the functions that extracts the metadata from the
414    mathematical notions (the main functionality of the crawler).
415    The \texttt{whelp} \component{} implements a search engine that performs
416    approximated queries by matching/instantiation/generalization. The queries
417    operate only on the metadata and do not involve any actual matching
418    (that will be described later on and that is implemented in the
419     \texttt{cic\_unification} \component). Not performing any actual matching
420    the query only returns a complete and hopefully small set of matching
421    candidates. The process that has issued the query is responsible of
422    actually retrieving from the distributed library the candidates to prune
423    out false matches if interested in doing so.
424
425    The Whelp search engine is the Web service that provides an interface to
426    the \texttt{whelp} \component.
427
428    According to our vision, the library is developed collaboratively so that
429    changing or removing a notion can invalidate other notions in the library.
430    Moreover, changing or removing a notion requires a corresponding change
431    in the metadata database. The \texttt{library} \component{} is responsible
432    of preserving the coherence of the library and the database. For instance,
433    when a notion is removed, all the notions that depend on it and their
434    metadata are removed from the library. This aspect will be better detailed
435    in Sect.~\ref{sec:libmanagement}.
436    
437 \subsection{Partially specified terms}
438 \label{sec:partiallyintro}
439
440 \emph{Partially specified terms} are CIC terms where subterms can be omitted.
441 Omitted subterms can bear no information at all or they may be associated to
442 a sequent. The formers are called \emph{implicit terms} and they occur only
443 linearly. The latters may occur multiple times and are called
444 \emph{metavariables}. An \emph{explicit substitution} is applied to each
445 occurrence of a metavariable. A metavariable stand for a term whose type is
446 given by the conclusion of the sequent. The term must be closed in the
447 context that is given by the ordered list of hypotheses of the sequent.
448 The explicit substitution instantiates every hypothesis with an actual
449 value for the variable bound by the hypothesis.
450
451 Partially specified terms are not required to be well-typed. However a
452 partially specified term should be \emph{refinable}. A \emph{refiner} is
453 a type-inference procedure that can instantiate implicit terms and
454 metavariables and that can introduce \emph{implicit coercions} to make a
455 partially specified term well-typed. The refiner of \MATITA{} is implemented
456 in the \texttt{cic\_unification} \component. As the type checker is based on
457 the conversion check, the refiner is based on \emph{unification} that is
458 a procedure that makes two partially specified term convertible by instantiating
459 as few as possible metavariables that occur in them.
460
461 Since terms are used in CIC to represent proofs, correct incomplete
462 proofs are represented by refinable partially specified terms. The metavariables
463 that occur in the proof correspond to the conjectures still to be proved.
464 The sequent associated to the metavariable is the conjecture the user needs to
465 prove.
466
467 \emph{Tactics} are the procedures that the user can apply to progress in the
468 proof. A tactic proves a conjecture possibly creating new (and hopefully
469 simpler) conjectures. The implementation of tactics is given in the
470 \texttt{tactics} \component. It is heavily based on the refinement and
471 unification procedures of the \texttt{cic\_unification} \component.
472
473 The \texttt{grafite} \component{} defines the abstract syntax tree (AST) for the
474 commands of the \MATITA{} proof assistant. Most of the commands are tactics.
475 Other commands are used to give definitions and axioms or to state theorems
476 and lemmas. The \texttt{grafite\_engine} \component{} is the core of \MATITA{}.
477 It implements the semantics of each command in the grafite AST as a function
478 from status to status.  It implements also an undo function to go back to
479 previous statuses.
480
481 As fully specified terms, partially specified terms are not well suited
482 for user consumption since their syntax is not extendible and it is not
483 possible to adopt the usual mathematical notation. However they are already
484 an improvement over fully specified terms since they allow to omit redundant
485 information that can be inferred by the refiner.
486
487 \subsection{Content level terms}
488 \label{sec:contentintro}
489
490 The language used to communicate proofs and especially formulae with the
491 user does not only needs to be extendible and accommodate the usual mathematical
492 notation. It must also reflect the comfortable degree of imprecision and
493 ambiguity that the mathematical language provides.
494
495 For instance, it is common practice in mathematics to speak of a generic
496 equality that can be used to compare any two terms. However, it is well known
497 that several equalities can be distinguished as soon as we care for decidability
498 or for their computational properties. For instance equality over real
499 numbers is well known to be undecidable, whereas it is decidable over
500 rational numbers.
501
502 Similarly, we usually speak of natural numbers and their operations and
503 properties without caring about their representation. However the computational
504 properties of addition over the binary representation are very different from
505 those of addition over the unary representation. And addition over two natural
506 numbers is definitely different from addition over two real numbers.
507
508 Formal mathematics cannot hide these differences and obliges the user to be
509 very precise on the types he is using and their representation. However,
510 to communicate formulae with the user and with external tools, it seems good
511 practice to stick to the usual imprecise mathematical ontology. In the
512 Mathematical Knowledge Management community this imprecise language is called
513 the \emph{content level} representation of formulae.
514
515 In \MATITA{} we provide two translations: from partially specified terms
516 to content level terms and the other way around. The first translation can also
517 be applied to fully specified terms since a fully specified term is a special
518 case of partially specified term where no metavariable or implicit term occurs.
519
520 The translation from partially specified terms to content level terms must
521 discriminate between terms used to represent proofs and terms used to represent
522 formulae. The firsts are translated to a content level representation of
523 proof steps that can in turn easily be rendered in natural language
524 using techniques inspired by~\cite{natural,YANNTHESIS}. The representation
525 adopted has greatly influenced the OMDoc~\cite{omdoc} proof format that is now
526 isomorphic to it. Terms that represent formulae are translated to \MATHML{}
527 Content formulae. \MATHML{} Content~\cite{mathml} is a W3C standard
528 for the representation of content level formulae in an XML extensible format.
529
530 The translation to content level is implemented in the
531 \texttt{acic\_content} \component. Its input are \emph{annotated partially
532 specified terms}, that are maximally unshared
533 partially specified terms enriched with additional typing information for each
534 subterm. This information is used to discriminate between terms that represent
535 proofs and terms that represent formulae. Part of it is also stored at the
536 content level since it is required to generate the natural language rendering
537 of proofs. The terms need to be maximally unshared (i.e. they must be a tree
538 and not a DAG). The reason is that to the occurrences of a subterm in
539 two different positions we need to associate different typing informations.
540 This association is made easier when the term is represented as a tree since
541 it is possible to label each node with an unique identifier and associate
542 the typing information using a map on the identifiers.
543 The \texttt{cic\_acic} \component{} unshares and annotates terms. It is used
544 by the \texttt{library} \component{} since fully specified terms are stored
545 in the library in their annotated form.
546
547 We do not provide yet a reverse translation from content level proofs to
548 partially specified terms. But in \texttt{cic\_disambiguation} we do provide
549 the reverse translation for formulae. The mapping from
550 content level formulae to partially specified terms is not unique due to
551 the ambiguity of the content level. As a consequence the translation
552 is guided by an \emph{interpretation}, that is a function that chooses for
553 every ambiguous formula one partially specified term. The
554 \texttt{cic\_disambiguation} \component{} implements the
555 disambiguation algorithm we presented in~\cite{disambiguation} that is
556 responsible of building in an efficient way the set of all ``correct''
557 interpretations. An interpretation is correct if the partially specified term
558 obtained using the interpretation is refinable.
559
560 In Sect.~\ref{sec:partiallyintro} the last section we described the semantics of
561 a command as a
562 function from status to status. We also suggested that the formulae in a
563 command are encoded as partially specified terms. However, consider the
564 command ``\texttt{replace} $x$ \texttt{with} $y^2$''. Until the occurrence
565 of $x$ to be replaced is located, its context is unknown. Since $y^2$ must
566 replace $x$ in that context, its encoding as a term cannot be computed
567 until $x$ is located. In other words, $y^2$ must be disambiguated in the
568 context of the occurrence $x$ it must replace.
569
570 The elegant solution we have implemented consists in representing terms
571 in a command as functions from a context to a partially refined term. The
572 function is obtained by partially applying our disambiguation function to
573 the content term to be disambiguated. Our solution should be compared with
574 the one adopted in the \COQ{} system, where ambiguity is only relative to
575 De Brujin indexes.
576 In \COQ{} variables can be bound either by name or by position. A term
577 occurring in a command has all its variables bound by name to avoid the need of
578 a context during disambiguation.  Moreover, this makes more complex every
579 operation over terms (i.e. according to our architecture every module that
580 depends on \texttt{cic}) since the code must deal consistently with both kinds
581 of binding. Also, this solution cannot cope with other forms of ambiguity (as
582 the context dependent meaning of the exponent in the previous example).
583
584 \subsection{Presentation level terms}
585 \label{sec:presentationintro}
586
587 Content level terms are a sort of abstract syntax trees for mathematical
588 formulae and proofs. The concrete syntax given to these abstract trees
589 is called \emph{presentation level}.
590
591 The main important difference between the content level language and the
592 presentation level language is that only the former is extendible. Indeed,
593 the presentation level language is a finite language that comprises all
594 the usual mathematical symbols. Mathematicians invent new notions every
595 single day, but they stick to a set of symbols that is more or less fixed.
596
597 The fact that the presentation language is finite allows the definition of
598 standard languages. In particular, for formulae we have adopt \MATHML{}
599 Presentation~\cite{mathml} that is an XML dialect standardized by the W3C. To
600 visually
601 represent proofs it is enough to embed formulae in plain text enriched with
602 formatting boxes. Since the language of formatting boxes is very simple,
603 many equivalent specifications exist and we have adopted our own, called
604 \BOXML.
605
606 The \texttt{content\_pres} \component{} contains the implementation of the
607 translation from content level terms to presentation level terms. The
608 rendering of presentation level terms is left to the application that uses
609 the \component. However, in the \texttt{hgdome} \component{} we provide a few
610 utility functions to build a \GDOME~\cite{gdome2} \MATHML+\BOXML{} tree from our
611 presentation
612 level terms. \GDOME{} \MATHML+\BOXML{} trees can be rendered by the
613 \GTKMATHVIEW{}
614 widget developed by Luca Padovani~\cite{padovani}. The widget is
615 particularly interesting since it allows to implement \emph{semantic
616 selection}.
617
618 Semantic selection is a technique that consists in enriching the presentation
619 level terms with pointers to the content level terms and to the partially
620 specified terms they correspond to. Highlight of formulae in the widget is
621 constrained to selection of meaningful expressions, i.e. expressions that
622 correspond to a lower level term, that is a content term or a partially or
623 fully specified term.
624 Once the rendering of a lower level term is
625 selected it is possible for the application to retrieve the pointer to the
626 lower level term. An example of applications of semantic selection is
627 \emph{semantic cut\&paste}: the user can select an expression and paste it
628 elsewhere preserving its semantics (i.e. the partially specified term),
629 possibly performing some semantic transformation over it (e.g. renaming
630 variables that would be captured or lambda-lifting free variables).
631
632 The reverse translation from presentation level terms to content level terms
633 is implemented by a parser that is also found in \texttt{content\_pres}.
634 Differently from the translation from content level terms to partially
635 refined terms, this translation is not ambiguous. The reason is that the
636 parsing tool we have adopted (CamlP4) is not able to parse ambiguous
637 grammars. Thus we require the mapping from presentation level terms
638 (concrete syntax) to content level terms (abstract syntax) to be unique.
639 This means that the user must fix once and for all the associativity and
640 precedence level of every operator he is using. In practice this limitation
641 does not seem too strong. The reason is that the target of the
642 translation is an ambiguous language and the user is free to associate
643 to every content level term several different interpretations (as a
644 partially specified term).
645
646 Both the direct and reverse translation from presentation to content level
647 terms are parameterized over the user provided mathematical notation. 
648 The \texttt{lexicon} \component{} is responsible of managing the lexicon,
649 that is the set of active notations. It defines an abstract syntax tree
650 of commands to declare and activate new notations and it implements the
651 semantics of these commands. It also implements undoing of the semantic
652 actions. Among the commands there are hints to the
653 disambiguation algorithm that are used to control and speed up disambiguation.
654 These mechanisms will be further discussed in Sect.~\ref{sec:disambiguation}.
655
656 Finally, the \texttt{grafite\_parser} \component{} implements a parser for
657 the concrete syntax of the commands of \MATITA. The parser process a stream
658 of characters and returns a stream of abstract syntax trees (the ones
659 defined by the \texttt{grafite} component and whose semantics is given
660 by \texttt{grafite\_engine}). When the parser meets a command that changes
661 the lexicon, it invokes the \texttt{lexicon} \component{} to immediately
662 process the command. When the parser needs to parse a term at the presentation
663 level, it invokes the already described parser for terms contained in
664 \texttt{content\_pres}.
665
666 The \MATITA{} proof assistant and the \WHELP{} search engine are both linked
667 against the \texttt{grafite\_parser} \components{}
668 since they provide an interface to the user. In both cases the formulae
669 written by the user are parsed using the \texttt{content\_pres} \component{} and
670 then disambiguated using the \texttt{cic\_disambiguation} \component.  However,
671 only \MATITA{} is linked against the \texttt{grafite\_engine} and
672 \texttt{tactics} components (summing up to a total of 11'200 lines of code)
673 since \WHELP{} can only execute those ASTs that correspond to queries
674 (implemented in the \texttt{whelp} component).
675
676 The \UWOBO{} Web service wraps the \texttt{content\_pres} \component,
677 providing a rendering service for the documents in the distributed library.
678 To render a document given its URI, \UWOBO{} retrieves it using the
679 \GETTER{} obtaining a document with fully specified terms. Then it translates
680 it to the presentation level passing through the content level. Finally
681 it returns the result document to be rendered by the user's
682 browser.\NOTE{\TODO{manca la passata verso HTML}}
683
684 The \components{} not yet described (\texttt{extlib}, \texttt{xml},
685 \texttt{logger}, \texttt{registry} and \texttt{utf8\_macros}) are 
686 minor \components{} that provide a core of useful functions and basic
687 services missing from the standard library of the programming language.
688 %In particular, the \texttt{xml} \component{} is used to easily represent,
689 %parse and pretty-print XML files.
690
691 \section{The interface to the library}
692 \label{sec:library}
693
694 A proof assistant provides both an interface to interact with its library and
695 an \emph{authoring} interface to develop new proofs and theories. According
696 to its historical origins, \MATITA{} strives to provide innovative
697 functionalities for the interaction with the library. It is more traditional
698 in its script based authoring interface.
699
700 In the remaining part of the paper we focus on the user view of \MATITA{}.
701 This section is devoted to the aspects of the tool that arise from the
702 document centric approach to the library. Sect.~\ref{sec:authoring} describes
703 the peculiarities of the authoring interface.
704
705 The library of \MATITA{} comprises mathematical concepts (theorems,
706 axioms, definitions) and notation. The concepts are authored sequentially
707 using scripts that are (ordered) sequences of procedural commands.
708 However, once they are produced we store them independently in the library.
709 The only relation implicitly kept between the notions are the logical,
710 acyclic dependencies among them. This way the library forms a global (and
711 distributed) hypertext.
712
713 \begin{figure}[!ht]
714  \begin{center}
715   \includegraphics[width=0.40\textwidth]{pics/cicbrowser-screenshot-browsing}
716   \hspace{0.05\textwidth}
717   \includegraphics[width=0.40\textwidth]{pics/cicbrowser-screenshot-query}
718   \caption{Browsing and searching the library\strut}
719   \label{fig:cicbrowser1}
720  \end{center}
721 \end{figure}
722
723 \begin{figure}[!ht]
724  \begin{center}
725   \includegraphics[width=0.70\textwidth]{pics/cicbrowser-screenshot-con}
726   \caption[Natural language rendering]{Natural language rendering of a theorem
727   from the library\strut}
728   \label{fig:cicbrowser2}
729  \end{center}
730 \end{figure}
731
732 Several useful operations can be implemented on the library only,
733 regardless of the scripts. For instance, searching and browsing is
734 implemented by the ``cicBrowser'' window available from the \MATITA{}
735 GUI. Using it, the hierarchical structure of the library can be
736 explored (on the left of Fig.~\ref{fig:cicbrowser1}), the natural
737 language rendering of proofs can be inspected
738 (Fig.~\ref{fig:cicbrowser2}), and content based searches on the
739 library can be performed (on the right of Fig.~\ref{fig:cicbrowser1}).
740 Available content based searches are described in
741 Sect.~\ref{sec:indexing}.  Other examples of library operations are
742 disambiguation of content level terms (see
743 Sect.~\ref{sec:disambiguation}) and automatic proof searching (see
744 Sect.~\ref{sec:automation}).
745
746 The key requisite for the previous operations is that the library must
747 be fully accessible and in a logically consistent state. To preserve
748 consistency, a concept cannot be altered or removed unless the part of the
749 library that depends on it is modified accordingly. To allow incremental
750 changes and cooperative development, consistent revisions are necessary.
751 For instance, to modify a definition, the user could fork a new version
752 of the library where the definition is updated and all the concepts that
753 used to rely on it are absent. The user is then responsible to restore
754 the removed part in the new branch, merging the branch when the library is
755 fully restored.
756
757 To implement the proposed versioning system on top of a standard one
758 it is necessary to implement \emph{invalidation} first. Invalidation
759 is the operation that locates and removes from the library all the concepts
760 that depend on a given one. As described in Sect.~\ref{sec:libmanagement} removing
761 a concept from the library also involves deleting its metadata from the
762 database.
763
764 For non collaborative development, full versioning can be avoided, but
765 invalidation is still required. Since nobody else is relying on the
766 user development, the user is free to change and invalidate part of the library
767 without branching. Invalidation is still necessary to avoid using a
768 concept that is no longer valid.
769 So far, in \MATITA{} we address only this non collaborative scenario
770 (see Sect.~\ref{sec:libmanagement}). Collaborative development and versioning
771 is still under design.
772
773 Scripts are not seen as constituents of the library. They are not published
774 and indexed, so they cannot be searched or browsed using \HELM{} tools.
775 However, they play a central role for the maintenance of the library.
776 Indeed, once a notion is invalidated, the only way to restore it is to
777 fix the possibly broken script that used to generate it.
778 Moreover, during the authoring phase, scripts are a natural way to
779 group notions together. They also constitute a less fine grained clustering
780 of notions for invalidation.
781
782 In the rest of this section we present in more details the functionalities of
783 \MATITA{} related to library management and exploitation.
784 Sect.~\ref{sec:authoring} is devoted to the description of the peculiarities of
785 the \MATITA{} authoring interface.
786
787 \subsection{Indexing and searching}
788 \label{sec:indexing}
789
790 The \MATITA{} system is first of all an interface between the user and
791 the mathematical repository. For this reason, it is important to be
792 able to search and retrieve mathematical notions in a quick and 
793 effective way, assuming as little knowledge as possible about the 
794 library. To this aim, \MATITA{} uses a sophisticated indexing mechanism
795 for mathemtical items, based on a reach metadata set that has been 
796 tuned along the European Project IST-2001-33562 MoWGLI. The metadata
797 set, and the searching facilites built on top of them --- collected 
798 in the so called \WHELP{} search engine --- have been
799 extensively described in~\cite{whelp}. Let us just recall here that
800 the \WHELP{} metadata model is essentially based a single ternary relation 
801 \REF{p}{s}{t} stating that an object $s$ refers an object $t$ at a
802  given position $p$, where the position specify the place of the 
803 occurrence of $t$ inside $s$ (we currently work with a fixed set of 
804 positions, discriminating, the hypothesis form the conclusion and
805 outermost form innermost occurrences). This approach is extremely 
806 flexible, since extending the set of positions 
807 we may improve the granularity and the precision of our indexing technique,
808 with no additional architectural impact.
809
810 Every time a new mathematical object is created and saved by the user it gets 
811 indexed, and becomes immediately visible in the library. Several 
812 interesting and innovative features of \MATITA{} described in the following
813 sections rely in a direct or indirect way on its metadata system and
814 the searching features. Here, we shall just recall some of its most
815 direct applications.
816
817 A first, very simple but not negligeable feature is the check for duplicates.
818 As soon as a new statement is defined, and before proving it, 
819 the library is searched 
820 to check that no other equivalent statement has been already proved
821 (based on the pattern matching functionality of \WHELP); if this is the case,
822 a warning is raised to the user. At present, the notion of equivalence 
823 adopted by \MATITA{} is convertibility, but we may imagine to weaken it 
824 in the future, covering for instance isomorphisms.    
825
826 Another usefull \WHELP{} operation is \HINT; we may invoke this query
827 at any moment during the development of a proof, resulting in the list
828 of all theorems of the library which can be applied to the current
829 goal. In practice, this is mostly used not really to discover what theorems
830 can be applied to a given goal, but to actually retrieve a theorem that 
831 we wish to apply, but whose name we have forgotten.
832 In fact, even if \MATITA{} adopts a semi-rigid naming convention for 
833 statements \ref{sec:naming} that greatly simplifies the effort of recalling
834 names, the naming discipline remains one of the most
835 annoying aspects of formal developments, and the hint feature provides
836 a very friendly solution.
837 In the near feature, we expect to extend the \HINT{} operation to
838 a \REWRITEHINT, resulting in all equational statements that
839 can be applied to rewrite the current goal.
840
841 \subsection{Disambiguation}
842 \label{sec:disambiguation}
843
844 Software applications that involve input of mathematical content should strive
845 to require the user as less drift from informal mathematics as possible. We
846 believe this to be a fundamental aspect of such applications user interfaces.
847 Being that drift in general very large when inputing
848 proofs~\cite{debrujinfactor}, in \MATITA{} we achieved good results for
849 mathematical formulae which can be input using a \TeX-like encoding (the
850 concrete syntax corresponding to presentation level terms) and are then
851 translated (in multiple steps) to partially specified terms as sketched in
852 Sect.~\ref{sec:contentintro}.
853
854 The key component of the translation is the generic disambiguation algorithm
855 implemented in the \texttt{disambiguation} component of Fig.~\ref{fig:libraries}
856 and presented in~\cite{disambiguation}. In this section we present how to use
857 that algorithm in the context of the development of a library of formalized
858 mathematics. We will see that using multiple passes of the algorithm, varying
859 some of its parameters, helps in keeping the input terse without sacrificing
860 expressiveness.
861
862 \subsubsection{Disambiguation aliases}
863 \label{sec:disambaliases}
864
865 Consider the following command to state a theorem over integer numbers:
866
867 \begin{grafite}
868 theorem Zlt_compat:
869   \forall x, y, z. x < y \to y < z \to x < z.
870 \end{grafite}
871
872 The symbol \OP{<} is likely to be overloaded in the library
873 (at least over natural numbers). 
874 Thus, according to the disambiguation algorithm, two different
875 refinable partially specified terms could be associated to it.
876 \MATITA{} asks the user what interpretation he meant. However, to avoid
877 posing the same question in case of a future re-execution (e.g. undo/redo),
878 the choice must be recorded. Since scripts need to be re-executed after
879 invalidation, the choice record must be permanently stored somewhere. The most
880 natural place is in the script itself.
881
882 In \MATITA{} disambiguation is governed by \emph{disambiguation aliases}.
883 They are mappings, stored in the library, from ambiguity sources
884 (identifiers, symbols and literal numbers at the content level) to partially
885 specified terms. In case of overloaded sources there exists multiple aliases
886 with the same source. It is possible to record \emph{disambiguation
887 preferences} to select one of the aliases of an overloaded source.
888
889 Preferences can be explicitely given in the script (using the
890 misleading \texttt{alias} commands), but
891 are also implicitly added when a new concept is introduced (\emph{implicit
892 preferences}) or after a sucessfull disambiguation that did not require
893 user interaction. Explicit preferences are added automatically by \MATITA{} to
894 record the disambiguation choices of the user. For instance, after the
895 disambiguation of the command above, the script is altered as follows:
896
897 \begin{grafite}
898 alias symbol "lt" = "integer 'less than'".
899 theorem Zlt_compat:
900   \forall x, y, z. x < y \to y < z \to x < z.
901 \end{grafite}
902
903 The ``alias'' command in the example sets the preferred alias for the
904 \OP{lt} symbol.
905
906 Implicit preferences for new concepts are set since a concept just defined is
907 likely to be the preferred one in the rest of the script. Implicit preferences
908 learned from disambiguation of previous commands grant the coherence of
909 the disambiguation in the rest of the script and speed up disambiguation
910 reducing the search space.
911
912 Disambiguation preferences are included in the lexicon status
913 (see Sect.~\ref{sec:presentationintro}) that is part of the authoring interface
914 status.  Unlike aliases, they are not part of the library.
915
916 When starting a new authoring session the set of disambiguation preferences
917 is empty. Until it contains a preference for each overloaded symbol to be
918 used in the script, the user can be faced with questions from the disambiguator.
919 To reduce the likelyhood of user interactions, we introduced
920 the \texttt{include} command. With \texttt{include} it is possible to import
921 at once in the current session the set of preferences that was in effect
922 at the end of the execution of a given script.
923
924 Preferences can be changed. For instance, at the start of the development
925 of integer numbers the preference for the symbol \OP{<} is likely
926 to be the one over natural numbers; sooner or later it will be set to the one
927 over integer numbers.
928
929 Nothing forbids the set of preferences to become incoherent. For this reason
930 the disambiguator cannot always respect the user preferences.
931 Consider, for example:
932 \begin{grafite}
933 theorem Zlt_mono:
934   \forall x, y, k. x < y \to x < y + k.
935 \end{grafite}
936
937 No refinable partially specified term corresponds to the preferences:
938 \OP{+} over natural numbers, \OP{<} over integer numbers. To overcome this
939 limitation we organized disambiguation in \emph{multiple passes}: when the
940 disambiguator fails, disambiguation is tried again with a less strict set of
941 preferences.
942
943 Several disambiguation parameters can vary among passes. With respect to
944 preference handling we implemented three passes.  In the first pass, called
945 \emph{mono-preferences}, we consider only the aliases corresponding to the
946 current preferences.  In the second pass, called \emph{multi-preferences}, we
947 consider every alias corresponding to a current or past preference.  For
948 instance, in the example above disambiguation succeeds in the multi-preference
949 pass. In the third pass, called \emph{library-preferences}, all aliases
950 available in the library are considered.
951
952 \TODO{rivedere questo periodo\ldots}
953 The rationale behind this choice is trying to respect user preferences in early
954 passes that complete quickly in case of failure; later passes are slower but
955 have more chances of success.
956
957 \subsubsection{Operator instances}
958 \label{sec:disambinstances}
959
960 Consider now the following theorem:
961 \begin{grafite}
962 theorem lt_to_Zlt_pos_pos:
963   \forall n, m: nat. n < m \to pos n < pos m. 
964 \end{grafite}
965 and assume that there exist in the library aliases for \OP{<} over natural
966 numbers and over integer numbers. None of the passes described above is able to
967 disambiguate \texttt{lt\_to\_Zlt\_pos\_pos}, no matter how preferences are set.
968 This is because the \OP{<} operator occurs twice in the content level term (it
969 has two \emph{instances}) and two different interpretations for it have to be
970 used in order to obtain a refinable partially specified term.
971
972 To address this issue, we have the ability to consider each instance of a single
973 symbol as a different ambiguous expression in the content level term, and thus
974 we can use a different alias for each of them. Exploiting or not this feature is
975 one of the disambiguation pass parameters. A disambiguation pass which exploit
976 it is said to be using \emph{fresh instances} (opposed to a \emph{shared
977 instances} pass).
978
979 Fresh instances lead to a non negligible performance loss (since the choice of
980 an alias for one instances does not constraint the choice of the others). For
981 this reason we always attempt a fresh instances pass only after attempting a
982 non-fresh one.
983
984 \paragraph{One-shot preferences} Disambiguation preferecens as seen so far are
985 instance-independent. However, implicit preferences obtained as a result of a
986 disambiguation pass which uses fresh instances ought to be instance-dependent.
987 Informally, the set of preferences that can be satisfied by the disambiguator on
988 the theorem above is: ``the first instance of the \OP{<} symbol is over natural
989 numbers, while the second is on integer numbers''.
990
991 Instance-depend preferences are meaningful only for the term whose
992 disambiguation generated it. For this reason we call them \emph{one-shot
993 preferences} and \MATITA{} does not use them to disambiguate further terms in
994 the script.
995
996 \subsubsection{Implicit coercions}
997 \label{sec:disambcoercions}
998
999 Consider the following theorem about derivation:
1000 \begin{grafite}
1001 theorem power_deriv:
1002   \forall n: nat, x: R. d x ^ n dx = n * x ^ (n - 1).
1003 \end{grafite}
1004 and assume that in the library there is an alias mapping \OP{\^} to a partially
1005 specified term having type: \texttt{R \TEXMACRO{to} nat \TEXMACRO{to} R}. In
1006 order to disambiguate \texttt{power\_deriv}, the occurrence of \texttt{n} on the
1007 right hand side of the equality need to be ``injected'' from \texttt{nat} to
1008 \texttt{R}.  The refiner of \MATITA{} supports \emph{implicit coercions} for
1009 this reason: given as input the above presentation level term, it will return a
1010 partially specified term where in place of \texttt{n} the application of a
1011 coercion from \texttt{nat} to \texttt{R} appears (assuming such a coercion has
1012 been defined in advance).
1013
1014 Coercions are not always desirable. For example, in disambiguating
1015 \texttt{\TEXMACRO{forall} x: nat. n < n + 1} we do not want the term which uses
1016 two coercions from \texttt{nat} to \texttt{R} around \OP{<} arguments to show up
1017 among the possible partially specified term choices. For this reason we always
1018 attempt a disambiguation pass which require the refiner not to use the coercions
1019 before attempting a coercion-enabled pass.
1020
1021 The choice of whether implicit coercions are enabled or not interact with the
1022 choice about operator instances. Indeed, consider again
1023 \texttt{lt\_to\_Zlt\_pos\_pos}, which can be disambiguated using fresh operator
1024 instances. In case there exists a coercion from natural numbers to (positive)
1025 integers (which indeed does, it is the \texttt{pos} constructor itself), the
1026 theorem can be disambiguated using twice that coercion on the left hand side of
1027 the implication. The obtained partially specified term however would not
1028 probably be the expected one, being a theorem which prove a trivial implication.
1029 For this reason we choose to always prefer fresh instances over implicit
1030 coercions, i.e.  we always attempt disambiguation passes with fresh instances
1031 and no implicit coercions before attempting passes with implicit coercions.
1032
1033 \subsubsection{Disambiguation passes}
1034 \label{sec:disambpasses}
1035
1036 According to the criteria described above in \MATITA{} we choose to perform the
1037 sequence of disambiguation passes depicted in Tab.~\ref{tab:disambpasses}. In
1038 our experience that choice gives reasonable performance and minimize the need of
1039 user interaction during the disambiguation.
1040
1041 \begin{table}[ht]
1042  \caption{Disambiguation passes sequence\strut}
1043  \label{tab:disambpasses} 
1044  \begin{center}
1045   \begin{tabular}{c|c|c|c}
1046    \multicolumn{1}{p{1.5cm}|}{\centering\raisebox{-1.5ex}{\textbf{Pass}}}
1047    & \multicolumn{1}{p{3.1cm}|}{\centering\textbf{Preferences}}
1048    & \multicolumn{1}{p{2.5cm}|}{\centering\textbf{Operator instances}}
1049    & \multicolumn{1}{p{2.5cm}}{\centering\textbf{Implicit coercions}} \\
1050    \hline
1051    \PASS & Mono-preferences     & Shared instances  & Disabled \\
1052    \PASS & Multi-preferences    & Shared instances  & Disabled \\
1053    \PASS & Mono-preferences     & Fresh instances   & Disabled \\
1054    \PASS & Multi-preferences    & Fresh instances   & Disabled \\
1055    \PASS & Mono-preferences     & Fresh instances   & Enabled  \\
1056    \PASS & Multi-preferences    & Fresh instances   & Enabled  \\
1057    \PASS & Library-preferences  & Fresh instances   & Enabled
1058   \end{tabular}
1059  \end{center}
1060 \end{table}
1061
1062 \subsection{Generation and invalidation}
1063 \label{sec:libmanagement}
1064
1065 The aim of this section is to describe the way \MATITA{} 
1066 preserves the consistency and the availability of the library
1067 using the \WHELP{} technology, in response to the user alteration or 
1068 removal of mathematical objects.
1069
1070 As already sketched in Sect.~\ref{sec:fullyintro} what we generate 
1071 from a script is split among two storage media, a
1072 classical filesystem and a relational database. The former is used to
1073 store the XML encoding of the objects defined in the script, the
1074 disambiguation aliases and the interpretation and notational convention defined,
1075 while the latter is used to store all the metadata needed by
1076 \WHELP{}.
1077
1078 While the consistency of the data store in the two media has
1079 nothing to do with the nature of
1080 the content of the library and is thus uninteresting (but really
1081 tedious to implement and keep bug-free), there is a deeper
1082 notion of mathematical consistency we need to provide. Each object
1083 must reference only defined object (i.e. each proof must use only
1084 already proved theorems). 
1085
1086 We will focus on how \MATITA{} ensures the interesting kind
1087 of consistency during the formalization of a mathematical theory, 
1088 giving the user the freedom of adding, removing, modifying objects
1089 without loosing the feeling of an always visible and browsable
1090 library.
1091
1092 \subsubsection{Compilation}
1093
1094 The typechecker component guarantees that if an object is well typed
1095 it depends only on well typed objects available in the library,
1096 that is exactly what we need to be sure that the logic consistency of
1097 the library is preserved. We have only to find the right order of
1098 compilation of the scripts that compose the user development.
1099
1100 For this purpose we provide a tool called \MATITADEP{}
1101 that takes in input the list of files that compose the development and
1102 outputs their dependencies in a format suitable for the GNU \texttt{make} tool.
1103 The user is not asked to run \MATITADEP{} by hand, but
1104 simply to tell \MATITA{} the root directory of his development (where all
1105 script files can be found) and \MATITA{} will handle all the compilation
1106 related tasks, including dependencies calculation.
1107 To compute dependencies it is enough to look at the script files for
1108 inclusions of other parts of the development or for explicit
1109 references to other objects (i.e. with explicit aliases, see
1110 \ref{sec:disambaliases}). 
1111
1112 The output of the compilation is immediately available to the user
1113 trough the \WHELP{} technology, since all metadata are stored in a
1114 user-specific area of the database where the search engine has read
1115 access, and all the automated tactics that operates on the whole
1116 library, like \AUTO, have full visibility of the newly defined objects.
1117
1118 Compilation is rather simple, and the only tricky case is when we want
1119 to compile again the same script, maybe after the removal of a
1120 theorem. Here the policy is simple: clean the output before recompiling.
1121 As we will see in the next section cleaning will ensure that
1122 there will be no theorems in the development that depends on the
1123 removed items.
1124
1125 \subsubsection{Cleaning}
1126
1127 With the term ``cleaning'' we mean the process of removing all the
1128 results of an object compilation. In order to keep the consistency of
1129 the library, cleaning an object requires the (recursive) cleaning
1130 of all the objects that depend on it (\emph{reverse dependencies}).
1131
1132 The calculation of the reverse dependencies can be computed in two
1133 ways, using the relational database or using a simpler set of metadata
1134 that \MATITA{} saves in the filesystem as a result of compilation. The
1135 former technique is the same used by the \emph{Dependency Analyzer}
1136 described in~\cite{zack-master} and really depends on a relational
1137 database.
1138
1139 The latter is a fall-back in case the database is not
1140 available.\footnote{Due to the complex deployment of a large piece of
1141 software like a database, it is a common practice for the \HELM{} team
1142 to use a shared remote database, that may be unavailable if the user
1143 workstation lacks network connectivity.} This facility has to be
1144 intended only as a fall-back, since the queries of the \WHELP{}
1145 technology depend require a working database.
1146
1147 Cleaning guarantees that if an object is removed there are no dandling
1148 references to it, and that the part of the library still compiled is
1149 consistent. Since cleaning involves the removal of all the results of
1150 the compilation, metadata included, the library browsable trough the
1151 \WHELP{} technology is always kept up to date.
1152
1153 \subsubsection{Batch vs Interactive}
1154
1155 \MATITA{} includes an interactive authoring interface and a batch
1156 ``compiler'' (\MATITAC). Only the former is intended to be used directly by the
1157 user, the latter is automatically invoked when a
1158 part of the user development is required (for example issuing an
1159 \texttt{include} command) but not yet compiled.
1160
1161 While they share the same engine for compilation and cleaning, they
1162 provide different granularity. The batch compiler is only able to
1163 compile a whole script and similarly to clean only a whole script
1164 (together with all the other scripts that rely on an object defined in
1165 it). The interactive interface is able to execute single steps of
1166 compilation, that may include the definition of an object, and
1167 similarly to undo single steps. Note that in the latter case there is
1168 no risk of introducing dangling references since the \MATITA{} user
1169 interface inhibit undoing a step which is not the last executed.
1170
1171 \subsection{Automation}
1172 \label{sec:automation}
1173
1174 \TODO{sezione sull'automazione}
1175
1176 \subsection{Naming convention}
1177 \label{sec:naming}
1178
1179 A minor but not entirely negligible aspect of \MATITA{} is that of
1180 adopting a (semi)-rigid naming convention for identifiers, derived by 
1181 our studies about metadata for statements. 
1182 The convention is only applied to identifiers for theorems 
1183 (not definitions), and relates the name of a proof to its statement.
1184 The basic rules are the following:
1185 \begin{itemize}
1186 \item each identifier is composed by an ordered list of (short)
1187 names occurring in a left to right traversal of the statement; 
1188 \item all identifiers should (but this is not strictly compulsory) 
1189 separated by an underscore,
1190 \item identifiers in two different hypothesis, or in an hypothesis
1191 and in the conclusion must be separated by the string ``\verb+_to_+'';
1192 \item the identifier may be followed by a numerical suffix, or a
1193 single or double apostrophe.
1194
1195 \end{itemize}
1196 Take for instance the theorem
1197 \[\forall n:nat. n = plus \; n\; O\]
1198 Possible legal names are: \verb+plus_n_O+, \verb+plus_O+, 
1199 \verb+eq_n_plus_n_O+ and so on. 
1200 Similarly, consider the theorem 
1201 \[\forall n,m:nat. n<m \to n \leq m\]
1202 In this case \verb+lt_to_le+ is a legal name, 
1203 while \verb+lt_le+ is not.\\
1204 But what about, say, the symmetric law of equality? Probably you would like 
1205 to name such a theorem with something explicitly recalling symmetry.
1206 The correct approach, 
1207 in this case, is the following. You should start with defining the 
1208 symmetric property for relations
1209
1210 \[definition\;symmetric\;= \lambda A:Type.\lambda R.\forall x,y:A.R x y \to R y x \]
1211
1212 Then, you may state the symmetry of equality as
1213 \[ \forall A:Type. symmetric \;A\;(eq \; A)\]
1214 and \verb+symmetric_eq+ is valid \MATITA{} name for such a theorem. 
1215 So, somehow unexpectedly, the introduction of semi-rigid naming convention
1216 has an important beneficial effect on the global organization of the library, 
1217 forcing the user to define abstract notions and properties before 
1218 using them (and formalizing such use).
1219
1220 Two cases have a special treatment. The first one concerns theorems whose
1221 conclusion is a (universally quantified) predicate variable, i.e. 
1222 theorems of the shape
1223 $\forall P,\dots.P(t)$.
1224 In this case you may replace the conclusion with the word
1225 ``elim'' or ``case''.
1226 For instance the name \verb+nat_elim2+ is a legal name for the double
1227 induction principle.
1228
1229 The other special case is that of statements whose conclusion is a
1230 match expression. 
1231 A typical example is the following
1232 \begin{verbatim}
1233   \forall n,m:nat. 
1234       match (eqb n m) with
1235         [ true  \Rightarrow n = m 
1236         | false \Rightarrow n \neq m]
1237 \end{verbatim}
1238 where $eqb$ is boolean equality.
1239 In this cases, the name can be build starting from the matched
1240 expression and the suffix \verb+_to_Prop+. In the above example, 
1241 \verb+eqb_to_Prop+ is accepted. 
1242
1243 \section{The authoring interface}
1244 \label{sec:authoring}
1245
1246 The authoring interface of \MATITA{} is very similar to Proof General.  We
1247 chose not to build the \MATITA{} UI over Proof General for two reasons. First
1248 of all we wanted to integrate our XML-based rendering technologies, mainly
1249 \GTKMATHVIEW{}.  At the time of writing Proof General supports only text based
1250 rendering.\footnote{This may change with the future release of Proof General
1251 based on Eclipse, but is not yet the case.} The second reason is that we wanted
1252 to build the \MATITA{} UI on top of a state-of-the-art and widespread toolkit
1253 as GTK is.
1254
1255 Fig.~\ref{fig:screenshot} is a screenshot of the \MATITA{} authoring interface,
1256 featuring two windows. The background one is very like to the Proof General
1257 interface. The main difference is that we use the \GTKMATHVIEW{} widget to
1258 render sequents. Since \GTKMATHVIEW{} renders \MATHML{} markup we take
1259 advantage of the whole bidimensional mathematical notation. The foreground
1260 window is an instance of the cicBrowser used to render the proof being
1261 developed.
1262
1263 Note that the syntax used in the script view is \TeX-like, however Unicode is 
1264 fully supported so that mathematical glyphs can be input as such.
1265
1266 \begin{figure}[!ht]
1267  \begin{center}
1268   \includegraphics[width=0.95\textwidth]{pics/matita-screenshot}
1269   \caption{\MATITA{} look and feel\strut}
1270   \label{fig:screenshot}
1271  \end{center}
1272 \end{figure}
1273
1274 Since the concepts of script based proof authoring are well-known, the
1275 remaining part of this section is dedicated to the distinguishing
1276 features of the \MATITA{} authoring interface.
1277
1278 \subsection{Direct manipulation of terms}
1279 \label{sec:directmanip}
1280
1281 While terms are input as \TeX-like formulae in \MATITA, they are converted to a
1282 mixed \MATHML+\BOXML{} markup for output purposes and then rendered by
1283 \GTKMATHVIEW. As described in~\cite{latexmathml} this mixed choice enables both
1284 high-quality bidimensional rendering of terms (including the use of fancy
1285 layout schemata like radicals and matrices) and the use of a
1286 concise and widespread textual syntax.
1287
1288 Keeping pointers from the presentations level terms down to the
1289 partially specified ones \MATITA{} enable direct manipulation of
1290 rendered (sub)terms in the form of hyperlinks and semantic selection.
1291
1292 \emph{Hyperlinks} have anchors on the occurrences of constant and
1293 inductive type constructors and point to the corresponding definitions
1294 in the library. Anchors are available notwithstanding the use of
1295 user-defined mathematical notation: as can be seen on the right of
1296 Fig.~\ref{fig:directmanip}, where we clicked on $\not|$, symbols
1297 encoding complex notations retain all the hyperlinks of constants or
1298 constructors used in the notation.
1299
1300 \emph{Semantic selection} enables the selection of mixed
1301 \MATHML+\BOXML{} markup, constraining the selection to markup
1302 representing meaningful CIC (sub)terms. In the example on the left of
1303 Fig.~\ref{fig:directmanip} is thus possible to select the subterm
1304 $\mathrm{prime}~n$, whereas it would not be possible to select
1305 $\to n$ since the former denotes an application while the
1306 latter it not a subterm. Once a meaningful (sub)term has been
1307 selected actions can be done on it like reductions or tactic
1308 applications.
1309
1310 \begin{figure}[!ht]
1311  \begin{center}
1312   \includegraphics[width=0.40\textwidth]{pics/matita-screenshot-selection}
1313   \hspace{0.05\textwidth}
1314   \raisebox{0.4cm}{\includegraphics[width=0.50\textwidth]{pics/matita-screenshot-href}}
1315   \caption[Semantic selection and hyperlinks]{Semantic selection (on the left)
1316   and hyperlinks (on the right)\strut}
1317   \label{fig:directmanip}
1318  \end{center}
1319 \end{figure}
1320
1321 \subsection{Patterns}
1322 \label{sec:patterns}
1323
1324 In several situations working with direct manipulation of terms is 
1325 simpler and faster than typing the corresponding textual 
1326 commands~\cite{proof-by-pointing}.
1327 Nonetheless we need to record actions and selections in scripts.
1328
1329 In \MATITA{} \emph{patterns} are textual representations of selections.
1330 Users can select using the GUI and then ask the system to paste the
1331 corresponding pattern in this script, but more often this process is
1332 transparent: once an action is performed on a selection, the corresponding
1333 textual command is computed and inserted in the script.
1334
1335 \subsubsection{Pattern syntax}
1336
1337 Patterns are composed of two parts: \NT{sequent\_path} and
1338 \NT{wanted}; their concrete syntax is reported in Tab.~\ref{tab:pathsyn}.
1339
1340 \NT{sequent\_path} mocks-up a sequent, discharging unwanted subterms
1341 with $?$ and selecting the interesting parts with the placeholder
1342 $\%$.  \NT{wanted} is a term that lives in the context of the
1343 placeholders.
1344
1345 Textual patterns produced from a graphical selection are made of the
1346 \NT{sequent\_path} only. Such patterns can represent every selection,
1347 but are quite verbose. The \NT{wanted} part of the syntax is meant to
1348 help the users in writing concise and elegant patterns by hand.
1349
1350 \begin{table}
1351  \caption{Patterns concrete syntax\strut}
1352  \label{tab:pathsyn}
1353 \hrule
1354 \[
1355 \begin{array}{@{}rcll@{}}
1356   \NT{pattern} & 
1357     ::= & [~\verb+in+~\NT{sequent\_path}~]~[~\verb+match+~\NT{wanted}~] & \\
1358   \NT{sequent\_path} & 
1359     ::= & \{~\NT{ident}~[~\verb+:+~\NT{multipath}~]~\}~
1360       [~\verb+\vdash+~\NT{multipath}~] & \\
1361   \NT{multipath} & ::= & \NT{term\_with\_placeholders} & \\
1362   \NT{wanted} & ::= & \NT{term} & \\
1363 \end{array}
1364 \]
1365 \hrule
1366 \end{table}
1367
1368 \subsubsection{Pattern evaluation}
1369
1370 Patterns are evaluated in two phases. The first selects roots
1371 (subterms) of the sequent, using the $\NT{sequent\_path}$,  while the
1372 second searches the $\NT{wanted}$ term starting from these roots.
1373 % Both are optional steps, and by convention the empty pattern selects
1374 % the whole conclusion.
1375
1376 \begin{description}
1377 \item[Phase 1]
1378   concerns only the $[~\verb+in+~\NT{sequent\_path}~]$
1379   part of the syntax. $\NT{ident}$ is an hypothesis name and
1380   selects the assumption where the following optional $\NT{multipath}$
1381   will operate. \verb+\vdash+ can be considered the name for the goal.
1382   If the whole pattern is omitted, the whole goal will be selected.
1383   If one or more hypotheses names are given the selection is restricted to 
1384   these assumptions. If a $\NT{multipath}$ is omitted the whole
1385   assumption is selected. Remember that the user can be mostly
1386   unaware of this syntax, since the system is able to write down a 
1387   $\NT{sequent\_path}$ starting from a visual selection.
1388   \NOTE{Questo ancora non va in matita}
1389
1390   A $\NT{multipath}$ is a CIC term in which a special constant $\%$
1391   is allowed.
1392   The roots of discharged subterms are marked with $?$, while $\%$
1393   is used to select roots. The default $\NT{multipath}$, the one that
1394   selects the whole term, is simply $\%$.
1395   Valid $\NT{multipath}$ are, for example, $(?~\%~?)$ or $\%~\verb+\to+~(\%~?)$
1396   that respectively select the first argument of an application or
1397   the source of an arrow and the head of the application that is
1398   found in the arrow target.
1399
1400   The first phase not only selects terms (roots of subterms) but
1401   determines also their context that will be eventually used in the
1402   second phase.
1403
1404 \item[Phase 2] 
1405   plays a role only if the $[~\verb+match+~\NT{wanted}~]$
1406   part is specified. From the first phase we have some terms, that we
1407   will see as subterm roots, and their context. For each of these
1408   contexts the $\NT{wanted}$ term is disambiguated in it and the
1409   corresponding root is searched for a subterm that can be unified to
1410   $\NT{wanted}$. The result of this search is the selection the
1411   pattern represents.
1412
1413 \end{description}
1414
1415 \subsubsection{Examples}
1416 %To explain how the first phase works let us give an example. Consider
1417 %you want to prove the uniqueness of the identity element $0$ for natural
1418 %sum, and that you can rely on the previously demonstrated left
1419 %injectivity of the sum, that is $inj\_plus\_l:\forall x,y,z.x+y=z+y \to x =z$.
1420 %Typing
1421 %\begin{grafite}
1422 %theorem valid_name: \forall n,m. m + n = n \to m = O.
1423 %  intros (n m H).
1424 %\end{grafite}
1425 %\noindent
1426 Consider the following sequent 
1427 \sequent{
1428 n:nat\\
1429 m:nat\\
1430 H: m + n = n}{
1431 m=O
1432 }
1433 \noindent
1434 To change the right part of the equivalence of the $H$
1435 hypothesis with $O + n$ the user selects and pastes it as the pattern
1436 in the following statement.
1437 \begin{grafite}
1438   change in H:(? ? ? %) with (O + n).
1439 \end{grafite}
1440 \noindent
1441 To understand the pattern (or produce it by hand) the user should be
1442 aware that the notation $m+n=n$ hides the term $(eq~nat~(m+n)~n)$, so
1443 that the pattern selects only the third argument of $eq$.
1444
1445 The experienced user may also write by hand a concise pattern
1446 to change at once all the occurrences of $n$ in the hypothesis $H$:
1447 \begin{grafite}
1448   change in H match n with (O + n).
1449 \end{grafite}
1450 \noindent
1451 In this case the $\NT{sequent\_path}$ selects the whole $H$, while
1452 the second phase locates $n$.
1453
1454 The latter pattern is equivalent to the following one, that the system
1455 can automatically generate from the selection.
1456 \begin{grafite}
1457   change in H:(? ? (? ? %) %) with (O + n).
1458 \end{grafite}
1459 \noindent
1460
1461 \subsubsection{Tactics supporting patterns}
1462
1463 \TODO{mergiare con il successivo facendo notare che i patterns sono una
1464 interfaccia comune per le tattiche}
1465
1466 In \MATITA{} all the tactics that can be restricted to subterm of the working
1467 sequent accept the pattern syntax. In particular these tactics are: simplify,
1468 change, fold, unfold, generalize, replace and rewrite.
1469
1470 \NOTE{attualmente rewrite e fold non supportano phase 2. per
1471 supportarlo bisogna far loro trasformare il pattern phase1+phase2 
1472 in un pattern phase1only come faccio nell'ultimo esempio. lo si fa
1473 con una pattern\_of(select(pattern))}
1474
1475 \subsubsection{Comparison with \COQ{}}
1476
1477 \COQ{} has two different ways of restricting the application of tactics to
1478 subterms of the sequent, both relaying on the same special syntax to identify
1479 a term occurrence.
1480
1481 The first way is to use this special syntax to tell the
1482 tactic what occurrences of a wanted term should be affected.
1483 The second is to prepare the sequent with another tactic called
1484 pattern and then apply the real tactic. Note that the choice is not
1485 left to the user, since some tactics needs the sequent to be prepared
1486 with pattern and do not accept directly this special syntax.
1487
1488 The base idea is that to identify a subterm of the sequent we can
1489 write it and say that we want, for example, the third and the fifth
1490 occurrences of it (counting from left to right). In our previous example,
1491 to change only the left part of the equivalence, the correct command
1492 is:
1493
1494 \begin{grafite}
1495   change n at 2 in H with (O + n)
1496 \end{grafite} 
1497
1498 meaning that in the hypothesis $H$ the $n$ we want to change is the
1499 second we encounter proceeding from left to right.
1500
1501 The tactic pattern computes a
1502 $\beta$-expansion of a part of the sequent with respect to some
1503 occurrences of the given term. In the previous example the following
1504 command:
1505 \begin{grafite}
1506   pattern n at 2 in H
1507 \end{grafite}
1508
1509 would have resulted in this sequent:
1510
1511 \begin{grafite}
1512   n : nat
1513   m : nat
1514   H : (fun n0 : nat => m + n = n0) n
1515   ============================
1516    m = 0
1517 \end{grafite}
1518
1519 where $H$ is $\beta$-expanded over the second $n$
1520 occurrence. 
1521
1522 At this point, since \COQ{} unification algorithm is essentially
1523 first-order, the application of an elimination principle (of the
1524 form $\forall P.\forall x.(H~x)\to (P~x)$) will unify 
1525 $x$ with \texttt{n} and $P$ with \texttt{(fun n0 : nat => m + n = n0)}.
1526
1527 Since rewriting, replacing and several other tactics boils down to
1528 the application of the equality elimination principle, the previous
1529 trick deals the expected behaviour.
1530
1531 The idea behind this way of identifying subterms in not really far
1532 from the idea behind patterns, but fails in extending to
1533 complex notation, since it relays on a mono-dimensional sequent representation.
1534 Real math notation places arguments upside-down (like in indexed sums or
1535 integrations) or even puts them inside a bidimensional matrix.  
1536 In these cases using the mouse to select the wanted term is probably the 
1537 more effective way to tell the system what to do. 
1538
1539 One of the goals of \MATITA{} is to use modern publishing techniques, and
1540 adopting a method for restricting tactics application domain that discourages 
1541 using heavy math notation, would definitively be a bad choice.
1542
1543 \subsection{Tacticals}
1544 \label{sec:tinycals}
1545
1546 There are mainly two kinds of languages used by proof assistants to recorder
1547 proofs: tactic based and declarative. We will not investigate the philosophy
1548 around the choice that many proof assistant made, \MATITA{} included, and we
1549 will not compare the two different approaches. We will describe the common
1550 issues of the tactic-based language approach and how \MATITA{} tries to solve
1551 them.
1552
1553 \subsubsection{Tacticals overview}
1554
1555 Tacticals first appeared in LCF and can be seen as programming
1556 constructs, like looping, branching, error recovery or sequential composition.
1557 The following simple example shows three tacticals in action
1558 \begin{grafite}
1559 theorem trivial: 
1560   \forall A,B:Prop. 
1561     A = B \to ((A \to B) \land (B \to A)).
1562   intros (A B H).
1563   split; intro; 
1564     [ rewrite < H. assumption.
1565     | rewrite > H. assumption.
1566     ]
1567 qed.
1568 \end{grafite}
1569
1570 The first is ``\texttt{;}'' that combines the tactic \texttt{split}
1571 with \texttt{intro}, applying the latter to each goal opened by the
1572 former. Then we have ``\texttt{[}'' that branches on the goals (here
1573 we have two goals, the two sides of the logic and).
1574 The first goal $B$ (with $A$ in the context)
1575 is proved by the first sequence of tactics
1576 \texttt{rewrite} and \texttt{assumption}. Then we move to the second
1577 goal with the separator ``\texttt{|}''. The last tactical we see here
1578 is ``\texttt{.}'' that is a sequential composition that selects the
1579 first goal opened for the following tactic (instead of applying it to
1580 them all like ``\texttt{;}''). Note that usually ``\texttt{.}'' is
1581 not considered a tactical, but a sentence terminator (i.e. the
1582 delimiter of commands the proof assistant executes).
1583
1584 Giving serious examples here is rather difficult, since they are hard
1585 to read without the interactive tool. To help the reader in
1586 understanding the following considerations we just give few common
1587 usage examples without a proof context.
1588
1589 \begin{grafite}
1590   elim z; try assumption; [ ... | ... ].
1591   elim z; first [ assumption | reflexivity | id ].
1592 \end{grafite}
1593
1594 The first example goes by induction on a term \texttt{z} and applies
1595 the tactic \texttt{assumption} to each opened goal eventually recovering if
1596 \texttt{assumption} fails. Here we are asking the system to close all
1597 trivial cases and then we branch on the remaining with ``\texttt{[}''.
1598 The second example goes again by induction on \texttt{z} and tries to
1599 close each opened goal first with \texttt{assumption}, if it fails it
1600 tries \texttt{reflexivity} and finally \texttt{id}
1601 that is the tactic that leaves the goal untouched without failing. 
1602
1603 Note that in the common implementation of tacticals both lines are
1604 compositions of tacticals and in particular they are a single
1605 statement (i.e. derived from the same non terminal entry of the
1606 grammar) ended with ``\texttt{.}''. As we will see later in \MATITA{}
1607 this is not true, since each atomic tactic or punctuation is considered 
1608 a single statement.
1609
1610 \subsubsection{Common issues of tactic(als)-based proof languages}
1611 We will examine the two main problems of tactic(als)-based proof script:
1612 maintainability and readability. 
1613
1614 Huge libraries of formal mathematics have been developed, and backward
1615 compatibility is a really time consuming task. \\
1616 A real-life example in the history of \MATITA{} was the reordering of
1617 goals opened by a tactic application. We noticed that some tactics
1618 were not opening goals in the expected order. In particular the
1619 \texttt{elim} tactic on a term of an inductive type with constructors
1620 $c_1, \ldots, c_n$ used to open goals in order $g_1, g_n, g_{n-1}
1621 \ldots, g_2$. The library of \MATITA{} was still in an embryonic state
1622 but some theorems about integers were there. The inductive type of
1623 $\mathcal{Z}$ has three constructors: $zero$, $pos$ and $neg$. All the
1624 induction proofs on this type where written without tacticals and,
1625 obviously, considering the three induction cases in the wrong order.
1626 Fixing the behavior of the tactic broke the library and two days of
1627 work were needed to make it compile again. The whole time was spent in
1628 finding the list of tactics used to prove the third induction case and
1629 swap it with the list of tactics used to prove the second case.  If
1630 the proofs was structured with the branch tactical this task could
1631 have been done automatically. 
1632
1633 From this experience we learned that the use of tacticals for
1634 structuring proofs gives some help but may have some drawbacks in
1635 proof script readability. We must highlight that proof scripts
1636 readability is poor by itself, but in conjunction with tacticals it
1637 can be nearly impossible. The main cause is the fact that in proof
1638 scripts there is no trace of what you are working on. It is not rare
1639 for two different theorems to have the same proof script (while the
1640 proof is completely different).\\
1641 Bad readability is not a big deal for the user while he is
1642 constructing the proof, but is considerably a problem when he tries to
1643 reread what he did or when he shows his work to someone else.  The
1644 workaround commonly used to read a script is to execute it again
1645 step-by-step, so that you can see the proof goal changing and you can
1646 follow the proof steps. This works fine until you reach a tactical.  A
1647 compound statement, made by some basic tactics glued with tacticals,
1648 is executed in a single step, while it obviously performs lot of proof
1649 steps.  In the fist example of the previous section the whole branch
1650 over the two goals (respectively the left and right part of the logic
1651 and) result in a single step of execution. The workaround does not work
1652 anymore unless you de-structure on the fly the proof, putting some
1653 ``\texttt{.}'' where you want the system to stop.\\
1654
1655 Now we can understand the tradeoff between script readability and
1656 proof structuring with tacticals. Using tacticals helps in maintaining
1657 scripts, but makes it really hard to read them again, cause of the way
1658 they are executed.
1659
1660 \MATITA{} uses a language of tactics and tacticals, but tries to avoid
1661 this tradeoff, alluring the user to write structured proof without
1662 making it impossible to read them again.
1663
1664 \subsubsection{The \MATITA{} approach: Tinycals}
1665
1666 \begin{table}
1667  \caption{Concrete syntax of tacticals\strut}
1668  \label{tab:tacsyn}
1669 \hrule
1670 \[
1671 \begin{array}{@{}rcll@{}}
1672   \NT{punctuation} & 
1673     ::= & \SEMICOLON \quad|\quad \DOT \quad|\quad \SHIFT \quad|\quad \BRANCH \quad|\quad \MERGE \quad|\quad \POS{\mathrm{NUMBER}~} & \\
1674   \NT{block\_kind} & 
1675     ::= & \verb+focus+ ~|~ \verb+try+ ~|~ \verb+solve+ ~|~ \verb+first+ ~|~ \verb+repeat+ ~|~ \verb+do+~\mathrm{NUMBER} & \\
1676   \NT{block\_delimiter} & 
1677     ::= & \verb+begin+ ~|~ \verb+end+ & \\
1678   \NT{tactical} & 
1679     ::= & \verb+skip+ ~|~ \NT{tactic} ~|~ \NT{block\_delimiter} ~|~ \NT{block\_kind} ~|~ \NT{punctuation} ~|~& \\
1680 \end{array}
1681 \]
1682 \hrule
1683 \end{table}
1684
1685 \MATITA{} tacticals syntax is reported in Tab.~\ref{tab:tacsyn}.
1686 While one would expect to find structured constructs like 
1687 $\verb+do+~n~\NT{tactic}$ the syntax allows pieces of tacticals to be written.
1688 This is essential for base idea behind \MATITA{} tacticals: step-by-step
1689 execution.
1690
1691 The low-level tacticals implementation of \MATITA{} allows a step-by-step
1692 execution of a tactical, that substantially means that a $\NT{block\_kind}$ is
1693 not executed as an atomic operation. This has two major benefits for the user,
1694 even being a so simple idea:
1695 \begin{description}
1696 \item[Proof structuring] 
1697   is much easier. Consider for example a proof by induction, and imagine you
1698   are using classical tacticals in one of the state of the
1699   art graphical interfaces for proof assistant like Proof General or \COQIDE.
1700   After applying the induction principle you have to choose: structure
1701   the proof or not. If you decide for the former you have to branch with
1702   ``\texttt{[}'' and write tactics for all the cases separated by 
1703   ``\texttt{|}'' and then close the tactical with ``\texttt{]}''. 
1704   You can replace most of the cases by the identity tactic just to
1705   concentrate only on the first goal, but you will have to go one step back and
1706   one further every time you add something inside the tactical. Again this is
1707   caused by the one step execution of tacticals and by the fact that to modify
1708   the already executed script you have to undo one step.
1709   And if you are board of doing so, you will finish in giving up structuring
1710   the proof and write a plain list of tactics.\\
1711   With step-by-step tacticals you can apply the induction principle, and just
1712   open the branching tactical ``\texttt{[}''. Then you can interact with the
1713   system reaching a proof of the first case, without having to specify any
1714   tactic for the other goals. When you have proved all the induction cases, you
1715   close the branching tactical with ``\texttt{]}'' and you are done with a 
1716   structured proof. \\
1717   While \MATITA{} tacticals help in structuring proofs they allow you to 
1718   choose the amount of structure you want. There are no constraints imposed by
1719   the system, and if the user wants he can even write completely plain proofs.
1720   
1721 \item[Rereading]
1722   is possible. Going on step by step shows exactly what is going on.  Consider
1723   again a proof by induction, that starts applying the induction principle and
1724   suddenly branches with a ``\texttt{[}''. This clearly separates all the
1725   induction cases, but if the square brackets content is executed in one single
1726   step you completely loose the possibility of rereading it and you have to
1727   temporary remove the branching tactical to execute in a satisfying way the
1728   branches.  Again, executing step-by-step is the way you would like to review
1729   the demonstration. Remember that understanding the proof from the script is
1730   not easy, and only the execution of tactics (and the resulting transformed
1731   goal) gives you the feeling of what is going on.
1732 \end{description}
1733
1734 \section{Standard library}
1735 \label{sec:stdlib}
1736
1737 \MATITA{} is \COQ{} compatible, in the sense that every theorem of \COQ{}
1738 can be read, checked and referenced in further developments. 
1739 However, in order to test the actual usability of the system, a
1740 new library of results has been started from scratch. In this case, 
1741 of course, we wrote (and offer) the source script files, 
1742 while, in the case of \COQ, \MATITA{} may only rely on XML files of
1743 \COQ{} objects. 
1744 The current library just comprises about one thousand theorems in 
1745 elementary aspects of arithmetics up to the multiplicative property for 
1746 Eulers' totient function $\phi$.
1747 The library is organized in five main directories: \texttt{logic} (connectives,
1748 quantifiers, equality, \ldots), \texttt{datatypes} (basic datatypes and type 
1749 constructors), \texttt{nat} (natural numbers), \texttt{Z} (integers), \texttt{Q}
1750 (rationals). The most complex development is \texttt{nat}, organized in 25
1751 scripts, listed in Tab.~\ref{tab:scripts}.
1752
1753 \begin{table}[ht]
1754  \begin{tabular}{lll}
1755   \FILE{nat.ma}    & \FILE{plus.ma} & \FILE{times.ma}  \\
1756   \FILE{minus.ma}  & \FILE{exp.ma}  & \FILE{compare.ma} \\
1757   \FILE{orders.ma} & \FILE{le\_arith.ma} &  \FILE{lt\_arith.ma} \\   
1758   \FILE{factorial.ma} & \FILE{sigma\_and\_pi.ma} & \FILE{minimization.ma}  \\
1759   \FILE{div\_and\_mod.ma} & \FILE{gcd.ma} & \FILE{congruence.ma} \\
1760   \FILE{primes.ma} & \FILE{nth\_prime.ma} & \FILE{ord.ma} \\
1761   \FILE{count.ma}  & \FILE{relevant\_equations.ma} & \FILE{permutation.ma} \\ 
1762   \FILE{factorization.ma} & \FILE{chinese\_reminder.ma} &
1763   \FILE{fermat\_little\_th.ma} \\     
1764   \FILE{totient.ma} & & \\
1765  \end{tabular}
1766  \caption{Scripts on natural numbers in the standard library\strut}
1767  \label{tab:scripts}
1768 \end{table}
1769
1770 We do not plan to maintain the library in a centralized way, 
1771 as most of the systems do. On the contrary we are currently
1772 developing wiki-technologies to support a collaborative 
1773 development of the library, encouraging people to expand, 
1774 modify and elaborate previous contributions.
1775
1776 \section{Conclusions}
1777 \label{sec:conclusion}
1778
1779 \TODO{conclusioni}
1780
1781 \acknowledgements
1782 We would like to thank all the students that during the past
1783 five years collaborated in the \HELM{} project and contributed to 
1784 the development of \MATITA{}, and in particular
1785 M.~Galat\`a, A.~Griggio, F.~Guidi, P.~Di~Lena, L.~Padovani, I.~Schena, M.~Selmi,
1786 and V.~Tamburrelli.
1787
1788 \theendnotes
1789
1790 \bibliography{matita}
1791
1792 \end{document}
1793