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