Debian Codegraph @

rpython/jit/tl/tiny2.py

raw symbols SCIP
1 """
2 An interpreter for a strange word-based language: the program is a list
3 of space-separated words. Most words push themselves on a stack; some
4 words have another action. The result is the space-separated words
5 from the stack.
6
7 Hello World => 'Hello World'
8 6 7 ADD => '13' 'ADD' is a special word
9 7 * 5 = 7 5 MUL => '7 * 5 = 35' '*' and '=' are not special words
10
11 Arithmetic on non-integers gives a 'symbolic' result:
12
13 X 2 MUL => 'X*2'
14
15 Input arguments can be passed on the command-line, and used as #1, #2, etc.:
16
17 #1 1 ADD => one more than the argument on the command-line,
18 or if it was not an integer, concatenates '+1'
19
20 You can store back into an (existing) argument index with ->#N:
21
22 #1 5 ADD ->#1
23
24 Braces { } delimitate a loop. Don't forget spaces around each one.
25 The '}' pops an integer value off the stack and loops if it is not zero:
26
27 { #1 #1 1 SUB ->#1 #1 } => when called with 5, gives '5 4 3 2 1'
28
29 """
30 from rpython.rlib.jit import hint, promote, dont_look_inside
31
32 #
33 # See pypy/doc/jit.txt for a higher-level overview of the JIT techniques
34 # detailed in the following comments.
35 #
36
37
38 class Box:
39 # Although all words are in theory strings, we use two subclasses
40 # to represent the strings differently from the words known to be integers.
41 # This is an optimization that is essential for the JIT and merely
42 # useful for the basic interpreter.
43 pass
44
45 class IntBox(Box):
46 def __init__(self, intval):
47 self.intval = intval
48 def as_int(self):
49 return self.intval
50 def as_str(self):
51 return str(self.intval)
52
53 class StrBox(Box):
54 def __init__(self, strval):
55 self.strval = strval
56 def as_int(self):
57 return myint(self.strval)
58 def as_str(self):
59 return self.strval
60
61
62 def func_add_int(ix, iy): return ix + iy
63 def func_sub_int(ix, iy): return ix - iy
64 def func_mul_int(ix, iy): return ix * iy
65
66 def func_add_str(sx, sy): return sx + '+' + sy
67 def func_sub_str(sx, sy): return sx + '-' + sy
68 def func_mul_str(sx, sy): return sx + '*' + sy
69
70 def op2(stack, func_int, func_str):
71 # Operate on the top two stack items. The promotion hints force the
72 # class of each arguments (IntBox or StrBox) to turn into a compile-time
73 # constant if they weren't already. The effect we seek is to make the
74 # calls to as_int() direct calls at compile-time, instead of indirect
75 # ones. The JIT compiler cannot look into indirect calls, but it
76 # can analyze and inline the code in directly-called functions.
77 y = stack.pop()
78 promote(y.__class__)
79 x = stack.pop()
80 promote(x.__class__)
81 try:
82 z = IntBox(func_int(x.as_int(), y.as_int()))
83 except ValueError:
84 z = StrBox(func_str(x.as_str(), y.as_str()))
85 stack.append(z)
86
87
88 def interpret(bytecode, args):
89 """The interpreter's entry point and portal function.
90 """
91 # ------------------------------
92 # First a lot of JIT hints...
93 #
94 # A portal needs a "global merge point" at the beginning, for
95 # technical reasons, if it uses promotion hints:
96 hint(None, global_merge_point=True)
97
98 # An important hint: 'bytecode' is a list, which is in theory
99 # mutable. Let's tell the JIT compiler that it can assume that the
100 # list is entirely frozen, i.e. immutable and only containing immutable
101 # objects. Otherwise, it cannot do anything - it would have to assume
102 # that the list can unpredictably change at runtime.
103 bytecode = hint(bytecode, deepfreeze=True)
104
105 # Now some strange code that makes a copy of the 'args' list in
106 # a complicated way... this is a workaround forcing the whole 'args'
107 # list to be virtual. It is a way to tell the JIT compiler that it
108 # doesn't have to worry about the 'args' list being unpredictably
109 # modified.
110 oldargs = args
111 argcount = promote(len(oldargs))
112 args = []
113 n = 0
114 while n < argcount:
115 hint(n, concrete=True)
116 args.append(oldargs[n])
117 n += 1
118 # ------------------------------
119 # the real code starts here
120 loops = []
121 stack = []
122 pos = 0
123 while pos < len(bytecode):
124 # It is a good idea to put another 'global merge point' at the
125 # start of each iteration in the interpreter's main loop. The
126 # JIT compiler keeps a table of all the times it passed through
127 # the global merge point. It allows it to detect when it can
128 # stop compiling and generate a jump back to some machine code
129 # that was already generated earlier.
130 hint(None, global_merge_point=True)
131
132 opcode = bytecode[pos]
133 hint(opcode, concrete=True) # same as in tiny1.py
134 pos += 1
135 if opcode == 'ADD': op2(stack, func_add_int, func_add_str)
136 elif opcode == 'SUB': op2(stack, func_sub_int, func_sub_str)
137 elif opcode == 'MUL': op2(stack, func_mul_int, func_mul_str)
138 elif opcode[0] == '#':
139 n = myint(opcode, start=1)
140 stack.append(args[n-1])
141 elif opcode.startswith('->#'):
142 n = myint(opcode, start=3)
143 if n > len(args):
144 raise IndexError
145 args[n-1] = stack.pop()
146 elif opcode == '{':
147 loops.append(pos)
148 elif opcode == '}':
149 if stack.pop().as_int() == 0:
150 loops.pop()
151 else:
152 pos = loops[-1]
153 # A common problem when interpreting loops or jumps: the 'pos'
154 # above is read out of a list, so the hint-annotator thinks
155 # it must be red (not a compile-time constant). But the
156 # hint(opcode, concrete=True) in the next iteration of the
157 # loop requires all variables the 'opcode' depends on to be
158 # green, including this 'pos'. We promote 'pos' to a green
159 # here, as early as possible. Note that in practice the 'pos'
160 # read out of the 'loops' list will be a compile-time constant
161 # because it was pushed as a compile-time constant by the '{'
162 # case above into 'loops', which is a virtual list, so the
163 promote(pos)
164 else:
165 stack.append(StrBox(opcode))
166 return stack
167
168 def repr(stack):
169 # this bit moved out of the portal function because JIT'ing it is not
170 # very useful, and the JIT generator is confused by the 'for' right now...
171 return ' '.join([x.as_str() for x in stack])
172
173
174 # ------------------------------
175 # Pure workaround code! It will eventually be unnecessary.
176 # For now, myint(s, n) is a JIT-friendly way to spell int(s[n:]).
177 # We don't support negative numbers, though.
178 @dont_look_inside
179 def myint_internal(s, start=0):
180 if start >= len(s):
181 return -1
182 res = 0
183 while start < len(s):
184 c = s[start]
185 n = ord(c) - ord('0')
186 if not (0 <= n <= 9):
187 return -1
188 res = res * 10 + n
189 start += 1
190 return res
191 def myint(s, start=0):
192 n = myint_internal(s, start)
193 if n < 0:
194 raise ValueError
195 return n
196 # ------------------------------
197
198
199 def test_main():
200 main = """#1 5 ADD""".split()
201 res = interpret(main, [IntBox(20)])
202 assert repr(res) == '25'
203 res = interpret(main, [StrBox('foo')])
204 assert repr(res) == 'foo+5'
205
206 FACTORIAL = """The factorial of #1 is
207 1 { #1 MUL #1 1 SUB ->#1 #1 }""".split()
208
209 def test_factorial():
210 res = interpret(FACTORIAL, [IntBox(5)])
211 assert repr(res) == 'The factorial of 5 is 120'
212
213 FIBONACCI = """Fibonacci numbers:
214 { #1 #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 }""".split()
215
216 def test_fibonacci():
217 res = interpret(FIBONACCI, [IntBox(1), IntBox(1), IntBox(10)])
218 assert repr(res) == "Fibonacci numbers: 1 1 2 3 5 8 13 21 34 55"