What does it mean to declare a 'local' variable inside a 'let'?

230 views Asked by At

As I understand it, let defines a reference, which can be seen as an alias, so for example let x = y * y * y doesn't compute y * y * y but the occurrences of x will be replaced by y * y * y. Local variables are similar to other languages local variables.

As in https://www.cairo-lang.org/docs/hello_cairo/dict.html, what does it mean to write let (local dict_start : DictAccess*) = alloc()? That every instance of local dict_start : DictAccess* will be replaced by alloc()? Why not just local (dict_start : DictAccess*) = alloc() or let (dict_start : DictAccess*) = alloc()?

1

There are 1 answers

0
Ariel On BEST ANSWER

First note that when a function is called, the returned values are placed in memory, so e.g. in the case of alloc which returns a single value, the return value can be found in [ap-1] (you can read more about the stack structure and function calls here).

let (dict_start : DictAccess*) = alloc() is actually valid, and is a syntactic sugar for the following:

alloc()
let dict_start = [ap-1]

let (local dict_start : DictAccess*) = alloc() is equivalent to:

alloc()
let dict_start = [ap-1]
local dict_start = dict_start

In the last line, I substitute the value referenced by dict_start value into a local variable, and rebind the reference dict_start to the location of the local variable. The motivation to use this might be to avoid potential revocations (which may be solved by putting the return value in a local variable). This is probably what you want to do with local (dict_start : DictAccess*) = alloc(), which is simply not supported by the current version of the compiler.