[-*- emacs-lisp -*-] [ Copyright 2012 Ken Takusagawa 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 3 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, see . ] [-----grammar (gz start (prog)) (gz prog (module)) (gz module (id language-pragma-opt exports imports topdecl-star ::pr("[[language-pragma-opt]]module [[id]] [[exports]] where {\n[[imports]]\n" "[[topdecl-star('',';\n\n','\n')]]}\n"))) (gz language-pragma ( :language-pragma f id-non-star j ::pr ("{-# LANGUAGE [[id-non-star('',',','')]] #-}\n"))) (gz exports (f export-star j ::pr("[[export-star('\n ( ','\n , ','\n )')]]")) (:export-everything ::pr(""))) (gz export (id) (f :module-export id j ::pr("module [[id]]")) (f :type-export id constructors-export j ::pr("[[id]][[constructors-export]]")) ) (gz constructors-export (:all-constructors ::pr("(..)")) (id-non-star ::pr("[[id-non-star('(',',',')')]]")) ) (gz imports (f import-star j ::pr("[[import-star('',';\n',';\n')]]"))) (gz import(id ::pr( "import [[id]]")) (f :qualified (original-name ::is id) (new-name ::is id) j ::pr ( "import qualified [[original-name]] as [[new-name]]")) (f :specific id id-non-star j ::pr ("import [[id]][[id-non-star('(',',',')')]]")) (f :hiding import id-non-star j ::pr("[[import]] hiding[[id-non-star('(',',',')')]]") [dunno if this will work for complicated cases] )) (gz type-class (f decl-mark (class-name ::is id) :type-class context-opt f id-non-plus j type-class-decl-star j ::pr("class [[context-opt]][[class-name]] [[id-non-plus('',' ','')]] where{\n" "[[type-class-decl-star('',';\n','\n')]]}"))) (gz topdecl (decl) (data)(type-synonym)(newtype)(instance)(type-class)) (gz type-class-decl (type-signature)(decl)) (gz type-signature (f decl-mark name :tysig ret-type-and-params j ::pr("[[name]] :: [[ret-type-and-params]]"))) (gz instance (f :instance (type ::is id) (name ::is simpletype) context-opt decls j ::pr ("instance [[context-opt]] [[type]] ([[name]]) where [[decls]]"))) [(gz instance (f :instance context-opt (type ::is id) simpletype-plus :x decls j ::pr ("instance [[context-opt]][[type]] [[simpletype-plus('(',')(',')')]] where [[decls]]")))] (gz newtype (f decl-mark (name ::is id) :newtype type-vars-opt constr-or-wrap deriving-opt j ::pr("newtype [[name]] [[type-vars-opt]] = [[constr-or-wrap{my_name}]][[deriving-opt]]"))) (gz constr-or-wrap ::gets "tr-id*{name}" (outer-constr)(wrap-constr ::pr("[[wrap-constr{name}]]"))) (gz wrap-constr ::gets "tr-id*{name}" ( :wrap id ::pr( (::c "name->print();") " {un" (::c "name->print();") " :: [[id]]}"))) (gz deriving (:deriving f id-non-plus j ::pr("\n deriving [[id-non-plus('(',', ',')')]]"))) (gz id-non (id)) (gz type-synonym (f decl-mark id :type-synonym type-vars-opt type j ::pr("type [[id]] [[type-vars-opt]] = [[type]]"))) (gz data (f decl-mark id :data type-vars-opt constrs deriving-opt j ::pr("data [[id]] [[type-vars-opt]] = [[constrs]][[deriving-opt]]"))) (gz simpletype (f id-non-plus j ::pr ("[[id-non-plus('',' ','')]]"))) (gz type-vars (:args f id-non-star j ::pr ("[[id-non-star('',' ','')]]"))) (gz constrs(outer-constr-star ::pr("[[outer-constr-star('','\n | ','')]]"))) (gz field-type-and-param (f param type j ::pr("[[param]] :: [[type]]"))) (gz type-and-param ( f param type j ::pr("[[type]]"))) (gz outer-constr(outer-positional-constructor) (field-label-constructor) ) (gz field-label-constructor(f type-ctor :field field-type-and-param-star j ::pr("[[type-ctor]][[field-type-and-param-star('{',', ','}')]]"))) (gz decls ( decl-star ::pr("{[[decl-star('\n',';\n','\n')]]}"))) (gz context (:context f a-context-plus j ::pr ("[[a-context-plus('(',', ',')')]] => "))) (gz a-context [(f (type ::is id) id-non-plus j ::pr("[[type]] [[id-non-plus('',' ','')]]"))] (f (class ::is id) type-plus j ::pr("[[class]] [[type-plus('',' ','')]]")) ) (gz forall (:forall f id-non-plus j ::pr("forall [[id-non-plus('',' ','')]] . "))) (gz ret-type-and-params (type f type-and-param-star j forall-opt context-opt ::pr("[[forall-opt]][[context-opt]][[type-and-param-star('',' \x2d> ','')]]" (::c "if(my_type_and_param_star->v.size()>0)out(' \x2d> ');") "[[type]]"))) (gz decl (f decl-mark name :fun haddock-opt ret-type-and-params expr j ::pr("[[haddock-opt]]" "[[name]] :: [[ret-type-and-params]];\n" "[[name]]" (::c "for(many_trees::const_iterator pos = my_ret_type_and_params->my_type_and_param_star->v.begin();pos!= my_ret_type_and_params->my_type_and_param_star->v.end();++pos){" "const tr_type_and_param* t=dynamic_cast(*pos);" "assert(t);" "out(' ');" "t->my_param->print();" "}") " = [[expr]]")) (f decl-mark name :fun :no-sig ret-type-and-params expr j ::pr("[[name]]" (::c "for(many_trees::const_iterator pos = my_ret_type_and_params->my_type_and_param_star->v.begin();pos!= my_ret_type_and_params->my_type_and_param_star->v.end();++pos){" "const tr_type_and_param* t=dynamic_cast(*pos);" "assert(t);" "out(' ');" "t->my_param->print();" "}") " = [[expr]]")) (f decl-mark name :simple expr j ::pr("[[name]] = [[expr]]")) ) (gz name (id)) (gz outer-positional-constructor ["this one is sketchy"] (type-ctor ::pr("[[type-ctor]]")) (f type-ctor type-star j ::pr("[[type-ctor]][[type-star(' ',' ','')]]")) (f :tuple type-plus j ::pr("[[type-plus('(',', ',')')]]")) ) (gz positional-constructor ["this one is sketchy"] (type-ctor ::pr("[[type-ctor]]")) (f type-ctor type-star j ::pr("([[type-ctor]][[type-star(' ',' ','')]])")) (f :tuple type-plus j ::pr("[[type-plus('(',', ',')')]]")) ) (gz pattern (id) ["avoid pattern-star because it causes weird spacing"] (f pattern-ctor j ::pr ("[[pattern-ctor]]")) (f pattern-ctor pattern-plus j ::pr ("([[pattern-ctor]] [[pattern-plus('',' ','')]])")) (f pattern-ctor :fpat f fpat-star j j ::pr ("([[pattern-ctor]][[fpat-star('{',', ','}')]])")) (f :ptuple pattern-plus j [pattern-plus cuz :nil exists for empty lists] ::pr("[[pattern-plus('(',', ',')')]]")) (f :plist pattern-plus j [pattern-plus cuz :nil exists for empty lists] ::pr("[[pattern-plus('\x5b',', ','\x5d')]]")) (f :pchar astring j ::pr("\x27[[astring]]\x27")) (f :pstring astring j ::pr("\x22[[astring]]\x22")) (f :as id pattern j ::pr("([[id]]@[[pattern]])")) ) (gz pattern-ctor (id) (:cons ::pr ("(:)")) (:nil ::pr ("[]")) (:paren id ::pr("([[id]])")) ["workaround for Qualified parenthesized constructors"] ( :v id type ::pr("([[id]] :: [[type]])")) ) (gz fpat (f (variable ::is id) pattern j ::pr("[[variable]] = [[pattern]]"))) (gz type (f :fn ret-type-and-params j ::pr ("([[ret-type-and-params]])")) (:inforall f id-non-plus j type ::pr("(forall [[id-non-plus('',' ','')]] . [[type]])")) (:unit ::pr("()")) (positional-constructor) (f :strict type j ::pr ("![[type]]")) ) [(gz typepls (paren-type-plus))] [(gz strict-type (type ::pr( "[[type]]")) (f :strict type j ::pr("![[type]]")) [(f :generic id j ::pr (" [[id]] "))])] (gz type-ctor(id)(:list ::pr ("[]")) [(:nondet ::pr ("[]"))]) (gz param (pattern)) (gz qastring (astring ::pr("\x22[[astring]]\x22"))) (gz expr (id) (:mcons ::pr ("(:)")) (f :chain astring expr-plus j ::pr ([("[[expr-plus('(',' op ',')')]]")] "(" (::c "for(many_trees::const_iterator pos=my_expr_plus->v.begin();pos!=my_expr_plus->v.end();++pos){") (::c "if(pos!=my_expr_plus->v.begin()){") "[[astring]]" (::c "}(*pos)->print();}") ")" )) (f :join expr-plus j ::pr("[[expr-plus('(',' >>= ',')')]]")) (f :cc expr-star j ::pr ("[[expr-star('(',' ++ ',')')]]")) (f :msum expr-star j ::pr ("[[expr-star('(',' \x60mplus\x60 ',')')]]")) (f :rpipe expr-plus j ::pr[("[[expr-star('(',' $ ',')')]]")] (["http;//gcc.gnu.org/bugzilla/show_bug.cgi?id=11729"] (::c "for(many_trees::reverse_iterator pos = my_expr_plus->v.rbegin();" "pos!=my_expr_plus->v.rend();++pos){") "(" (::c "(*pos)->print();" "}") (::c "for(many_trees::const_iterator pos = my_expr_plus->v.begin();" "pos!=my_expr_plus->v.end();++pos){") ")" (::c "}") )) (f :rcompose expr-plus j ::pr ("(" (::c "for(many_trees::reverse_iterator pos = my_expr_plus->v.rbegin();" "pos!=my_expr_plus->v.rend();++pos){") (::c "if(pos!=my_expr_plus->v.rbegin())") " . " (::c "(*pos)->print();" "}") ")" )) (qastring) (f :lit astring j ::pr("[[astring]]")) (f :ty type expr j ::pr("([[expr]] :: [[type]])")) (f (fun-name ::is expr) expr-star j ::pr ("([[fun-name]][[expr-star(' ',' ','')]])")) (f :do stmt-star j ::pr("(do {\n[[stmt-star(' ','\n ','\n')]]})")) (f :case expr alt-star j ::pr("(case [[expr]] of {\n[[alt-star(' ',';\n ','\n')]]})")) (f :mzerocase expr alt-star j ::pr("(case [[expr]] of {\n[[alt-star(' ',';\n ',';\n')]]" " _ -> mzero\n" "})")) (f :case expr alt-plus :else (underbar ::is expr) j ["the else is there so the grammar does not have a reduce/reduce conflict"] ::pr("(case [[expr]] of {\n[[alt-plus(' ',';\n ',';\n')]]" " _ -> [[underbar]]\n" "})")) (f :case expr :else (underbar ::is expr) alt-star j ::pr("(case [[expr]] of {\n[[alt-star(' ',';\n ',';\n')]]" " _ -> [[underbar]]\n" "})")) (f :lcase alt-star j ::pr("(\x5clambda_case_var ->" "case lambda_case_var of {\n" "[[alt-star(' ',';\n ','\n')]]})")) (f :lcase alt-plus :else (underbar ::is expr) j ::pr("(\x5clambda_case_var ->" "case lambda_case_var of {\n" "[[alt-plus(' ',';\n ',';\n')]]" " _ -> [[underbar]]\n" "})")) (f :lcase :else (underbar ::is expr) alt-star j ::pr("(\x5clambda_case_var ->" "case lambda_case_var of {\n" "[[alt-star(' ',';\n ',';\n')]]" " _ -> [[underbar]]\n" "})")) (f :let decl-star expr j ::pr("(let {[[decl-star('\n',';\n','\n')]]} in [[expr]])")) (f :rlet expr decl-star j ::pr("(let {[[decl-star('\n',';\n','\n')]]} in [[expr]])")) (f :cfd expr assignments-star j ::pr("([[expr]][[assignments-star('{',', ','}')]])")) (f :mlist expr-star j ::pr("[[expr-star('\x5b',', ','\x5d')]]")) (f :cons-list expr-plus j ::pr("[[expr-plus('(',':',')')]]")) (f :mtuple expr-star j ::pr("[[expr-star('(',', ',')')]]")) (:nothing ::pr ("()")) (f :lambda name ret-type-and-params expr j ::pr("(let {[[name]] :: [[ret-type-and-params]];\n" "[[name]]" (::c "for(many_trees::const_iterator pos = my_ret_type_and_params->my_type_and_param_star->v.begin();pos!= my_ret_type_and_params->my_type_and_param_star->v.end();++pos){" "const tr_type_and_param* t=dynamic_cast(*pos);" "assert(t);" "out(' ');" "t->my_param->print();" "}") " = [[expr]]} in [[name]])")) (f :lambda-simple id-non expr j [recommended only for reordering arguments to functions and other simple expressions] [only one variable to keep it simple] ::pr ("(\x5c[[id-non]] -> [[expr]])")) (f :field-edit expr field-edit-plus j [plus is required by Haskell] ::pr("([[expr]][[field-edit-plus('{',',','}')]])")) ) (gz field-edit (f id expr j ::pr ("[[id]] = [[expr]]"))) (gz assignments (f id expr j ::pr("[[id]] = [[expr]]"))) (gz stmt (expr ::pr("[[expr]];")) (f ":=" pattern expr j ::pr("[[pattern]] <- [[expr]];")) (f :dlet decl-star j ::pr ("let {[[decl-star('\n',';\n','\n')]]};")) ) (gz alt (f pattern expr-or-gpat j ::pr("[[pattern]][[expr-or-gpat]]"))) (gz expr-or-gpat (expr ::pr (" -> [[expr]]")) (where-opt :gpats pred-expr-star [silly lookahead limitation] ::pr ("[[pred-expr-star('\n ','\n ','')]][[where-opt]]\n " ))) (gz pred-expr ( f (pred ::is expr) (do ::is expr) j ::pr ("| [[pred]] -> [[do]]"))) (gz where (:where decls ::pr ("\n where [[decls]]"))) (gz decl-mark (":")) (gz haddock ( :doc f docline-star j ::pr ("[[docline-star('\x7b\x2d |','\n',' \x2d\x7d\n')]]"))) (gz docline (astring)) ] Main :language-pragma ( ScopedTypeVariables ) :export-everything ( (:specific Control.Monad replicateM foldM) (:specific Data.List intersperse) (:specific Control.Exception assert) (:specific System.Environment getArgs) (:specific Data.Array.IO newListArray range getBounds readArray getElems writeArray readArray IOArray) (:specific System.Random getStdRandom randomR StdGen mkStdGen setStdGen) ) (: Fdouble :type-synonym Float) (: Coord :type-synonym (:tuple Int Int)) (: Image :type-synonym (IOArray Coord Fdouble)) (: image-bounds :fun (:tuple Coord Coord)((size Int)) (:mtuple (:mtuple 0 0 )(:mtuple (pred size)(pred size)))) (: full :fun :doc("image with all pixels defined.") (IO Image)((rand Rand-function)(size Int)) (:join (:rpipe rand getStdRandom (replicateM (* size size))) (newListArray (image-bounds size)))) (: Rand-function :type-synonym (:fn(:tuple Fdouble StdGen)((g StdGen)))) (: gray :fun :doc ("returns real number uniformly between 0 and 1") Rand-function () (randomR (:mtuple 0 1))) (: black-white :fun :doc ("returns 0 or 1") Rand-function () (:let (: inner :fun (:tuple Int StdGen)((g StdGen)) (randomR (:mtuple 0 1) g)) (: convert :fun (:tuple Fdouble StdGen)((g StdGen)) (:case (inner g) ((:ptuple i g2)(:mtuple (fromIntegral i) g2)))) convert)) (: checkerboard :fun :doc("sets half the pixels in a checkerboard pattern") (IO Image)((rand Rand-function)(size Int)) (:join (:rpipe (image-bounds size) range (mapM (init-checkerboard rand))) (newListArray (image-bounds size)) )) (: init-checkerboard :fun (IO Fdouble)((rand Rand-function)(c Coord)) (:case (odd-index c) (False (getStdRandom rand)) (True (return (error "checkerboard not filled"))))) (: getImageSize :fun (IO Int)((image Image)) (:do (:= (:ptuple _ (:ptuple x _)) (getBounds image)) (return (succ x)) )) (: odd-index :fun Bool (((:ptuple x y)Coord)) (:case (mod (+ x y)2) (1 True) :else False)) (: wrapped-read :fun (IO Fdouble)((image Image)((:ptuple x y)Coord)) (:do (:= (:ptuple _z (:ptuple xmax ymax)) (getBounds image)) (readArray image (:mtuple (mod x (+ 1 xmax))(mod y (+ 1 ymax)))) )) (: coords-checkerboard :fun :doc("orthogonal neighbors") (:list Coord)(((:ptuple x y)Coord)) (:mlist (:mtuple (pred x) y) (:mtuple (succ x) y) (:mtuple x (pred y)) (:mtuple x (succ y)) )) (: coords-double :fun :doc("diagonal neighbors, forming an X") (:list Coord)(((:ptuple x y)Coord)) (:do (:= (:plist f g) (replicateM 2(:mlist pred succ))) (return (:mtuple (f x)(g y))))) (: average-read :fun (IO Fdouble)((image Image)(c(:list Coord))) (:do (:= (:v vals (:list Fdouble)) (mapM (wrapped-read image) c)) (return (/ (sum vals) (fromIntegral(length c)))))) (: one-pixel :fun :doc("sets a pixel with a value averaged from given neighbors") (IO :unit) ((image Image) (which-neighbors(:fn(:list Coord)((c Coord)))) (c Coord)) (:join (:rpipe c which-neighbors (average-read image)) (writeArray image c))) (: fill-checkerboard :fun (IO :unit)((image Image)) (:join (getBounds image) (:rcompose range (filter odd-index) return) (mapM- (one-pixel image coords-checkerboard)) ) ) (: pgm-image :fun (IO :unit)((image Image)) (:do (putStrLn "P2") (:= (:v size Int) (getImageSize image)) (putStrLn (:cc (show size)" "(show size))) (putStrLn "255") (:join (getElems image)(mapM- (:rcompose clip-round print))) )) (: clip-round :fun Int ((x Fdouble)) (:case (floor (* 256 x)) (256 255) (i i))) (: double-image :fun :doc("doubles image, leaving 3/4 pixels undefined") (IO Image)((image Image)) (:do (:= (:v oldsize Int) (getImageSize image)) (:dlet (: newsize :fun Int () (* 2 oldsize))) (:join (:rpipe (image-bounds newsize) range (mapM (init-double image))) (newListArray (image-bounds newsize))) )) (: init-double :fun (IO Fdouble)((old Image)((:ptuple x y)Coord)) (:case (:mtuple (divMod x 2)(divMod y 2)) ((:ptuple (:ptuple sx 0)(:ptuple sy 0)) (readArray old (:mtuple sx sy))) :else (return (error "undefined double pixel")))) (: double-fillable-index :fun Bool (((:ptuple x y)Coord)) (&& (== 1 (mod x 2))(== 1 (mod y 2)))) (: fill-double :fun :doc("fills in some undefined pixels from a recently doubled image") (IO :unit)((image Image)) (:join (getBounds image) (:rcompose range (filter double-fillable-index) return) (mapM- (one-pixel image coords-double)))) (: auto-double :fun :doc("doubles the dimensions of the image, applying smoothing") (IO Image)((small Image)) (:do (:= image (double-image small)) (fill-double image) (fill-checkerboard image) (return image) )) (: auto-checkerboard :fun (IO Image)((rand Rand-function)(size Int)) (:do (:= image (checkerboard rand size)) (fill-checkerboard image) (return image))) (: multiple-smooth1 :fun (IO Image)((n Integer)(small Image)) (:case (compare n 0) (EQ (return small)) (GT (:join (auto-double small) (multiple-smooth1 (pred n)))))) (: multiple-smooth :fun (IO Image)((n Int)(small Image)) (iterateM auto-double small n)) (: iterateM :fun (m a)((f(:fn(m a)((x a))))(start a)(n Int)) :forall(a m) :context((Monad m)) (:let (: inner :fun (m a)((x a)(_ :unit)) (f x)) (foldM inner start (replicate n :nothing)) )) (: read-rand :fun Rand-function ((s String)) (:case s ((:pstring "binary")black-white) ((:pstring "gray")gray) :else (error "rand = {binary | gray}") )) (: read-starting :fun (:fn(IO Image)((rand Rand-function)(size Int)))((s String)) (:case s ((:pstring "full")full) ((:pstring "checkerboard")auto-checkerboard) :else (error "starting = {full | checkerboard}") )) (: main :fun (IO :unit) () (:do [(:rpipe 1 mkStdGen setStdGen)] (:join getArgs (:lcase ((:plist starting rand size iterations) (:join ((read-starting starting)(read-rand rand)(read size))(multiple-smooth (read iterations)) pgm-image)) :else (putStrLn "starting rand size iterations"))) ))