| 1 |
.. _language: |
| 2 |
|
| 3 |
RPython Language |
| 4 |
================ |
| 5 |
|
| 6 |
Definition |
| 7 |
---------- |
| 8 |
|
| 9 |
RPython is a restricted subset of Python that is amenable to static analysis. |
| 10 |
Although there are additions to the language and some things might surprisingly |
| 11 |
work, this is a rough list of restrictions that should be considered. Note |
| 12 |
that there are tons of special cased restrictions that you'll encounter |
| 13 |
as you go. The exact definition is "RPython is everything that our translation |
| 14 |
toolchain can accept" :) |
| 15 |
|
| 16 |
|
| 17 |
Flow restrictions |
| 18 |
----------------- |
| 19 |
|
| 20 |
**variables** |
| 21 |
|
| 22 |
variables should contain values of at most one type as described in |
| 23 |
`Object restrictions`_ at each control flow point, that means for |
| 24 |
example that joining control paths using the same variable to |
| 25 |
contain both a string and a int must be avoided. It is allowed to |
| 26 |
mix None (basically with the role of a null pointer) with many other |
| 27 |
types: wrapped objects, class instances, lists, dicts, strings, etc. |
| 28 |
but *not* with int, floats or tuples. |
| 29 |
|
| 30 |
**constants** |
| 31 |
|
| 32 |
all module globals are considered constants. Their binding must not |
| 33 |
be changed at run-time. Moreover, global (i.e. prebuilt) lists and |
| 34 |
dictionaries are supposed to be immutable: modifying e.g. a global |
| 35 |
list will give inconsistent results. However, global instances don't |
| 36 |
have this restriction, so if you need mutable global state, store it |
| 37 |
in the attributes of some prebuilt singleton instance. |
| 38 |
|
| 39 |
**control structures** |
| 40 |
|
| 41 |
all allowed, ``for`` loops restricted to builtin types, generators |
| 42 |
very restricted. |
| 43 |
|
| 44 |
**range** |
| 45 |
|
| 46 |
``range`` and ``xrange`` are identical. ``range`` does not necessarily create an array, |
| 47 |
only if the result is modified. It is allowed everywhere and completely |
| 48 |
implemented. The only visible difference to CPython is the inaccessibility |
| 49 |
of the ``xrange`` fields start, stop and step. |
| 50 |
|
| 51 |
**definitions** |
| 52 |
|
| 53 |
run-time definition of classes or functions is not allowed. |
| 54 |
|
| 55 |
**generators** |
| 56 |
|
| 57 |
generators are supported, but their exact scope is very limited. you can't |
| 58 |
merge two different generator in one control point. |
| 59 |
|
| 60 |
**exceptions** |
| 61 |
|
| 62 |
fully supported. |
| 63 |
see below `Exception rules`_ for restrictions on exceptions raised by built-in operations |
| 64 |
|
| 65 |
|
| 66 |
Object restrictions |
| 67 |
------------------- |
| 68 |
|
| 69 |
We are using |
| 70 |
|
| 71 |
**integer, float, boolean** |
| 72 |
|
| 73 |
works. |
| 74 |
|
| 75 |
**strings** |
| 76 |
|
| 77 |
a lot of, but not all string methods are supported and those that are |
| 78 |
supported, not necessarily accept all arguments. Indexes can be |
| 79 |
negative. In case they are not, then you get slightly more efficient |
| 80 |
code if the translator can prove that they are non-negative. When |
| 81 |
slicing a string it is necessary to prove that the slice start and |
| 82 |
stop indexes are non-negative. There is no implicit str-to-unicode cast |
| 83 |
anywhere. Simple string formatting using the ``%`` operator works, as long |
| 84 |
as the format string is known at translation time; the only supported |
| 85 |
formatting specifiers are ``%s``, ``%d``, ``%x``, ``%o``, ``%f``, plus |
| 86 |
``%r`` but only for user-defined instances. Modifiers such as conversion |
| 87 |
flags, precision, length etc. are not supported. Moreover, it is forbidden |
| 88 |
to mix unicode and strings when formatting. |
| 89 |
|
| 90 |
**tuples** |
| 91 |
|
| 92 |
no variable-length tuples; use them to store or return pairs or n-tuples of |
| 93 |
values. Each combination of types for elements and length constitute |
| 94 |
a separate and not mixable type. |
| 95 |
|
| 96 |
There is no general way to convert a list into a tuple, because the |
| 97 |
length of the result would not be known statically. (You can of course |
| 98 |
do ``t = (lst[0], lst[1], lst[2])`` if you know that ``lst`` has got 3 |
| 99 |
items.) |
| 100 |
|
| 101 |
**lists** |
| 102 |
|
| 103 |
lists are used as an allocated array. Lists are over-allocated, so list.append() |
| 104 |
is reasonably fast. However, if you use a fixed-size list, the code |
| 105 |
is more efficient. Annotator can figure out most of the time that your |
| 106 |
list is fixed-size, even when you use list comprehension. |
| 107 |
Negative or out-of-bound indexes are only allowed for the |
| 108 |
most common operations, as follows: |
| 109 |
|
| 110 |
- *indexing*: |
| 111 |
positive and negative indexes are allowed. Indexes are checked when requested |
| 112 |
by an IndexError exception clause. |
| 113 |
|
| 114 |
- *slicing*: |
| 115 |
the slice start must be within bounds. The stop doesn't need to, but it must |
| 116 |
not be smaller than the start. All negative indexes are disallowed, except for |
| 117 |
the [:-1] special case. No step. Slice deletion follows the same rules. |
| 118 |
|
| 119 |
- *slice assignment*: |
| 120 |
only supports ``lst[x:y] = sublist``, if ``len(sublist) == y - x``. |
| 121 |
In other words, slice assignment cannot change the total length of the list, |
| 122 |
but just replace items. |
| 123 |
|
| 124 |
- *other operators*: |
| 125 |
``+``, ``+=``, ``in``, ``*``, ``*=``, ``==``, ``!=`` work as expected. |
| 126 |
|
| 127 |
- *methods*: |
| 128 |
append, index, insert, extend, reverse, pop. The index used in pop() follows |
| 129 |
the same rules as for *indexing* above. The index used in insert() must be within |
| 130 |
bounds and not negative. |
| 131 |
|
| 132 |
**dicts** |
| 133 |
|
| 134 |
dicts with a unique key type only, provided it is hashable. Custom |
| 135 |
hash functions and custom equality will not be honored. |
| 136 |
Use ``rpython.rlib.objectmodel.r_dict`` for custom hash functions. |
| 137 |
|
| 138 |
**sets** |
| 139 |
|
| 140 |
sets are not directly supported in RPython. Instead you should use a |
| 141 |
plain dict and fill the values with None. Values in that dict |
| 142 |
will not consume space. |
| 143 |
|
| 144 |
**list comprehensions** |
| 145 |
|
| 146 |
May be used to create allocated, initialized arrays. |
| 147 |
|
| 148 |
**functions** |
| 149 |
|
| 150 |
+ function declarations may use defaults and ``*args``, but not |
| 151 |
``**keywords``. |
| 152 |
|
| 153 |
+ function calls may be done to a known function or to a variable one, |
| 154 |
or to a method. You can call with positional and keyword arguments, |
| 155 |
and you can pass a ``*args`` argument (it must be a tuple). |
| 156 |
|
| 157 |
+ as explained above, tuples are not of a variable length. If you need |
| 158 |
to call a function with a dynamic number of arguments, refactor the |
| 159 |
function itself to accept a single argument which is a regular list. |
| 160 |
|
| 161 |
+ dynamic dispatch enforces the use of signatures that are equal for all |
| 162 |
possible called function, or at least "compatible enough". This |
| 163 |
concerns mainly method calls, when the method is overridden or in any |
| 164 |
way given different definitions in different classes. It also concerns |
| 165 |
the less common case of explicitly manipulated function objects. |
| 166 |
Describing the exact compatibility rules is rather involved (but if you |
| 167 |
break them, you should get explicit errors from the rtyper and not |
| 168 |
obscure crashes.) |
| 169 |
|
| 170 |
**builtin functions** |
| 171 |
|
| 172 |
A number of builtin functions can be used. The precise set can be |
| 173 |
found in :source:`rpython/annotator/builtin.py` (see ``def builtin_xxx()``). |
| 174 |
Some builtin functions may be limited in what they support, though. |
| 175 |
|
| 176 |
``int, float, str, ord, chr``... are available as simple conversion |
| 177 |
functions. Note that ``int, float, str``... have a special meaning as |
| 178 |
a type inside of isinstance only. |
| 179 |
|
| 180 |
**classes** |
| 181 |
|
| 182 |
+ methods and other class attributes do not change after startup |
| 183 |
+ single inheritance is fully supported |
| 184 |
+ use `rpython.rlib.objectmodel.import_from_mixin(M)` in a class |
| 185 |
body to copy the whole content of a class `M`. This can be used |
| 186 |
to implement mixins: functions and staticmethods are duplicated |
| 187 |
(the other class attributes are just copied unmodified). |
| 188 |
|
| 189 |
+ classes are first-class objects too |
| 190 |
|
| 191 |
**objects** |
| 192 |
|
| 193 |
Normal rules apply. The only special methods that are honoured are |
| 194 |
``__init__``, ``__del__``, ``__len__``, ``__getitem__``, ``__setitem__``, |
| 195 |
``__getslice__``, ``__setslice__``, and ``__iter__``. To handle slicing, |
| 196 |
``__getslice__`` and ``__setslice__`` must be used; using ``__getitem__`` and |
| 197 |
``__setitem__`` for slicing isn't supported. Additionally, using negative |
| 198 |
indices for slicing is still not support, even when using ``__getslice__``. |
| 199 |
|
| 200 |
Note that the destructor ``__del__`` should only contain `simple |
| 201 |
operations`__; for any kind of more complex destructor, consider |
| 202 |
using instead ``rpython.rlib.rgc.FinalizerQueue``. |
| 203 |
|
| 204 |
.. __: garbage_collection.html |
| 205 |
|
| 206 |
This layout makes the number of types to take care about quite limited. |
| 207 |
|
| 208 |
|
| 209 |
Integer Types |
| 210 |
------------- |
| 211 |
|
| 212 |
While implementing the integer type, we stumbled over the problem that |
| 213 |
integers are quite in flux in CPython right now. Starting with Python 2.4, |
| 214 |
integers mutate into longs on overflow. In contrast, we need |
| 215 |
a way to perform wrap-around machine-sized arithmetic by default, while still |
| 216 |
being able to check for overflow when we need it explicitly. Moreover, we need |
| 217 |
a consistent behavior before and after translation. |
| 218 |
|
| 219 |
We use normal integers for signed arithmetic. It means that before |
| 220 |
translation we get longs in case of overflow, and after translation we get a |
| 221 |
silent wrap-around. Whenever we need more control, we use the following |
| 222 |
helpers (which live in :source:`rpython/rlib/rarithmetic.py`): |
| 223 |
|
| 224 |
**ovfcheck()** |
| 225 |
|
| 226 |
This special function should only be used with a single arithmetic operation |
| 227 |
as its argument, e.g. ``z = ovfcheck(x+y)``. Its intended meaning is to |
| 228 |
perform the given operation in overflow-checking mode. |
| 229 |
|
| 230 |
At run-time, in Python, the ovfcheck() function itself checks the result |
| 231 |
and raises OverflowError if it is a ``long``. But the code generators use |
| 232 |
ovfcheck() as a hint: they replace the whole ``ovfcheck(x+y)`` expression |
| 233 |
with a single overflow-checking addition in C. |
| 234 |
|
| 235 |
**intmask()** |
| 236 |
|
| 237 |
This function is used for wrap-around arithmetic. It returns the lower bits |
| 238 |
of its argument, masking away anything that doesn't fit in a C "signed long int". |
| 239 |
Its purpose is, in Python, to convert from a Python ``long`` that resulted from a |
| 240 |
previous operation back to a Python ``int``. The code generators ignore |
| 241 |
intmask() entirely, as they are doing wrap-around signed arithmetic all the time |
| 242 |
by default anyway. (We have no equivalent of the "int" versus "long int" |
| 243 |
distinction of C at the moment and assume "long ints" everywhere.) |
| 244 |
|
| 245 |
**r_uint** |
| 246 |
|
| 247 |
In a few cases (e.g. hash table manipulation), we need machine-sized unsigned |
| 248 |
arithmetic. For these cases there is the r_uint class, which is a pure |
| 249 |
Python implementation of word-sized unsigned integers that silently wrap |
| 250 |
around. ("word-sized" and "machine-sized" are used equivalently and mean |
| 251 |
the native size, which you get using "unsigned long" in C.) |
| 252 |
The purpose of this class (as opposed to helper functions as above) |
| 253 |
is consistent typing: both Python and the annotator will propagate r_uint |
| 254 |
instances in the program and interpret all the operations between them as |
| 255 |
unsigned. Instances of r_uint are special-cased by the code generators to |
| 256 |
use the appropriate low-level type and operations. |
| 257 |
Mixing of (signed) integers and r_uint in operations produces r_uint that |
| 258 |
means unsigned results. To convert back from r_uint to signed integers, use |
| 259 |
intmask(). |
| 260 |
|
| 261 |
|
| 262 |
Type Enforcing and Checking |
| 263 |
--------------------------- |
| 264 |
|
| 265 |
RPython provides a helper decorator to force RPython-level types on function |
| 266 |
arguments. The decorator, called ``enforceargs()``, accepts as parameters the |
| 267 |
types expected to match the arguments of the function. |
| 268 |
|
| 269 |
Functions decorated with ``enforceargs()`` have their function signature |
| 270 |
analyzed and their RPython-level type inferred at import time (for further |
| 271 |
details about the flavor of translation performed in RPython, see the |
| 272 |
`Annotation pass documentation`_). Encountering types not supported by RPython |
| 273 |
will raise a ``TypeError``. |
| 274 |
|
| 275 |
``enforceargs()`` by default also performs type checking of parameter types |
| 276 |
each time the function is invoked. To disable this behavior, it's possible to |
| 277 |
pass the ``typecheck=False`` parameter to the decorator. |
| 278 |
|
| 279 |
.. _Annotation pass documentation: http://rpython.readthedocs.io/en/latest/translation.html#annotator |
| 280 |
|
| 281 |
|
| 282 |
Exception rules |
| 283 |
--------------- |
| 284 |
|
| 285 |
Exceptions are by default not generated for simple cases.:: |
| 286 |
|
| 287 |
#!/usr/bin/python |
| 288 |
|
| 289 |
lst = [1,2,3,4,5] |
| 290 |
item = lst[i] # this code is not checked for out-of-bound access |
| 291 |
|
| 292 |
try: |
| 293 |
item = lst[i] |
| 294 |
except IndexError: |
| 295 |
# complain |
| 296 |
|
| 297 |
Code with no exception handlers does not raise exceptions (after it has been |
| 298 |
translated, that is. When you run it on top of CPython, it may raise |
| 299 |
exceptions, of course). By supplying an exception handler, you ask for error |
| 300 |
checking. Without, you assure the system that the operation cannot fail. |
| 301 |
This rule does not apply to *function calls*: any called function is |
| 302 |
assumed to be allowed to raise any exception. |
| 303 |
|
| 304 |
For example:: |
| 305 |
|
| 306 |
x = 5.1 |
| 307 |
x = x + 1.2 # not checked for float overflow |
| 308 |
try: |
| 309 |
x = x + 1.2 |
| 310 |
except OverflowError: |
| 311 |
# float result too big |
| 312 |
|
| 313 |
But:: |
| 314 |
|
| 315 |
z = some_function(x, y) # can raise any exception |
| 316 |
try: |
| 317 |
z = some_other_function(x, y) |
| 318 |
except IndexError: |
| 319 |
# only catches explicitly-raised IndexErrors in some_other_function() |
| 320 |
# other exceptions can be raised, too, and will not be caught here. |
| 321 |
|
| 322 |
The ovfcheck() function described above follows the same rule: in case of |
| 323 |
overflow, it explicitly raise OverflowError, which can be caught anywhere. |
| 324 |
|
| 325 |
Exceptions explicitly raised or re-raised will always be generated. |
| 326 |
|
| 327 |
|
| 328 |
PyPy is debuggable on top of CPython |
| 329 |
------------------------------------ |
| 330 |
|
| 331 |
PyPy has the advantage that it is runnable on standard |
| 332 |
CPython. That means, we can run all of PyPy with all exception |
| 333 |
handling enabled, so we might catch cases where we failed to |
| 334 |
adhere to our implicit assertions. |