11.19Static variable pointers. 4tH 4tH Forth compiler
Reklam
Reklam
CHAPTER 11. ADVANCED PROGRAMMING 157
Which 4tH compiles to:
[
[
[
[
[
[
0] literal
1] literal
2] c!
3] literal
4] literal
5] c!
(1)
(768)
(0)
(5)
(769)
(0)
Without the peephole optimizer the addresses of the members of the structure would not have been calculated at compile time. Even more, optimizing this code by hand would not have been easy without writing some pretty murky source code. It is in these situations that the peephole optimizer excels.
11.19
Static variable pointers
The peephole optimizer is an integral part of 4tH and quickly and efficiently optimizes a whole range of expressions that can be resolved at runtime, including strings and variables.
E.g. if you want to set a static pointer to a classic counted string, you could define it like this:
16 string str-len str-len char+ constant str-string
That is because a ’STRING’ expression can be optimized to a single literal. However, this is not the case with a variable and consequently this pig won’t fly:
16 array array-len \ won’t compile!
array-len cell+ constant array-payload
It is for this kind of situation that we have ’EQUATES’. It takes a variable and an optional literal expression and create a static pointer that behaves like any other variable, yes, even including a ’:REDO’ or ’DOES>’ definition
10
: variable <literal expression> EQUATES name
In its most basic form an ’EQUATES’ expression is equal to ’AKA’
11
: variable A
A equates B
Is equivalent to: variable A aka A B
Now we can rewrite our expression so it can be compiled properly:
16 array array-len \ this will compile!
array-len cell+ equates array-payload
An ’EQUATES’ expression will save you from writing this kind of code:
16 array array-len
: array-payload array-len cell+ ;
Which not only requires extra code, but will definitely run much slower.
10
See section 11.11.
11
See section 11.10.
İndir
Reklam