Skip to content

5 Module var

Luiz Felipe edited this page May 29, 2020 · 5 revisions

This module declares commands to make a stack frame reserving space to local variables. The rk register is used to preserve the base address of the stack frame.

At 'ases' target, these instructions have side effects with ra, rb, and memory pointed by dp.

The module is inside the target folder, import it using $:

[import "$/var"]

Requires

  • $/lia

alloc and free

alloc x:i
free x:i

The command alloc allocates x cells to variables, and free is used to free the x cells. You can use these commands to creates and destroys the stack frame. For example if you allocate 5 cells, the variables of index 0 to 4 can be used inside these stack frame.

If you try free a stack frame of different size that be allocated by alloc, the behavior is undefined. Try reads or modify a variable outside the boundary of the stack frame is also a undefined behavior.

proc example
  alloc 5

  # Use variables here...

  free 5
endproc

The alloc command pushes the latest value of the rk register, and free restores its value. It's not necessary to manually preserve the register to preservers a previous stack frame.

Side-effects:

  • ra and rk.

getvar

getvar x:r v:i

Gets the value of variable v and writes in the x register.

movvar and setvar

movvar v:i x:r
setvar v:i x:i

The commands set the value of a variable to the register (movvar) or the immediate value (setvar).

Side-effects:

  • ra and rb

outvar and invar

outvar v:i
invar v:i

The outvar outputs the value of the variable v like a character, the invar gets the input of one character and saves in the variable.

addr

addr x:r v:i

Gets the address of the variable v and writes in the x register. The variables inside the stack frame is ordered from "right" to "left", it's that means the variable 2 is before at memory of the variable 1.

getaddr

getaddr x:r v:r

Gets the value at address v and saves in the x register.

movaddr and setaddr

movaddr v:r x:r setaddr v:r x:i

The movaddr sets the value at v address to x register, and setaddr do the same thing but x is an immediate value.

readline

readline x:r s:i

Reads a line from the input and writes in the x address. Operand s is the maximum number of characters to write in the memory.

puts

puts s:r

Prints a string from address s to output.

Examples

Using variables

[import "$/lia", "$/var"]

proc test
  alloc 1

  setvar 0, 'x'
  getvar rc, 0

  free 1
endproc

alloc 1
setvar 0, '\n'

call test

out rc
outvar 0

free 1

Using strings

[import "$/lia", "$/var"]

alloc 32

addr rd, 31

say "Inserts your name: "
readline rd, 32

say "Hi "
puts rd
say "!\n"

free 32