-
Notifications
You must be signed in to change notification settings - Fork 2
/
Mrifk_print.hs
362 lines (255 loc) · 10.2 KB
/
Mrifk_print.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
{-
Mrifk, a decompiler for Glulx story files.
Copyright 2004 Ben Rudiak-Gould.
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 2
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 can read the GNU General Public License at this URL:
http://www.gnu.org/copyleft/gpl.html
-}
module Mrifk_print (
ppRoutine, ppObject, ppQuotedString, ppVerbs
) where
import Mrifk_code
import Mrifk_grammar
import Mrifk_objects
import Mrifk_memmap
import Mrifk_storyfile
import Mrifk_strings
import Mrifk_util
import Data.Char (ord,isDigit)
import Data.Array
import Data.Ix (inRange)
import Data.Maybe (fromMaybe)
import Numeric (showHex)
{--------------}
ppRoutine (addr,type_,params,body) =
(if type_ == 193 then [] else ["! Stack-parameter routine"])
++ (if all (== 4) params
then []
else ["! Local lengths: " ++ unwords [show n | n <- params]])
++ (unwords ("[" : nameRoutine addr : [nameLocal n | n <- scanl (+) 0 params | _ <- params] ++ [";"]))
: indentBlock (ppStatements body)
++ ["];",""]
ppStatements x@(Print _ _ : _) =
let (prints,rest) = break (not.isPrint) x
(isRet,rest') = case rest of
(NewLine : Eval "return " (Imm 1) : rest') -> (True,rest')
_ -> (False,rest)
in (ppPrints prints isRet ++ ";") : ppStatements rest'
ppStatements (x : xs) = ppStatement x ++ ppStatements xs
ppStatements [] = []
ppPrints [Print "" s@(ImmString _)] True =
ppExpr 0 s
ppPrints prints isRet =
let prefix = if isRet then "print_ret " else "print "
args = map ppPrint prints
in prefix ++ join ", " args
isPrint (Print _ _) = True
isPrint _ = False
ppPrint (Print prefix val) = prefix ++ ppExpr 1 val
ppStatement (Label addr Phantom) = []
ppStatement (Label addr _) = ["<." ++ nameLabel addr ++ ":"]
ppStatement (GInstr (name,loads,stores,branches,_) args) =
let prefixes = replicate loads "" ++ replicate stores "-> " ++ replicate branches "label"
printableArgs = zipWith (++) prefixes (map (ppExpr 99) args)
in [join " " (('@' : name) : printableArgs) ++ ";"]
ppStatement (Eval cmd expr) = [cmd ++ ppExpr 0 expr ++ ";"]
ppStatement (Push expr) = ["{{{PUSH}}} " ++ ppExpr 0 expr ++ ";"]
ppStatement NewLine = ["new_line;"]
ppStatement (IfThenElse cond thenClause []) =
("if (" ++ ppExpr 0 cond ++ ") {") : indentBlock (ppStatements thenClause) ++ ["}"]
ppStatement (IfThenElse cond thenClause elseClause) =
let elseClauseText = ppStatements elseClause
elseText = case elseClauseText of
(line@('i':'f':' ':_) : lines@(_:_)) -> ("} else " ++ line) : lines
_ -> "} else {" : indentBlock elseClauseText ++ ["}"]
in ("if (" ++ ppExpr 0 cond ++ ") {") : indentBlock (ppStatements thenClause) ++ elseText
ppStatement (JCond cond label) =
["if (" ++ ppExpr 0 cond ++ ") " ++ ppJump label ++ ";"]
ppStatement (Jump label) =
[ppJump label ++ ";"]
ppStatement (Give obj b attr) =
["give " ++ ppExpr 0 obj ++ (if b then " " else " ~") ++ nameAttr attr ++ ";"]
ppStatement x = ["{{{" ++ show x ++ "}}}"]
ppJump 0 = "rfalse"
ppJump 1 = "rtrue"
ppJump label = "jump " ++ nameLabel label
ppExpr prec (Assign dst src) =
parenIf (1 <= prec) (ppExpr 1 dst ++ " = " ++ ppExpr 0 src)
ppExpr prec (Call func args) =
parenIf (11 <= prec) (ppExpr 10 func ++ "(" ++ join "," (map (ppExpr 0) args) ++ ")")
ppExpr prec (Binary left op right) =
let p = binopPrec op in
parenIf (p <= prec) (ppExpr (p-1) left ++ binopName op ++ ppExpr p right)
ppExpr prec (Unary op opPrec expr) =
parenIf (opPrec <= prec) (op ++ ppExpr (opPrec-1) expr)
ppExpr prec (PostIncDec expr op) =
parenIf (9 <= prec) (ppExpr 8 expr ++ op)
ppExpr prec SP = "sp"
ppExpr prec (Imm n) = ppValue n
ppExpr prec (ImmString n) = ppQuotedString (evalFrom n decodeString) -- FIXME: quote
ppExpr prec (Mem n) = "mem" ++ show n
ppExpr prec (Local n) = nameLocal n
ppExpr prec (SpecialName x) = x
-- ppExpr prec foo = "{{{" ++ show foo ++ "}}}"
{--------------}
ppObject treeDepth n (Object name attribs props) =
"" : firstLine : indentWith (map ppProp props)
++ [" has\t" ++ ppAttribs attribs ++ ";"]
where
firstLine = "Object" ++ take (3*treeDepth+1) (cycle " ->")
++ nameObject n ++ ' ' : ppQuotedString name
ppProp (n, private, vals) =
unwords (nameProp n : map ppValue vals) ++ ";"
ppAttribs attribs =
join " " [nameAttr attr | attr <- attribs]
indentWith [] = []
indentWith (firstLine : lines) =
(" with\t" ++ firstLine) : map ('\t' :) lines
{--------------}
-- FIXME: leaves something to be desired
ppValue val
| val <= 16 || not (inRange wholeFile val)
= show val -- FIXME: negatives?
| otherwise
= case byteAt val of
0x70 -> nameObject val
0x60 -> ppDictWord (dictWordAt val)
0xC0 -> nameRoutine val
0xC1 -> nameRoutine val
0xE0 -> ppQuotedString (evalFrom val decodeString)
0xE1 -> ppQuotedString (evalFrom val decodeString)
_ -> show val
{--------------}
ppQuotedString s = '"' : ppString s ++ "\""
ppString "" = ""
ppString (x : rest)
| x == '\10' = '^' : ppString rest
| x == '"' = '~' : ppString rest
| x <= '\x153' = (informEscapes ! x) ++ ppString rest
| otherwise = informEscapeChar x (ppString rest)
ppString' "" = ""
ppString' (x : rest)
| x == '\'' = '^' : ppString' rest
| x == '"' = '"' : ppString' rest
| x <= '\x153' = (informEscapes ! x) ++ ppString' rest
| otherwise = informEscapeChar x (ppString' rest)
-- correct behavior of showHex requires GHC 6.2
informEscapeChar x rest =
"@{" ++ showHex (ord x) ('}' : rest)
informEscapes :: Array Char String
informEscapes =
accumArray (\a b -> b) undefined ('\0','\x153') $
[(x,[x]) | x <- ['\32'..'\126']]
++ [(x,informEscapeChar x "") | x <- ['\0'..'\31'] ++ "^~@\"" ++ ['\127'..'\x153']]
++ informSpecialEscapes
informSpecialEscapes :: [(Char,String)]
informSpecialEscapes =
[('\xE4',"@:a"), ('\xF6',"@:o"), ('\xFC',"@:u"),
('\xC4',"@:A"), ('\xD6',"@:O"), ('\xDC',"@:U"),
('\xDF',"@ss"), ('\xAB',"@>>"), ('\xBB',"@<<"),
('\xEB',"@:e"), ('\xEF',"@:i"), ('\xFF',"@:y"),
('\xCB',"@:E"), ('\xCF',"@:I"), ('\xE1',"@'a"),
('\xE9',"@'e"), ('\xED',"@'i"), ('\xF3',"@'o"),
('\xFA',"@'u"), ('\xFD',"@'y"), ('\xC1',"@'A"),
('\xC9',"@'E"), ('\xCD',"@'I"), ('\xD3',"@'O"),
('\xDA',"@'U"), ('\xDD',"@'Y"), ('\xE0',"@`a"),
('\xE8',"@`e"), ('\xEC',"@`i"), ('\xF2',"@`o"),
('\xF9',"@`u"), ('\xC0',"@`A"), ('\xC8',"@`E"),
('\xCC',"@`I"), ('\xD2',"@`O"), ('\xD9',"@`U"),
('\xE2',"@^a"), ('\xEA',"@^e"),
('\xEE',"@^i"), ('\xF4',"@^o"),
('\xFB',"@^u"), ('\xC2',"@^A"),
('\xCA',"@^E"), ('\xCE',"@^I"),
('\xD4',"@^O"), ('\xDB',"@^U"),
('\xE5',"@oa"), ('\xC5',"@oA"),
('\xF8',"@/o"), ('\xD8',"@/O"),
('\xE3',"@~a"), ('\xF1',"@~n"), ('\xF5',"@~o"),
('\xC3',"@~A"), ('\xD1',"@~N"), ('\xD5',"@~O"),
('\xE6',"@ae"), ('\xC6',"@AE"),
('\xE7',"@cc"), ('\xC7',"@cC"),
('\xFE',"@th"), ('\xF0',"@et"), ('\xDE',"@Th"), ('\xD0',"@Et"),
('\xA3',"@LL"),
('\x0153',"@oe"), ('\x0152',"@OE"),
('\xA1',"@!!"), ('\xBF',"@??")]
{---------------}
ppVerbs :: [([String],[GrammarLine])] -> [String]
ppVerbs = concatMap ppVerb
ppVerb (verbs,grammars) =
-- FIXME: check meta
"" : unwords ("Verb" : map ppDictWord verbs)
: map ppVerbGrammarLine grammars ++ [";"]
ppVerbGrammarLine (GrammarLine tokens action reverse) =
tab 7 (" * " ++ unwords (map ppVerbToken tokens))
("-> " ++ nameAction action ++ if reverse then " reverse" else "")
-- FIXME
ppVerbToken (ElementaryToken s) = s
ppVerbToken (Preposition p) = ppDictWord p
ppVerbToken (Attribute n) = nameAttr n
ppVerbToken (ParseRoutine prefix n) = prefix ++ nameRoutine n
ppVerbToken (Alternatives tokens) =
join "/" (map ppVerbToken tokens)
ppDictWord w = '\'' : ppString' w ++ "'"
{--------------}
parenIf True x = '(' : x ++ ")"
parenIf False x = x
nameObject :: Int -> String
nameObject 0 = "nothing"
nameObject n =
case tableLookup n objectNames of
Just name -> name
Nothing -> "unknownObj" ++ show n
objectNames =
makeLookupTable $
-- earlier in the list takes precedence
map guessObjName objects
guessObjName (n,obj) =
case obj of
Object "" _ _ -> (n,baseName)
Object desc _ _ -> (n,baseName ++ '_' : makeIdent desc)
where baseName = "obj" ++ show n
makeIdent name =
map helper name
where helper c = if isLegalIdentChar c then c else '_'
isLegalIdentChar c =
inRange ('0','9') c || inRange ('A','Z') c || inRange ('a','z') c
nameProp n =
maybeIdx commonPropNames n $
maybeIdx indivPropNames n $
"prop" ++ show n
nameAttr n =
maybeIdx attribNames n $
"attr" ++ show n
nameAction n =
maybeIdx actionNames n $
"Action" ++ show n
nameRoutine :: Int -> String
nameRoutine addr =
fromMaybe ("routine" ++ show addr)
(addr `tableLookup` routineNames)
routineNames =
makeLookupTable $
-- earlier in the list takes precedence
[(addr, nameAction n ++ "Sub")
| addr <- actionRoutines | n <- [0..]]
nameLocal n = "local" ++ show n
nameLabel n = "label" ++ show n
maybeIdx array n def
| inRange (bounds array) n = fromMaybe def (array ! n)
| otherwise = def
indentBlock = map indentBlock'
indentBlock' ('<':rest) = ' ':' ':rest
indentBlock' rest = ' ':' ':' ':' ':rest
join sep [] = []
join sep xs = foldr1 (\x y -> x ++ sep ++ y) xs
tab :: Int -> String -> String -> String
tab n x y =
x ++ makeTabs (n - length x `div` 8) ++ y
makeTabs n | n <= 0 = " "
| otherwise = replicate n '\t'