wails/v3/internal/generator/collect/declaration.go
Ian VanSchooten bbd5d99667
[v3] Typed Events, revisited (#4633)
* Add strong event typings

* Make `EmitEvent` take one data argument only

* Add event registration logic

* Report event cancellation to the emitter

* Prevent registration of system events

* Add support for typed event data initialisation

* Binding generation for events

* Tests for event bindings

* Add vite plugin for typed events

* Fix dev command execution order

Co-authored-by: Fabio Massaioli <fabio.massaioli@gmail.com>

* Propagate module path to templates

* Update templates

Co-authored-by: Ian VanSchooten <ian.vanschooten@gmail.com>

* Go mod tidy for examples

* Switch to tsconfig.json for jetbrains IDE support

* Replace jsconfig in example

* Convert vite plugin to typescript

* Downgrade vite for now

The templates all use 5.x

* Remove root plugins dir from npm files

It's now '/dist/plugins'

* Include types for Create

But keep out of the docs

* Assign a type for cancelAll results

* Restore variadic argument in EmitEvent methods

* Support registered events with void data

* Test cases for void alias support

* Support strict mode

* Support custom event hooks

* Update docs

* Update changelog

* Testdata for typed events

* Test data for void alias support

* fix webview_window emit event

* Update changelog.mdx

* Update events

* Fix generator test path normalization for cross-platform compatibility

The generator tests were failing on CI because they compared absolute file paths
in warning messages. These paths differ between development machines and CI environments.

Changes:
- Normalize file paths in warnings to be relative to testcases/ directory
- Handle both Unix and Windows path separators
- Use Unix line endings consistently in test output
- Update all test expectation files to use normalized paths

This ensures tests pass consistently across different environments including
Windows, macOS, Linux, and CI systems.

* Remove stale comment

* Handle errors returned from validation

* Restore variadic argument to Emit (fix bad rebase)

* Event emitters return a boolean

* Don't use `EmitEvent` in docs

Supposedly it's for internal use, according to comment

* Fix event docs (from rebase)

* Ensure all templates specify @wailsio/runtime: "latest"

* Fix Windows test failure due to CRLF line endings

The test was failing on Windows because:
1. Hardcoded "\n" was being used instead of render.Newline when writing
   warning logs, causing CRLF vs LF mismatch
2. The render package import was missing
3. .got.log files weren't being skipped when building expected file list

Changes:
- Add render package import
- Use render.Newline instead of hardcoded "\n" for cross-platform compatibility
- Skip .got.log files in test file walker

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Fix template tests by using local runtime package

The template tests were failing because they were installing @wailsio/runtime@latest from npm, which doesn't have the new vite plugin yet. This change packs the local runtime and uses it in template tests instead.

Changes:
- Pack the runtime to a tarball in test_js job
- Upload the runtime package as an artifact
- Download and install the local runtime in template tests before building
- Update cleanup job to delete the runtime package artifact

* Apply suggestion from @leaanthony

* Fix: Install local runtime in frontend directory with correct path

The previous fix wasn't working because:
1. npm install was run in the project root, not in frontend/
2. wails3 build runs npm install again, which would reinstall from npm

Fixed by:
- Using npm pkg set to modify package.json to use file:// protocol
- This ensures subsequent npm install calls use the local tarball

* Fix Vue template syntax conflicts with Go template delimiters

The Vue templates were converted to .tmpl files to support dynamic module
paths, but Vue's template syntax {{ }} conflicts with Go's template syntax.

Fixed by escaping Vue template braces:
- {{ becomes {{"{{"}}
- }} becomes {{"}}"}}

This allows the Go template engine to output the literal {{ }} for Vue to process.

* Fix Vue template escaping and Windows shell compatibility

Two issues fixed:

1. Vue template escaping: Changed from {{"{{"}} to {{ "{{" }}
   - The previous syntax caused "missing value for command" error
   - Correct Go template syntax uses spaces between delimiters and strings

2. Windows PowerShell compatibility: Added 'shell: bash' to template generation step
   - The bash syntax (ls, head, $()) doesn't work in PowerShell
   - Git Bash is available on all GitHub runners including Windows

* Fix: test_templates depends on test_js for runtime package artifact

The runtime-package artifact is created in test_js job, not test_go.
Added test_js to the needs array so the artifact is available for download.

* Fix Windows path compatibility for runtime package artifact

Changed from absolute Unix path '/tmp/wails-runtime' to relative path
'wails-runtime-temp' which works cross-platform. Using realpath to
convert to absolute path for file:// URL in npm pkg set command.

* Fix realpath issue on Windows for runtime package

realpath on Windows Git Bash was producing malformed paths with duplicate
drive letters (D:\d\a\...). Replaced with portable solution using pwd
that works correctly across all platforms.

* Use pwd -W on Windows to get native Windows paths

Git Bash's pwd returns Unix-style paths (/d/a/wails/wails) which npm
then incorrectly resolves as D:/d/a/wails/wails. Using pwd -W returns
native Windows paths (D:\a\wails\wails) that npm can handle correctly.

This is the root cause of all the Windows path issues.

* Improve typechecking for Events.Emit()

* [docs] Clarify where `Events` is imported from in each example

* Add docs for runtime Events.Emit()

* Revert to v2-style Events.Emit (name, data)

* Update changelog

---------

Co-authored-by: Fabio Massaioli <fabio.massaioli@gmail.com>
Co-authored-by: Atterpac <Capretta.Michael@gmail.com>
Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-11-11 20:25:57 +11:00

246 lines
6.4 KiB
Go

package collect
import (
"cmp"
"go/ast"
"go/token"
"go/types"
"slices"
)
// findDeclaration returns the AST spec or declaration
// that defines the given _global_ type-checker object.
//
// Specifically, the first element in the returned slice
// is the relevant spec or declaration, followed by its chain
// of parent nodes up to the declaring [ast.File].
//
// If no corresponding declaration can be found within
// the set of registered packages, the returned slice is nil.
//
// Resulting node types are as follows:
// - global functions and concrete methods (*types.Func)
// map to *ast.FuncDecl nodes;
// - interface methods from global interfaces (*types.Func)
// map to *ast.Field nodes within their interface expression;
// - struct fields from global structs (*types.Var)
// map to *ast.Field nodes within their struct expression;
// - global constants and variables map to *ast.ValueSpec nodes;
// - global named types map to *ast.TypeSpec nodes;
// - for type parameters, the result is always nil;
// - for local objects defined within functions,
// field types, variable types or field values,
// the result is always nil;
//
// findDeclaration supports unsynchronised concurrent calls.
func (collector *Collector) findDeclaration(obj types.Object) (path []ast.Node) {
pkg := collector.Package(obj.Pkg()).Collect()
if pkg == nil {
return nil
}
file := findEnclosingFile(pkg.Files, obj.Pos())
if file == nil {
return nil
}
// Find enclosing declaration.
decl := findEnclosingNode(file.Decls, obj.Pos())
if decl == nil {
// Invalid position.
return nil
}
var gen *ast.GenDecl
switch d := decl.(type) {
case *ast.FuncDecl:
if obj.Pos() == d.Name.Pos() {
// Object is function.
return []ast.Node{decl, file}
}
// Ignore local objects defined within function bodies.
return nil
case *ast.BadDecl:
// What's up??
return nil
case *ast.GenDecl:
gen = d
}
// Handle *ast.GenDecl
// Find enclosing ast.Spec
spec := findEnclosingNode(gen.Specs, obj.Pos())
if spec == nil {
// Invalid position.
return nil
}
var def ast.Expr
switch s := spec.(type) {
case *ast.ValueSpec:
if s.Names[0].Pos() <= obj.Pos() && obj.Pos() < s.Names[len(s.Names)-1].End() {
// Object is variable or constant.
return []ast.Node{spec, decl, file}
}
// Ignore local objects defined within variable types/values.
return nil
case *ast.TypeSpec:
if obj.Pos() == s.Name.Pos() {
// Object is named type.
return []ast.Node{spec, decl, file}
}
if obj.Pos() < s.Type.Pos() || s.Type.End() <= obj.Pos() {
// Type param or invalid position.
return nil
}
// Struct or interface field?
def = s.Type
}
// Handle struct or interface field.
var iface *ast.InterfaceType
switch d := def.(type) {
case *ast.StructType:
// Find enclosing field
field := findEnclosingNode(d.Fields.List, obj.Pos())
if field == nil {
// Invalid position.
return nil
}
if len(field.Names) == 0 {
// Handle embedded field.
ftype := ast.Unparen(field.Type)
// Unwrap pointer.
if ptr, ok := ftype.(*ast.StarExpr); ok {
ftype = ast.Unparen(ptr.X)
}
// Unwrap generic instantiation.
switch t := field.Type.(type) {
case *ast.IndexExpr:
ftype = ast.Unparen(t.X)
case *ast.IndexListExpr:
ftype = ast.Unparen(t.X)
}
// Unwrap selector.
if sel, ok := ftype.(*ast.SelectorExpr); ok {
ftype = sel.Sel
}
// ftype must now be an identifier.
if obj.Pos() == ftype.Pos() {
// Object is this embedded field.
return []ast.Node{field, d.Fields, def, spec, decl, file}
}
} else if field.Names[0].Pos() <= obj.Pos() && obj.Pos() < field.Names[len(field.Names)-1].End() {
// Object is one of these fields.
return []ast.Node{field, d.Fields, def, spec, decl, file}
}
// Ignore local objects defined within field types.
return nil
case *ast.InterfaceType:
iface = d
default:
// Other local object or invalid position.
return nil
}
path = []ast.Node{file, decl, spec, def, iface.Methods}
// Handle interface method.
for {
field := findEnclosingNode(iface.Methods.List, obj.Pos())
if field == nil {
// Invalid position.
return nil
}
path = append(path, field)
if len(field.Names) == 0 {
// Handle embedded interface.
var ok bool
iface, ok = ast.Unparen(field.Type).(*ast.InterfaceType)
if !ok {
// Not embedded interface, ignore.
return nil
}
path = append(path, iface, iface.Methods)
// Explore embedded interface.
} else if field.Names[0].Pos() <= obj.Pos() && obj.Pos() < field.Names[len(field.Names)-1].End() {
// Object is one of these fields.
slices.Reverse(path)
return path
} else {
// Ignore local objects defined within interface method signatures.
return nil
}
}
}
// findEnclosingFile finds the unique file in files, if any, that encloses the given position.
func findEnclosingFile(files []*ast.File, pos token.Pos) *ast.File {
// Perform a binary search to find the file enclosing the node.
// We can't use findEnclosingNode here because it is less accurate and less efficient with files.
fileIndex, exact := slices.BinarySearchFunc(files, pos, func(f *ast.File, p token.Pos) int {
return cmp.Compare(f.FileStart, p)
})
// If exact is true, pkg.Files[fileIndex] is the file we are looking for;
// otherwise, it is the first file whose start position is _after_ obj.Pos().
if !exact {
fileIndex--
}
// When exact is false, the position might lie within an empty segment in between two files.
if fileIndex < 0 || files[fileIndex].FileEnd <= pos {
return nil
}
return files[fileIndex]
}
// findEnclosingNode finds the unique node in nodes, if any,
// that encloses the given position.
//
// It uses binary search and therefore expects
// the nodes slice to be sorted in source order.
func findEnclosingNode[S ~[]E, E ast.Node](nodes S, pos token.Pos) (node E) {
// Perform a binary search to find the nearest node.
index, exact := slices.BinarySearchFunc(nodes, pos, func(n E, p token.Pos) int {
return cmp.Compare(n.Pos(), p)
})
// If exact is true, nodes[index] is the node we are looking for;
// otherwise, it is the first node whose start position is _after_ pos.
if !exact {
index--
}
// When exact is false, the position might lie within an empty segment in between two nodes.
if index < 0 || nodes[index].End() <= pos {
return // zero value, nil in practice.
}
return nodes[index]
}