mirror of
https://github.com/micropython/micropython.git
synced 2025-09-07 10:20:52 +02:00
Document integer expressions that include viper
@@ -194,6 +194,16 @@ As a result, arithmetic operations on viper variables behave like operations in
|
||||
|
||||
Arithmetic and logic operations for viper ```int``` are very fast, since there is no need to check for data types, conversion rules and other conditions at runtime, and the necessary code can be generated at compile time.
|
||||
|
||||
Integer expressions that include viper `int` are of type viper `int`, example:
|
||||
```py
|
||||
@micropython.viper
|
||||
def viper_expression():
|
||||
x = 1
|
||||
print(x<<31)
|
||||
# the value printed is -2147483648
|
||||
```
|
||||
Although `x<<31` is not being assigned to a viper int, the expression is truncated to the size of a viper `int` *before* passing it to the called function (print). This is a behavior a bit different from integer constant expressions, where the expression is evaluated, and *then* tested if the result fits into a viper `int` or `builtins.int`.
|
||||
|
||||
|
||||
There are no automatic conversion rules if a viper ```int``` is used together with other data types. For example, this code will raise a compile time error: "ViperTypeError: can't do binary op between 'object' and 'int'":
|
||||
```py
|
||||
@@ -435,7 +445,7 @@ def fun2( mypointer:ptr8 ):
|
||||
x = mypointer[0]
|
||||
```
|
||||
|
||||
A side effect of this behaviour is that `type(viper_variable)` always returns class `builtins.int`
|
||||
A side effect of this behavior is that `type(viper_variable)` always returns class `builtins.int`
|
||||
|
||||
Talking about detecting type: `isinstance(viper_variable,int)` will give a compile-time error `NotImplementedError: conversion to object`, since `int` is a viper data type, not a MicroPython class. However, `isinstance(viper_variable, builtins.int)` will return `True` since the viper_variable has been converted to a MicroPython int.
|
||||
|
||||
@@ -575,8 +585,6 @@ In runtime, to distinguish between a viper int and a `builtins.int`:
|
||||
```
|
||||
The expression in the if statement will be true if x is a signed viper `int`, as opposed to a `builtins.int`. A `builtins.int` will remain positive, no matter how many times you shift the value.
|
||||
|
||||
|
||||
|
||||
## Source code of the viper code emitter
|
||||
The viper code emitter is in the MicroPython code repository in `py/emitnative.c`, embedded in the native code emitter.
|
||||
|
||||
|
Reference in New Issue
Block a user