Skip to content

Commit

Permalink
Fix consistency check when using line compiler directive.
Browse files Browse the repository at this point in the history
  • Loading branch information
tetafro committed Nov 10, 2023
1 parent aeefda5 commit eed2760
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
8 changes: 6 additions & 2 deletions getters.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,13 @@ func newParsedFile(file *ast.File, fset *token.FileSet) (*parsedFile, error) {
return nil, errUnsuitableInput
}

// Check consistency to avoid checking slice indexes in each function
// Check consistency to avoid checking slice indexes in each function.
// Note that `PositionFor` is used with `adjusted=false` to skip `//line`
// directives that can set references to other files (e.g. templates)
// instead of the real ones, and break consistency here.
// Issue: https://github.com/tetafro/godot/issues/32
lastComment := pf.file.Comments[len(pf.file.Comments)-1]
if p := pf.fset.Position(lastComment.End()); len(pf.lines) < p.Line {
if p := pf.fset.PositionFor(lastComment.End(), false); len(pf.lines) < p.Line {
return nil, fmt.Errorf("inconsistency between file and AST: %s", p.Filename)
}

Expand Down
17 changes: 17 additions & 0 deletions godot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ func TestRun(t *testing.T) {
}
})

t.Run("line directive", func(t *testing.T) {
testFile := filepath.Join("testdata", "line", "main.go")
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, testFile, nil, parser.ParseComments)
if err != nil {
t.Fatalf("Failed to parse input file: %v", err)
}

issues, err := Run(f, fset, Settings{})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
if len(issues) > 0 {
t.Fatal("Unexpected issues")
}
})

testFile := filepath.Join("testdata", "check", "main.go")
fset := token.NewFileSet()
file, err := parser.ParseFile(fset, testFile, nil, parser.ParseComments)
Expand Down
12 changes: 12 additions & 0 deletions testdata/line/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// This is a test for `//line` compiler directive. It can add references
// to other files, for parsed code. If it happens, it breaks consistency
// between the source code and the parsed files, which godot relies on.
package main

import "fmt"

func main() {
//line main.tpl:100
fmt.Println("Template")
// Bye!
}
1 change: 1 addition & 0 deletions testdata/line/main.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Template file

0 comments on commit eed2760

Please sign in to comment.