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

Accessing struct field behind interface, lazy run-time resolve #957

Open
ii64 opened this issue Nov 6, 2024 · 1 comment
Open

Accessing struct field behind interface, lazy run-time resolve #957

ii64 opened this issue Nov 6, 2024 · 1 comment
Labels
needsInvestigation Need to investigate

Comments

@ii64
Copy link

ii64 commented Nov 6, 2024

Given this scenaro where a variable defined in run-time

{%%
for path, pathItem := range ctx.Doc.Paths.Map() {
    var selectedOp any = nil 

    // some condition

    debugS("%+#v", selectedOp) // compiled
    if selectedOp {  /* .... */  } // compiled 
    if selectedOp.Tags { /* .... */ } // failed to compile
    if selectedOp && selectedOp.Tags { /* .... */ } // failed to compile
}
%%}
@gazerro gazerro added the needsInvestigation Need to investigate label Nov 7, 2024
@ii64
Copy link
Author

ii64 commented Nov 7, 2024

@gazerro Here is the MRE for github.com/open2b/scriggo v0.57.1, this should fail with the following error:

        	Error Trace:	<REDACTED>:70
        	Error:      	Received unexpected error:
        	            	repr.tpl:18:29: selectedOp.Foo undefined (type interface {} has no field or method Foo)
        	Test:       	TestReproducible
func TestReproducible(t *testing.T) {
	type st1 struct {
		Foo string

		A *st1
		B *st1
		C *st1

		Map map[string]*st1
	}
	var ctx any = &st1{
		Foo: "Bar",
		Map: map[string]*st1{
			"/": {
				Foo: "Baz",
				A:   &st1{Foo: "BazA"},
			},
			"/foo": {
				Foo: "BazFoo",
				B:   &st1{Foo: "BazFoo"},
			},
		},
	}
	fsys := scriggo.Files{
		"repr.tpl": []byte(`{%%
		for path, pathItem := range ctx.Map {
			var selectedOp any = nil

			for chk in []any{
				pathItem.A,
				pathItem.B,
				pathItem.C,
			} {
				if chk {
				selectedOp = chk	
				break
				}
			}

			debugS("%+#v %+#v", selectedOp, pathItem)

			debugS("%+#v", selectedOp.Foo) // failed to compile
		}
		%%}`),
	}
	tpl, err := scriggo.BuildTemplate(fsys, "repr.tpl", &scriggo.BuildOptions{
		Globals: native.Declarations{
			"ctx":    ctx,
			"debugS": fmt.Printf,
		},
	})
	require.NoError(t, err)

	var b bytes.Buffer
	err = tpl.Run(&b, nil, nil)
	require.NoError(t, err)

	fmt.Println(b.String())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needsInvestigation Need to investigate
Projects
None yet
Development

No branches or pull requests

2 participants