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