content: module MkConstants where
  
  -- build a lexicon extension from a configuration file
  -- that annotates Dedukti constants with information for GF
  -- Usage:
  --
  --  RunInformath <file>.dkgf
  --  make Informath.pgf
  --
  -- the format of an annotation is one of
  --
  --   <dkid> NEW <project> <gfcat> <gffun>
  --   #LIN <lang> <gffun> = <gfexp>
  --
  -- E.g.
  --
  --   Polynomial NEW top100 Noun polynomial_Noun
  --   #LIN Eng polynomial_Noun = mkNoun "polynomial"
  --
  -- from which it generates lines in two files
  --
  --   grammars/UserConstants.gf       :  fun <gffun> : <gfcat> ; -- <project>
  --   grammars/UserConstants<lang>.gf :  lin <gffun> = <gfexp> ; -- <project>
  --
  -- Annotations are read from the file constant_data.dkgf.
  -- For the time being, it is a global file
  
  import Data.List (intersperse)
  import qualified Data.Map as M
  
  constantsFile gfname langid = "grammars/" ++ gfname ++ langid ++ ".gf"
  
  mkConstants :: FilePath -> String -> IO ()
  mkConstants file gfname = do
    ls <- readFile file >>= return . map words . lines
    let absannots = [(fun, cat, proj) | _:"NEW":proj:cat:fun:_ <- ls]
    let cncannots = M.fromListWith (++) [(lang, [(fun, unwords ws)]) | "#LIN":lang:fun:"=":ws <- ls]
    writeAndReport (constantsFile gfname "") $ mkConstantsGF gfname absannots
    mapM_ (\ (lang, lins) -> 
      writeAndReport (constantsFile gfname lang) $ mkConstantsCncGF gfname lang lins) (M.toList cncannots)
    if gfname /= "UserConstants"
      then putStrLn "to use these files, add them to MathCore* inheritance lists"
      else return ()
  
  
  mkConstantsGF gfname annots = unlines $ [
    "abstract " ++ gfname ++ " = BaseConstants ** {",
    "",
    "-- generated by MkConstants.hs",
    ""
    ] ++
    map mkConstant annots ++
    ["}"]
   where
     mkConstant (fun, cat, proj) =
       unwords(["fun", fun, ":", cat, ";", "--", proj])
  
  
  mkConstantsCncGF gfname lang annots = unlines $ [
    "concrete " ++ gfname ++ lang ++ " of " ++ gfname ++ " = BaseConstants" ++ lang ++ " **",
    "",
    "-- generated by MkConstants.hs",
    "",
    "open",
    "  Utilities" ++ lang ++ ",",
    "  Syntax" ++ lang ++ ",",
    "  Paradigms" ++ lang ++ ",",
    "  Symbolic" ++ lang ++ ",",
    "  (L=BaseConstantsLatex),",
    "  Formal",
    "",
    "in {"
    ] ++
    map mkConstant annots ++
    ["}"]
   where
     mkConstant (fun, lin) = unwords ["lin", fun, "=", lin, ";"]
  
  writeAndReport :: FilePath -> String -> IO ()
  writeAndReport file s = do
    writeFile file s
    putStrLn $ "wrote " ++ file
  
  