packages feed

derivation-trees (empty) → 0.7.1

raw patch · 9 files changed

+1206/−0 lines, 9 filesdep +applicative-extrasdep +basedep +mtlsetup-changed

Dependencies added: applicative-extras, base, mtl

Files

+ Data/LabeledTree.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE TypeOperators #-}+module Data.LabeledTree where++import Data.Traversable+import Data.Foldable+import Control.Applicative++data Tree k a = Node  {+      rootLabel :: a,+      subForest :: Forest k a+} deriving Show++data k ::> a = k ::> a+ deriving Show++type Forest k a = [k ::> Tree k a]++instance Functor ((::>) k) where+    fmap = fmapDefault++instance Foldable ((::>) k) where+    foldMap = foldMapDefault++instance Traversable ((::>) k) where+    traverse f (k ::> v) = (::>) k <$> f v++instance Functor (Tree k) where+    fmap = fmapDefault++instance Foldable (Tree k) where+    foldMap = foldMapDefault++instance Traversable (Tree k) where   +    traverse f (Node l sf) = Node <$> f l <*> (traverse (traverse (traverse f)) sf)
+ DerivationTrees.hs view
@@ -0,0 +1,215 @@+{-# LANGUAGE DisambiguateRecordFields, NamedFieldPuns, RecordWildCards, PostfixOperators, LiberalTypeSynonyms, TypeOperators #-}++module DerivationTrees (+-- * Basics+module Data.Monoid,+module Data.LabeledTree,++-- * TeX extras+brace, paren, brack, tex, text, (!),++-- * Derivation' building+-- axiom, rule, etc, aborted, +emptyDrv, haltDrv, haltDrv', abortDrv, delayPre, +dummy, rule, Derivation, Premise, Rule(..),++-- * Figure building+Figure(..),++-- * Engine+compile++) where++import DerivationTrees.Basics+import Data.List+import Data.Traversable hiding (mapM)+import Control.Monad.Writer +import Control.Monad.State +import Control.Applicative +import System.IO.Unsafe+import Data.LabeledTree+import Control.Applicative.State+import Data.Monoid++data Rule tag = Rule {tag :: tag, style :: LineStyle, delimiter :: TeX, label :: TeX, conclusion :: TeX}+  deriving Show+++instance Monoid t => Applicative (Writer t) where+    pure = return+    (<*>) = ap++type Premise = Link ::> Derivation' ()+type Derivation' tag = Tree Link (Rule tag) +type Derivation = Derivation' ()++data Figure tag = Figure {ident :: Int, contents :: Derivation' tag}++alloc = do+  x <- get+  put (x + 1)+  return x++------------------------------------------------------------+-- Phase 1: Detach++type Detach x = x -> Writer [Figure ()] x++detachP :: Detach Premise+detachP (Detached{..} ::> d) = do+  d'@(Node r ps) <- detachD d+  tell [Figure {contents = Node r {delimiter = label} ps,..}]+  return $ (defaultLink ::> haltDrv label d)+detachP (l ::> d) = (l ::>) <$> detachD d++detachD :: Detach Derivation+detachD (Node n ps) = Node n <$> for ps detachP++detachF :: Figure () -> Writer [Figure ()] ()+detachF Figure{..} = do+  contents <- detachD contents+  tell [Figure{..}]++detachTop :: [Figure ()] -> [Figure ()]+detachTop fs = snd $ runWriter $ for fs detachF++--------------------------------------------------+-- Phase 2: Delay++insertAt n x xs = take n xs ++ x : drop n xs++rm idx [] = []+rm 0 (x:xs) = xs+rm n (x:xs) = x : rm (n-1) xs++depth (Detached{} ::> _) = 2+depth (Link{steps} ::> Node _ ps) = 1 + steps + maximum (0 : map depth ps)++isDelayed :: Premise -> Bool+isDelayed (Delayed{} ::> _) = True+isDelayed _ = False++delayPre a s (Link {..} ::> j) = Link {steps = s, align = a, ..} ::> j++delayD :: Derivation -> Derivation+delayD (Node r ps0) = Node r [Link {..} ::> d | l ::> d <- ps, +                               let (steps,align) = case l of+                                                     Delayed{..} -> (1 + maximum (0 : map depth ps'),align)+                                                     Link{..} -> (steps,align)]+    where style = Dotted+          label = mempty+          ps = fmap (fmap delayD) ps0+          ps' = filter (not . isDelayed) ps+       ++delayF :: Figure () -> Figure ()+delayF (Figure{..}) = Figure{contents = delayD contents,..}++delayTop = map delayF++++---------------------------------------------------------+-- Phase 3: Tag++type Tag x = x () -> State Int (x Int)++tagify :: Tag Rule+tagify (Rule {..}) = do+  tag <- alloc+  return $ Rule {..}++tagifyFig :: Tag Figure+tagifyFig (Figure {..}) = Figure ident <$> traverse tagify contents++tagifyTop :: [Figure ()] -> State Int [Figure Int]+tagifyTop = mapM tagifyFig++----------------------------------------------------------+-- Phase 4: Texify++fromTeX :: TeX -> String+fromTeX (TeX s) = "\""  ++ s ++ "\""++mkTuple :: [String] -> String+mkTuple l = " (" ++ intercalate "," l ++ ") "+++link (Link {..} ::> Node (Rule{tag}) _) +    | steps == 0 = show tag+    | otherwise = "MVD " ++ show tag ++ " " ++ +                  mkTuple [show steps,show "",fromTeX label,show align,show (fromEnum style)]++type Stringize x = x Int -> Writer [String] ()++stringize :: Stringize Derivation'+stringize (Node Rule {tag = t, ..} premises) = do+  traverse (traverse stringize) premises+  tell ["jgm " ++ show t ++ " " ++ fromTeX conclusion ++ ";"]+  tell ["Nfr " ++ show t ++ mkTuple (map link premises)  ++ " " +++                            mkTuple [fromTeX label,fromTeX delimiter,fromTeX (TeX ""),show (fromEnum style)] ++ ";"]++stringizeFig :: Figure Int -> Writer [String] () +stringizeFig (Figure {..}) = do+  tell ["beginfig(" ++ show ident ++")"]+  stringize contents+  tell ["draw drv_tree;", +        "endfig;"]+  +preamble = ["outputtemplate := \"%j-%c.mps\";",+            "input drv;",+              "verbatimtex %&latex"] ++ lines texPreamble ++ +             [+              "\\begin{document}",+              "etex;",+              "prologues:=3;"+             ]++texPreamble = unsafePerformIO $ readFile "preamble.tex"++stringizeTop figs = do+  tell preamble+  mapM_ stringizeFig figs+  tell ["end"]++------------------------------------------+-- Pipeline++compile :: [Figure ()] -> [String]+compile j = snd $ runWriter $ stringizeTop $ fst $ flip runState 0 $ tagifyTop $ delayTop $ detachTop $ j++-----------------------++rule label conclusion = Rule {tag = (), delimiter = mempty, style = Simple, ..}++dummy :: Rule ()+dummy = (rule mempty mempty) {DerivationTrees.style = None}+emptyDrv = Node dummy []++abortDrv (Node Rule {..} _) = Node Rule {style = Waved, ..} []++-- | Used when the rest of the derivation is known.+haltDrv' :: TeX -> Derivation -> Derivation+haltDrv' tex (Node r _) = Node r {DerivationTrees.style = None} +     [defaultLink {DerivationTrees.Basics.style = TeXDotted, steps = 1, DerivationTrees.Basics.label = tex} ::> emptyDrv]++-- | More compact variant+haltDrv :: TeX -> Derivation -> Derivation+haltDrv t (Node r _) = Node r [defaultLink ::> Node dummy {conclusion = tex "vdots" [] <> tex "hspace" [TeX "2pt"] <> t} []]+++-------------------------+brace :: TeX -> TeX+brace (TeX x) = TeX $ '{' : x ++ ['}']+paren (TeX x) = TeX $ '(' : x ++ [')']+brack (TeX x) = TeX $ "[" ++ x ++ "]"++tex :: String -> [TeX] -> TeX+tex macro args = TeX ('\\' : macro) <> mconcat (map brace args)+text x = tex "text" [TeX x]++f ! x = brace f <> TeX "_" <> brace x+++
+ DerivationTrees/Basics.hs view
@@ -0,0 +1,34 @@+{-# LANGUAGE NoMonomorphismRestriction, GeneralizedNewtypeDeriving #-}++module DerivationTrees.Basics ++ where++import Data.Monoid++data LineStyle = None | Simple | Double | Dotted | Dashed | Waved | TeXDotted +  deriving (Enum,Show)++data Link = Link {label :: TeX, style :: LineStyle, align :: Alignment, steps :: Int}  -- ^ Regular link+          | Detached {ident :: Int, label :: TeX}                                      -- ^ Detach the derivation as another figure+          | Delayed {align :: Alignment} -- ^ automatic delaying+ deriving Show++defaultLink :: Link+defaultLink = Link mempty Dotted CenterA 0++data Alignment = LeftA | CenterA | RightA+instance Show Alignment where    +    show LeftA = "l"+    show CenterA = "c"+    show RightA = "r"++newtype TeX = TeX String+  deriving (Show, Monoid)++(<>) = mappend++void :: TeX -> Bool+void (TeX x) = null x++
+ DerivationTrees/CPTS.hs view
@@ -0,0 +1,296 @@+{-# LANGUAGE RecordWildCards, DisambiguateRecordFields, GADTs, KindSignatures, GeneralizedNewtypeDeriving, TypeSynonymInstances #-}++module DerivationTrees.CPTS where++import Prelude hiding (abs, pi)+import Data.List+import DerivationTrees+import DerivationTrees.Basics+import Data.Monoid+import qualified DerivationTrees.ManualPTS as M+import Debug.Trace++class Unifyable a where+    (===) :: a -> a -> Bool++class TeXable a where+    texify :: a -> TeX++instance Show (a -> b) where+    show _ = "<fct>"+++data V = V Name | Unbound+ deriving (Eq, Show)++type Name = String+type Sort = String+type Colour = String+++data Binding :: * where+   (:-) :: V -> Term -> Binding+   Base :: Name -> Binding+   Mult :: Binding -> Binding+ deriving (Eq, Show)++data Term :: * where+  Lam :: Colour -> Binding -> Term -> Term+  Pi  :: Colour -> Binding -> Term -> Term+  App :: Colour -> Term -> Term -> Term+  Sub :: Term -> Binding -> Term+  Var :: Name -> Term+  Con :: Name -> Term+  Sor :: Sort -> Term+  Many :: Term -> Term+ deriving (Eq, Show)++-- Short notation (for colourless)+lam    = Lam ""+(~~>)  = Pi  ""+($$)   = App ""+subs   = Sub +var = Var+(|=>) = Sub++infixl |=>+++-- TODO: BIG FAT HACK!+dS :: (Name,Term) -> Term -> Term+dS (n,s) t | s == t = Var n+dS s (Sub t b) = t+dS s (App k f a) = App k (dS s f) (dS s a)+dS s (Pi k f a) = Pi k f (dS s a)+dS s (Many t) = Many (dS s t)+dS s t = t++-- Helper for non-dependent arrow+(Many t) --> u = Mult (Unbound :- t) ~~> u+t --> u = (Unbound :- t) ~~> u++data Jug = Jug {value :: Term, typ :: Term, env :: Env}+ deriving Show++data Drv :: * where+  Ax :: Drv+  St :: Sort -> Drv -> Drv+  Wk :: Int -> Sort -> Drv -> Drv -> Drv+  Ab :: Sort -> Drv -> Drv -> Drv+  Ap :: Binding -> Drv -> Drv -> Drv+  Pr :: Colour -> (Sort,Sort) -> Drv -> Drv -> Drv+  Co :: Sort -> Term -> Drv -> Drv -> Drv+  An :: (Derivation -> Derivation) -> Drv -> Drv -- Arbitrary annotation / change+  Ln :: Link -> Drv -> Drv+  -- Ma :: Drv -> Drv+  -- Re :: TeX -> Jug -> Drv -> Drv+ deriving Show++wk = Wk 0  ++type Env = [Binding]++unbound :: Binding -> Bool+unbound (Mult x) = unbound x+unbound (Unbound :- _) = True+unbound (_ :- _) = False++bound = not . unbound+++instance Unifyable V where+    Unbound === _ = True+    _ === Unbound  = True+    x === y = x == y++instance Unifyable Term where+    (===) = (==)++instance Unifyable Binding where+    (x :- t) === (x' :- t') = (x === x') && (t === t')+    Mult x === Mult x' = x === x'+    x === x' = False++instance TeXable Sort where+    texify ('~':v) = M.tso (TeX v)+    texify v = TeX v+++interpV :: V -> TeX+interpV (V v) = texify v+interpV (Unbound) = TeX "?"++interpB :: Binding -> TeX+interpB = interpB' (tex "IS" [mempty])++interpB' :: TeX -> Binding -> TeX+interpB' ass (x :- t) = interpV x <> ass <> interpT ColonRhs t+interpB' ass (Base x) = texify x+interpB' ass (Mult x) = M.many (interpB' ass x)+++col :: Colour -> String -> [TeX] -> TeX+col "" macro args = tex macro args+col c  macro args = tex (macro ++ "C") (TeX c:args)++data Ctx = ArrowLhs | TopLvl | ColonRhs | BinderRhs | ApplLhs | ApplRhs | SubsLhs++havePrn :: Ctx -> Term -> Bool+havePrn SubsLhs  (Sub _ _) = False+havePrn ApplLhs (Sub _ _) = False+havePrn ApplLhs (App _ _ _) = False++havePrn TopLvl _ = False+havePrn BinderRhs _ = False+havePrn ColonRhs (Lam _ _ _) = True+havePrn ColonRhs (Pi _ b _) | bound b = True+havePrn ColonRhs _ = False +havePrn _ _ = True++parn context t = if havePrn context t then paren else id++interpT :: Ctx -> Term -> TeX++interpT d (App _ (Var ('\\':macroName)) t)    = tex macroName [interpT TopLvl t]++interpT d e@(Lam c a b)             = parn d e $ col c "LAMBDA" [interpB a, interpT BinderRhs b]+interpT d e@(Pi c a b) | unbound a  = parn d e $ col c "ARROW"  [interpT ArrowLhs (bToT a), (interpT BinderRhs b)]+interpT d e@(Pi c a b)              = parn d e $ col c "FORALL" [interpB a, interpT BinderRhs b]+interpT d e@(App c f a)             = parn d e $ col c "APP"    [interpT ApplLhs f, interpT ApplRhs a]+interpT d e@(Sub t b)               = parn d e $ (interpT SubsLhs t <> brack (interpB' (tex "mapsto" [mempty]) b))+interpT d e@(Var x)                     = texify x+interpT d e@(Con x)                     = texify x+interpT d e@(Many t)                    = M.many (interpT d t)+interpT d e@(Sor s)                     = texify s++instance TeXable Term where+    texify t = interpT ColonRhs t++(+:) :: Binding -> Env -> Env+b +: e | unbound b = e+b +: e = b : e++interpE :: Env -> [TeX]+interpE e = (map interpB $ reverse e)++renam :: Term -> TeX+renam (Sor x) = texify x+renam x = (interpT ApplRhs x ! TeX "i")++-- nterpret the non-context part of an assertion.+interpA :: Term -> Term -> (TeX,TeX)+interpA (Many x) (Many t) = (renam x, renam t)+interpA (Many x) (Sor t) = (renam x, texify t)+interpA x t = (texify x,texify t)++interpJ :: Jug -> TeX+interpJ (Jug v t env) = M.assert (interpE env) v' t'+    where (v',t') = interpA v t                 ++check :: Bool -> String -> (a -> a)+check True _ = id+check False msg = error msg++-- Binding to 1 type.+bToT :: Binding -> Term+bToT (Mult b) = Many (bToT b)+bToT (_ :- t) = t+bToT _ = error "invalid binding for extraction"++-- Reconstruct a binding, assuming the 1st term is a variable-like thing.+rebind :: Term -> Term -> Binding+rebind (Many x) (Many t) = Mult (rebind x t)+rebind (Many x) (Sor s) = Mult (rebind x (Sor s))+rebind (Var x) t = V x :- t+rebind x t = error $ "Expected variable, but got: " ++ show x++push (Many (App c f a)) = App c (push (Many f)) (push (Many a))+push t = t++subsOf (V x :- _ , t)  = (x,t)+subsOf (Mult x,Many t) = subsOf (x,t)+subsOf _ = ("no variable",Con "no term")+++jug' :: Term -> Sort -> Env -> Jug+jug' (Many x) s env = Jug (Many x) (Many (Sor s)) env+jug' x s env = Jug x (Sor s) env++rtext = rule . text++rm idx [] = []+rm 0 (x:xs) = xs+rm n (x:xs) = x : rm (n-1) xs++stp :: Drv -> Jug -> (TeX -> Rule (), [(Drv,Jug)])+stp Ax _ = (\c -> (rtext "" c) {-DerivationTrees.style = None-}, [])+stp (St s d) (Jug v t (b':env)) = check (b === b') ("Start: bindings do not match: " ++ show (b, b'))+   $  (rtext "st", [(d, Jug t (Sor s) env)])+  where b = rebind v t+stp (Wk idx s rest d)  (Jug v t env) = (rtext label, [(rest,Jug v t env'), (d, jug' (bToT b) s env')])+   where env' = rm idx env+         b = env !! idx+         label | idx == 0 = "wk"+               | otherwise = "wk (" ++ show idx ++ ")" ++stp (Co s typ d e) (Jug v t env) = +   (rtext "conv", [(d,Jug v typ env), (e, jug' t s env)])+  where betaCond = rule mempty (interpT TopLvl typ <> TeX "=_\\beta " <> interpT TopLvl t)+stp (Ab s d e) (Jug (Lam k a bo) (Pi k' a' b) env) = check (k == k') ("Abstraction: colours do not match" ++ show (k,k')) $+                                                     check (a === a') ("Abstraction: bindings do not match: " ++ show (a, a')) $+  (rtext "abs", [(d,Jug bo b (a:env)), (e,Jug (Pi k a' b) (Sor s) env)])+stp (Pr k (s1,s2) d e) (Jug (Pi k' a b) (Sor s3) env) = check (k == k') ("Product: colours do not match" ++ show (k,k')) $+ (rule name, [(d,jug' (bToT a) s1 env),(e,jug' b s2 (a+:env))])+ where (cname,cargs) = if s2 == s3 then ("ptsrule",[s1,s2]) else ("prodrule",[s1,s2,s3])+       (fname,fargs) = if null k then (id,id) else ((++ "c"), (k:))+       name = tex (fname cname) (map texify $ fargs cargs)+       +-- stp (Ma d) (Jug v t env) = (rule (text "many"),  [(d,Jug (push v) (push t) env)])++-- if a substitution is there, eat it.+stp (Ap b d e) (Jug (App k f a) t env) = trace (show subst) $+    (rtext "app", [(d,Jug f (Pi k b (dS subst t)) env),(e,Jug a (bToT b) env)])++    where subst = subsOf (b, a)+stp (Ap (Mult b) d e) (Jug (Many (App k f a)) (Many t) env) = +    (rtext "app", [(d,Jug (Many f) (Many (Pi k b t)) env),(e,Jug (Many a) (Many (bToT b)) env)])+    -- Used only once in the product rule (many (f x))++++-- stp (An f d) j = (rtext "usr", [(d,j)])+-- stp (Re t j d) j' = (rule t, [(d,j)])+++stp r j = error $ "Unsupported: rule " ++ show r ++ " on judgement " ++ show j++interp :: Drv -> Jug -> Derivation+interp (An f x) j = f $ interp x j+interp (Ln l x) j = interp x j+interp d j =  Node (r (interpJ j)) [link d' ::> interp d' j' | (d',j') <- x]+    where (r,x) = (stp d j)+          link (Ln l _) = l+          link _ = defaultLink++-------------------++dL = Ln (Delayed {align = LeftA})+dC = Ln (Delayed {align = CenterA})+dR = Ln (Delayed {align = RightA})++delay :: Alignment -> Int -> Drv -> Drv+delay align steps = Ln (Link {DerivationTrees.Basics.style = Dotted, ..})+         where label=mempty++detach l ident = Ln (Detached {label = text ('(' : l ++ ")"),..})++halt :: String -> Drv+halt txt = An (haltDrv (text txt)) Ax++named :: String -> Drv -> Drv+-- named txt = An (\(Node r ps) -> Node r [defaultLink ::> Node (rule mempty (text txt)) {DerivationTrees.style = Double} ps])+named txt = An (\(Node r ps) -> Node r {delimiter = text txt} ps)++abort :: Drv+abort = An abortDrv Ax -- (error "abort: Should stop")+
+ DerivationTrees/ManualPTS.hs view
@@ -0,0 +1,19 @@+module DerivationTrees.ManualPTS where++import DerivationTrees+import DerivationTrees.Basics+import Data.List++assert env val typ = tex "Assert" [mconcat $ intersperse (TeX ",") env,val,typ]+(-:) var typ = brace var <> tex "IS" [] <> brace typ++lam   binding body    = tex "LAMBDA" [binding, body]+pi    binding body    = tex "FORALL" [binding, body]+subs  term var s      = tex "SUBS" [term,var,s]+($$)   fun arg      = tex "APP" [fun, arg]+tso s = tex "tsort" [s]+many x = tex "many" [x]+x --> y = brace x <> tex "to" [mempty] <> brace y+++
+ LICENSE view
@@ -0,0 +1,340 @@+		    GNU GENERAL PUBLIC LICENSE+		       Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.+     59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++			    Preamble++  The licenses for most software are designed to take away your+freedom to share and change it.  By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users.  This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it.  (Some other Free Software Foundation software is covered by+the GNU Library General Public License instead.)  You can apply it to+your programs, too.++  When we speak of free software, we are referring to freedom, not+price.  Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++  To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have.  You must make sure that they, too, receive or can get the+source code.  And you must show them these terms so they know their+rights.++  We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++  Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software.  If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++  Finally, any free program is threatened constantly by software+patents.  We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary.  To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++  The precise terms and conditions for copying, distribution and+modification follow.++		    GNU GENERAL PUBLIC LICENSE+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++  0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License.  The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language.  (Hereinafter, translation is included without limitation in+the term "modification".)  Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope.  The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++  1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++  2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++    a) You must cause the modified files to carry prominent notices+    stating that you changed the files and the date of any change.++    b) You must cause any work that you distribute or publish, that in+    whole or in part contains or is derived from the Program or any+    part thereof, to be licensed as a whole at no charge to all third+    parties under the terms of this License.++    c) If the modified program normally reads commands interactively+    when run, you must cause it, when started running for such+    interactive use in the most ordinary way, to print or display an+    announcement including an appropriate copyright notice and a+    notice that there is no warranty (or else, saying that you provide+    a warranty) and that users may redistribute the program under+    these conditions, and telling the user how to view a copy of this+    License.  (Exception: if the Program itself is interactive but+    does not normally print such an announcement, your work based on+    the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole.  If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works.  But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++  3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++    a) Accompany it with the complete corresponding machine-readable+    source code, which must be distributed under the terms of Sections+    1 and 2 above on a medium customarily used for software interchange; or,++    b) Accompany it with a written offer, valid for at least three+    years, to give any third party, for a charge no more than your+    cost of physically performing source distribution, a complete+    machine-readable copy of the corresponding source code, to be+    distributed under the terms of Sections 1 and 2 above on a medium+    customarily used for software interchange; or,++    c) Accompany it with the information you received as to the offer+    to distribute corresponding source code.  (This alternative is+    allowed only for noncommercial distribution and only if you+    received the program in object code or executable form with such+    an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it.  For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable.  However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++  4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License.  Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++  5. You are not required to accept this License, since you have not+signed it.  However, nothing else grants you permission to modify or+distribute the Program or its derivative works.  These actions are+prohibited by law if you do not accept this License.  Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++  6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions.  You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++  7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License.  If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all.  For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices.  Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++  8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded.  In such case, this License incorporates+the limitation as if written in the body of this License.++  9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time.  Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number.  If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation.  If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++  10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission.  For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this.  Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++			    NO WARRANTY++  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++		     END OF TERMS AND CONDITIONS++	    How to Apply These Terms to Your New Programs++  If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++  To do so, attach the following notices to the program.  It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software; you can redistribute it and/or modify+    it under the terms of the GNU General Public License as published by+    the Free Software Foundation; either version 2 of the License, or+    (at your option) any later version.++    This program is distributed in the hope that it will be useful,+    but WITHOUT ANY WARRANTY; without even the implied warranty of+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the+    GNU General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program; if not, write to the Free Software+    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA+++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++    Gnomovision version 69, Copyright (C) year  name of author+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary.  Here is a sample; alter the names:++  Yoyodyne, Inc., hereby disclaims all copyright interest in the program+  `Gnomovision' (which makes passes at compilers) written by James Hacker.++  <signature of Ty Coon>, 1 April 1989+  Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs.  If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library.  If this is what you want to do, use the GNU Library General+Public License instead of this License.
+ Main.hs view
@@ -0,0 +1,236 @@+{-# LANGUAGE RecordWildCards, DisambiguateRecordFields #-}+import Prelude hiding (abs)+import DerivationTrees+import DerivationTrees.Basics+import DerivationTrees.CPTS+++translateE :: [Binding] -> [Binding]+translateE = concatMap translateB++translateJ (Jug v t e) = Jug (translate v) (translate t $$ Many v) (translateE e)++translateB :: Binding -> [Binding]+translateB (V x :- a) = [(V ("\\subR " ++ x) :- (translate a $$ Many (var x))), Mult (V x :- a)]+translateB (Base (x)) = [Base ("\\trans " ++ x)]++translate :: Term -> Term+translate (Var x) = Var ("\\subR " ++ x) +translate (Con x) = Con ("\\trans " ++ x) +translate (Sor s) = (lam (Mult (V "A" :- Sor s)) ((Many $ var "A") --> Sor ('~':s)))++translate (App k f a) = App (k++"_m") (App (k++"_i") (translate f) (Many a)) (translate a)+translate (Lam k a b) = Lam (k++"_i") w $+                        Lam (k++"_m") w' $+                        translate b        +   where [w',w] = translateB a+translate (Sub t (V x :- a)) = Sub (Sub (translate t) w) w'+    where w  = Mult (V x :- a)+          w' = V ("\\subR " ++ x) :- translate a+translate t@(Pi k a@(V x :- _) b) +   = lam (Mult (V "f" :- t)) $+     Pi (k++"_i") w $+     Pi (k++"_m") w' $+     (translate b $$ Many (App k (var "f") (var x)))+   where [w',w] = translateB a+++++pr0 = Pr ""++axiomJ = translateJ (Jug (Sor "s") (Sor "t") [])+       where a = V "A"+             a' = Many $ var "A"+++axiomT = Co "~u" (Many (Sor "s") --> Sor "~t")+          (Ab "~u" +              (pr0 ("s","~t")+                  (St "t" Ax)+                  (wk "t" Ax Ax))+              +              (pr0 ("t","~u")+                  Ax+                  Ax))          +          (delay CenterA 4 $ Ap (Mult (Unbound :- Sor "t")) +              (Ab "~v" +                  (pr0 ("t","~u")+                      (St "u" Ax)+                      (wk "u" Ax Ax))+                  (pr0 ("u","~v") Ax Ax))+                    +              Ax)++ind' = halt "ind'"+ind = halt "ind"+lem = halt "lem"+gamma = [Base "\\Gamma"]++startJ = translateJ $ Jug (Var "x") (Con "A") [V "x" :- Con "A" ,Base ("\\Gamma")]+startT = St "~s" (Ap (Mult (Unbound :- Con "A"))+                     (wk "s~" ind' lem)+                     (St "s" lem))++weakJ = translateJ $ Jug (Con "A") (Con "B") [V "x" :- Con "C" ,Base ("\\Gamma")]+weakT = wk "~s" +           (wk "s" +               ind+               lem)+           (Ap (Mult (Unbound :- Con "C"))+               (wk "s" ind' lem) +               (St "s" lem))++protoPi = (Pi "k" (V "x" :- Con "A") (Con "B"))+protoLam = (Lam "k" (V "x" :- Con "A") (Con "b"))++prodJ = translateJ $ Jug protoPi (Sor "s_3") gamma+prodT = Co "~t_3" (Many protoPi --> Sor "~s_3") +          (dL $ +           Ab "~t_3"+             (dL $ Pr "k_i" ("s_1","~s_3") +                 (wk "s_3" lem lem)+                 (dR $ Pr "k_m" ("~s_1","~s_2") +                      (detach "1" 31 $ Ap (Mult (Unbound :- Con "A")) +                          (dL $ wk "s_1" +                              (wk "s_3"+                                 ind'+                                 lem)+                              lem)+                          (St "s_1" +                             (named "(2)" $ wk "s_3"+                                             lem+                                             lem))+                          )+                      (wk "~s_1" +                       (dL $ Ap (Mult (Unbound :- Con "B")) +                          (wk "s_1" +                              (wk "s_3"+                                 ind'+                                 lem)+                              lem)+                          (dR $ Ap (Mult (V "x" :- Con "A")) +                              (dC $wk "s_1" +                                      (St "s_3" +                                          lem) +                                      (halt "(2)")) +                              (St "s_1" (halt "(2)")))+                          )+                       (halt "(1)"))+                 ))+             (pr0 ("s_3","~t_3") lem Ax)+          )+          (Ap (Mult (Unbound :- Sor "s_3")) +              (dL $ Ab "~u_3" +                  (pr0 ("s_3","~t_3")+                    (St "t_3" Ax)+                    (wk "t_3" Ax Ax))+                  (pr0 ("t_3", "~u_3") +                   Ax+                   Ax))+              (halt "lem"))++{-+subst x a b = ++nf (App _ (Lam _ (Mult (V x :- _)) b) a) = subst x a b++-}+++++applJ = translateJ $ Jug (App "k" (Con "F") (Con "a")) (Sub (Con "B") (V "x" :- Con "a")) gamma+applT = (Ap (V "\\subR x" :- (translate (Con "A") $$ (Many $ Con "a"))) +            (Ap (Mult (V "x" :- Con "A"))+                (dL $ Co "~s_B" (translate protoPi) +                  (dL $ ind)+                  (Pr "k_i" ("s_A","~s_B") +                      (lem)+                      (Pr "k_m" ("~s_A","~s_B") +                          (dL $ named "(1)" $ wk "s_A"+                                  (Ap (Mult (Unbound :- Con "A")) (ind') (lem))+                                  lem)+                          (wk "~s_A" +                              (Ap (Mult (Unbound :- Con "B")) +                                      (wk "s_A" +                                       (ind')+                                       (lem)) +                                      (dC $ Ap (Mult (V "x" :- Con "A")) +                                              (wk "s_A" lem lem) +                                              (St "s_A" lem)))+                              (halt "(1)")+                          ))+                   ))+                lem) +            ind)++abstJ = translateJ $ Jug protoLam protoPi gamma+abstT = Co "~s" (Pi "k_i" (Mult ((:-) (V "x") (Con "A"))) (Pi "k_m" ((:-) (V "\\subR x") (App "" (Con "\\trans A") (Many (Var "x")))) (App "" (Con "\\trans B") (Many $ Con "b"))))+           (dL $ Ab "~s"+             (dL $ Ab "~s"+                 (wk "~s_A" +                     (wk "s_A" ind lem)+                     (halt "(1)"))+                 (dR $ named "(3)" $ +                  Pr "k_m" ("~s_A","~s")+                     (named "(1)" $ Ap (Mult (Unbound :- Con "A"))+                         (wk "s_A" ind' lem)+                         (St "s_A" lem))+                     (delay CenterA 3 $ wk "~s_A" +                         (wk "s_A" +                             (Ap (Mult (Unbound :- Con "B"))+                                 ind'+                                 lem) +                             lem) +                         (halt "(1)"))+                  )+                 )+             (Pr "k_i" ("s_A","~s") +                     lem+                     (halt ("(3)"))))+           (detach "S" 51 $ Ap (Mult (V "f" :- protoPi))+               (dL $ Ab "~t"+                    (dL $ Pr "k_i" ("s_A","~s") +                        (wk "s" lem lem) +                        (dR $ Pr "k_m" ("~s_A","~s") +                            (named "(2)" $ Wk 1 "s" +                               (halt "(1)") +                               (wk "s_A" lem lem))+                            (dR $ wk "~s_A" +                               (dL $ Ap (Mult (Unbound :- Con "B")) +                                   (wk "s_A" +                                    (wk "~s"+                                      ind'+                                      lem)+                                    -- (wk "s" lem lem)+                                    (named "(4)" $ wk "s" lem lem)+                                   ) +                                   (dR $ Ap (Mult (V "x" :- Con "A"))+                                       (dC $ wk "s_A" +                                           (St "s" lem) +                                           (halt "(4)")+                                       )+                                       (St "s_A" (halt "(4)"))+                                       ))+                               (halt "(2)"))))+                    (pr0 ("s","~t") lem +                         (wk "s" Ax lem)))+               lem)++convJ = translateJ $ Jug (Con "A") (Con "B'") gamma+convT = Co "~s" (translate (Con "B") $$ (Many $ Con "A"))+          ind+          (Ap (Mult (Unbound :- Con "B'"))+               ind'+               lem)++main = writeFile "AbsProof.mp" $ unlines $ compile [Figure 0 (interp axiomT axiomJ),+                                 Figure 1 (interp startT startJ),+                                 Figure 2 (interp weakT weakJ),+                                 Figure 3 (interp prodT prodJ),+                                 Figure 4 (interp applT applJ),+                                 Figure 5 (interp abstT abstJ),+                                 Figure 6 (interp convT convJ)+                                ]+
+ Setup.hs view
@@ -0,0 +1,4 @@+#!/usr/bin/env runhaskell+import Distribution.Simple+main :: IO ()+main = defaultMain
+ derivation-trees.cabal view
@@ -0,0 +1,28 @@+name:           derivation-trees+version:        0.7.1+category:       Graphics, Math+synopsis:       Typeset Derivation Trees via MetaPost+description:+  A library to typeset derivation trees via Laurent Mehats metapost package.+  Also contains a module to ease the generation of trees for (coloured) pure type systems.+license:        GPL+license-file:   LICENSE+author:         Jean-Philippe Bernardy+maintainer:     jeanphilippe.bernardy@gmail.com+Cabal-Version:  >= 1.8+tested-with:    GHC==6.12.1+build-type:     Simple++extra-source-files: Main.hs++library+  build-depends: base==4.*+  build-depends: mtl==1.1.*+  build-depends: applicative-extras==0.1.*+  exposed-modules:+     Data.LabeledTree+     DerivationTrees+     DerivationTrees.Basics+     DerivationTrees.ManualPTS+     DerivationTrees.CPTS+