(* MOSCOW ML VERSION *) (* New implementation of Mark2 theorem prover *) (* now officially called "Watson" *) (* copyright M. Randall Holmes, 2001 -- you may freely distribute as long as this notice is preserved *) (* also July 2, 2003: other ideas which should be worked out, taken from earlier notes: application of reference types, especially to the tactic interpreter. figure out how to apply all functions to terms with reference types. Aim for unique reference? Interaction with parsing and display. references need to know about local hypotheses. look at Dec 1 notes. examine currentmenu fix -- what is this about? implement s.c. separation. More generally, implement something more like a type system. *) (* July 2, 2003: This note summarizes ideas for implementation of partial functions. A new value "error" is introduced, standing for the unique nonexistent object, which is the value of any function at the places where it is undefined. ?f@error = error for all ?f. [P]@?x = if error = ?x then error else P[?x/?1] To replicate the usual function of abstraction and reduction as far as possible, we want to be able to recognize situations under which P[?x/?1] = if error = ?x then error else P[?x/?1]. We would like to automate this process. ?n <> error can always be assumed. (bound variables do not take the error value). This should be implemented as a theorem and also as part of an automatic function. When applying BIND@x to P, we have normal behavior if we can verify one of two things: either x <> error (x exists) or P is error if x is error (P is strict relative to x). So we would like to have an existence detector and a relative strictness detector. When applying EVAL to P@x, we are safe if we can tell that P is error if x is error (relative strictness again), or if we can tell that x exists. Operators have possibly interesting properties: an operator is total if its value exists whenever its arguments exist, and an operator is strict if its value does not exist whenever its arguments do not exist. Totality is useful for the recursion component of an existence detector, and strictness is useful for the recursion component of a relative strictness detector. Effects on definition: defined _functions_ must be strict; the relative strictness detector needs to be at work. Defined operators need not be strict, but we might want the ability to register a defined operator as strict in spite of a non-strict definition (by recording a theorem?). Certain operations (equality for example) are not strict. The case construction is not strict. Effects on theorem application: theorems are no longer equivalent to universally quantified equations: quantifiers have only existent objects in their domain of applicability (we implement free logic), whereas theorems are permitted to match free variables which may not have existent values. Would it be a good idea to add variables which share the property of bound variables that they can only match things known to exist? Effects on higher-order matching: existence or relative strictness is needed to match P@x (or explicit appearance of if error = x...). I was thinking that this didn't apply to @! or @*, but in fact it must if we are to preserve standard reasoning about equality of abstractions along with the fact that we have just one kind of abstraction. Our unstratified quantifiers also must satisfy free logic. Note that issues of relative strictness are independent of stratification. Now I have to read the program to see how easy or difficult it will be to implement this everywhere. Is it possible to implement it as a "toggle" which can be turned on or off in a single Watson source, or do we need two different versions? The type system can then be modified so that t:x = x for all x in type t, and t:x = error for all x not in type t. This has corresponding effects on type definition, etc. *) (* July 25: I should work on smart memory management (including storage of rewrites -- replace 0|-|n's with explicit equations) inside the tactic interpreter. This should make the tactic interpreter faster. There should be an option to declare connectives "always break". This would be a vast improvement in formatting. A detailed review of the innards of the system is needed...particularly the complicated stuff that has been added recently. *) (* March 1: changed former exporttheorem and exportall to interfacetheorem and draftinterface everywhere (including comments) [these are the "theory modularity" commands). Also improved the interface theorem command using a technique which probably should be used to simplify the older dependency update commands. (these are long overdue for careful review!) Relevant display commands for theory modularity (one might want to look at the theory interface, for example) and support for enforcement of "locality" of identifiers (declare _new_ identifiers as local, and set up interfacetheorem to abort if it tries to put a local identifier in the interface). Also, declaration safety for the interface commands. *) (* Feb. 28: eliminated level=0 clauses in strat. This should have no effect at all. I installed theory modularity. If the command interfacetheorem is not used anywhere in a script, everything is exported by newsegment(). If it is used, only things required for theorems which are exported are actually exported. There may be bugs, as always; the exact way that the new segment is edited may be in error. To be precise, the function segmentedit needs to be examined carefully, especially re the dependency lists. The storeall command will carry out the restrictions on the theory; backuptheory will not. The command draftinterface() nulls the export list and so restores the ability to back up the entire theory. This needs to be tested! I made a better effort to edit the inverse dependency lists intelligently, but this is still a hard issue. I want the new type system. I think it will be independent of the stratification (relative) type system: it should return deducible types for subterms of a given term (a given subterm as an argument?) -- focus would be on scin types, since scout types can be seen anyway? This will go along with matching taking implicit type labels into account -- bool:?x should match ?y&?z, for example. Complex types (arrow and product types) may come into play. This may all be quite complex, depending on how much of the information provided by scin/scout we use? We may want to accept more general forms of theorems as "typing theorems" (with induced effects on scin/scout itself). A possible approach: develop a global procedure for automatically generating (and eliminating) types; always apply it to the target before matching and apply it again after substitution. *) (* Feb. 27: It is necessary to restore "linearity" of the stratification procedure (it cannot, as presently designed, take identifications between variables representing type shifting operators into account, without complicating the relative_type data type.) Further, it seems that the upgrade of relative_type isn't worthwhile; the circumstances under which @* is used are limited and likely to remain limited. The reason why linearity is important is that the way force_equation is implemented assumes that whenever a term with a given "unknown displacement" is "floated", all terms with that unknown displacement are floated; this allows us to avoid calculations with unknown types by just arbitrarily shifting that unknown floated value when it becomes rigid again. Stuff from agendadir outlining changes to be made: Definitely plan on changing form of definition theorems, exploiting automatic matching, so that patterns are always universally applicable. Further, extend generality of scin theorems to cover things like FORALLBOOL2. (for FORALLBOOL2, the correct form of theorem would be forall@?p = forall@[bool:?p@?1]). This extension to scin would eliminate problems with quantifier switching theorems, for example. Further, idea of extending matching to exploit scin/scout info (perhaps also the extended type system). Test the proposed s.c. separation theorem. Idea of extending automatic projection operators to the proposed but never implemented ?m..n (and ?m...n final) iterated projection operators for argument lists. Could that generalization of matching be automatically extended by allowing all "functional programs" to be executed before matching (in whatever sense this is done with p1 and p2?) Review theorems and tactics to be predeclared (appropriate for preparation of new manual). The new user manual for the prover is definitely looking like a serious prospect. The function strat, in spite of our forebodings, has been correct (in Feb18.sml); I found and fixed a bug in the new stratification scheme (fix_function wasn't working correctly) which restored it to good order. But strat2 was in error in Feb18.sml; it has now been repaired by setting it up to type bound variables as well as free variables in the same way that strat does (by defining a function prestrat2 "basically the same" as strat, mod type manipulations). The level=0 clauses in strat seem to be pointless; they are a relic of an early stage of development (and had to be deleted from prestrat2 for it to work). They do no damage at this point, but should be removed. I should think very carefully before installing any update of scin based on the case of FORALLBOOL2. *) (* Feb. 26: Further minor repairs to "type unification" function before making this the official version. It should now be the best possible solution to the @* typing issue; it recognizes identifications between unknown displacements of identical argument places of type-raising operators represented by the same variable. *) (* Feb. 23: the solution for unkonwn displacements is incorrect -- and so was the CHECKTYPE solution, apparently. To simplify matters, arguments of @* are now required to be "meta-free" (no occurrences of @*, thus no repeated "unknown displacements"). *) (* Feb. 22: new version testing a more transparent implementation of stratification, using single functions with domains including indeterminate types. changed union so that it eliminates duplications from the first argument as well as the second. This appears to be completely implemented. The one thing that remains is to determine how to eliminate the need for CHECKTYPE by defining special (possibly "must-float"?) types for subterms of @* expressions. Plan to save old file as Feb18.sml It appears that I now have an implementation of stratification of @* terms using "unknown rigid displacements" which must be "floated" for stratification. Added restriction to the effect that the same term cannot get an "unknown" displacement more than once (operators with @* are not composed). This allows justification of the typing convention for @* and doesn't eliminate any realistic possibilities for higher-order matching. But there may still be type coincidences to worry about? *) (* Feb. 18: fixed bug in incremental backup -- attempts to do scratch work without running a script first produced a crash because cleartheories didn't save the preamble theory into the theories list. Problem should now be fixed. *) (* Dec. 6: an idea (no code change). Maintain lists of things declared in the current theory and of things renamed or forgotten in the current theory. Don't allow new things to be renamed or forgotten, and don't allow repeated renaming. This could support the idea of renaming the + * of the natural numbers to allow use of the usual terminology for the rationals in newlib*, for example. I should start working on applications of the new reference term construction. The most evident use of this construction would be to make the tactic interpreter a bit smarter (avoiding duplication of effort). There is a great deal of tedious case-checking, installing the new term type for existing functions where it is not hard to see what to do. *) (* Dec. 1: Reference terms are installed as a formal possibility, though term operations are not yet implemented for them. I should set about doing that implementation. High priorities: display of terms with embedded references (this is trivial) and creation of such terms with unique reference properties. Other tricks possible with references: one could manipulate many places in a term at once if one had explicit notation for shared subterms? added commands showcounter() showmaxcounter() longestproof() to view counter information. I made all counter viewing and manipulation commands "secure". This means, for example, that if the max counter is set, one can reset the counter to avoiding "timing out" during an INPUT (or other) proof in progress. The = built in tactic may need another fix to behave as one would like. Is it possible to arrange for it to set new variables using the variables found in the given equation? An inventory of dubious aspects of the software (places where bugs might hide) would be handy. There is a lurking idea that a term constructor using a reference to a term is something that might be added for "meta-substitution" purposes (attempts at efficient memory management and efficiency of substitution). It could also be accompanied by free atomic term information. Then new stuff could be added while avoiding wholesale invalidation of the old approach. It is in the tactic interpreter that such an idea could be useful? Copied terms might actually be the same term, and manipulation of one subterm implies similar manipulation of all identical subterms? This might have the effect that execution of a term may cause nonlocal execution of terms somewhere else, but this doesn't seem too bad? The manipulations carried out elsewhere should be valid (though one must be careful about local hypothesis executions; they will have to be somehow indexed with their actual context), and much wasted effort might be averted? One could work with a table of term references (the table is needed to tell when a given reference has already been accessed); term references created under global hypotheses need to be eliminated when one vacates the appropriate local context (and need to be kept distinct from possibly typographically identical terms elsewhere, so that modifications of terms legitimate in one context are not carried out in another). The goal of unique representation can be approximated in ML... Idea: reference terms for subterms with local hyps might actually include references to the local hyps, or at least be indexed using such references (rather than just by hlevel). The handling of the "current menu" is ugly (though now apparently valid); I should change this. *) (* Nov. 29: New features to avoid infinite looping. There is a command setmaxcounter n, which, if n is positive, sets a bound to the number of times the new variable counter can be incremented (if n is negative, there is no bound, as before). This will bound the number of times theorems can be applied, which prevents infinite loops from taking place. The error message "Ran out of time" is issued by the tactic interpreter if the bound is overrun. The start command now initializes the new variable counter (which I should have done a long time ago; this would have largely eliminated the unpredictability of the new variable counter!) This will be valuable when using the GUI, which has no graceful way to issue interrupts. Detected a bug which causes suspend to mess up the menu inside scripts. load was making the same mistake. I hope it is fixed; the fix is awkward (look at the functions currentmenu, setcurrentmenu). *) (* Nov. 22: Implemented numeral variables of the form ??n. Variables with two leading question marks will match only numerals or other variables of the same kind. This will facilitate definition of natural number typing theorems, for example. There are apparently no uses of variables of this form in the current library, so no conflicts should be created. This will allow avoidance of some inelegant hacks in the current libraries, and should be regarded as a precedent if other built-in data types are added (such as strings). *) (* Nov. 20: minor bug fix to new precedence commands leftprecabove and rightprecabove (they would not raise precedence of a command with the opposite grouping just stronger than the new infix/prefix). *) (* Nov. 7: internal change (no change of version): the stratification function will not do the second stratification check if the term is metafree (which means it won't contain @* ). *) (* Nov. 6: The @* connective is installed, compiled, but not tested yet. The crux of the matter lies in functions inserttype, deletetype, raisebind and raisestrongeval. There are clauses for @* in metahead/metastrat/metafree, declarescheck, match, autoeval, and strat. Only free variable headed terms with @* are regarded as stratified. The semantics of @* are that it represents application of operations which raise or lower type uniformly. It is used only for purposes of higher-order matching. The idea is that a term like (?f@*?1)@*?2 matches an arbitrary stratified but possibly inhomogeneous term. Heads of terms built with @* are restricted in the same way as heads of terms built with @!. @* is not technically opaque, but a term built with @* is only stratifiable if it is headed by a free variable. The net effect of this is that it is impossible to abstract into the head of a @* term and only possible to abstract into the arguments under controlled conditions. The fact that stratification tests have to be carried out twice for the sole benefit of @*, plus possible doubts about its soundness, suggest that there ought to be a way to turn it off (or else that there ought to be a defter way to do the strat check).FIXED This connective is a technicality of interest mostly to students of the logic underlying the prover (and as such it is still important, but users don't need to worry about it unless I come up with important applications). It is essentially the version of the connective @! found in the old version design.sml; it allows stronger forms of higher-order matching in true stratified functions. Preliminary tests suggest that it works. We shall see! *) (* Nov. 3: All current commands and built-in theorems are now found in the web documentation. No code changes. Think stratification refinements: I am thinking of introducing @* (the application operator for type-raising or lowering operations) with higher-order matching and stratification privileges; I would also like to implement s.c. separation. There should be no eval or bind analogue for @*; it should be managed strictly by matching and substitution functions. The clue is that [T] is stratified for @* exactly if [bool:T] is stratified. This should actually make this easy. Then one needs the CHECKTYPE trick to ascertain that the type of terms built with this operator can be freely raised and lowered. The advantage of @* is that it can be used to build true functions where @! cannot. But is it really needed? When will one want to generalize over possibly type-raising operators? There is some danger that one will become able to quantify over things one would rather not quantify over (the whole range of functions and their type-raised versions). This should probably be avoided! The original motivation for @* was that it was needed for uniform treatment of nested quantifiers in the context of higher-order matching. But @! handles this just fine. A new application for @* will be a situation like that with nested quantifiers where we want to be able to do matching on "stratified but inhomogeneous" expressions, where type differentials are not known in advance, as in (Ax.(Ay.Pxy)) = (Ay.(Ax.Pxy)), where x and y may have any type differential and the whole will remain stratified. This is exactly what (P@*x)@*y is supposed to match: an expression which is stratified with unknown types for x and y. Will thoughts along these lines make things easier? If we are using it only for matching and substitution, we can impose the same well-formedness requirements as with @! -- leading terms must be free variables or "eliminable" abstractions. The advantage it will have over @! will be the ability to appear in true functions. So @* will be mentioned as a variant of @! in metastrat. It will have its own clauses in higher-order matching and correlated clauses in substitution. Stratified terms will have to stratify with @* having types 0 0 and types 1 0. (a sketch of a proof that this is enough to verify that it works would be nice). For s.c. separation, we need to be able to explicitly s.c. type the top level term (use scin/scout or explicit type label) and we also need to be able to type the local bound variable as s.c., while forbidding violations of opacity. This suggests thinking about tools for deducing s.c. types. These are both mathematically rather than practically motivated ideas; there is no hurry. *) (* Nov. 2: All current commands are now documented in babydocs.tex. They have not been put on the web. It is still necessary to document new built-in theorems (there are a number of these to put in!) combination of old notes and some new stuff with SCOUT family of commands, scin/scout declarations, and installation of the match test on the = command. Major cleanup of old comments! (old note) automatically generated scripts should include verify statements (no change yet) (old note) Idea for interface: type terms to be "started" in the Global Term window; then a keystroke could carry out the start command. fields for entering arguments to other commands would make it possible to do this with other commands as well. bug with display of backed up environment after use of autoedit; backed up environment gets wrong name? Of course, is it really a bug? This goes with not wanting prove to rename environments, to avoid having loads of backed-up environments. The redundant parenthesis problem with unary terms still exists. Incompatibility of incremental backup with forget still an issue; this can be addressed when we do theory modularity. Do I want @*? Related in spirit is the question of implementation of s.c. separation. an old note: idea that operators declared scin or scout should be retyped (scin as flat and scout so as to get smallest type to 0). Recognize that if one is on two of the scin/scout lists one should be on all three? another old note: Idea about internalizing type information: provide a built-in tactic which will convert an infix term to a functional form, with appropriate introduction of constant functions and values.another old note: an INPUTP@?tactic command which allows one to input parameters to a tactic. A built-in theorem which implements matchtri might be of interest. This is likely to be more unpredictable than the = builtin theorem. It is important to note that it is dependent on the order of the theorems in the master theorems list, which changes! NEW COMMENT: could such a command be made interactive? another loose end: target search should also look at local hypotheses? items reproduced from an old list of gaps: a redefinition command appropriate for type definitions. This can wait for proof that redefinition will actually be used. the general, hard problem of scin/scout for functions or operators with lists of arguments. This is hard, and requires reflection. add application of commutative laws (and perhaps other laws of stereotyped form) to tri. There is a vague idea of having an ability to register new abstract forms which theorems can take and have the system flag theorems of these kinds? (so one could add idempotent laws, for example, without modifying code). Do this, or at least think about it. rewrite logic? refinement of success/failure? theoretical questions about infix variables (generation of new ones, unification?) All things not to worry about now. other built-in data types? (strings, terms?) I definitely need to implement sensible binding and abstraction with multiple variables of each type (?m..n). Try doing it in structural, but be open to idea of doing it hard-wired. Do this, but first try writing tactics for structural.wat that do it. see note below (Aug. 20) about "makescinvar"; is there a use for this any longer? Stratification problems in embedded theorems (or in paramterized new variables) are no longer a problem, for unexpected reasons. I probably need to look at the documentation re documentation of all recently introduced commands. restricted makescinleft and makescinright so that fully "scin" operators cannot have their types changed without use of the makescin command. some qualms about unary operators and functions in relation to scinright are removed: these are treated as "scin" and can't be touched by makescinright anyway. Only infixes can be made scinleft or scinright proper. Would it make sense for SCINL and SCINR to be restricted to "true" scinleft and scinright operators? Yes: restricted SCINL and SCINR so that they apply only when scinleftof and scinrightof are different theorems. This makes the forms of the theorems they will apply predictable! It also means that they will be much less often used. added the "match check" to the = built in theorem; the target needs to match the appropriate side of the given equation, not just the matching theorem. This allows one to automatically create restricted versions of theorems... This broke some tactics in newlib2 where I wasn't careful to maintain disjointness of variables in theorems built with = from those in the target term. newlib2 seems to be fixed... No obvious problems in omnibus, but it is harder to tell. *) (* Nov. 1: for GUI-related reasons, seedeps now does its output via nopausemessage. I have a much better idea, involving less fiddling with the innards of the prover (in fact, none!); provide built-in theorems which execute the theorems witnessing scin/scout properties of operators and functions! The practical problem with this is that scin/scout theorem directionality needs to be determined. Otherwise it would be difficult to write tactics with predictable effects. It looks as if one would want functions to determine the precise forms of theorems. Direction of theorems is an issue; the difference between scinform on the one hand and scinleftform, scinrightform on the other is also an issue. Alternatively, the internal functions could use the theorems to determine relevant types, and proceed to do appropriate types without explicitly worrying about the exact forms of the theorems? But they would still need to post the correct dependencies. The advantage of this approach is that it does not create any new data structures to keep track of at all, and still will provide a new generalized type facility (while actively encouraging use of the scin/scout facilities :-) This suggests that it ought to be possible to change scin/scout information about operators. It also suggests that we ought to accept scin/scout theorems for type labels; these won't be useful for scin/scout, but they will be useful for subtyping judgments. The built in theorems SCOUT, SCIN, SCINL and SCINR are now installed! They can be executed in direct or converse senses; in the direct sense, they add types and in the converse sense they remove types (no matter what the sense of the actual scin/scout witness theorems may be). This all seems about right. Whatever information we have about the "type system" of s.c. types which is available for stratification is already coded in the scin/scout lists. The new built-in theorems make this information available to tactics as well. Moreover, notice that term types (and maybe even dependent types?) are made available by this maneuver, since complex types can appear in scin/scout theorems. Sensitivity to directionality has been tested. The functions introduced Oct. 31 have been commented out for the moment. What remains to be done: things about changing scin/scout information; support for subtyping theorems. The interesting issue of s.c. separation remains open... A built-in theorem which automatically expands definitions is no harder than the SCOUT family to write, and might be useful. It is easy enough to provide the ability to change the scin/scout lists (so changing s.c. typing of operators) but it is unclear that this is something one would use? I went ahead and did it; the functions will warn you if the operator or function is already scin/scout, but they will go ahead with the new scin/scout assignment anyway. *) (* Oct. 26: Added "cef" abbreviation for "clearerrorflag". I changed the version date to Oct. 25, but only because of the optimizations; there should be no change in prover behavior. Upgrades being seriously considered now: 1. the type system upgrade. The practical aim of this upgrade is to allow a general implementation of the problem of assigning explicit types to terms and eliminating them where necessary. A secondary aim of theoretical interest is to see whether there is a nice way to implement s.c. separation and so get a stronger logic. It is not clear that this is useful in a practical sense. A very basic thing is to change the declarations of constants and operators to record input and output types; add built in theorems which will add and remove these types. The scin/scout functions would then modify the declaration lists.NO - the scin/scout lists themselves are the source of type information. A very basic implementation of this idea might go no farther than this. A full implementation might also add arrow and product types and more complex facilities for type inference. I'm not sure what's desirable. THE scin/scout approach does support complex types. 2. Theory level modularity. This would mean that theorems would be copied into an inheriting theory only if explicitly "exported" from within the inheriting theory. This is a very good idea! A related issue is to deal systematically with any remaining awkwardnesses with the theory module system (as with "forget"). 3. Memory management for the term type. This should have no effect at all on behavior of the prover, but might conceivably have a dramatic effect on performance (as in the GoL example, where automated proof is attempted)! Ideas from the Portland conference are relevant here. Memory sharing, delaying substitution are the issues. The idea of tagging terms with their free variables (probably with both their free and their bound variables in Watson) is nice. *) (* Oct. 25: thinking about upgrading the "type system". No code changes as yet. First idea: upgrade the stratification function so that it reports types for well-typed variables even when problems exist for other variables. This would allow implementation of s.c. separation. Some optimization of stratification functions (as in crushtypes). Also optimized merge. The non-optimized version of merge might have been wasting quite a lot of cycles? A way to achieve s.c. separation: the idea is to avoid assigning types to any bound variables higher in type than the binding variable in a function; if one does this and gets "shiftable" type for the local bound variable, then s.c. separation should apply? Note that failures of opacity should still be a problem. The previous idea seems not to work too well? It depends. It seems that if a term T is stratified wrt ?1 (ignoring types of all variables above ?1) and has "floating" type for ?1, that the whole expression will be typable? Operations that would allow sabotage of this would seem to be opaque (unstratified recursions, for example). But this does require some proof. If it works, then it is fairly easy to implement s.c. separation without any extension of type inference. Another query: can we really tell using strat whether ?1 is in an s.c. domain? This query also applies to the implemented technique for stratifying types. The fact that we eliminate single typed variables when they are "floated" might be challenged? Of course, the "floating" of a single typed variable might be regarded as putting it through a type filter? I see problems with this: images of typable sets under the formation of unstratified abstractions are apt to be problematic? In fact, this criterion would allow one to form the function taking x to (lambda y.y(y)+Nat:x); this is clearly problematic (though it is not altogether clear that it really causes a problem; we still can't apply these functions). *) (* Sept 11: The built in tactic #! has been installed, which causes the prover to remember the particular case of the rewrite being applied, so that it can apply it in one step if it is encountered later. This allows very efficient computation of recursively defined functions. A tricky point is that reverse application of #! format will allow reverse application of the stored rewrite rule; new effects can be produced by doing this (tactics can be applied in reverse!) #! is disabled in steps. Since different saved rewrite rules may be available in different branches of case expressions, it seems that there isn't any way to enable #! for steps; #! is incompatible with the parallelism in steps. Do I want to allow saved rewrites at level 0 to persist? In this case, they should be stored in theory structures. For the moment, keep them internal to execute and steps. Internally, the =>> and <<= tactics have been rewritten so that they will behave sensibly with the UP and #! tactics (and any other tactics whose behavior is mediated by execute instead of thmresult). They will also exhibit more fine-grained behavior in relation to steps. The same modification has been carried out for *> and <*. Something similar may need to be done with the functional programming feature? (only if complex programs are to be allowed will this be needed). Can saved rewrites be registered by level+hlevel? I think so... Safest version: use an operator # to signal intention to register a rewrite (# format executes format if it finds no registered rewrite, and otherwise uses the registered rewrite). Registered rewrites are remembered only in the environment where they are registered. I'm erasing earlier comments about the tactic module system and summarizing. The tactic module system allows tactics to be "hidden" in modules associated with other theorems. The intention is to keep components of recursively defined tactics off the main theorem list; there are other possible applications. User commands: Push name1 name2: put theorem name1 in module associated with theorem name2. name1 cannot equal name2; name1 cannot be a pure equation (it must either have parameters or involve embedded theorem applications). Other theorems using name1 may automatically be Pushed into the module. Open name: open the module associated with name. This means that theorems in the module will appear (temporarily) on the main theorem list. Close name: close the module associated with name. This may force any new theorems depending on theorems into the module into the module. CloseAll(): close all modules. This command is automatically invoked by steps(), ex(), and prove, and possibly by other commands as well. PopModule name: unpack the module associated with the theorem name, returning the theorems to the same level of visibility as name. It is possible to nest modules, but the rules for this are rather restrictive. There is no way to take theorems out of a module individually. Note issue of using blocking elements to prevent reappearance of old material when material in the current theory is deleted. New theorysize() user command reports number of theorems. The ability to display modules is wanted. New command showmodule does this. The theorem display command issues a message when a theorem has an associated module. showscout and showscin user commands (to view scin/scout information). *) (* Sept. 5: The prover now automatically declares undeclared operator variables as opaque infix or prefix operators as appropriate. This may require changes (as it did in structural.wat) if an operator has been used without a declaration and later declared. The reason for this change is that the prover could have been crashed by using an operator variable implicitly as an infix then later typing it explicitly as a prefix. Now the earlier use as an infix will cause an automatic declaration. New command tacticdisplay displays tactics with argument lists; it checks for well-formedness of argument lists and makes substitutions into theorems as the argument lists require. This could be used by the GUI to extract arguments for ri from the equation window. There might be places in the existing code where Modified treatment of ill-formed case expressions (it produces a well-formed term). Reviewed all error messages for conversion to nopausemessage. In general, display commands should now not set the error flag! ideas, not code changes: Idea of storing "absolute theorems", which contain all information about the axioms, definitions, and scin/scout theorems they need. "Absolute theorems" might make theorem export easier. re modularity: Note that a list of modules (list of theorem lists labelled by theorem names) will work just as well, and involve no changes at all to existing data types. Opening a module = (weakly) copying theorems to the head of the theorem list; closing a module = (strongly) copying them back from the theorem list (not just erasing them!). In this way, we can edit theorems inside modules in a secure way. None of this will involve any modification of the existing data types. Nested modules will work just fine with this format. I like the idea of referring to objects applicable with @! as "contexts", and objects applicable with @ as "functions". I should write an update for the online documentation (an appendix to the submitted paper) discussing context abstraction and application, and quoting the theorems (it should discuss the solution to the existential quantification problem as well as the results of the Portland paper). add a connective (say :=:) such that T :=: U denotes both T and U. A term of the form T :=: U cannot be freely constructed: it must be introduced as T :=: T (to avoid the formation of such horrors as true :=: false). There might be alternative approaches? For example, it might be safe to even introduce such terms as long as they were never copied (so that two different copies were collapsed in different ways). But this would complicate matters at a deeper level than the other solution. Is there a general solution using case expressions to the problem that leads to this (needing to transform a term to a different form but wanting to recover the equality between the two forms quickly)? The semantics are that T :=: U is well-formed (in a context) just in case T and U are interchangeable in that context. :=: amounts to recording a local theorem; perhaps the right way to use it is as the hypothesis of a case expression? Perhaps T :=: U should be equal to "true", not to T, and usable as a case expression hypothesis. It can only be introduced by a variation of REFLEX and can only be eliminated by conversion to = (after which it can be applied as hypothesis of a case expression?). Controlling theorems: ?x = (?y:=:?y)||?x,?z, ?x:=:?y = true (not reversible!) , prover restriction that :=: cannot appear in a starting expression (and can't be introduced by assignment or as new material introduced by a theorem), and privileges for ?x:=:?y as hypothesis of a case expression. Direct support for cases in pattern matching: an idea is to allow theorems of the form T,U = V,W to be applied to prove T = V and U = W as well as the obvious... Further thoughts about how to cope with the @! operator. Could it be the application of untyped lambda-calculus, always automatically evaluated? This would mean that we would have to deal with the possibility of terms like ?f @! ?x being undefined (partial functions). Evaluation of the Curry paradox term would present no problems, precisely because it would crash! Alternatively, is there a tidier way to deal with the current solution (which amounts to excluding @! from contexts, except in terms ?P@!?x@!?y... (left grouped) in which ?P must eliminate all the @!'s (it must be sufficiently bracketed). What I don't like is the implicit typing of ?P and the resulting restriction on assignment; in some sense this is unavoidable, but I'd like to get a neater justification for it? Is there a way to eliminate term formation restrictions (as we did for @ when @! was introduced) and have the work done entirely by restrictions on application of EVALM, BINDM? But in fact there is a great deal to be said for strong restrictions on @!, which is a very dangerous connective! *) (* Sept. 1: I need to modify the stratification function so that it only accepts bindings into type labels when there is no nontrivial type information therein (all bound variables are restricted to s.c. types).DONE and tested on omnibus. The reason is that I would like to adopt a logical axiom to the effect that f(x) = f:x whenever f is a retraction with s.c. domain, and this is incompatible with the existence of most functions binding into type labels. This will also impact the type definition facility (I'm not sure how) though it will also essentially make that facility obsolete (no, it doesn't!). The new axiom is only possible to state because we now have unstratified quantification. The axiom can be written elegantly as [?T@(?T@?1)] = [?T@?1] & [[?T@?1]] = [[[?T@?2]]@?1] -> [?T@?1] = [?T:?1] My guess is that there is no effect on the type definition command, and that that command will remain useful. The new viewpoint still probably requires that the general arrow type constructor (for example) be an opaque operator, though it allows the definition of non-opaque restrictions of the arrow type constructor by other means. Though it does seem that any abstraction into a type label with a constructor is actually safe (where the embedded abstraction into the type built with the constructor might not be). Under the old stratification rules, [[?1@?2]=[?1:?2]] would be stratified, defining the _set_ of functions ?f equivalent as functions and as type labels, which could then be proved not to coincide with the retractions with s.c. domain. How about "Sigma_2 Replacement"? This would require a change in the structure of the stratification function, since subterms of allowed terms may turn out to be unstratified. Sigma_2 replacement comes in with the upgrade to a true polymorphic type system. It would come in if we kept type information even when stratification fails -- some variables would be typed as "bad" in the course of stratification, but the type information about others would be kept. This approach would make the implementation of Sigma_2 replacement possible. (what is wanted is the ability to stratify any class function with s.c. domain and range). Also, matchtri and amtri will now display the proposed theorem. *) (* August 31: error messages now raise a flag which prevents proofs; this flag is reset by the start command (and by derived commands like startover, starthere). It is also reset by a new clearerrorflag() user command. This is a seemingly minor feature which should protect one against the effects of overeager drag-and-drop proofs (since these carry on through error messages without stopping). It seems that only the prove command needs to look at this flag, and it is sufficient to have the start family of commands set it. Experience will tell us whether it is too finicky! It does mean that proofs by hand will need to be started over whenever an error message is raised. I added a clearerrorflag() user command which will also clear the error flag. Another improvement: files with the iri "theorem";; format for talking to the INPUT command now work as scripts. But the format is still quite rigid: the iri lines need to appear one to a line with no intervening commands. So scripts are still much more limited than top-level dialogue at the INPUT prompt. Still, this makes it easier to edit interactively developed INPUT files to scripts, and it means that scripts can be written to run interactively as well. *) (* August 20: UP tactic has been tested and appears to work. Version now has the UP tactic installed! Complete installation but not much testing. Oddly, competing UP tactics are executed from the back of the term. For the moment, I think that UP tactics at top level should be left hanging; one might want to go up and execute again, and the droprule command exists. Notes made on laptop after TPHOLs: 3 corrections to file made during conference. Hypothesis display added a return for the sake of the interface. I changed the pause message to Watson: Paused, again for the sake of the interface. Finally, I fixed an actual bug in the "functional programming" feature: the program attempted to execute constant names rather than their associated programs. As an immediate upgrade, I project the UP built-in tactic. *) (* August 10: corrects an oversight re the INPUT command: the display will now tell you if the theorem supplied to INPUT is being applied in the converse sense. I don't know if anyone will ever use this, but it should be there. changed "errormessage" in envname() to "nopausemessage" -- probably fixed problem with demo scripts? The SHELL built-in tactic has been disabled, since it is now redundant. One still might like it in guimode, but guimode is deprecated anyway... Is it a good idea to display a theorem whenever it is introduced by a ruleintro command, for purposes of the interface?DONE for matchtri, amtri. I have set up tabular displays so that they are captured in the equation window, and messages so that they are appended to the local term window. I think that essentially all Watson output is now captured in one of the special windows in the GUI, though some only gets "flashed". *) (* June 19: added defaultprecsame command, which sets default precedence to be the same as that of an existing operator, completing the suite of "relative" precedence commands *) (* June 16: planning an upgrade to precedence setting, allowing precedences to be set relative to precedences of existing operators, without any reference to numbers. new commands sameprec leftprecabove rightprecabove leftprecbelow rightprecbelow Each command takes two arguments, the first being an operator to be assigned precedence, and the second being an operator which presumably already has precedence. The new precedence is set to be the same, inserted just above, or inserted just below the old precedence, and set to group left or right as appropriate. *) (* June 15 note (no change): For easy use of precedences, there should be a device for "inserting" precedences -- give an operator a certain precedence and raise the precedence of all operators with precedence higher than that by one. An idea: don't use numbers at all! Define precedence as "same as ^+" (a simple assignment), "just above ^+" (an insertion) or "just below ^+" (another kind of insertion). This should make for a much more natural approach! (the showprecedences command can then be used to look at the resulting order of precedence). New "verify" command added. Also new "showdef" command. *) (* June 15: updated documentation again. Added new commands showdef (which displays the defining theorem, if any, of a constant or operator) and verify (which can be used in scripts to check that theorems are proved correctly). *) (* Apr. 27-8: I regard the higher-order matching upgrades as now complete, barring discovery of bugs. The next issue is adding security to incremental theory saving to file and desktop by enforcing a tree-like structure of dependency between theories. The simplest technique is to maintain a registry of precursor lists of theories, and prevent a theory name from being assigned if the list of precursor theories (SCRIPTS) is not appropriate. A registry of theory dependencies is now maintained and checked. I do not know whether it works. I think that the current registry scheme is secure against at least the most obvious kinds of abuse of mutual calls of theory files; it enforces a sensible tree structure. There is a new user command droptheory; droptheory s will delete theory s and every theory which depends on it from the desktop. A nice addition would be the ability to load a theory file with a different name than the file name? Same for scripts. *) (* Apr. 19: a change in the treatment of formats which may make higher-order matching more powerful. The match of formats is used to make substitutions into the theorem to be used before it is applied. This should make it possible to implement BIND, for example. The change is strictly confined to the function USE. Further refinements will be needed. The match that will allow user implementation of UNEVAL will also allow elimination of possible unexpected behavior of the new approach to format matching. Also, @! should be made more like @ in higher order matching (but no need to support the pair). *) (* Mar. 3: mod minor difficulties, the segmented desktop and save file system now seems to work. Invariants: the first element of the SCRIPTS list should always be the current theory. the second element of the SCRIPTS list should always be the theory to be loaded just before the current theory. The hierarchy of "modules" is still strictly linear, though I have some ideas how this might be changed. The file sizes are _dramatically_ smaller. On the other hand, one needs .sav.wat files for all precursors of a theory to load it; this is a new situation. Maybe the old load command could be preserved? It is quite likely that there will be other peculiar problems. *) (* June 28: This has been tested with SML 96. The only problem in building it is that the Io x exception in noml doesn't work; use IO.Io instead. It appears that SML96 is perfectly happy with the Moscow ML source-- except for the same problem with the Io exception. What is the I/O exception type for SML 96? Stuff about exportML: exportML, heap image files, @SMLload command line parameter Question: Calling the function exportML, as in - SMLofNJ.exportML "image"; creates a file called "image.mipseb-irix" that is not executable, while with SML/NJ 93 I would get an executable file called "image". I wonder if I am doing the export correctly or if there is a new procedure for using the exported image? Answer: The file "image.mipseb-irix" is a heap image -- not an executable. You can load it as follows: % sml @SMLload=image Note that you do not need to specify the ".mipseb-irix" suffix when specifying the image file, it will be inferred. *) (* June 16: very slight refinement of comments in INPUT text In the June 15 version, either { or } started a comment to the end of the line; now it is only { which starts a comment, which will go either to the end of the line or to a }. A } acts like an end of line and could be used to put more than one input on the same line. changes to script, reset and demo *) (* comment these out for SML 93 *) (* SML 96 Conversion functions *) (* load "Int"; *) (* val load = load; *) val std_in = TextIO.stdIn; val std_out = TextIO.stdOut; fun output (out, msg) = TextIO.output(out,msg); fun input (inp, n) = TextIO.inputN(inp,n); fun makestring(value) = Int.toString(value); fun explode (s) = (List.map str (String.explode s)); fun implode (ls) = String.concat ls; fun max(n1,n2) = Int.max(n1,n2); fun open_out(s) = TextIO.openOut(s); fun close_out(s) = TextIO.closeOut(s); fun flush_Out(s) = TextIO.flushOut(s); fun open_in(s) = TextIO.openIn(s); fun close_in(s) = TextIO.closeIn(s); fun flush_Out(s) = TextIO.flushOut(s); fun substring s = String.substring(s); (* fun exit() = OS.Process.exit(OS.Process.success); *) (* fun abort() = OS.Process.exit(OS.Process.failure); *) (* END SML 96 Conversion functions *) (* used for SML 93 compatibility *) (* fun flush_Out s = (); *) (* Error message function with pause control functions *) val ERRORPAUSE = ref false; fun setpause() = ERRORPAUSE := true; fun setnopause() = ERRORPAUSE := false; exception Breakout; val Returns = ref("\n\n"); fun compress() = Returns := "\n"; fun expand() = Returns := "\n\n"; (* due to the needs of the GUI, the error message command raises an exception rather than pausing (and so waiting for input that the GUI can't handle) *) val ERRORFLAG = ref false; fun clearerrorflag() = ERRORFLAG:=false; fun errormessage s = (output(std_out,(!Returns)^"Watson: "^s^(!Returns)); flush_Out(std_out);ERRORFLAG:=true; if (!ERRORPAUSE) then raise Breakout else ()); (* this command is used for merely informative messages that should not interrupt script execution *) fun nopausemessage s = (output(std_out,(!Returns)^"Watson: "^s^(!Returns)); flush_Out(std_out)); (* this toggle tells the prover to use the new method of handling INPUT at top level -- but the old method is available *) (* It may eventually be used to turn off some other changes used by the GUI. In general, turning GUI mode off is deprecated, and it is not guaranteed to restore previous behavior in all respects. *) val GUIMODE = ref true; fun guimode() = (GUIMODE := not(!GUIMODE);nopausemessage ("GUI mode is "^(if (!GUIMODE) then "on" else "off"))); (* verbosity of output *) val VERBOSITY = ref 2; fun bequiet() = VERBOSITY := 0; fun thmsonly() = VERBOSITY := 1; fun speakup() = VERBOSITY := 2; (* version command *) fun versiondate() = nopausemessage "March 1, 2001 (first-order, segmented, for GUI)"; (* container classes *) (* Watson requires two kinds of container classes, finite sets and finite functions. These were implemented as balanced binary trees in Mark2. In this design, they are implemented in a very simple way as lists. There doesn't seem to be any deficit in performance. *) (* all operations attempt to maintain the invariant that any set or function element appears no more than once *) (* sets *) (* a set of objects of a given type is simply a list of objects of that type *) (* is an object x found in a given set? *) fun foundinset x nil = false | foundinset x (a::rest) = if x = a then true else foundinset x rest; (* add x to a given set *) fun addtoset x L = if foundinset x L then L else (x::L); (* drop x from given set *) fun dropfromset x nil = nil | dropfromset x (a::rest) = if x = a then rest else (a::(dropfromset x rest)); (* union of sets *) fun union nil nil = nil | union nil L = union L nil | union (a::L) M = a::(union (dropfromset a L) (dropfromset a M)); (* faster, less safe old form: fun union nil L = L | union (a::L) M = a::(union L (dropfromset a M)); *) fun union2 nil = nil | union2 (L::M) = union L (union2 M); fun intersection nil L = nil | intersection (a::L) M = if foundinset a M then a::(intersection L M) else intersection L M; (* subset relation *) fun subset nil L = true | subset (a::L) M = (foundinset a M) andalso (subset L M); (* the subset of a list of which the predicate f is true *) fun separate f nil = nil | separate f (a::L) = if (f a) then (a::(separate f L)) else separate f L; (* suppose one only wants to find one object for which f is true... *) fun separate2 f nil = nil | separate2 f (a::L) = if (f a) then [a] else separate2 f L; fun restriction L f = separate (fn (x,y) => foundinset x L) f; fun setminus a b = separate (fn x=>not(foundinset x b)) a; (* sorting a set *) fun sortsetput (s:string) nil = [s] | sortsetput (s:string) (a::L) = if s < a then (s::(a::L)) else (a::(sortsetput s L)); fun sortset nil = nil | sortset (a::L) = sortsetput a (sortset L); (* functions *) (* find an object in the list associated with key s; return a one-element list of the found object if it is found, otherwise nil *) fun find s nil = nil | find s ((t,x)::rest) = if s = t then [x] else find s rest; (* a safe version of find which gives the object found and a default when there is no such object *) fun safefind default s L = let val A = find s L in if A = nil then default else (hd A) end; (* is there an object with key s in L? *) (* changed so that lists of things not of equality types can be handled *) (* fun foundin s L = find s L <> nil; *) fun foundin s L = length(find s L) > 0; (* drop item with given key *) fun drop s nil = nil | drop s ((t,x)::L) = if s = t then L else ((t,x)::(drop s L)); (* an optimization, perhaps; it brings the found item to the front of the list. this version of find is used inside the thmresult function below. *) fun Find s reference = let val A = find s (!reference) in if A = nil then nil else (reference:=((s,hd A)::drop s (!reference));A) end; fun Safefind default s reference = let val A = Find s reference in if A = nil then default else (hd A) end; fun Foundin s L = Find s L <> nil; (* add item with given key; the first will not overwrite and the second will *) fun addto s x L = if foundin s L then L else ((s,x)::L); fun strongadd s x L = addto s x (drop s L); (* this is the union operation for the theory segments construction; keys in the second file override keys found in the first. *) fun strongunion nil L = L | strongunion L nil = L | strongunion ((s,x)::L) ((t,y)::M) = strongadd t y( addto s x(strongunion L M)); (* this is the difference operation for the theory segments construction *) fun strongdiff L nil = L | strongdiff nil M = nil | strongdiff ((s,x)::L) M = let val FOUND = find s M in if FOUND = nil then ((s,x)::strongdiff L M) else if (hd FOUND) = x then strongdiff L M else ((s,x)::strongdiff L M) end; (* is a list of pairs a function? *) fun isfun nil = true | isfun ((s,x)::L) = let val A = find s L in if A = nil orelse A = [x] then isfun L else false end; (* merge function used with match lists; it returns nil as an error object, and packages resultant lists in a unit list *) fun merge L M = let val U = union L M in if isfun U then [U] else nil end; (* sorting a function *) fun sortfunput (s:string,x) nil = [(s,x)] | sortfunput (s:string,x) ((a,y)::L) = if s < a then ((s,x)::((a,y)::L)) else ((a,y)::(sortfunput(s:string,x) L)); (* this is an update function like strongadd which maintains sortedness *) fun sortfunput2 (s:string) x nil = [(s,x)] | sortfunput2 (s:string) x ((a,y)::L) = if s < a then ((s,x)::((a,y)::L)) else if s = a then ((s,x)::L) else ((a,y)::(sortfunput2 s x L)); fun sortfun nil = nil | sortfun (a::L) = sortfunput a (sortfun L); (* The primary objects manipulated by Mark2 are terms; the manipulations allowed are algebraic. Atomic terms in Mark2 are of three kinds, constants (which must be declared), free and bound variables. Composite terms are of three kinds: terms constructed using binary infix operators (which must be declared; though there is a provision for variable infixes), function terms, and terms defined by cases. Unary operators are also supported, but they are coded as binary operators as will be seen below. *) (* the separate clauses for reserved identifiers and for case expressions are a new idea *) (* term data type declaration *) (* type of infix operators *) datatype operator = ConOp of string | VarOp of string | ResOp of string | (* reserved operator *) ParOp of string; (* an internal device *) datatype term = (* atomic terms *) Constant of string | Numeral of int list | (* Mark2 has built in arithmetic *) FreeVar of string | BoundVar of int | (* composite terms *) Infix of term*operator*term | Function of term | CaseExp of term*term*term | Parenthesis of term (* Parenthesis is a special construction used internally for various purposes *) | Reference of term (* reference terms might also contain some additional data, telling something about the term referenced -- a bit to tell whether term is rulefree, for example *) ; (* There are some differences between the surface form of Mark2 terms (as displayed and understood by a user) and the "deep structure" exhibited in the type declaration above. There are also some notational points not capable of being made in this format. All atomic terms are represented by strings made of alphanumeric characters plus the special characters "?" and "_". The empty string does not represent a constant; Constant "" is used internally as an error object. Strings made up entirely of digits stand for numerals. They are stored as lists of digits (in reverse order). The built in arithmetic of Mark2 is unlimited precision arithmetic of non-negative integers. Strings made up of the special character "?" followed by a non-zero-initial numeral represent bound variables. Strings which begin with "?" and do not represent bound variables are used to represent free variables. Strings which do not represent any of the above represent constants. Unlike the three other sorts of atomic term, constants need to be declared by the user. We now consider terms defined using operators. This includes the case of unary prefix operators, which are in fact supported by Mark2, though this is not reflected in the data type. An infix which has been declared may be used as a prefix operator if a declaration has been made which assigns to that infix a default left argument; when the operator is used as a prefix, an invisible left argument is present, equal to the default; moreover, when a term is entered in binary form whose left term happens to be the default left argument for its infix, the prover will display it in unary form. Operators are represented by nonempty strings made up entirely of special characters other than the two special characters allowed in atomic terms. Operators of more than one character beginning with "^" are operator variables. All other operators are constant operators and must be declared. A final refinement: an operator may actually end with alphanumerics: it consists of (zero or more) special characters possibly followed by a suffix consisting of one backquote "`" followed by zero or more alphanumerics, with the length of the whole being nonzero. Function terms are of the form [term]; a term enclosed in brackets is a function term. The appearance of bound variables is restricted to appropriate function terms; the bound variable ?n may only appear in a context within at least n nested brackets. Case expression terms take the surface form ?x || ?y , ?z This causes some peculiarities because the apparent subterm ?y , ?z does not correspond to any actual term. This is handled differently in the current version of Mark2, but a related problem occurs. *) (* we now give code for functions which retrieve the first token of a given kind (atomic term or operator) from a list of characters; it has a companion function which returns the rest of the string *) (* the tokenizer does not consult the declaration lists, but it does recognize reserved constants and operators *) (* the list of reserved operators *) val RESERVED = ref([("bogus",(0,0))]); (* RESERVED := nil; *) fun isreserved x = foundin x (!RESERVED); (* kinds of character *) fun iscap x = x = "A" orelse x= "B" orelse x = "C" orelse x = "D" orelse x = "E" orelse x = "F" orelse x = "G" orelse x = "H" orelse x = "I" orelse x = "J" orelse x = "K" orelse x = "L" orelse x = "M" orelse x = "N" orelse x = "O" orelse x = "P" orelse x = "Q" orelse x = "R" orelse x = "S" orelse x = "T" orelse x = "U" orelse x = "V" orelse x = "W" orelse x = "X" orelse x = "Y" orelse x = "Z"; fun islowercase x = x = "a" orelse x= "b" orelse x = "c" orelse x = "d" orelse x = "e" orelse x = "f" orelse x = "g" orelse x = "h" orelse x = "i" orelse x = "j" orelse x = "k" orelse x = "l" orelse x = "m" orelse x = "n" orelse x = "o" orelse x = "p" orelse x = "q" orelse x = "r" orelse x = "s" orelse x = "t" orelse x = "u" orelse x = "v" orelse x = "w" orelse x = "x" orelse x = "y" orelse x = "z"; fun isspecial x = x = "!" orelse x = "@" orelse x = "#" orelse x = "$" orelse x = "%" orelse x = "^" orelse x = "&" orelse x = "*" orelse x = "=" orelse x = "+" orelse x = "-" orelse x = "<" orelse x = ">" orelse x = "/" orelse x = "," orelse x = ";" orelse x = "." orelse x = ":" orelse x = "~" orelse x = "|"; fun isdigit x = x = "0" orelse x = "1" orelse x = "2" orelse x = "3" orelse x = "4" orelse x = "5" orelse x = "6" orelse x = "7"orelse x = "8" orelse x = "9"; (* remove whitespace *) fun strip nil = nil | strip (" "::L) = strip L | strip ("\n"::L) = strip L | strip ("\t"::L) = strip L | strip L = L; fun isalpha x = iscap x orelse islowercase x orelse isdigit x orelse x = "?" orelse x = "_"; (* get desired characters from a list of characters *) fun getalpha nil = nil | getalpha (a::L) = if isalpha a then a::(getalpha L) else nil and restalpha nil = nil | restalpha (a::L) = if isalpha a then restalpha L else (a::L); fun getnumeral nil = nil | getnumeral (a::L) = if isdigit a then a::(getnumeral L) else nil and restnumeral nil = nil | restnumeral (a::L) = if isdigit a then restnumeral L else (a::L); fun getspecial nil = nil | getspecial (a::L) = if isspecial a then (a::(getspecial L)) else if a = "`" then (a::(getalpha L)) else nil and restspecial nil = nil | restspecial (a::L) = if isspecial a then restspecial L else if a = "`" then restalpha L else (a::L); (* integer character value *) fun numvalue "0" = 0 | numvalue "1" = 1 | numvalue "2" = 2 | numvalue "3" = 3 | numvalue "4" = 4 | numvalue "5" = 5 | numvalue "6" = 6 | numvalue "7" = 7 | numvalue "8" = 8 | numvalue "9" = 9 | numvalue x = ~1; (* fun evalnum nil = 0 | evalnum ("0"::L) = 0 + 10*(evalnum L) | evalnum ("1"::L) = 1 + 10*(evalnum L) | evalnum ("2"::L) = 2 + 10*(evalnum L) | evalnum ("3"::L) = 3 + 10*(evalnum L) | evalnum ("4"::L) = 4 + 10*(evalnum L) | evalnum ("5"::L) = 5 + 10*(evalnum L) | evalnum ("6"::L) = 6 + 10*(evalnum L) | evalnum ("7"::L) = 7 + 10*(evalnum L) | evalnum ("8"::L) = 8 + 10*(evalnum L) | evalnum ("9"::L) = 9 + 10*(evalnum L) | evalnum x = ~1; *) fun evalnum nil = 0 | evalnum (x::L) = if isdigit x then let val A = evalnum L in if A = ~1 then ~1 else (numvalue x) + (10*A) end else ~1; fun listtoint nil = 0 | listtoint (n::L) = n + 10*(listtoint L); (* strips unwanted zeroes off fronts of numerals *) fun stripzeroes nil = (0::nil) | stripzeroes (0::nil) = 0::nil | stripzeroes (0::L) = stripzeroes L | stripzeroes L = L; (* strips unwanted zeroes off ends of reversed lists of digits (our internal representation of integers) *) fun stripzeroes2 L = rev(stripzeroes(rev L)); (* functions which extract the first atom represented in a list of characters and return the rest of the list *) fun prefirstatom s = let val A = getnumeral s and B = getalpha s in if A <> nil andalso A = B then Numeral (rev (stripzeroes(map numvalue A))) else if B<>nil then if hd B = "?" then let val C = getnumeral (tl B) in if C <> nil andalso C = tl B then BoundVar (evalnum (rev C)) else FreeVar (implode B) end else Constant (implode B) else Constant "" end (* conventional error value *) and prerestfirstatom s = let val A = getnumeral s and B = getalpha s in if A <> nil andalso A = B then restnumeral s else if B<>nil then restalpha s else s end (* conventional error value *) (* this function returns the first atomic term in the string s, if any. A locution like "stringtocon s = FreeVar s" asks whether s is a free variable; in the case of constants, one also needs to stipulate that s is not "" *) fun stringtocon s = prefirstatom (strip (explode s)); fun firstatom s = prefirstatom (strip s); fun restfirstatom s = prerestfirstatom (strip s); (* functions for getting the first operator from a list of characters and the rest of the list *) fun prefirstop s = let val A = getspecial s in if A = nil then ConOp "" (* error value *) else if hd A = "^" andalso tl A <> nil then VarOp (implode A) else if isreserved (implode A) then ResOp (implode A) else ConOp (implode A) end; (* this function gets the first operator from a string; see comments under stringtocon *) fun stringtoop s = prefirstop (strip (explode s)); fun firstop s = prefirstop (strip s); fun restfirstop s = restspecial (strip s); (* cleans up parentheses -- appears here because stringtoop is needed *) fun deparenthesize1 (Parenthesis t) = t | deparenthesize1 t = t; fun deparenthesize (Parenthesis t) = deparenthesize t | deparenthesize (Function s) = Function(deparenthesize s) | deparenthesize (Infix(x,ParOp s,y)) =Infix(deparenthesize x, stringtoop s, deparenthesize y) | deparenthesize (Infix(x,i,y)) = Infix(deparenthesize x,i, deparenthesize y) | deparenthesize (CaseExp(u,v,w)) = CaseExp(deparenthesize u, deparenthesize v,deparenthesize w) | deparenthesize t = t; (* We now construct a family of functions culminating in the parser. In this version, we do not allow user declared precedence, which is found in the full implementation; most users have been content with the APL precedence (all operators have same precedence, all operators group to the right) which is the default in the full implementation *) (* We begin with the declaration lists (needed by the display function to handle prefix operators, as well as by the parser), follow with the display functions, and conclude with the parser *) (* the constant declaration list *) val CONSTANTS = ref(["bogus"]); fun isaconstant s = (stringtocon s = Numeral (rev(stripzeroes(map (numvalue) (explode s))))) orelse foundinset s (!CONSTANTS); (* USER COMMAND *) fun declareconstant s = if s <> "" andalso stringtocon s = Constant s then if foundinset s (!CONSTANTS) then errormessage ("Constant "^s^" already declared") else CONSTANTS:=addtoset s (!CONSTANTS) else errormessage ("Ill-formed constant "^s^" cannot be declared"); (* operator declarations *) (* operators require integer "left type" and "right type" parameters for the stratification function *) val OPERATORS = ref([("bogus",(1,2))]); (* (* declarations of operators declared with s.c. types *) val OPERATORTYPES = ref([("bogus",("bogus","bogus","bogus"))]); val _ = OPERATORTYPES:=nil; *) fun isoperator s = if stringtoop s = VarOp s then true else if stringtoop s = ResOp s then true else if s <> "" andalso stringtoop s = ConOp s then if foundin s (!OPERATORS) then true else false else false; val defaultop = (0,0); fun opof s = if (stringtoop s) = ResOp s then safefind defaultop s (!RESERVED) else safefind defaultop s (!OPERATORS); fun lefttype s = (fn (a,b) => a) (opof s); fun righttype s = (fn (a,b) => b) (opof s); (* val defaultoptype = ("","",""); fun optypeof s = safefind defaultoptype s (!OPERATORTYPES); fun topsctype s = (fn (a,b,c) => a) (optypeof s); fun leftsctype s = (fn (a,b,c) => b) (optypeof s); fun rightsctype s = (fn (a,b,c) => c) (optypeof s); *) (* It is permissible to declare variable operators in order to record their type information *) (* in fact, it is now mandatory that they be declared; undeclared variable operators are automatically declared as opaque *) (* USER COMMAND *) fun declaretypedinfix m n s = if stringtoop s = ResOp s then errormessage ("Reserved operator "^s^" cannot be redeclared") else if stringtoop s = VarOp s then if foundin s (!OPERATORS) then errormessage ("Variable operator "^s^" has already been typed") else OPERATORS:= addto s (m,n)(!OPERATORS) else if s <> "" andalso stringtoop s = ConOp s then if foundin s (!OPERATORS) then errormessage ("Operator "^s^" has already been declared") else OPERATORS:= addto s (m,n) (!OPERATORS) else errormessage ("Ill-formed operator "^s^" cannot be declared"); (* (* function for declaring operators with explicit s.c. types *) (* output type followed by left, right input types *) (* it accepts numerals for polymorphically typed arguments *) fun declarescinfix a b c s = if stringtoop s = ResOp s then errormessage ("Reserved operator "^s^" cannot be redeclared") else if stringtoop s = VarOp s then errormessage ("Variable operators with sc types not supported") else if s <> "" andalso stringtoop s = ConOp s then if foundin s (!OPERATORS) then errormessage ("Operator "^s^" has already been declared") else if ((not (isaconstant a)) orelse (not (isaconstant b)) orelse (not (isaconstant c))) then errormessage ("Incorrect types for proposed operator") else let val A = evalnum(rev(explode a)) and B = evalnum(rev(explode b)) and C = evalnum(rev(explode c)) in (OPERATORTYPES:= addto s ((if A = ~1 then a else ""), (if B = ~1 then b else ""), (if C = ~1 then c else "")) (!OPERATORTYPES); declaretypedinfix ((if B = ~1 then 0 else B) - (if A = ~1 then 0 else A)) ((if C = ~1 then 0 else C) - (if A = ~1 then 0 else A)) s) end else errormessage ("Proposed operator "^s^" ill-formed"); *) (* Declaration of reserved operators: not a user command! *) fun reserveop m n s = if s <> "" andalso stringtoop s = ConOp s andalso (not (isoperator s)) then RESERVED:=addto s (m,n) (!RESERVED) else errormessage ("Improper operator reservation of "^s); (* reserveop 0 0 "||"; reserveop 0 0 ","; *) (* declares the usual "flat" operators with only trivial type information *) (* USER COMMAND *) fun declareinfix s = declaretypedinfix 0 0 s; (* lists of operators with special properties needed by the stratification functions of the prover *) val OPAQUE = ref["bogus"]; val SCOUT = ref[("bogus","bogus")]; val SCINLEFT = ref[("bogus","bogus")]; val SCINRIGHT = ref[("bogus","bogus")]; (* opaque operators are "opaque" to abstraction; one cannot define a function in a way which essentially involves an opaque operator (an opaque operator could appear in the name of a constant) *) (* distinct from defined opaque "constant" operators (not used in any current theory, though they could be) are opaque variable operators; an operator variable with declared type matches only operators of that same type, while an opaque operator matches any operator, and for that reason must observe the same restrictions on abstraction as an opaque declared operator *) fun isopaque s = s = "@!" orelse foundinset s (!OPAQUE); fun istypedoperator s = (foundin s (!RESERVED) orelse foundin s (!OPERATORS)) andalso not (isopaque s); (* declare opaque operator *) fun declareopaque s = if stringtoop s = ResOp s then errormessage ("Reserved operator "^s^" cannot be made opaque") else if stringtoop s = VarOp s then if foundin s (!OPERATORS) then errormessage ("Reserved or variable operator "^s^" has already been typed") else (OPERATORS:= addto s (0,0)(!OPERATORS);OPAQUE:=addtoset s (!OPAQUE)) else if s <> "" andalso stringtoop s = ConOp s then if foundin s (!OPERATORS) then errormessage ("Operator "^s^" has already been declared") else (OPERATORS:= addto s (0,0) (!OPERATORS);OPAQUE:=addtoset s (!OPAQUE)) else errormessage ("Ill-formed operator "^s^" cannot be declared"); (* scout = strongly Cantorian output; scinleft = strongly Cantorian input (left argument) and scinright = strongly Cantorian input (right argument) strongly Cantorian = (in practice) belonging to some data type *) val SCINSCOUT = ref ["bogus"]; (* list used in posting axiom dependencies induced by scin/scout functions *) fun scoutof s = safefind "" s (!SCOUT); fun scinleftof s = safefind "" s (!SCINLEFT); fun scinrightof s = safefind "" s (!SCINRIGHT); fun scinof s = if scinleftof s = scinrightof s then scinleftof s else ""; fun isscout s = let val A = foundin s (!SCOUT) in (if A then SCINSCOUT:=addtoset (scoutof s) (!SCINSCOUT) else ();A) end; fun isscinleft s = let val A = foundin s (!SCINLEFT) in (if A then SCINSCOUT:=addtoset (scinleftof s) (!SCINSCOUT) else ();A) end; fun isscinright s = let val A = foundin s (!SCINRIGHT) in (if A then SCINSCOUT:=addtoset (scinrightof s) (!SCINSCOUT) else ();A) end; (* assignment of scin/scout properties to theorems needs to be witnessed by existence of theorems of appropriate forms and will be handled later *) (* prefix display declarations -- needed for display as well as parser *) (* variable prefix operators are needed! *) (* the default left argument of an operator will be an atomic constant *) val PREFIX = ref([("bogus","bogus")]); (* PREFIX := nil; *) fun prefixof s = safefind "" s (!PREFIX); fun hasprefix s = foundin s (!PREFIX); (* command to assign a default left argument to an operator; this version only permits such an assignment to be made once *) (* USER COMMAND *) fun declareprefix s t = if hasprefix s then errormessage ("Cannot reassign default left argument of "^s) else if (stringtoop s = ResOp s orelse (stringtoop s = ConOp s andalso isoperator s)) andalso isaconstant t then PREFIX := addto s t (!PREFIX) else errormessage ("Invalid prefix "^t^" proposed for operator "^s); (* NOT a user command -- this command creates strict prefix operators, which are those operators which have a prefix on the list equal to "" *) (* it is necessary to be able to declare strict prefix operator variables so that one can build structural tactics which will work on prefix terms *) fun isstrictprefix s = hasprefix s andalso prefixof s = ""; fun declarestrictprefix s = if (stringtoop s = ResOp s orelse stringtoop s = VarOp s orelse (stringtoop s = ConOp s andalso isoperator s)) then PREFIX := addto s "" (!PREFIX) else errormessage ("Undeclared operator "^s^" cannot be declared strict prefix"); (* declarations of strictly unary operators *) fun declaretypedunary n s = (declaretypedinfix 0 n s; declarestrictprefix s); fun declareunary s = declaretypedunary 0 s; (* fun declarescunary a b s = (declarescinfix a "0" b s;declarestrictprefix s); *) fun declareunaryopaque s = (declareopaque s; declarestrictprefix s); (* default type handling: this allows the suppression of type labels on variables which are understood to usually have a given type; the type label infix : appears as a prefix operator in this case *) val VARTYPES = ref [("bogus",Constant "")]; (* VARTYPES := nil; *) fun hasdefaulttype v = foundin v (!VARTYPES); fun defaulttypeof v = safefind (Constant "") v (!VARTYPES); fun hasdtprefix ":" (FreeVar v) = hasdefaulttype v | hasdtprefix s t = false; fun dtprefixof ":" (FreeVar v) = defaulttypeof v | dtprefixof s t = Constant ""; fun haseitherprefix s t = hasprefix s orelse hasdtprefix s t; fun eitherprefixof s t = if hasprefix s then stringtocon (prefixof s) else dtprefixof s t; (* USER COMMAND *) fun notypeinfo v = if foundin v (!VARTYPES) then VARTYPES:=drop v (!VARTYPES) else errormessage ("No default type for "^v^" found to drop"); (* function for assigning types is found below; it requires declaration checking *) (* I might want to add scin/scout information *) fun showdec s = if stringtocon s = Constant s then if isaconstant s then nopausemessage (s^" is a declared constant") else nopausemessage ("Undeclared constant "^s) else if stringtocon s = Numeral (rev (stripzeroes(map numvalue (explode s)))) then nopausemessage "Numerals are predeclared" else if (stringtoop s = ResOp s) then if isopaque s then nopausemessage ("Opaque reserved operator "^s) else if isoperator s then nopausemessage ("Reserved operator "^s^" left type: " ^(makestring (lefttype s))^" right type: " ^(makestring(righttype s)^ " left arg (if any): "^(prefixof s))) else errormessage ("Undeclared reserved operator?!") else if (stringtoop s = ConOp s) then if isopaque s then nopausemessage ("Opaque declared operator "^s) else if isoperator s then nopausemessage ("Declared operator "^s^ " left type: " ^(makestring (lefttype s))^" right type: " ^(makestring(righttype s))^ (if hasprefix s then if prefixof s = "" then " Prefix operator only" else " Default left argument: "^(prefixof s) else " Infix argument only")) else nopausemessage ("Undeclared operator") else if stringtoop s = VarOp s andalso foundin s (!OPERATORS) then nopausemessage ("Typed variable operator "^s^" left type: " ^(makestring (lefttype s))^" right type: "^ (makestring(righttype s))^ (if hasprefix s then " (strict prefix)" else "")) else if stringtoop s = VarOp s andalso isopaque s then nopausemessage ("Opaque operator variable "^s^ (if hasprefix s then " (strict prefix)" else "")) else if stringtoop s = VarOp s then nopausemessage ("Undeclared operator variable "^s) else errormessage "No applicable declaration"; (* simple display function *) fun opdisplay (ConOp s) = s | opdisplay (VarOp s) = s | opdisplay (ResOp s) = s | opdisplay (ParOp s) = "{"^s^"}"; (* the master precedence list *) val PRECEDENCES = ref ([("bogus",0)]); (* PRECEDENCES:=nil; *) (* default precedence *) val DEFAULTPREC = ref 0; (* user command to set precedence of an operator *) fun setprecedence s n = if n<0 then setprecedence s 0 else PRECEDENCES := strongadd s n (!PRECEDENCES); (* user command to set default precedence *) fun setdefaultprec n = if n < 0 then setdefaultprec 0 else DEFAULTPREC := n; (* user command to reset precedences to standard *) fun clearprecs () = (PRECEDENCES := nil; DEFAULTPREC := 0); fun precedenceof s = safefind (!DEFAULTPREC) s (!PRECEDENCES); (* sophisticated precedence commands *) fun preraiseprecs n nil = nil | preraiseprecs n ((s,m)::L) = (s,if m>=n then m+2 else m)::(preraiseprecs n L); fun raiseprecs n = PRECEDENCES := preraiseprecs n (!PRECEDENCES); (* USER COMMANDS (5) *) (* these commands allow precedences to be set relative to an existing precedence -- either the same, just above, or just below (making insertions in the latter two cases) and with left or right grouping as indicated *) fun sameprec s t = setprecedence s (precedenceof t); fun defaultprecsame s = setdefaultprec (precedenceof s); fun leftprecabove s t = (raiseprecs ((precedenceof t)+1); setprecedence s ((precedenceof t)+1+ ((precedenceof t) mod 2))); fun rightprecabove s t = (raiseprecs ((precedenceof t)+1); setprecedence s ((precedenceof t)+2- ((precedenceof t) mod 2))); fun leftprecbelow s t = (raiseprecs ((precedenceof t)); setprecedence s ((precedenceof t)-1+ ((precedenceof t) mod 2))); fun rightprecbelow s t = (raiseprecs ((precedenceof t)); setprecedence s ((precedenceof t)-2+ ((precedenceof t) mod 2))); (* NORULES supports a mode in which embedded theorems are not displayed (when it is true) *) val NORULES = ref false; (* in the old version, =>> and <<= were rule infixes as well, but they are not in this version (they are operators linking a pair of theorems) *) fun ruleinfix s = s = "=>" orelse s = "<="; fun stickiness (Infix(x,s,y)) = if (!NORULES) andalso ruleinfix (opdisplay s) then stickiness y else precedenceof (opdisplay s) | stickiness (CaseExp(u,v,w)) = precedenceof "||" | stickiness x = 0; (* this refers to surface form *) fun isinfixterm (Infix(x,s,y)) = if (!NORULES) andalso ruleinfix (opdisplay s) then isinfixterm y else true | isinfixterm (CaseExp(u,v,w)) = true | isinfixterm x = false; fun isprefixterm (Infix(x,s,y)) = (x = eitherprefixof (opdisplay s) y) | isprefixterm x = false; (* parentest x s b tells us whether term x needs to be parenthesized when it is term b (left term has b=0, right term has b=1) in an infix term with infix s *) (* there is a difficulty with parentheses around prefix terms to the right of an infix; such parentheses are sometimes eliminable, but this depends on context in a way which is hard to implement. *) fun parentest x s b = ((not (!NORULES)) orelse (not (ruleinfix (opdisplay s)))) andalso (isinfixterm x andalso ((stickiness x < precedenceof (opdisplay s)) orelse (stickiness x = precedenceof (opdisplay s) andalso ((stickiness x) mod 2 = b)))); (* pp for "possible parenthesis" *) fun pp x s b p = if parentest x s b then p else ""; (* function for converting preparsed terms to correct form *) fun reassociate1 (Infix(x,s,Infix(y,t,z))) = if ((precedenceof (opdisplay s) > precedenceof (opdisplay t)) orelse (precedenceof (opdisplay s) = precedenceof (opdisplay t) andalso ((precedenceof (opdisplay s)) mod 2) = 1)) andalso y <> eitherprefixof (opdisplay t) z then Infix(reassociate1(Infix(x,s,y)),t,z) else (Infix(x,s,Infix(y,t,z))) | reassociate1 t = t; fun reassociate (Parenthesis t) = Parenthesis (reassociate t) | reassociate (Function t) = Function (reassociate t) | reassociate (Infix(x,s,y)) = reassociate1 (Infix(reassociate x,s,reassociate y)) | reassociate t = t; (* baredisplay should now handle user-defined precedence correctly *) fun baredisplay (Constant s) = s | baredisplay (Numeral n) = implode(rev (map makestring n)) | baredisplay (FreeVar s) = s | baredisplay (BoundVar s) = "?"^(makestring s) | baredisplay (Infix(t,i,u)) = let val T = baredisplay t in (* the baredisplay function does not use default type information; this avoids trouble for load and save commands *) if T = prefixof (opdisplay i) then (opdisplay i)^" "^(pp u i 1 "(")^ (baredisplay u)^(pp u i 1 ")") else (pp t i 0 "(")^T^(pp t i 0 ")")^" " ^(opdisplay i)^" " ^(pp u i 1 "(") ^(baredisplay u)^(pp u i 1 ")") end | baredisplay (Function t) = "["^(baredisplay t)^"]" | (* display of case expressions "cheats"; it relies on the surface form of case expressions as complex infix expressions *) (* this works because the display functions are independent of declarations *) baredisplay (CaseExp(t,u,v)) = baredisplay (Infix(t,ResOp("||"),Infix(u,ResOp(","),v))) | (* the case for Parenthesis handles highlighting the current subterm *) baredisplay (Parenthesis t) = "{"^(baredisplay t)^"}"; val CURSOR = ref 0; fun bumpcursor s = (CURSOR:=(!CURSOR)+(length(explode s));s); val MARGIN = ref 50; fun setline n = MARGIN:=n; fun spaces 0 = " " | spaces n = (spaces (n-1))^" "; fun predashes 0 = "" | predashes 1 = " " | predashes 2 = " " | predashes 3 = " " | predashes n = if n<0 then "" else (predashes (n-1))^"-"; fun dashes() = predashes (!MARGIN); fun Newline() = (CURSOR:=0;"\n"); fun maybebreak d = if (!CURSOR) >= (!MARGIN) then (Newline()^bumpcursor(spaces d)) else ""; fun predisplay d (Constant s) = (bumpcursor s) | predisplay d (Numeral n) = (bumpcursor (implode(rev (map makestring n)))) | predisplay d (FreeVar s) =(bumpcursor s) | predisplay d (BoundVar s) = (bumpcursor ("?"^(makestring s))) | predisplay d (Infix(t,i,u)) = if (!NORULES) andalso ruleinfix (opdisplay i) then predisplay d u else let val T = baredisplay t in if T = baredisplay(eitherprefixof (opdisplay i) u) then (bumpcursor (opdisplay i)) ^" " ^(bumpcursor (pp u i 1 "(")) ^(predisplay (if parentest u i 1 then d+1 else d) u) ^(bumpcursor (pp u i 1 ")")) else (bumpcursor (pp t i 0 "(")) ^(predisplay (if parentest t i 0 then d+1 else d) t) ^(bumpcursor (pp t i 0 ")")) ^(bumpcursor " ") ^(maybebreak d) ^(bumpcursor(opdisplay i)) ^(bumpcursor " ") ^(bumpcursor (pp u i 1 "(")) ^(predisplay (if parentest t i 0 then d+1 else d) u) ^(bumpcursor (pp u i 1 ")")) end | predisplay d (Function t) = (bumpcursor "[")^ (predisplay (d+1) t)^(bumpcursor "]") | (* display of case expressions "cheats"; it relies on the surface form of case expressions as complex infix expressions *) (* this works because the display functions are independent of declarations *) predisplay d (CaseExp(t,u,v)) = predisplay d (Infix(t,ResOp("||"),Infix(u,ResOp(","),v))) | (* the case for Parenthesis handles highlighting the current subterm *) predisplay d (Parenthesis t) = (bumpcursor "{") ^(predisplay (d+1) t)^(bumpcursor "}"); fun display t = (CURSOR:=0;(spaces 0)^(predisplay 0 t)); (* the parser *) (* the parser engine works, like the tokenizer, with a list of characters *) (* functions for extracting projections from pairs *) fun p1(x,y) = x; fun p2(x,y) = y; (* the only change involved in user-defined precedence is recording of user-supplied parentheses *) fun getfirstterm L = if (strip L) = nil then (Constant "", nil) else let val A = firstatom L and B = strip(restfirstatom L) in if A <> Constant "" then (* first term is atomic *) (A,B) else let val C = firstop L and D = strip(restfirstop L) in if C <> ConOp "" then (* first term has a prefix operator *) let val E = getterm D in if haseitherprefix (opdisplay C) (p1 E) then if p1 E = Constant "" then (Constant "",nil) else ((* Parenthesis *)( Infix(eitherprefixof(opdisplay C)(p1 E), C,p1 E)),p2 E) else (Infix(Constant "",C,p1 E),p2 E) end else if hd (strip L) = "[" then (* function term *) let val G = getterm (tl(strip L)) in if p1 G = Constant "" orelse p2 G = nil orelse hd(p2 G) <> "]" then (Constant "", nil) else (Function(p1 G),strip(tl(p2 G))) end else if hd (strip L) = "(" then (* parenthesis term *) let val G = getterm (tl(strip L)) in if p1 G = Constant "" orelse p2 G = nil orelse hd(p2 G) <> ")" then (Constant "", nil) else (Parenthesis (p1 G),strip(tl(p2 G))) end else (Constant "",nil) end end and getterm L = let val (A,B) = getfirstterm L in if A = Constant "" then (Constant "",nil) else if B = nil orelse hd B = "]" orelse hd B = ")" then (A,B) else let val C = firstop B and D = strip(restfirstop B) in if C = ConOp "" then (Constant "",nil) else let val E = getterm D in if p1 E = Constant "" then (Constant "",nil) else (Infix(A,C,p1 E),p2 E) end end end; (* the parser reads case expressions as a particular kind of infix expression; the casefix function rectifies this situation and rejects expressions of the form ?x || ?y where ?y is not a pair. *) fun casefix (Infix(x, ResOp "||",Infix(y,ResOp",",z))) = CaseExp(casefix x,casefix y,casefix z) | casefix (Infix(x,ResOp"||",y)) = (errormessage "Ill-formed case expression"; CaseExp(casefix x,Infix(Constant "p1",ResOp"@",casefix y), Infix(Constant "p2",ResOp"@",casefix y))) | casefix (Function t) = Function (casefix t) | casefix (Infix (x,s,y)) = Infix(casefix x,s,casefix y) | casefix t = t; fun parse s = let val A = getterm(explode s) in if p2 A = nil then casefix(deparenthesize(reassociate(p1 A))) else Constant "" end; (* the theorem-embedding infixes which signal intentions to rewrite *) (* reserveop 0 0 "=>"; reserveop 0 0 "<="; *) (* they are actually declared in the setup command at the end *) (* operators of built-in arithmetic *) (* the declarations are actually made later in the setup command *) (* reserveop 0 0 "+!"; reserveop 0 0 "-!"; reserveop 0 0 "*!"; reserveop 0 0 "/!"; reserveop 0 0 "%!"; reserveop 0 0 "!"; reserveop 0 0 "=!"; *) fun arithop s = s = "+!" orelse s = "-!" orelse s = "*!" orelse s = "/!" orelse s = "%!" orelse s = "!" orelse s = "=!"; (* the rulefree function certifies a term as free of "execution behaviour" *) (* execution behaviour refers to presence of embedded theorems, operations of the built-in arithmetic, or case expressions whose hypotheses are truth values or equations with first term true. *) (* declarations for functional programming *) val PROGRAMS = ref ([("bogus","bogus")]); (* command setprogram to bind a program to a constant or operator is found below *) (* USER COMMAND *) (* user program to remove any tactic bound to a function or operator *) fun deprogram s = PROGRAMS := drop s (!PROGRAMS); fun hasprogram s = foundin s (!PROGRAMS); fun programof s = safefind "" s (!PROGRAMS); (* moved here from near changehlevel below because of needs of enhanced higher-order matching *) fun changelevel source target (BoundVar s) = if s <= source andalso s <= target then BoundVar s else if s <= source andalso s > target then Constant "" else BoundVar (target + (s - source)) | changelevel source target (Function t) = let val TRY = changelevel source target t in if TRY = Constant "" then Constant "" else Function TRY end | changelevel source target (Infix(x,i,y)) = let val TRY1 = changelevel source target x and TRY2 = changelevel source target y in if (TRY1 = Constant "" andalso ((not(hasprefix (opdisplay i))) orelse prefixof (opdisplay i) <> "")) orelse TRY2 = Constant "" then Constant "" else Infix(TRY1,i,TRY2) end | changelevel source target (CaseExp(u,v,w)) = let val TRY1 = changelevel source target u and TRY2 = changelevel source target v and TRY3 = changelevel source target w in if TRY1 = Constant "" orelse TRY2 = Constant "" orelse TRY3 = Constant "" then Constant "" else (CaseExp(TRY1,TRY2,TRY3)) end | changelevel source target (Parenthesis u) = let val TRY = changelevel source target u in if TRY = Constant "" then Constant "" else Parenthesis TRY end | changelevel source target t = t; fun rulefree (Infix(Numeral m,ResOp s,Numeral n)) = not(arithop s) | rulefree (Infix(x,ResOp s, y)) = (not(ruleinfix s)) andalso rulefree x andalso rulefree y | rulefree (CaseExp(Infix(Constant"true",ResOp"=",x),y,z)) = false | rulefree (CaseExp (u,v,w)) = u <> Constant "true" andalso u <> Constant "false" andalso rulefree u andalso rulefree v andalso rulefree w | rulefree (Function t) = rulefree t | rulefree (Infix(x,i,y)) = rulefree x andalso rulefree y | rulefree t = true; (* list of "locally free" bound variables on which a term depends -- obviously this needs the level as a parameter *) fun boundvarlist level (BoundVar s) = if s=0 then nil else [s] | boundvarlist level (Infix(u,i,v)) = union (boundvarlist level u) (boundvarlist level v) | boundvarlist level (Function t) = dropfromset (level + 1) (boundvarlist (level+1) t) | boundvarlist level (CaseExp(u,v,w)) = union (boundvarlist level u) (union (boundvarlist level v)(boundvarlist level w)) | boundvarlist level t = nil; (* the "stratification" function for "predicate" abstraction: roughly, no bound variables to occur free in applied position *) (* it's actually rather more elegantly described now; the constraint described above is obtained without any direct reference to bound variables per se *) fun metahead level n (Function t) = metahead (level+1) (n-1) t | metahead level n (Infix(x,ResOp"@!",y)) = metastrat level y andalso metahead level (n+1) x | metahead level n (Infix(x,ResOp"@*",y)) = metastrat level y andalso metahead level (n+1) x | metahead level n (FreeVar x) = true | metahead level n (Infix(x,ResOp"=>",y)) = metahead level n y | metahead level n (Infix(x,ResOp"<=",y)) = metahead level n y | metahead level n (Parenthesis t) = metahead level n t | metahead level n (CaseExp(u,v,w)) = metahead level n v andalso metahead level n w | metahead level n t = (n<=0 andalso metastrat level t) and metastrat level (Infix (x,ResOp"@!",y)) = metahead level 1 x andalso metastrat level y | metastrat level (Infix (x,ResOp"@*",y)) = metahead level 1 x andalso metastrat level y | metastrat level (Infix(x,i,y)) = metastrat level x andalso metastrat level y | metastrat level (Function t) = metastrat (level+1) t | metastrat level (CaseExp(t,u,v)) = metastrat level t andalso metastrat level u andalso metastrat level v | metastrat level (Parenthesis t) = metastrat level t | metastrat level t = true; (* the master declaration checking function; it checks constants, operators, and bound variables for meaningfulness *) (* declarecheck sends error messages (if the quiet parameter is false), but only for the first error it encounters *) (* design decision: we do not check for meaningless m|-|n, because such things appear to be harmless (and even potentially useful) *) fun declarecheck quiet (level:int) (Constant s) = if isaconstant s then true else ((if quiet then () else errormessage ("Undeclared constant "^s^" found"));false) | declarecheck quiet level (Numeral n) = true | declarecheck quiet level (FreeVar s) = true | declarecheck quiet level (BoundVar s) = if s<=level then true else ((if quiet then () else errormessage ("Meaningless bound variable ?"^(makestring s)^" found"));false) | declarecheck quiet level (Function t) = metastrat level (Function t) andalso declarecheck quiet ((level:int)+1) t | declarecheck quiet level (CaseExp(u,v,w)) = (declarecheck quiet level u) andalso (declarecheck quiet level v) andalso (declarecheck quiet level w) | declarecheck quiet level (Infix(x,ResOp"@!",y)) = declarecheck quiet level x andalso declarecheck quiet level y andalso metahead level 1 x | declarecheck quiet level (Infix(x,ResOp"@*",y)) = declarecheck quiet level x andalso declarecheck quiet level y andalso metahead level 1 x | declarecheck quiet level (Infix(u,ResOp s,v)) = if isstrictprefix s then if u = Constant "" then declarecheck quiet level v else ((if quiet then () else errormessage ("Exclusive prefix operator "^s^" used as infix"));false) else (declarecheck quiet level u) andalso (declarecheck quiet level v) | declarecheck quiet level (Infix(u,VarOp s,v)) = if stringtoop s <> VarOp s then ((if quiet then () else errormessage ("Ill-formed infix variable "^s));false) else if isstrictprefix s then if u = Constant "" then declarecheck quiet level v else ((if quiet then () else errormessage ("Exclusive prefix operator "^s^" used as infix"));false) else if isopaque s then (declarecheck quiet level u) andalso (declarecheck quiet level v) else if u = Constant "" then (nopausemessage ("Automatically declaring opaque prefix operator "^s); declarestrictprefix s; declareopaque s; declarecheck quiet level v) else ((nopausemessage ("Automatically declaring opaque infix operator "^s); declareopaque s); (declarecheck quiet level u) andalso (declarecheck quiet level v)) | declarecheck quiet level (Infix(u,ConOp s,v)) = if isstrictprefix s then if u = Constant "" then (declarecheck quiet level v) andalso if isoperator s then true else ((if quiet then () else errormessage ("Undeclared operator "^s^" found"));false) else ((if quiet then () else errormessage ("Exclusive prefix operator "^s^" used as infix"));false) else (declarecheck quiet level u) andalso (declarecheck quiet level v) andalso if isoperator s then true else ((if quiet then () else errormessage ("Undeclared operator "^s^" found"));false) | declarecheck quiet level (Parenthesis u) = ((if quiet then () else errormessage ("Braces found"));false); (* stratification checking *) (* reserveop 0 0 ":"; *) (* the type label (retraction) infix *) (* the actual declaration is deferred to setup *) (* the stratification function takes as its parameter a local type and generates a list of lists of type assignments to bound variables, which will be empty if there is no consistent type assignment; otherwise, the first of these lists will be the types fixed for bound variables in the given context, while subsequent lists record known "relative" types which may be shifted by a constant amount *) (* BEGIN deleted stuff for old stratification algorithm (* utilities which operate on lists of type assignments *) fun shifttype n nil = nil | shifttype (n:int) ((p,q)::L) = ((p,q+n)::shifttype n L); (* finds a candidate for the displacement between two type assignments -- does not check for consistency! *) (* returns nil if there is no point of contact between the lists *) fun typediff nil L = nil | typediff ((p,q:int)::L) M = let val A = find p M in if A = nil then typediff L M else [q -(hd A)] end; (* shiftmerge, given two type assignment lists, returns the list of the two if they have no point of contact, returns nil if they are inconsistent, and returns the merged list otherwise (shifting the second list by the amount reported by typediff) *) (* the first two clauses allow for considerable simplification; "floating" lists with zero or one entry do not supply any information, but may not merge using the third clause *) fun shiftmerge L nil = [L] | shiftmerge L (x::nil) = [L] | shiftmerge L M = if typediff L M = nil then [L, M] else merge L (shifttype (hd (typediff L M)) M); (* crushtypes simplifies a list of type assignment lists, merging any lists which have a point of contact and preserving the special role of the head of the list (whose types must be fixed) *) fun crushtypes nil = nil | crushtypes (L::nil) = (L::nil) | crushtypes (L::(M::rest)) = let val A = crushtypes (M::rest) in if A = nil then nil else let val (N::rest2) = A in let val B = shiftmerge L N in if B = nil then nil else if B = [L,N] then ((crushtypes (L::rest2))@[N]) else crushtypes (B@rest2) end end end; (* merges two type lists *) fun mergetypes nil L = nil | mergetypes M nil = nil | mergetypes (L::rest1) (M::rest2) = if merge L M = nil then nil else crushtypes((merge L M)@rest1@rest2); (* checkappend is used in strat for "floating" a type list; we check that the list we are "floating" isn't nil before we prepend [nil] to it *) fun checkappend L M = if M = nil then nil else L@M; END deleted stuff for old stratification algorithm *) (* development of type of "variables plus numerals" used for new extended stratification algorithm *) (* simplifying assumptions for "unknown displacements": forbid @* terms in arguments of @*. Further, forbid floating types in arguments of @*. These are reasonable restrictions, met for example by any higher-order pattern. If you do this, then all types in any given argument of a @* will have the same fixed unknown displacement, so an unknown displacement can safely be converted directly to a floating displacement when it is floated? forall @ [forall @ [ forall@[((?P@*?1)@*?2)@?3]]] so all types assigned to a given argument will have the same unknown displacement from an assortment of rigid types. Another idea: can we suppose that all rigid types in a problem are floated by the same unknown amount -- then when an assignment is made to one floated rigid type, all other floated rigid types become unfloated unknown types again? Add additional condition to stratification of @* terms -- all types in the stratification of the argument must be concrete integers. Further, unknown floating types may only be equated with rigid types, and when one unknown floating type is equated with a rigid type, all other unknown floating types revert to rigidity. In fact, when any type equation is imposed, all unknown floating types revert to rigidity? *) datatype relative_type = rigid_type of int | floating_type of (int*int) | unknown_rigid_type of (int*int) | unknown_floating_type of (int*int*int); (* probably we can broaden this to allow floating types to match unknown types. Unknown floating types with different floats can probably also be coordinated. *) (* string coding argument place of a variable type-raising operator *) (* fun sillystring (FreeVar s) = s | sillystring (Infix(t,ResOp "@*",u)) = (sillystring t)^"#"; *) fun force_equation (floating_type(p,q)) (floating_type(r,s)) (floating_type(t,u)) = if p<>r andalso t=p then floating_type(r,u+(s-q)) else floating_type(t,u) | force_equation (floating_type(p,q)) (floating_type(r,s)) (unknown_floating_type(t,u,v)) = if p=t then unknown_floating_type(r,u,v) else unknown_floating_type(t,u,v) | force_equation x (floating_type(p,q)) (floating_type(p1,q1)) = force_equation (floating_type(p,q)) x (floating_type(p1,q1)) | force_equation x (floating_type(p,q)) (unknown_floating_type(p1,q1,r)) = force_equation (floating_type(p,q)) x (unknown_floating_type(p1,q1,r)) | force_equation (floating_type(p,q)) (unknown_floating_type(t,u,v)) (floating_type(w,x)) = if p=w then unknown_floating_type(t,u,x+(v-q)) else (floating_type(w,x)) | force_equation (floating_type(p,q)) (unknown_floating_type(t,u,v)) (unknown_floating_type(w,x,y)) = if p=w then (unknown_floating_type(t,x,y)) else (unknown_floating_type(w,x,y)) | force_equation (floating_type(p,q)) (rigid_type n) (floating_type(r,s)) = if p=r then rigid_type(s+(n-q)) else (floating_type(r,s)) | force_equation (floating_type(p,q)) (rigid_type n) (unknown_floating_type(r,s,t)) = if p=r then unknown_rigid_type(s,t) else (unknown_floating_type(r,s,t)) | force_equation (floating_type(p,q)) (unknown_rigid_type(i,j)) (floating_type(r,s)) = if p=r then unknown_rigid_type(i,s+(j-q)) else (floating_type(r,s)) | force_equation (floating_type(p,q)) (unknown_rigid_type(i,j)) (unknown_floating_type(r,s,t)) = if p=r then unknown_rigid_type(s,t) else (unknown_floating_type(r,s,t)) | force_equation (unknown_floating_type(a,b,c)) (unknown_floating_type(d,e,f)) (unknown_floating_type(g,h,i)) = if a=g then if b=h then unknown_floating_type(d,e,i+(f-c)) else unknown_floating_type(d,h,i) else unknown_floating_type(g,h,i) | force_equation x (unknown_floating_type(a,b,c)) (unknown_floating_type(a1,b1,c1)) = force_equation (unknown_floating_type(a,b,c)) x (unknown_floating_type(a1,b1,c1)) | force_equation (unknown_floating_type(a,b,c)) (rigid_type n) (unknown_floating_type(d,e,f)) = if a=d then if b=e then rigid_type(f+(n-c)) else unknown_rigid_type(e,f) else unknown_floating_type(d,e,f) | force_equation (unknown_floating_type(a,b,c)) (rigid_type n) (floating_type(d,e)) = if a = d then unknown_rigid_type(b,e) else (floating_type(d,e)) | force_equation (unknown_floating_type(a,b,c)) (unknown_rigid_type(d,e)) (unknown_floating_type(f,g,h)) = if a=f then if b=g then unknown_rigid_type(d,h+(e-c)) else unknown_rigid_type(g,h) else unknown_floating_type(f,g,h) | force_equation (unknown_floating_type(a,b,c)) (unknown_rigid_type(d,e)) (floating_type(f,g)) = if a=f then unknown_rigid_type(b,g) else (floating_type(f,g)) | force_equation x y z = z; fun can_equal (floating_type(p,q)) (floating_type(r,s)) = if p=r then q=s else true | can_equal (floating_type(p,q)) (unknown_floating_type(r,s,t)) = p<>r | can_equal (floating_type(p,q)) x = true | can_equal x (floating_type(p,q)) = can_equal (floating_type(p,q)) x | can_equal (unknown_floating_type(r,s,t)) (unknown_floating_type(u,v,w)) = if r=u then s=v andalso t=w else true | can_equal (unknown_floating_type(r,s,t)) (unknown_rigid_type(u,v)) = if s=u then t=v else true | can_equal (unknown_floating_type(r,s,t)) x = true | can_equal x (unknown_floating_type(r,s,t)) = can_equal (unknown_floating_type(r,s,t)) x | can_equal x y = x=y; (* fun is_rigid (rigid_type n) = true | is_rigid x = false; (* recognizes completely rigid stratifications *) fun all_rigid nil = false | all_rigid [nil] = true | all_rigid [((x,rigid_type n)::L)] = all_rigid [L] | all_rigid x = false; *) (* is_rigid is generalized for subsequent (now all) uses *) fun is_rigid (rigid_type n) = true | is_rigid (unknown_rigid_type(i,j)) = true | is_rigid x = false; val TYPE_VAR_INDEX = ref 0; fun reset_type_var_index() = TYPE_VAR_INDEX := 0; fun bump_type_var_index() = TYPE_VAR_INDEX:=(!TYPE_VAR_INDEX)+1; fun fresh_type_var_index() = (bump_type_var_index();(!TYPE_VAR_INDEX)); (* fun prepend x nil = nil | prepend x [L] = [(x::L)] | prepend x y = nil; *) (* first argument = processed part of list; second argument = rest of list *) fun fix_function1 L nil = [L] | fix_function1 L ((x,n)::M) = let val F = find x M in if F = nil then fix_function1 ((x,n)::L) M else if can_equal (hd F) n then fix_function1 nil (map (fn (x,y) => (x,force_equation n (hd F) y)) (L@M)) else nil end; fun fix_function L = fix_function1 nil L; fun mergestrats nil L = nil | mergestrats L nil = nil | mergestrats [L] [M] = fix_function(union L M) | mergestrats x y = nil; fun float_list nil = nil | float_list [L] = [let val M = separate (fn (x,N) => is_rigid N) L in if length M < 2 then separate (fn (x,N) => not(is_rigid N)) L else let val T = fresh_type_var_index() in (map (fn (x,rigid_type n) => (x,floating_type(T,n))| (x,unknown_rigid_type(i,j)) => (x,unknown_floating_type(T,i,j))) M)@ (separate (fn (x,N) => not(is_rigid N)) L) end end]; fun displace_list T nil = nil | displace_list T [L] = [(map (fn (x,rigid_type n) => (x,unknown_rigid_type(T,n)) | (x,y) => (x,y)) L)]; fun metafree (Infix(x,ResOp t,y)) = t<>"@!" andalso t<>"@*" andalso metafree x andalso metafree y | metafree (Infix(x,i,y)) = metafree x andalso metafree y | metafree (Function t) = metafree t | metafree (CaseExp(u,v,w)) = metafree u andalso metafree v andalso metafree w | metafree (Parenthesis t) = metafree t | metafree t = true; (* the main stratification function *) (* another stratification function will be needed by the definition function -- it will type free variables rather than bound variables *) (* all changes to strat must also be made to prestrat2 *) (* val CHECKTYPE = ref 0; *) fun strat level localtype (Constant s) = [nil] | strat level localtype (FreeVar s) = [nil] | strat level localtype (Numeral s) = [nil] | strat level localtype (BoundVar s) = if s = 0 then [nil] else [[(s,rigid_type(localtype))]] | strat level localtype (Function s) = map (drop (level+1)) (mergestrats (strat (level+1) (localtype-1) s) [[(level+1,rigid_type(localtype-1))]]) | strat level localtype (CaseExp(t,u,v)) = mergestrats(float_list(strat level localtype t)) (mergestrats(strat level localtype u) (strat level localtype v)) | (* strat level localtype (Infix(t,ResOp":",u)) = mergetypes (strat level (localtype+1) t) (checkappend [nil] (strat level localtype u)) | *) strat level localtype (Infix(t,ResOp":",u)) = if (strat level (localtype) t = [nil]) then (float_list (strat level localtype u)) else nil | strat level localtype (Infix(Constant f,ResOp "@",t)) = (if (* level = 0 orelse *) isscout f orelse isscinright f then float_list else (fn x => x)) (strat level localtype t) | strat level localtype (Infix(Infix(t,ResOp"@*",m),ResOp"@*",n)) = let val N = strat level localtype n in if metafree n then mergestrats (displace_list (fresh_type_var_index()) N) (strat level (localtype) (Infix(t,ResOp"@*",m))) else nil end | strat level localtype (Infix(FreeVar t,ResOp "@*",n)) = let val N = strat level localtype n in if metafree n then displace_list (fresh_type_var_index()) N else nil end | strat level localtype (Infix(t,ResOp"@*",u)) = nil | strat level localtype (Infix(t,i,u)) = if istypedoperator (opdisplay i) then (if (* level = 0 orelse *) isscout (opdisplay i) then float_list else (fn x => x)) (mergestrats ((if (* level = 0 orelse *) isscinleft (opdisplay i) then float_list else (fn x => x)) (strat level (lefttype(opdisplay i)+localtype) t)) ((if (* level = 0 orelse *) isscinright (opdisplay i) then float_list else (fn x => x)) (strat level (righttype(opdisplay i)+localtype) u))) else (* case of opaque or undeclared variable operators *) if boundvarlist level (Infix(t,i,u)) = nil andalso strat level 0 t <> nil andalso strat level 0 u <> nil then [nil] else nil; fun isstratified level t = (reset_type_var_index(); strat level 0 t <> nil); (* USER COMMAND *) (* delayed to here because it uses declaration and stratification checking *) fun defaulttypeinfo v t = if stringtocon v = FreeVar v andalso declarecheck false 0 (parse t) (* andalso isstratified 0 (parse t) *) then VARTYPES := strongadd v (parse t) (!VARTYPES) else errormessage ("Declaration or syntax error in assigning type "^t^" to variable "^v); (* the prover environment comes into view! *) (* the prover environment consists of the following elements: name of environment (a string) "format" of environment (a term, used to indicate parameters of a parameterized theorem/tactic) left side of equation being proved (a term) right side of equation being proved (a term) current position in term (a list of booleans, true = right, false = left, the step into a function term is either right or left indifferently) current level and "hypothesis level" (two integers) list of local hypotheses (a list of "theorems" derived from hypotheses of case expressions -- a triple consisting of two terms to be equated and an integer coding the "sense" (positive, negative, or inactive) of the hypothesis) dependencies of current environment -- only the traditional kind will be considered; the new definition and theorem-text dependencies will be maintained separately The theorem data structure is almost the same, except that it does not have position-dependent components *) (* a workhorse function -- apply a function to a term at a position *) fun applyat f nil t = f t | applyat f (a::L) (Constant s) = (errormessage "Subterm error";Constant s) | applyat f (a::L) (FreeVar s) = (errormessage "Subterm error";FreeVar s) | applyat f (a::L) (BoundVar s) = (errormessage "Subterm error";BoundVar s) | applyat f (a::L) (Numeral s) = (errormessage "Subterm error";Numeral s) | applyat f (a::L) (Function t) = Function (applyat f L t) | applyat f (false::L) (Infix(u,i,v)) = if u = Constant "" then (errormessage "Subterm error";(Infix(u,i,v))) else (Infix(applyat f L u,i,v)) | applyat f (true::L) (Infix(u,i,v)) = (Infix(u,i,applyat f L v)) | applyat f (false::L) (CaseExp(u,v,w)) = CaseExp(applyat f L u,v,w) | applyat f (true::(false::L)) (CaseExp(u,v,w)) = CaseExp(u,applyat f L v,w) | applyat f (true::(true::L)) (CaseExp(u,v,w)) = CaseExp(u,v,applyat f L w) | (* the Parenthesis case below helps prevent the prover from issuing an error message when just looking at the virtual subterm *) applyat f (true::nil) (CaseExp(u,v,w)) = ((let val A = f (Infix(v,ResOp",",w)) in if A = (Infix(v,ResOp",",w)) orelse A = Parenthesis((Infix(v,ResOp",",w))) then () else errormessage "Virtual subterm of case expression" end); (CaseExp(u,v,w))); (* the prover environment data type *) (* this is a structure with nine fields as indicated above *) fun ename (na,fo,lt,rt,po,lev,hlev,hyps,deps) = na; fun formatof (na,fo,lt,rt,po,lev,hlev,hyps,deps) = fo; fun leftside (na,fo,lt,rt,po,lev,hlev,hyps,deps) = lt; fun rightside (na,fo,lt,rt,po,lev,hlev,hyps,deps) = rt; fun position (na,fo,lt,rt,po,lev,hlev,hyps,deps) = po; fun level (na,fo,lt,rt,po,lev,hlev,hyps,deps) = lev; fun hlevel (na,fo,lt,rt,po,lev,hlev,hyps,deps) = hlev; fun hypslist (na,fo,lt,rt,po,lev,hlev,hyps,deps) = hyps; fun deps (na,fo,lt,rt,po,lev,hlev,hyps,deps) = deps; (* functions which change environment fields to given values *) fun changeename na2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na2,fo,lt,rt,po,lev,hlev,hyps,deps); fun changeformatof fo2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo2,lt,rt,po,lev,hlev,hyps,deps); fun changeleftside lt2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt2,rt,po,lev,hlev,hyps,deps); fun changerightside rt2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt2,po,lev,hlev,hyps,deps); fun changeposition po2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt,po2,lev,hlev,hyps,deps); fun changeelevel lev2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt,po,lev2,hlev,hyps,deps); fun changeehlevel hlev2 (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt,po,lev,hlev2,hyps,deps); fun changehypslist hyps2 (na,fo,lt,rt,po,lev,hlev,hyps,deps)= (na,fo,lt,rt,po,lev,hlev,hyps2,deps); fun changedeps deps2 (na,fo,lt,rt,po,lev,hlev,hyps,deps)= (na,fo,lt,rt,po,lev,hlev,hyps,deps2); (* functions which apply given functions to environment fields *) fun changeename2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (f na,fo,lt,rt,po,lev,hlev,hyps,deps); fun changeformatof2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,f fo,lt,rt,po,lev,hlev,hyps,deps); fun changeleftside2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,f lt,rt,po,lev,hlev,hyps,deps); fun changerightside2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,f rt,po,lev,hlev,hyps,deps); fun changeposition2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt,f po,lev,hlev,hyps,deps); fun changelevel2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt,po,f lev,hlev,hyps,deps); fun changehlevel2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps) = (na,fo,lt,rt,po,lev,f hlev,hyps,deps); fun changehypslist2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps)= (na,fo,lt,rt,po,lev,hlev,f hyps,deps); fun changedeps2 f (na,fo,lt,rt,po,lev,hlev,hyps,deps)= (na,fo,lt,rt,po,lev,hlev,hyps,f deps); (* the current prover environment *) val ENV = ref("",Constant "", Constant "", Constant "", [true],0,0,[(Constant"",Constant"",[true],0,0)],["bogus"]); (* apply a function to the environment *) fun envmod f = ENV:=f (!ENV); (* reference for temporarily posting new dependencies *) val NEWDEPS = ref ["bogus"]; (* dependency posting function *) fun postdeps() = (envmod(changedeps2 (union(!NEWDEPS))) ;NEWDEPS:=nil); fun dropdeps() = NEWDEPS:=nil; (* term viewing functions *) (* these are actually identity functions with side effects *) val PROMPT = ref true; fun termprompts() = PROMPT := not (!PROMPT); fun showterm prompt t = (if (!VERBOSITY) = 2 then (output(std_out, (if (!PROMPT) then ("\n"^prompt^":") else "") ^"\n\n"^(display t)^(if (!GUIMODE) then ((!Returns)^". . .") else "") ^(!Returns)); flush_Out(std_out)) else ();t); fun exec f = envmod (changerightside2 (applyat f (position(!ENV)))); (* USER COMMAND *) (* look at current subterm *) fun lookhere() = exec (showterm "Local term display"); (* variables controlling the look display *) val LOCAL_DISPLAY = ref true; val GLOBAL_DISPLAY = ref true; (* USER COMMAND *) (* look at current subterm and at top of right side of equation *) (* insert a "parenthesis" temporarily to highlight current subterm *) fun look() = (exec Parenthesis; envmod(changerightside2 (if (!GLOBAL_DISPLAY) then (showterm "Global term display") else (fn x => x))); exec deparenthesize1; lookhere()); (* USER COMMANDS (3) *) (* control the look display *) fun localdisplayoff() = (LOCAL_DISPLAY:=false;GLOBAL_DISPLAY:=true;look()); fun globaldisplayoff()= (LOCAL_DISPLAY:=true;GLOBAL_DISPLAY:=false;look()); fun bothdisplays()= (LOCAL_DISPLAY:=true;GLOBAL_DISPLAY:=true;look()); (* USER COMMAND *) (* look at the left side of the equation under construction *) fun lookback() = envmod(changeleftside2 (showterm "Initial term display")); (* term starting functions appear below after the environment saving commands, which have to appear after the declaration of the theorem list *) val SWAPTERM = ref (Constant ""); (* USER COMMAND *) (* interchange the left and right sides of the equation under construction *) fun workback() = (SWAPTERM:=leftside(!ENV); envmod(changeleftside (rightside(!ENV))); envmod(changerightside (!SWAPTERM)); envmod(changeposition nil); envmod(changeelevel 0); envmod(changeehlevel 0); envmod(changehypslist nil);look()); (* functions acting on positions that implement the term navigation commands *) fun preup nil = (errormessage "At top already!";nil) | preup L = rev(tl(rev L)); fun preright L = rev (true::(rev L)); fun preleft L = rev (false::(rev L)); (* we also need functions acting on levels, hlevels, and hypothesis lists which support the movement commands *) (* when one moves into or out of a function term, one needs to adjust the level (the number of nested brackets enclosing one); when moving into or out of case expressions, one needs to adjust the hlevel (the number of relevant hypotheses of case expressions) and the list of relevant hypotheses with their senses (positive, negative, or (at the virtual subexpression) inactive) *) val CURRENTTERM = ref(Constant ""); fun makecurrent t = (CURRENTTERM:=t;t); fun getcurrent() = exec (makecurrent); fun levelchange (Function f) n = n+1 | levelchange t n = n; fun uplevelchange (Function f) n = n-1 | uplevelchange t n = n; fun hlevelchange (CaseExp(u,v,w)) n = n+1 | hlevelchange t n = n; fun uphlevelchange (CaseExp(u,v,w)) n = n-1 | uphlevelchange t n = n; (* builds equation from hypothesis of a case expression and records current position *) (* true=?y is indistinguishable from ?y *) fun equationfromterm (Infix(x,ResOp"=",y)) = (x,y,position(!ENV),0,level(!ENV)) | equationfromterm t = (Constant "true",t,position(!ENV),0,level(!ENV)); fun hypslistchange (CaseExp(u,v,w)) L = rev((equationfromterm u)::(rev L)) | hypslistchange t L = L; fun listindex n nil = nil | listindex 1 (a::L) = [a] | listindex n (a::L) = listindex (n-1) L; fun presethypslistsense (x,y,p,n,l) = let val A = listindex ((length p)+2) (position(!ENV)) in if A = nil then (x,y,p,0,l) else if A = [false] then (x,y,p,1,l) else if A = [true] then (x,y,p,2,l) else (x,y,p,0,l) end; fun sethypslistsense L = if L = nil then nil else rev((presethypslistsense(hd (rev L)))::(tl (rev L))); fun coercehypslistsense n lv (x,y,p,m,l) = (x,y,p,n,lv); fun uphypslistchange (CaseExp(u,v,w)) L = if L = nil then nil else rev(tl (rev L)) | uphypslistchange t L = L; (* the basic movement commands *) (* they have "silent" variants used by the fancy movement commands below *) (* USER COMMAND *) fun up() = if position(!ENV) = nil then errormessage "At top already!" else if hd (rev (position (!ENV))) = true then (* coming up from right *) (envmod (changeposition2 preup); getcurrent(); envmod (changelevel2 (uplevelchange (!CURRENTTERM))); envmod (changehlevel2 (uphlevelchange (!CURRENTTERM))); envmod (changehypslist2 (uphypslistchange(!CURRENTTERM))); envmod (changehypslist2 (sethypslistsense)); look()) else (* coming up from left *) (envmod (changeposition2 preup); getcurrent(); envmod (changelevel2 (uplevelchange (!CURRENTTERM))); envmod (changehypslist2 (sethypslistsense)); look()); fun sup() = if position(!ENV) = nil then errormessage "At top already!" else if hd (rev (position (!ENV))) = true then (* coming up from right *) (envmod (changeposition2 preup); getcurrent(); envmod (changelevel2 (uplevelchange (!CURRENTTERM))); envmod (changehlevel2 (uphlevelchange (!CURRENTTERM))); envmod (changehypslist2 (uphypslistchange(!CURRENTTERM))); envmod (changehypslist2 (sethypslistsense))) else (* coming up from left *) (envmod (changeposition2 preup); getcurrent(); envmod (changelevel2 (uplevelchange (!CURRENTTERM))); envmod (changehypslist2 (sethypslistsense)) ); (* USER COMMAND *) fun left() = (getcurrent(); envmod (changelevel2 (levelchange (!CURRENTTERM))); envmod (changeposition2 preleft); envmod (changehypslist2 (sethypslistsense)); look()); fun sleft() = (getcurrent(); envmod (changelevel2 (levelchange (!CURRENTTERM))); envmod (changeposition2 preleft); envmod (changehypslist2 (sethypslistsense)) ); (* USER COMMAND *) fun right() = (getcurrent(); envmod (changelevel2 (levelchange (!CURRENTTERM))); envmod (changehlevel2 (hlevelchange (!CURRENTTERM))); envmod (changehypslist2 (hypslistchange (!CURRENTTERM))); envmod (changeposition2 preright); envmod (changehypslist2 (sethypslistsense)); look()); fun sright() = (getcurrent(); envmod (changelevel2 (levelchange (!CURRENTTERM))); envmod (changehlevel2 (hlevelchange (!CURRENTTERM))); envmod (changehypslist2 (hypslistchange (!CURRENTTERM))); envmod (changeposition2 preright); envmod (changehypslist2 (sethypslistsense)) ); (* USER COMMAND *) fun top() = (envmod (changeelevel 0); envmod (changeehlevel 0); envmod(changehypslist nil); envmod (changeposition nil); look()); (* USER COMMAND *) (* used to check correct execution in scripts *) fun verify s = (top();if (parse s) = rightside(!ENV) then () else errormessage ("Verification failure")); (* theorem declaration list *) (* A theorem consists of the following components: a name (which appears as a key in the theorems list rather than part of the structure) a format (used to supply parameters) (a term) left side of equation (a term) right side of equation (a term) a dependency list (the new definition and theorem-text dependency schemes will be supported by separate lists) Note the similarity to a proof environment; eliminating the components of a proof environment which support navigation yields a theorem. *) val THEOREMS = ref ([("bogus",(Constant "",Constant "",Constant "",["bogus"]))]); fun theorysize() = nopausemessage(makestring(length(!THEOREMS))); (* theorems declared but to be proved later -- i.e., recursive tactics *) val PRETHEOREMS = ref ["bogus"]; (* list of tactic modules *) val MODULES = ref [("bogus",(!THEOREMS))]; (* what module is a given theorem in? *) val MODULES_INVERSE = ref [("bogus","bogus")]; fun whichmodule s = safefind "" s (!MODULES_INVERSE); fun addwhichmodule s m = (* if m = "" then MODULES_INVERSE := drop s (!MODULES_INVERSE) else *) MODULES_INVERSE := strongadd s m (!MODULES_INVERSE); (* commands for manipulating theorems list and individual theorems *) fun addtheorem name fo ls rs dps = (THEOREMS:= strongadd name (fo,ls,rs,dps) (!THEOREMS); PRETHEOREMS := dropfromset name (!PRETHEOREMS)); (* weak addtheorem command used for module manipulations *) fun addtheorem2 name thm = THEOREMS := addto name thm (!THEOREMS); fun droptheorem name = THEOREMS:= drop name (!THEOREMS); val dummythm = (Constant "", Constant "", Constant "", []); fun PreFormatof (a,b,c,d) = a; fun PreLeftside (a,b,c,d) = b; fun PreRightside (a,b,c,d) = c; fun PreDeps (a,b,c,d) = d; fun Thm name = safefind dummythm name (!THEOREMS); fun Formatof name = PreFormatof (safefind dummythm name (!THEOREMS)); fun Leftside name = PreLeftside (safefind dummythm name (!THEOREMS)); fun Rightside name = PreRightside (safefind dummythm name (!THEOREMS)); fun Deps name = PreDeps (safefind dummythm name (!THEOREMS)); (* string lists will be converted to terms when needed for theorem deps *) fun listtoterm nil = Numeral [0] | listtoterm (s::L) = Infix(if stringtocon s = Constant s then Constant s else Infix(FreeVar "?x",ConOp s,FreeVar "?y") ,ResOp ",",listtoterm L); fun listtoterm2 L = baredisplay(listtoterm L); fun termtolist (Numeral [0]) = nil | termtolist (Infix(Constant s,ResOp",",y)) = (s::(termtolist y)) | termtolist (Infix(Infix(x,ConOp s,y),ResOp",",z)) = (s::(termtolist z)) | termtolist x = nil; fun termtolist2 s = termtolist (parse s); (* either version of isatheorem is true only of "theorems" actually found on the theorem list; built-in tactics are treated separately *) fun isatheorem name = foundin name (!THEOREMS); (* this version of isatheorem is used inside thmresult only as a possible optimization *) fun Isatheorem name = Foundin name (THEOREMS); fun hasmodule name = safefind nil name (!MODULES) <> nil; fun moduleof name = if hasmodule name then hd(find name (!MODULES)) else nil; (* USER COMMANDS (4) *) (* name1 is pushed into the module associated with name2 *) (* this command needs to be moved later in the file and made safe with respect to dependencies *) (* but this form of push will still be wanted for the internals of the close command *) (* notice that this form will push into hidden modules, which is needed for CloseAll to work *) fun push name1 name2 = if not(isatheorem name1) then errormessage (name1^" is not a theorem") else if not(hasmodule name2 orelse isatheorem name2) then errormessage (name2^" is not a theorem") else if name1 = name2 then errormessage ("Theorem "^name1^" cannot be pushed into its own module") else if whichmodule name1 <> whichmodule name2 andalso whichmodule name1 <> name2 then errormessage (name1^" and "^name2^" need to originate in the same module") else (addwhichmodule name1 name2; MODULES:= strongadd name2 ((sortfunput2 name1 (Thm name1) (moduleof name2))) (!MODULES);