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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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
from __future__ import unicode_literals
import sys
import re
from StringIO import StringIO
from contextlib import contextmanager

class DecompilerBase(object):
    def __init__(self, out_file=None, indentation='    ', printlock=None):
        self.out_file = out_file or sys.stdout
        self.indentation = indentation
        self.skip_indent_until_write = False
        self.printlock = printlock

        self.linenumber = 0

        self.block_stack = []
        self.index_stack = []
        self.blank_line_queue = []

    def dump(self, ast, indent_level=0, linenumber=1, skip_indent_until_write=False):
        """
        Write the decompiled representation of `ast` into the opened file given in the constructor
        """
        self.indent_level = indent_level
        self.linenumber = linenumber
        self.skip_indent_until_write = skip_indent_until_write
        if not isinstance(ast, (tuple, list)):
            ast = [ast]
        self.print_nodes(ast)
        return self.linenumber

    @contextmanager
    def increase_indent(self, amount=1):
        self.indent_level += amount
        try:
            yield
        finally:
            self.indent_level -= amount

    def write(self, string):
        """
        Shorthand method for writing `string` to the file
        """
        string = unicode(string)
        self.linenumber += string.count('\n')
        self.skip_indent_until_write = False
        self.out_file.write(string)

    def write_lines(self, lines):
        """
        Write each line in lines to the file without writing whitespace-only lines
        """
        for line in lines:
            if line == '':
                self.write('\n')
            else:
                self.indent()
                self.write(line)

    def save_state(self):
        """
        Save our current state.
        """
        state = (self.out_file, self.skip_indent_until_write, self.linenumber,
            self.block_stack, self.index_stack, self.indent_level, self.blank_line_queue)
        self.out_file = StringIO()
        return state

    def commit_state(self, state):
        """
        Commit changes since a saved state.
        """
        out_file = state[0]
        out_file.write(self.out_file.getvalue())
        self.out_file = out_file

    def rollback_state(self, state):
        """
        Roll back to a saved state.
        """
        (self.out_file, self.skip_indent_until_write, self.linenumber,
            self.block_stack, self.index_stack, self.indent_level, self.blank_line_queue) = state

    def advance_to_line(self, linenumber):
        # If there was anything that we wanted to do as soon as we found a blank line,
        # try to do it now.
        self.blank_line_queue = filter(lambda m: m(linenumber), self.blank_line_queue)
        if self.linenumber < linenumber:
            # Stop one line short, since the call to indent() will advance the last line.
            # Note that if self.linenumber == linenumber - 1, this will write the empty string.
            # This is to make sure that skip_indent_until_write is cleared in that case.
            self.write("\n" * (linenumber - self.linenumber - 1))

    def do_when_blank_line(self, m):
        """
        Do something the next time we find a blank line. m should be a method that takes one
        parameter (the line we're advancing to), and returns whether or not it needs to run
        again.
        """
        self.blank_line_queue.append(m)

    def indent(self):
        """
        Shorthand method for pushing a newline and indenting to the proper indent level
        Setting skip_indent_until_write causes calls to this method to be ignored until something
        calls the write method
        """
        if not self.skip_indent_until_write:
            self.write('\n' + self.indentation * self.indent_level)

    def print_nodes(self, ast, extra_indent=0):
        # This node is a list of nodes
        # Print every node
        with self.increase_indent(extra_indent):
            self.block_stack.append(ast)
            self.index_stack.append(0)

            for i, node in enumerate(ast):
                self.index_stack[-1] = i
                self.print_node(node)

            self.block_stack.pop()
            self.index_stack.pop()

    @property
    def block(self):
        return self.block_stack[-1]

    @property
    def index(self):
        return self.index_stack[-1]

    @property
    def parent(self):
        if len(self.block_stack) < 2:
            return None
        return self.block_stack[-2][self.index_stack[-2]]

    def print_debug(self, message):
        if self.printlock:
            self.printlock.acquire()
        try:
            print(message)
        finally:
            if self.printlock:
                self.printlock.release()

    def write_failure(self, message):
        self.print_debug(message)
        self.indent()
        self.write("pass # <<<COULD NOT DECOMPILE: %s>>>" % message)

    def print_unknown(self, ast):
        # If we encounter a placeholder note, print a warning and insert a placeholder
        self.write_failure("Unknown AST node: %s" % str(type(ast)))

    def print_node(self, ast):
        raise NotImplementedError()

class First(object):
    # An often used pattern is that on the first item
    # of a loop something special has to be done. This class
    # provides an easy object which on the first access
    # will return True, but any subsequent accesses False
    def __init__(self, yes_value=True, no_value=False):
        self.yes_value = yes_value
        self.no_value = no_value
        self.first = True

    def __call__(self):
        if self.first:
            self.first = False
            return self.yes_value
        else:
            return self.no_value

def reconstruct_paraminfo(paraminfo):
    if paraminfo is None:
        return ""

    rv = ["("]

    sep = First("", ", ")
    positional = [i for i in paraminfo.parameters if i[0] in paraminfo.positional]
    nameonly = [i for i in paraminfo.parameters if i not in positional]
    for parameter in positional:
        rv.append(sep())
        rv.append(parameter[0])
        if parameter[1] is not None:
            rv.append("=%s" % parameter[1])
    if paraminfo.extrapos:
        rv.append(sep())
        rv.append("*%s" % paraminfo.extrapos)
    if nameonly:
        if not paraminfo.extrapos:
            rv.append(sep())
            rv.append("*")
        for parameter in nameonly:
            rv.append(sep())
            rv.append(parameter[0])
            if parameter[1] is not None:
                rv.append("=%s" % parameter[1])
    if paraminfo.extrakw:
        rv.append(sep())
        rv.append("**%s" % paraminfo.extrakw)

    rv.append(")")

    return "".join(rv)

def reconstruct_arginfo(arginfo):
    if arginfo is None:
        return ""

    rv = ["("]
    sep = First("", ", ")
    for (name, val) in arginfo.arguments:
        rv.append(sep())
        if name is not None:
            rv.append("%s=" % name)
        rv.append(val)
    if arginfo.extrapos:
        rv.append(sep())
        rv.append("*%s" % arginfo.extrapos)
    if arginfo.extrakw:
        rv.append(sep())
        rv.append("**%s" % arginfo.extrakw)
    rv.append(")")

    return "".join(rv)

def string_escape(s): # TODO see if this needs to work like encode_say_string elsewhere
    s = s.replace('\\', '\\\\')
    s = s.replace('"', '\\"')
    s = s.replace('\n', '\\n')
    s = s.replace('\t', '\\t')
    return s

# keywords used by ren'py's parser
KEYWORDS = set(['$', 'as', 'at', 'behind', 'call', 'expression', 'hide',
                'if', 'in', 'image', 'init', 'jump', 'menu', 'onlayer',
                'python', 'return', 'scene', 'set', 'show', 'with',
                'while', 'zorder', 'transform'])

word_regexp = '[a-zA-Z_\u00a0-\ufffd][0-9a-zA-Z_\u00a0-\ufffd]*'

def simple_expression_guard(s):
    # Some things we deal with are supposed to be parsed by
    # ren'py's Lexer.simple_expression but actually cannot
    # be parsed by it. figure out if this is the case
    # a slightly more naive approach woudl be to check
    # for spaces in it and surround it with () if necessary
    # but we're not naive
    s = s.strip()

    if Lexer(s).simple_expression():
        return s
    else:
        return "(%s)" % s

def split_logical_lines(s):
    return Lexer(s).split_logical_lines()

class Lexer(object):
    # special lexer for simple_expressions the ren'py way
    # false negatives aren't dangerous. but false positives are
    def __init__(self, string):
        self.pos = 0
        self.length = len(string)
        self.string = string

    def re(self, regexp):
        # see if regexp matches at self.string[self.pos].
        # if it does, increment self.pos
        if self.length == self.pos:
            return None

        match = re.compile(regexp, re.DOTALL).match(self.string, self.pos)
        if not match:
            return None

        self.pos = match.end()
        return match.group(0)

    def eol(self):
        # eat the next whitespace and check for the end of this simple_expression
        self.re(r"(\s+|\\\n)+")
        return self.pos >= self.length

    def match(self, regexp):
        # strip whitespace and match regexp
        self.re(r"(\s+|\\\n)+")
        return self.re(regexp)

    def python_string(self, clear_whitespace=True):
        # parse strings the ren'py way (don't parse docstrings, no b/r in front allowed)
        # edit: now parses docstrings correctly. There was a degenerate case where '''string'string''' would
        # result in issues
        if clear_whitespace:
            return self.match(r"""(u?(?P<a>"(?:"")?|'(?:'')?).*?(?<=[^\\])(?:\\\\)*(?P=a))""")
        else:
            return self.re(r"""(u?(?P<a>"(?:"")?|'(?:'')?).*?(?<=[^\\])(?:\\\\)*(?P=a))""")


    def container(self):
        # parses something enclosed by [], () or {}'s. keyword something
        containers = {"{": "}", "[": "]", "(": ")"}
        if self.eol():
            return None

        c = self.string[self.pos]
        if c not in containers:
            return None
        self.pos += 1

        c = containers[c]

        while not self.eol():
            if c == self.string[self.pos]:
                self.pos += 1
                return True

            if self.python_string() or self.container():
                continue

            self.pos += 1

        return None

    def number(self):
        # parses a number, float or int (but not forced long)
        return self.match(r'(\+|\-)?(\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?')

    def word(self):
        # parses a word
        return self.match(word_regexp)

    def name(self):
        # parses a word unless it's in KEYWORDS.
        pos = self.pos
        word = self.word()

        if word in KEYWORDS:
            self.pos = pos
            return None

        return word

    def simple_expression(self):
        # test if the start string was a simple expression
        start = self.pos

        # check if there's anything in here acctually
        if self.eol():
            return False

        # parse anything which can be called or have attributes requested
        if not(self.python_string() or
               self.number() or
               self.container() or
               self.name()):
            return False

        while not self.eol():

            # if the previous was followed by a dot, there should be a word after it
            if self.match(r'\.'):
                if not self.name():
                    # ren'py errors here. I just stop caring
                    return False

                continue

            # parses slices, function calls, and postfix {}
            if self.container():
                continue

            break

            # are we at the end of the simple expression?
        return self.eol()

    def split_logical_lines(self):
        # split a sequence in logical lines
        # this behaves similarly to .splitlines() which will ignore
        # a trailing \n
        lines = []

        contained = 0

        startpos = self.pos

        while self.pos < self.length:
            c = self.string[self.pos]

            if c == '\n' and not contained and (not self.pos or self.string[self.pos - 1] != '\\'):
                lines.append(self.string[startpos:self.pos])
                # the '\n' is not included in the emitted line
                self.pos += 1
                startpos = self.pos
                continue

            if c in ('(', '[', '{'):
                contained += 1
                self.pos += 1
                continue

            if c in (')', ']', '}') and contained:
                contained -= 1
                self.pos += 1
                continue

            if c == '#':
                self.re("[^\n]*")
                continue

            if self.python_string(False):
                continue

            self.re(r'\w+| +|.') # consume a word, whitespace or one symbol

        if self.pos != startpos:
            lines.append(self.string[startpos:])
        return lines

# Versions of Ren'Py prior to 6.17 put trailing whitespace on the end of
# simple_expressions. This class attempts to preserve the amount of
# whitespace if possible.
class WordConcatenator(object):
    def __init__(self, needs_space, reorderable=False):
        self.words = []
        self.needs_space = needs_space
        self.reorderable = reorderable

    def append(self, *args):
        self.words.extend(filter(None, args))

    def join(self):
        if not self.words:
            return ''
        if self.reorderable and self.words[-1][-1] == ' ':
            for i in xrange(len(self.words) - 1, -1, -1):
                if self.words[i][-1] != ' ':
                    self.words.append(self.words.pop(i))
                    break
        last_word = self.words[-1]
        self.words = map(lambda x: x[:-1] if x[-1] == ' ' else x, self.words[:-1])
        self.words.append(last_word)
        rv = (' ' if self.needs_space else '') + ' '.join(self.words)
        self.needs_space = rv[-1] != ' '
        return rv

# Dict subclass for aesthetic dispatching. use @Dispatcher(data) to dispatch
class Dispatcher(dict):
    def __call__(self, name):
        def closure(func):
            self[name] = func
            return func
        return closure

# ren'py string handling
def encode_say_string(s):
    """
    Encodes a string in the format used by Ren'Py say statements.
    """

    s = s.replace("\\", "\\\\")
    s = s.replace("\n", "\\n")
    s = s.replace("\"", "\\\"")
    s = re.sub(r'(?<= ) ', '\\ ', s)

    return "\"" + s + "\""

# Adapted from Ren'Py's Say.get_code
def say_get_code(ast, inmenu=False):
    rv = [ ]

    if ast.who:
        rv.append(ast.who)

    if hasattr(ast, 'attributes') and ast.attributes is not None:
        rv.extend(ast.attributes)

    if hasattr(ast, 'temporary_attributes') and ast.temporary_attributes is not None:
        rv.append("@")
        rv.extend(ast.temporary_attributes)

    # no dialogue_filter applies to us

    rv.append(encode_say_string(ast.what))

    if not ast.interact and not inmenu:
        rv.append("nointeract")

    if ast.with_:
        rv.append("with")
        rv.append(ast.with_)

    if hasattr(ast, 'arguments') and ast.arguments is not None:
        rv.append(reconstruct_arginfo(ast.arguments))

    return " ".join(rv)