neo-go icon indicating copy to clipboard operation
neo-go copied to clipboard

compiler: do not overwrite initialized global variable by default value

Open AnnaShaleva opened this issue 3 years ago • 1 comments

Given the following code:

package foo
var A = f()
var B int
func Main() int {
	return B
}
func f() int {
	B = 3
	return B
}

the resulting opcodes generated for it will be:

INDEX    OPCODE       PARAMETER
0        INITSSLOT    2    <<
2        CALL         10 (8/08)
4        STSFLD0      
5        PUSH0        
6        STSFLD1      
7        RET          
8        LDSFLD1      
9        RET          
10       PUSH3        
11       STSFLD1      
12       LDSFLD1      
13       RET         

Global variables initialisation is being performed by this code: https://github.com/nspcc-dev/neo-go/blob/e31c3b5246fcedabae506e6dbb297266d261c532/pkg/compiler/codegen.go#L599-L608 So firstly A is initialized by the call to f() and 3 is stored in the 1-st cell of the static slot as B's value. After that B is initialized by default value and 0 overwrites the previously stored 3. As a result, the program leaves 0 on stack, which is wrong.

We need to initialize global variable by default value only if there's no value stored for it yet.

AnnaShaleva avatar Aug 25 '22 07:08 AnnaShaleva

After that we need to enable test disabled in 61d9edda7f2db1cdf34bf6517ae6af779e153303.

AnnaShaleva avatar Aug 30 '22 11:08 AnnaShaleva