Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gnovm): handle loop variables #2429

Open
wants to merge 64 commits into
base: master
Choose a base branch
from
Open

feat(gnovm): handle loop variables #2429

wants to merge 64 commits into from

Conversation

jaekwon
Copy link
Contributor

@jaekwon jaekwon commented Jun 25, 2024

Problem Definition

The problem originates from the issue described in #1135. While the full scope of the issue is broader, it fundamentally relates to the concept of loop variable escapes block where it's defined.

e.g. 1:

package main

import "fmt"

var s1 []*int

func forLoopRef() {
	defer func() {
		for i, e := range s1 {
			fmt.Printf("s1[%d] is: %d\n", i, *e)
		}
	}()

	for i := 0; i < 3; i++ {
		z := i + 1
		s1 = append(s1, &z)
	}
}

func main() {
	forLoopRef()
}

e.g. 2:

package main

type f func()

var fs []f

func forLoopClosure() {
	defer func() {
		for _, f := range fs {
			f()
		}
	}()

	for i := 0; i < 3; i++ {
		z := i
		fs = append(fs, func() { println(z) })
	}
}

func main() {
	forLoopClosure()
}

e.g. 3:

package main

func main() {
	c := 0
	closures := []func(){}
loop:
	i := c
	closures = append(closures, func() {
		println(i)
	})
	c += 1
	if c < 10 {
		goto loop
	}

	for _, cl := range closures {
		cl()
	}
}

Solution ideas

  • identify escaped vars in preprocess:
    Detect situations where a loop variable is defined within a loop block(including for/range loops or loops constructed using goto statements), and escapes the block where it's defined.

  • runtime allocation:
    Allocate a new heap item for the loop variable in each iteration to ensure each iteration operates with its unique variable instance.

  • NOTE1: this is consistent with Go's Strategy:
    "Each iteration has its own separate declared variable (or variables) [Go 1.22]. The variable used by the first iteration is declared by the init statement. The variable used by each subsequent iteration is declared implicitly before executing the post statement and initialized to the value of the previous iteration's variable at that moment."

  • NOTE2: the loopvar feature of Go 1.22 is not supported in this version, and will be supported in next version.

    not supporting capture i defined in for/range clause;

	for i := 0; i < 3; i++ {
		s1 = append(s1, &i)
	}

Implementation Details

Preprocess Stage(Multi-Phase Preprocessor):

  • Phase 1: initStaticBlocks: Establish a cascading scope structure where predefine is conducted. In this phase Name expressions are initially marked as NameExprTypeDefine, which may later be upgraded to NameExprTypeHeapDefine if it is determined that they escape the loop block. This phase also supports other processes as a prerequisite#2077.

  • Phase 2: preprocess1: This represents the original preprocessing phase(not going into details).

  • Phase 3: findGotoLoopDefines: By traversing the AST, any name expression defined in a loop block (for/range, goto) with the attribute NameExprTypeDefine is promoted to NameExprTypeHeapDefine. This is used in later phase.

  • Phase 4: findLoopUses1: Identify the usage of NameExprTypeHeapDefine name expressions. If a name expression is used in a function literal or is referrnced(e.g. &a), and it was previously defined as NameExprTypeHeapDefine, the used name expression is then given the attribute NameExprTypeHeapUse. This step finalizes whether a name expression will be allocated on the heap and used from heap.
    Closures represent a particular scenario in this context. Each closure, defined by a funcLitExpr that captures variables, is associated with a HeapCaptures list. This list consists of NameExprs, which are utilized at runtime to obtain the actual variable values for each iteration. Correspondingly, within the funcLitExpr block, a list of placeholder values are defined. These placeholders are populated during the doOpFuncLit phase and subsequently utilized in the doOpCall to ensure that each iteration uses the correct data.

  • Phase 5: findLoopUses2: Convert non-loop uses of loop-defined names to NameExprTypeHeapUse. Also, demote NameExprTypeHeapDefine back to NameExprTypeDefine if no actual usage is found. Also , as the last phase, attributes no longer needed will be cleaned up after this phase.

Runtime Stage:

  1. Variable Allocation:

    • Modify the runtime so that encountering a NameExprTypeHeapDefine triggers the allocation of a new heapItemValue for it, which will be used by any NameExprTypeHeapUse.
  2. Function Literal Handling:

    • During the execution of doOpFuncLit, retrieve the HeapCapture values (previously allocated heap item values) and fill in the placeholder values within the funcLitExpr block.
    • When invoking the function (doOpCall), the placeHolder values(fv.Captures) are used to update the execution context, ensuring accurate and consistent results across iterations.

@github-actions github-actions bot added 📦 🌐 tendermint v2 Issues or PRs tm2 related 📦 ⛰️ gno.land Issues or PRs gno.land package related labels Jun 26, 2024
@jaekwon jaekwon changed the base branch from init_static to master June 26, 2024 01:08
@ltzmaxwell
Copy link
Contributor

ltzmaxwell commented Jul 29, 2024

This PR is ready for review, cc: @jaekwon @thehowl @mvertes @deelawn @leohhhn . 🙏

deelawn added a commit that referenced this pull request Jul 31, 2024
I noticed this while reviewing #2429. The previous conditional could
never evaluate to true: `if (1<<16 - 1) < sb.NumNames {`. `sb.NumNames`
is a `uint16` and the value it is being compared to, `1<<16 - 1` is the
max uint16 value, so it is impossible the the number of names to be
greater than this value. Instead, we should check to see if the current
number of names is the maximum value and panic if this is the case.

<details><summary>Contributors' checklist...</summary>

- [x] Added new tests, or not needed, or not feasible
- [x] Provided an example (e.g. screenshot) to aid review or the PR is
self-explanatory
- [x] Updated the official documentation or not needed
- [x] No breaking changes were made, or a `BREAKING CHANGE: xxx` message
was included in the description
- [x] Added references to related issues and PRs
- [x] Provided any useful hints for running manual tests
- [x] Added new benchmarks to [generated
graphs](https://gnoland.github.io/benchmarks), if any. More info
[here](https://github.com/gnolang/gno/blob/master/.benchmarks/README.md).
</details>
gnovm/pkg/gnolang/type_check.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/type_check.go Show resolved Hide resolved
Copy link
Member

@thehowl thehowl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpicks for now; will need some more time to go through it all.

gnovm/pkg/gnolang/machine.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/nodes.go Outdated Show resolved Hide resolved
gnovm/tests/file.go Show resolved Hide resolved
@thehowl thehowl mentioned this pull request Aug 29, 2024
7 tasks
Copy link
Contributor

@deelawn deelawn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The solution seems to work well. Please see the comments and questions I left.

gnovm/pkg/gnolang/preprocess.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/preprocess.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/preprocess.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/preprocess.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/preprocess.go Outdated Show resolved Hide resolved
gnovm/pkg/gnolang/preprocess.go Show resolved Hide resolved
gnovm/pkg/gnolang/values.go Show resolved Hide resolved
gnovm/pkg/gnolang/realm.go Show resolved Hide resolved
@Kouteki Kouteki added the in focus Core team is prioritizing this work label Oct 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
in focus Core team is prioritizing this work 📦 🌐 tendermint v2 Issues or PRs tm2 related 📦 ⛰️ gno.land Issues or PRs gno.land package related 📦 🤖 gnovm Issues or PRs gnovm related 🧾 package/realm Tag used for new Realms or Packages.
Projects
Status: In Progress
Status: In Review
Development

Successfully merging this pull request may close these issues.

6 participants