Search code examples
parsinghaskellhaskell-src-exts

Examples with Haskell-src-exts package


I'm working with Haskell and I want to build a typechecker for this language. To do this I need a way to parse it and I know that Haskell-src-exts suits the job well. However I don't have the slightest idea of how this package works; I've tried to find some examples/ tutorials on the internet without any result. Can anyone help me? Does anyone know some tutorial, or maybe can reference me a book which contains examples abouth this package? I'm also open to try another package, if it is well described and it comes with a load of examples.


Solution

  • A convenient entry point is parseFile. If the following program is used to parse itself:

    module HelloParser where
    
    import Language.Haskell.Exts
    
    main = print =<< parseFile "HelloParser.hs"
    

    then it produces the parsed output (stripped of SrcSpanInfo values and reformatted):

    ParseOk
      (Module (Just (ModuleHead (ModuleName "HelloParser") Nothing Nothing)) []
        [ ImportDecl { importModule = ModuleName "Language.Haskell.Exts"
                     , importQualified = False
                     , importSrc = False
                     , importSafe = False
                     , importPkg = Nothing
                     , importAs = Nothing
                     , importSpecs = Nothing} ]
        [ PatBind
          (PVar (Ident "main"))
          (UnGuardedRhs (InfixApp
                          (Var (UnQual (Ident "print")))
                          (QVarOp (UnQual (Symbol "=<<")))
                          (App
                            (Var (UnQual (Ident "parseFile")))
                            (Lit (String "HelloParser.hs" "HelloParser.hs")))))
          Nothing ])
    

    which seems relatively readable.

    To complete the task of type checking Haskell, I don't think there's any way to avoid individual consideration of the hundreds of parse tree data types and constructors in Language.Haskell.Exts.Syntax and the other package modules, so I'm not sure how much further a more in-depth tutorial can get you.