gpt4 book ai didi

haskell - 如何解析 GHC 核心?

转载 作者:行者123 更新时间:2023-12-01 03:35:17 24 4
gpt4 key购买 nike

我正在尝试解析从运行 ghc -c -ddump-simpl myfile.hs 获得的 ghc 核心代码.

我知道 extcore core 图书馆是我的选择。

我正在寻找一个简单的例子来描述这些库的使用。

[编辑] 解析结果应该是一个数据结构,应该很容易从中跟踪函数可以采用的不同路径。

考虑一个简单的 not功能

not True = False
not False = True

GHC 会将其转换为 case 表达式(仅考虑来自 ghc -c -ddump-simple 的输出)。我正在寻找解析 GHC 核心的这个输出。

最佳答案

我认为最简单的方法是放弃这些外部核心库,直接使用 GHC 作为库。基于 this example from the Haskell wiki ,我们可以做一个简单的函数,把一个模块变成Core:

import GHC
import GHC.Paths (libdir)
import HscTypes (mg_binds)
import CoreSyn
import DynFlags
import Control.Monad ((<=<))

compileToCore :: String -> IO [CoreBind]
compileToCore modName = runGhc (Just libdir) $ do
setSessionDynFlags =<< getSessionDynFlags
target <- guessTarget (modName ++ ".hs") Nothing
setTargets [target]
load LoadAllTargets
ds <- desugarModule <=< typecheckModule <=< parseModule <=< getModSummary $ mkModuleName modName
return $ mg_binds . coreModule $ ds

这是一个愚蠢的示例用法,它处理其输出以计算案例数量:
-- Silly example function that analyzes Core
countCases :: [CoreBind] -> Int
countCases = sum . map countBind
where
countBind (NonRec _ e) = countExpr e
countBind (Rec bs) = sum . map (countExpr . snd) $ bs

countExpr (Case e _ _ alts) = countExpr e + sum (map countAlt alts)
countExpr (App f e) = countExpr f + countExpr e
countExpr (Lam _ e) = countExpr e
countExpr (Let b e) = countBind b + countExpr e
countExpr (Cast e _) = countExpr e
countExpr (Tick _ e) = countExpr e
countExpr _ = 0

countAlt (_, _, rhs) = 1 + countExpr rhs

让我们在您的示例上运行它:
main :: IO ()
main = do
core <- compileToCore "MyNot"
print $ countCases core

正如预期的那样,这将输出 2。

关于haskell - 如何解析 GHC 核心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35449353/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com