From a611800bace968c20a8524d3d88d4c715a089758 Mon Sep 17 00:00:00 2001 From: bixb922 <70152274+bixb922@users.noreply.github.com> Date: Thu, 18 Apr 2024 22:24:05 -0400 Subject: [PATCH] Document integer expressions that include viper --- Improving-performance-with-Viper-code.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/Improving-performance-with-Viper-code.md b/Improving-performance-with-Viper-code.md index aaaef81..75005c6 100644 --- a/Improving-performance-with-Viper-code.md +++ b/Improving-performance-with-Viper-code.md @@ -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.