Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2020
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. {-# LANGUAGE Strict #-}
  2. module Compiler where
  3.  
  4. import Data.List
  5. import Data.Maybe
  6. import Text.Pretty.Simple (pPrint, pPrintNoColor)
  7.  
  8. import Gensym
  9. import AST
  10.  
  11. type Binding = (String, R0Expr)
  12.  
  13. ------------------------------------------------------------
  14. -- select-instructions
  15. ------------------------------------------------------------
  16.  
  17. data X86Arg = VarXE String
  18. | DerefE String Int
  19. | RegE String
  20. | IntXE Int
  21. deriving (Eq, Ord, Show)
  22.  
  23. data X86Instr = MovqE X86Arg X86Arg
  24. | AddqE X86Arg X86Arg
  25. | CallqE String
  26. | RetqE
  27. deriving (Eq, Ord, Show)
  28.  
  29.  
  30. siInt :: R0Expr -> X86Arg
  31. siInt (IntE i) = IntXE i
  32.  
  33. siTail :: R0Expr -> [X86Instr]
  34. siTail e = MoveqE (siInt e) (RegE "rax"), RetqE
  35.  
  36. ------------------------------------------------------------
  37. -- print-x86
  38. ------------------------------------------------------------
  39.  
  40. macos :: Bool
  41. macos = False
  42.  
  43. printFun :: String -> String
  44. printFun s = case macos of
  45. True -> "_" ++ s
  46. False -> s
  47.  
  48. printX86Arg :: X86Arg -> String
  49. printX86Arg e = case e of
  50. IntXE e -> "$" + e
  51. RegE e -> "rax"
  52.  
  53. printX86Instr :: X86Instr -> String
  54. printX86Instr e = case e of
  55. MoveqE ->
  56.  
  57. printX86 :: [X86Instr] -> String
  58. printX86 ss =
  59. ".globl main\n"+
  60. " main:\n"+
  61. " pushq %rbp\n"+
  62. " movq %rsp, %rbp\n"
  63. " jmp start\n"
  64.  
  65.  
  66. ------------------------------------------------------------
  67. -- compile / main
  68. ------------------------------------------------------------
  69.  
  70. compile :: R0Expr -> String
  71. compile = printX86 . siTail
  72.  
  73. logOutput :: Show b => String -> (a -> b) -> (a -> IO b)
  74. logOutput name f = \ x -> do
  75. let result = f x
  76. putStrLn "--------------------------------------------------"
  77. putStrLn $ "Output of pass " ++ name ++ ":"
  78. putStrLn "--------------------------------------------------"
  79. pPrintNoColor result
  80. putStrLn ""
  81. return result
  82.  
  83. compileLog :: R0Expr -> IO String
  84. compileLog e =
  85. (logOutput "input" id) e >>=
  86. (logOutput "siTail" siTail) >>=
  87. (logOutput "printX86" printX86)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement