-
Notifications
You must be signed in to change notification settings - Fork 519
Expand file tree
/
Copy pathgo_parser.go
More file actions
2961 lines (2688 loc) · 83.9 KB
/
go_parser.go
File metadata and controls
2961 lines (2688 loc) · 83.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Moderne Source Available License (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://docs.moderne.io/licensing/moderne-source-available-license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package parser
import (
"fmt"
"go/ast"
"go/build"
"go/importer"
"go/parser"
"go/token"
"go/types"
"path/filepath"
"strconv"
"strings"
"github.com/google/uuid"
"github.com/openrewrite/rewrite/rewrite-go/pkg/tree"
)
// GoParser parses Go source code into OpenRewrite LST nodes.
type GoParser struct {
// Importer resolves imported packages for type checking.
// Defaults to importer.Default() which resolves stdlib packages.
Importer types.Importer
// BuildContext drives `//go:build` and filename-suffix constraint
// evaluation in ParsePackage. Defaults to build.Default (the host's
// GOOS/GOARCH). Recipe authors that need cross-platform analysis can
// set this explicitly via NewGoParserWithBuildContext.
BuildContext build.Context
}
func NewGoParser() *GoParser {
return &GoParser{
Importer: importer.Default(),
BuildContext: build.Default,
}
}
// NewGoParserWithBuildContext returns a parser that filters input files
// against the given build context. Useful for recipes that need to
// analyze code as it would compile under a specific GOOS/GOARCH/cgo
// configuration. To switch contexts, build a new parser — A3 keeps
// BuildContext immutable per parser to avoid cache-key complexity.
func NewGoParserWithBuildContext(buildCtx build.Context) *GoParser {
return &GoParser{
Importer: importer.Default(),
BuildContext: buildCtx,
}
}
// FileInput is one file given to ParsePackage.
type FileInput struct {
Path string
Content string
}
// Parse parses a single Go source file and returns its CompilationUnit.
// Convenience wrapper around ParsePackage for the common one-file case;
// type attribution that depends on sibling files in the same package
// won't resolve here. Use ParsePackage when sibling files matter.
func (gp *GoParser) Parse(sourcePath string, source string) (*tree.CompilationUnit, error) {
cus, err := gp.ParsePackage([]FileInput{{Path: sourcePath, Content: source}})
if err != nil {
return nil, err
}
if len(cus) == 0 {
return nil, fmt.Errorf("no compilation unit produced")
}
return cus[0], nil
}
// ParsePackage parses every file in a single Go package together so
// type-checking sees them as one unit. File A's reference to file B's
// symbol resolves; the resulting CompilationUnits share a single
// types.Info populated by one types.Config.Check call.
//
// All files MUST belong to the same package (same `package` clause).
// Order in the returned slice matches the input order.
func (gp *GoParser) ParsePackage(files []FileInput) ([]*tree.CompilationUnit, error) {
if len(files) == 0 {
return nil, nil
}
// Filter out files excluded by the build context — `//go:build` /
// `// +build` constraints and OS/arch filename suffixes. Skipped
// files don't appear in the output at all (they're as if they
// weren't passed in).
filtered := make([]FileInput, 0, len(files))
for _, f := range files {
if MatchBuildContext(gp.BuildContext, filepath.Base(f.Path), f.Content) {
filtered = append(filtered, f)
}
}
files = filtered
if len(files) == 0 {
return nil, nil
}
fset := token.NewFileSet()
asts := make([]*ast.File, 0, len(files))
for _, f := range files {
a, err := parser.ParseFile(fset, f.Path, f.Content, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("parse %s: %w", f.Path, err)
}
asts = append(asts, a)
}
typeInfo := &types.Info{
Types: make(map[ast.Expr]types.TypeAndValue),
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
Selections: make(map[*ast.SelectorExpr]*types.Selection),
}
conf := types.Config{
Importer: gp.Importer,
// Don't fail on type errors — we want partial type info even when
// some imports can't be resolved.
Error: func(error) {},
}
// Use the first file's package name as the type-checker hint;
// types.Config.Check validates that all files agree.
pkgName := "main"
if asts[0].Name != nil {
pkgName = asts[0].Name.Name
}
_, _ = conf.Check(pkgName, fset, asts, typeInfo)
mapper := newTypeMapper()
cus := make([]*tree.CompilationUnit, 0, len(files))
for i, f := range files {
ctx := &parseContext{
src: []byte(f.Content),
fset: fset,
file: fset.File(asts[i].Pos()),
astFile: asts[i],
cursor: 0,
typeInfo: typeInfo,
mapper: mapper,
}
cus = append(cus, ctx.mapFile(asts[i], f.Path))
}
return cus, nil
}
// parseContext holds the state needed during AST-to-LST mapping.
type parseContext struct {
src []byte
fset *token.FileSet
file *token.File
astFile *ast.File
cursor int // current byte offset into src, tracks consumed positions
typeInfo *types.Info
mapper *typeMapper
}
// prefix extracts the whitespace and comments between the current cursor
// position and the given token position.
func (ctx *parseContext) prefix(pos token.Pos) tree.Space {
if !pos.IsValid() {
return tree.EmptySpace
}
targetOffset := ctx.file.Offset(pos)
if targetOffset <= ctx.cursor || targetOffset > len(ctx.src) {
return tree.EmptySpace
}
raw := string(ctx.src[ctx.cursor:targetOffset])
ctx.cursor = targetOffset
return tree.ParseSpace(raw)
}
// skip advances the cursor past n bytes (for consuming keywords, operators, etc.)
func (ctx *parseContext) skip(n int) {
ctx.cursor += n
}
// skipTo advances the cursor to the given position.
func (ctx *parseContext) skipTo(pos token.Pos) {
if pos.IsValid() {
off := ctx.file.Offset(pos)
if off <= len(ctx.src) {
ctx.cursor = off
}
}
}
// prefixAndSkip extracts the prefix before pos and advances past length bytes.
func (ctx *parseContext) prefixAndSkip(pos token.Pos, length int) tree.Space {
space := ctx.prefix(pos)
ctx.skip(length)
return space
}
// mapFile maps an ast.File to a CompilationUnit.
func (ctx *parseContext) mapFile(file *ast.File, sourcePath string) *tree.CompilationUnit {
// "package" keyword
prefix := ctx.prefixAndSkip(file.Package, len("package"))
// Package name identifier
pkgName := ctx.mapIdent(file.Name)
paddedPkgName := tree.RightPadded[*tree.Identifier]{Element: pkgName}
// Imports
var imports *tree.Container[*tree.Import]
imports = ctx.mapImports(file)
// Top-level declarations (functions, types, vars, consts - excluding imports)
var stmts []tree.RightPadded[tree.Statement]
for _, decl := range file.Decls {
if gd, ok := decl.(*ast.GenDecl); ok && gd.Tok == token.IMPORT {
continue
}
stmt := ctx.mapDecl(decl)
if stmt != nil {
stmts = append(stmts, tree.RightPadded[tree.Statement]{Element: stmt})
}
}
// EOF
eof := tree.EmptySpace
if ctx.cursor < len(ctx.src) {
eof = tree.ParseSpace(string(ctx.src[ctx.cursor:]))
}
return &tree.CompilationUnit{
ID: uuid.New(),
Prefix: prefix,
SourcePath: sourcePath,
PackageDecl: &paddedPkgName,
Imports: imports,
Statements: stmts,
EOF: eof,
}
}
// mapImports maps all import declarations in the file into a single Container.
// Go allows multiple import blocks; subsequent blocks are tracked via ImportBlock markers.
func (ctx *parseContext) mapImports(file *ast.File) *tree.Container[*tree.Import] {
// Collect all import GenDecls in order.
var importDecls []*ast.GenDecl
for _, decl := range file.Decls {
if gd, ok := decl.(*ast.GenDecl); ok && gd.Tok == token.IMPORT {
importDecls = append(importDecls, gd)
}
}
if len(importDecls) == 0 {
return nil
}
var elements []tree.RightPadded[*tree.Import]
var containerMarkers tree.Markers
prevGrouped := false
// First import block: captured into Container.Before and Container.Markers
first := importDecls[0]
before := ctx.prefixAndSkip(first.Pos(), len("import"))
if first.Lparen.IsValid() {
prevGrouped = true
openParenPrefix := ctx.prefix(first.Lparen)
ctx.skip(1) // skip "("
containerMarkers = tree.Markers{
ID: uuid.New(),
Entries: []tree.Marker{
tree.GroupedImport{Ident: uuid.New(), Before: openParenPrefix},
},
}
}
for _, spec := range first.Specs {
is := spec.(*ast.ImportSpec)
imp := ctx.mapImportSpec(is)
elements = append(elements, tree.RightPadded[*tree.Import]{Element: imp})
}
if first.Lparen.IsValid() {
closeParen := ctx.prefix(first.Rparen)
ctx.skip(1) // skip ")"
if len(elements) > 0 {
elements[len(elements)-1].After = closeParen
} else if len(closeParen.Comments) > 0 {
elements = append(elements, tree.RightPadded[*tree.Import]{
Element: &tree.Import{ID: uuid.New(), Qualid: &tree.Empty{ID: uuid.New()}},
After: closeParen,
})
}
}
// Subsequent import blocks: attach ImportBlock marker to first import of each
for _, importDecl := range importDecls[1:] {
blockBefore := ctx.prefixAndSkip(importDecl.Pos(), len("import"))
grouped := importDecl.Lparen.IsValid()
var groupedBefore tree.Space
if grouped {
groupedBefore = ctx.prefix(importDecl.Lparen)
ctx.skip(1) // skip "("
}
importBlockMarker := tree.ImportBlock{
Ident: uuid.New(),
ClosePrevious: prevGrouped,
Before: blockBefore,
Grouped: grouped,
GroupedBefore: groupedBefore,
}
ctx.mapImportBlockSpecs(importDecl, &elements, importBlockMarker)
if grouped {
closeParen := ctx.prefix(importDecl.Rparen)
ctx.skip(1) // skip ")"
if len(importDecl.Specs) > 0 {
elements[len(elements)-1].After = closeParen
} else if len(closeParen.Comments) > 0 {
imp := &tree.Import{ID: uuid.New(), Qualid: &tree.Empty{ID: uuid.New()}}
imp.Markers = tree.Markers{
ID: uuid.New(),
Entries: []tree.Marker{importBlockMarker},
}
elements = append(elements, tree.RightPadded[*tree.Import]{
Element: imp,
After: closeParen,
})
}
}
prevGrouped = grouped
}
container := tree.Container[*tree.Import]{Before: before, Elements: elements, Markers: containerMarkers}
return &container
}
// mapImportBlockSpecs maps the specs of a subsequent import block, attaching
// the ImportBlock marker to the first spec's Import node.
func (ctx *parseContext) mapImportBlockSpecs(decl *ast.GenDecl, elements *[]tree.RightPadded[*tree.Import], marker tree.ImportBlock) {
for j, spec := range decl.Specs {
is := spec.(*ast.ImportSpec)
imp := ctx.mapImportSpec(is)
if j == 0 {
imp.Markers = tree.Markers{
ID: uuid.New(),
Entries: []tree.Marker{marker},
}
}
*elements = append(*elements, tree.RightPadded[*tree.Import]{Element: imp})
}
}
// mapImportSpec maps a single import spec.
func (ctx *parseContext) mapImportSpec(spec *ast.ImportSpec) *tree.Import {
prefix := ctx.prefix(spec.Pos())
var alias *tree.LeftPadded[*tree.Identifier]
if spec.Name != nil {
ident := ctx.mapIdent(spec.Name)
lp := tree.LeftPadded[*tree.Identifier]{Element: ident}
alias = &lp
}
path := ctx.mapBasicLit(spec.Path)
return &tree.Import{ID: uuid.New(), Prefix: prefix, Qualid: path, Alias: alias}
}
// mapDecl maps a top-level declaration.
func (ctx *parseContext) mapDecl(decl ast.Decl) tree.Statement {
switch d := decl.(type) {
case *ast.FuncDecl:
return ctx.mapFuncDecl(d)
case *ast.GenDecl:
return ctx.mapGenDecl(d)
default:
return nil
}
}
// mapGenDecl maps a general declaration (var, const, type).
func (ctx *parseContext) mapGenDecl(decl *ast.GenDecl) tree.Statement {
switch decl.Tok {
case token.VAR, token.CONST:
return ctx.mapVarConstDecl(decl)
case token.TYPE:
return ctx.mapTypeDecl(decl)
default:
return nil
}
}
// mapVarConstDecl maps `var x int`, `var x = 5`, `const x = 5`, etc.
func (ctx *parseContext) mapVarConstDecl(decl *ast.GenDecl) tree.Statement {
prefix := ctx.prefix(decl.Pos())
leadingAnns, prefix := extractDirectives(prefix)
keyword := decl.Tok.String()
ctx.skip(len(keyword))
if len(decl.Specs) == 1 && !decl.Lparen.IsValid() {
// Single declaration: var x int = 5
spec := decl.Specs[0].(*ast.ValueSpec)
vd := ctx.mapValueSpec(spec, prefix, keyword)
vd.LeadingAnnotations = leadingAnns
return vd
}
// Grouped declaration: var ( ... ) or const ( ... )
lparenPrefix := ctx.prefix(decl.Lparen)
ctx.skip(1) // "("
var elements []tree.RightPadded[tree.Statement]
for _, s := range decl.Specs {
spec := s.(*ast.ValueSpec)
innerPrefix := ctx.prefix(spec.Pos())
vd := ctx.mapValueSpec(spec, innerPrefix, keyword)
vd.Markers.Entries = append(vd.Markers.Entries, tree.GroupedSpec{Ident: uuid.New()})
elements = append(elements, tree.RightPadded[tree.Statement]{Element: vd})
}
rparenPrefix := ctx.prefix(decl.Rparen)
ctx.skip(1) // ")"
if len(elements) > 0 {
elements[len(elements)-1].After = rparenPrefix
} else if len(rparenPrefix.Comments) > 0 {
elements = append(elements, tree.RightPadded[tree.Statement]{
Element: &tree.Empty{ID: uuid.New()},
After: rparenPrefix,
})
}
var markerEntries []tree.Marker
if keyword == "var" {
markerEntries = append(markerEntries, tree.VarKeyword{Ident: uuid.New()})
} else if keyword == "const" {
markerEntries = append(markerEntries, tree.ConstDecl{Ident: uuid.New()})
}
specs := &tree.Container[tree.Statement]{Before: lparenPrefix, Elements: elements}
return &tree.VariableDeclarations{
ID: uuid.New(),
Prefix: prefix,
Markers: tree.Markers{ID: uuid.New(), Entries: markerEntries},
LeadingAnnotations: leadingAnns,
Specs: specs,
}
}
// mapValueSpec maps a single var/const spec.
func (ctx *parseContext) mapValueSpec(spec *ast.ValueSpec, prefix tree.Space, keyword string) *tree.VariableDeclarations {
// Source order: keyword name[, name]... [type] [= value]
// Map names first (they appear first in source after keyword)
// Handle commas between multiple names
var nameIdents []*tree.Identifier
var nameAfters []tree.Space
for i, name := range spec.Names {
nameIdents = append(nameIdents, ctx.mapIdent(name))
if i < len(spec.Names)-1 {
// Capture space before comma and skip comma
commaOff := ctx.findNext(',')
var after tree.Space
if commaOff >= 0 {
after = ctx.prefix(ctx.file.Pos(commaOff))
ctx.skip(1) // ","
}
nameAfters = append(nameAfters, after)
} else {
nameAfters = append(nameAfters, tree.Space{})
}
}
// Then type (appears after name in source)
var typeExpr tree.Expression
if spec.Type != nil {
typeExpr = ctx.mapTypeExpr(spec.Type)
}
// Then initializers (after type and `=` in source)
// In Go, multi-value declarations use a single `=` followed by comma-separated values:
// var a, b = val1, val2
var variables []tree.RightPadded[*tree.VariableDeclarator]
for i, nameIdent := range nameIdents {
var init *tree.LeftPadded[tree.Expression]
if i < len(spec.Values) {
var sepPrefix tree.Space
if i == 0 {
eqOff := ctx.findNext('=')
if eqOff >= 0 {
sepPrefix = ctx.prefix(ctx.file.Pos(eqOff))
ctx.skip(1) // "="
}
} else {
commaOff := ctx.findNext(',')
if commaOff >= 0 {
sepPrefix = ctx.prefix(ctx.file.Pos(commaOff))
ctx.skip(1) // ","
}
}
val := ctx.mapExpr(spec.Values[i])
lp := tree.LeftPadded[tree.Expression]{Before: sepPrefix, Element: val}
init = &lp
}
vd := &tree.VariableDeclarator{
ID: uuid.New(),
Name: nameIdent,
Initializer: init,
}
variables = append(variables, tree.RightPadded[*tree.VariableDeclarator]{Element: vd, After: nameAfters[i]})
}
var markerEntries []tree.Marker
if keyword == "var" {
markerEntries = append(markerEntries, tree.VarKeyword{Ident: uuid.New()})
} else if keyword == "const" {
markerEntries = append(markerEntries, tree.ConstDecl{Ident: uuid.New()})
}
var markers tree.Markers
if len(markerEntries) > 0 {
markers = tree.Markers{ID: uuid.New(), Entries: markerEntries}
}
return &tree.VariableDeclarations{
ID: uuid.New(),
Prefix: prefix,
Markers: markers,
TypeExpr: typeExpr,
Variables: variables,
}
}
// mapTypeDecl maps a `type Name ...` declaration.
func (ctx *parseContext) mapTypeDecl(decl *ast.GenDecl) tree.Statement {
prefix := ctx.prefixAndSkip(decl.Pos(), len("type"))
leadingAnns, prefix := extractDirectives(prefix)
if len(decl.Specs) == 1 && !decl.Lparen.IsValid() {
spec := decl.Specs[0].(*ast.TypeSpec)
td := ctx.mapTypeSpec(spec, prefix)
td.LeadingAnnotations = leadingAnns
return td
}
// Grouped type declaration: type ( ... )
lparenPrefix := ctx.prefix(decl.Lparen)
ctx.skip(1) // "("
var elements []tree.RightPadded[tree.Statement]
for _, s := range decl.Specs {
spec := s.(*ast.TypeSpec)
innerPrefix := ctx.prefix(spec.Pos())
td := ctx.mapTypeSpec(spec, innerPrefix)
td.Markers.Entries = append(td.Markers.Entries, tree.GroupedSpec{Ident: uuid.New()})
elements = append(elements, tree.RightPadded[tree.Statement]{Element: td})
}
rparenPrefix := ctx.prefix(decl.Rparen)
ctx.skip(1) // ")"
if len(elements) > 0 {
elements[len(elements)-1].After = rparenPrefix
} else if len(rparenPrefix.Comments) > 0 {
elements = append(elements, tree.RightPadded[tree.Statement]{
Element: &tree.Empty{ID: uuid.New()},
After: rparenPrefix,
})
}
specs := &tree.Container[tree.Statement]{Before: lparenPrefix, Elements: elements}
return &tree.TypeDecl{
ID: uuid.New(),
Prefix: prefix,
LeadingAnnotations: leadingAnns,
Specs: specs,
}
}
// mapTypeSpec maps a single type spec: `type Name Type` or `type Name = Type`.
func (ctx *parseContext) mapTypeSpec(spec *ast.TypeSpec, prefix tree.Space) *tree.TypeDecl {
name := ctx.mapIdent(spec.Name)
var assign *tree.LeftPadded[tree.Space]
if spec.Assign.IsValid() {
eqPrefix := ctx.prefix(spec.Assign)
ctx.skip(1) // "="
lp := tree.LeftPadded[tree.Space]{Before: eqPrefix}
assign = &lp
}
def := ctx.mapTypeExpr(spec.Type)
return &tree.TypeDecl{
ID: uuid.New(),
Prefix: prefix,
Name: name,
Assign: assign,
Definition: def,
}
}
// mapFuncDecl maps a function declaration.
func (ctx *parseContext) mapFuncDecl(decl *ast.FuncDecl) *tree.MethodDeclaration {
prefix := ctx.prefixAndSkip(decl.Pos(), len("func"))
leadingAnns, prefix := extractDirectives(prefix)
var receiver *tree.Container[tree.Statement]
if decl.Recv != nil && len(decl.Recv.List) > 0 {
recv := ctx.mapFieldListAsParams(decl.Recv)
receiver = &recv
}
name := ctx.mapIdent(decl.Name)
params := ctx.mapFieldListAsParams(decl.Type.Params)
returnType := ctx.mapReturnType(decl.Type.Results)
var body *tree.Block
if decl.Body != nil {
body = ctx.mapBlockStmt(decl.Body)
}
md := &tree.MethodDeclaration{
ID: uuid.New(),
Prefix: prefix,
LeadingAnnotations: leadingAnns,
Receiver: receiver,
Name: name,
Parameters: params,
ReturnType: returnType,
Body: body,
}
// Type attribution for method declaration
if obj, ok := ctx.typeInfo.Defs[decl.Name]; ok && obj != nil {
if fn, ok := obj.(*types.Func); ok {
md.MethodType = ctx.mapper.mapMethodObject(fn)
}
}
return md
}
// mapReturnType maps function return types.
// Returns nil for no return, a single Expression for one type, or a TypeList for multiple.
// Handles both unnamed `(int, error)` and named `(n int, err error)` returns.
func (ctx *parseContext) mapReturnType(results *ast.FieldList) tree.Expression {
if results == nil || len(results.List) == 0 {
return nil
}
// Check if return types are parenthesized
if results.Opening.IsValid() {
// Parenthesized: `(int, error)`, `(int)`, or `(n int, err error)`
before := ctx.prefix(results.Opening)
ctx.skip(1) // "("
var elements []tree.RightPadded[tree.Statement]
for i, field := range results.List {
if len(field.Names) == 0 {
// Unnamed return: just a type expression
typeExpr := ctx.mapTypeExpr(field.Type)
vd := &tree.VariableDeclarations{
ID: uuid.New(),
TypeExpr: typeExpr,
Variables: []tree.RightPadded[*tree.VariableDeclarator]{
{Element: &tree.VariableDeclarator{ID: uuid.New(), Name: &tree.Identifier{ID: uuid.New()}}},
},
}
var after tree.Space
if i < len(results.List)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
after = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
elements = append(elements, tree.RightPadded[tree.Statement]{Element: vd, After: after})
} else {
// Named return(s): `n int` or `x, y int`
var vars []tree.RightPadded[*tree.VariableDeclarator]
for j, fieldName := range field.Names {
nameIdent := ctx.mapIdent(fieldName)
var nameAfter tree.Space
if j < len(field.Names)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
nameAfter = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
vars = append(vars, tree.RightPadded[*tree.VariableDeclarator]{
Element: &tree.VariableDeclarator{ID: uuid.New(), Name: nameIdent},
After: nameAfter,
})
}
typeExpr := ctx.mapTypeExpr(field.Type)
vd := &tree.VariableDeclarations{
ID: uuid.New(),
TypeExpr: typeExpr,
Variables: vars,
}
var after tree.Space
if i < len(results.List)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
after = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
elements = append(elements, tree.RightPadded[tree.Statement]{Element: vd, After: after})
}
}
closePrefix := ctx.prefix(results.Closing)
ctx.skip(1) // ")"
if len(elements) > 0 {
elements[len(elements)-1].After = closePrefix
}
return &tree.TypeList{
ID: uuid.New(),
Types: tree.Container[tree.Statement]{Before: before, Elements: elements},
}
}
// Single non-parenthesized return type
return ctx.mapTypeExpr(results.List[0].Type)
}
// mapFieldListAsParams maps function parameters.
// Handles named (x int), unnamed (int), and grouped (a, b int) parameters.
// Each ast.Field becomes one VariableDeclarations (possibly with multiple names).
func (ctx *parseContext) mapFieldListAsParams(fl *ast.FieldList) tree.Container[tree.Statement] {
before := ctx.prefix(fl.Opening)
ctx.skip(1) // "("
var elements []tree.RightPadded[tree.Statement]
for i, field := range fl.List {
if len(field.Names) == 0 {
// Unnamed parameter: just a type expression (e.g., `int` in `func(int)`)
typeExpr := ctx.mapTypeExpr(field.Type)
var varargs *tree.Space
if u, ok := typeExpr.(*tree.Unary); ok && u.Operator.Element == tree.Spread {
varargs = &u.Prefix
typeExpr = u.Operand
}
vd := &tree.VariableDeclarations{
ID: uuid.New(),
TypeExpr: typeExpr,
Varargs: varargs,
Variables: []tree.RightPadded[*tree.VariableDeclarator]{
{Element: &tree.VariableDeclarator{ID: uuid.New(), Name: &tree.Identifier{ID: uuid.New()}}},
},
}
var after tree.Space
if i < len(fl.List)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
after = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
elements = append(elements, tree.RightPadded[tree.Statement]{Element: vd, After: after})
} else {
// Named parameter(s): `a int` or `a, b int` (grouped names sharing a type)
// Map all names first (source order), then the shared type
var vars []tree.RightPadded[*tree.VariableDeclarator]
for j, fieldName := range field.Names {
nameIdent := ctx.mapIdent(fieldName)
var nameAfter tree.Space
if j < len(field.Names)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
nameAfter = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
vars = append(vars, tree.RightPadded[*tree.VariableDeclarator]{
Element: &tree.VariableDeclarator{ID: uuid.New(), Name: nameIdent},
After: nameAfter,
})
}
typeExpr := ctx.mapTypeExpr(field.Type)
var varargs *tree.Space
if u, ok := typeExpr.(*tree.Unary); ok && u.Operator.Element == tree.Spread {
varargs = &u.Prefix
typeExpr = u.Operand
}
vd := &tree.VariableDeclarations{
ID: uuid.New(),
TypeExpr: typeExpr,
Varargs: varargs,
Variables: vars,
}
var after tree.Space
if i < len(fl.List)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
after = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
elements = append(elements, tree.RightPadded[tree.Statement]{Element: vd, After: after})
}
}
var markers tree.Markers
if len(elements) > 0 {
trailingCommaOff := ctx.findNextBefore(',', int(fl.Closing)-ctx.file.Base())
if trailingCommaOff >= 0 {
commaBefore := ctx.prefix(ctx.file.Pos(trailingCommaOff))
ctx.skip(1) // ","
commaAfter := ctx.prefix(fl.Closing)
ctx.skip(1) // ")"
markers = tree.Markers{
ID: uuid.New(),
Entries: []tree.Marker{tree.TrailingComma{
Ident: uuid.New(),
Before: commaBefore,
After: commaAfter,
}},
}
} else {
closePrefix := ctx.prefix(fl.Closing)
ctx.skip(1) // ")"
elements[len(elements)-1].After = closePrefix
}
} else {
closeParen := ctx.prefix(fl.Closing)
ctx.skip(1) // ")"
if !closeParen.IsEmpty() {
elements = append(elements, tree.RightPadded[tree.Statement]{
Element: &tree.Empty{ID: uuid.New()},
After: closeParen,
})
}
}
return tree.Container[tree.Statement]{Before: before, Elements: elements, Markers: markers}
}
// mapBlockStmt maps a block statement.
//
// Multi-statements-per-line (`_ = 1; _ = 2`) carry a literal `;` that
// Go's tokenizer recognizes but doesn't surface as part of either
// statement's AST. To round-trip the source, we look for an inline `;`
// between this statement and the next, capture the leading whitespace
// as RightPadded.After, mark the entry with a Semicolon marker, and
// advance the cursor past the `;`. The Block printer emits `;` when
// the marker is present.
func (ctx *parseContext) mapBlockStmt(block *ast.BlockStmt) *tree.Block {
prefix := ctx.prefix(block.Lbrace)
ctx.skip(1) // "{"
var stmts []tree.RightPadded[tree.Statement]
for i, stmt := range block.List {
mapped := ctx.mapStmt(stmt)
if mapped == nil {
continue
}
rp := tree.RightPadded[tree.Statement]{Element: mapped}
// Detect inline `;` separator. Go inserts implicit semicolons
// at end-of-line, so a literal `;` between two statements only
// appears when they share a source line (or when a `;` appears
// before the closing `}` on the last statement's line). We
// avoid scanning comments/strings for stray `;` bytes by
// gating on line numbers from the tokenizer.
stmtEndLine := ctx.file.Position(stmt.End()).Line
var nextStartLine int
if i+1 < len(block.List) {
nextStartLine = ctx.file.Position(block.List[i+1].Pos()).Line
} else {
nextStartLine = ctx.file.Position(block.Rbrace).Line
}
if stmtEndLine == nextStartLine {
// Same line — look for the explicit `;`.
boundary := 0
if i+1 < len(block.List) {
boundary = ctx.file.Offset(block.List[i+1].Pos())
} else {
boundary = ctx.file.Offset(block.Rbrace)
}
semiOffset := ctx.findNextBefore(';', boundary)
if semiOffset >= 0 {
rp.After = ctx.prefix(ctx.file.Pos(semiOffset))
ctx.skip(1) // consume ";"
rp.Markers = tree.AddMarker(rp.Markers, tree.NewSemicolon())
}
}
stmts = append(stmts, rp)
}
end := ctx.prefix(block.Rbrace)
ctx.skip(1) // "}"
return &tree.Block{ID: uuid.New(), Prefix: prefix, Statements: stmts, End: end}
}
// mapStmt maps a statement.
func (ctx *parseContext) mapStmt(stmt ast.Stmt) tree.Statement {
switch s := stmt.(type) {
case *ast.ReturnStmt:
return ctx.mapReturnStmt(s)
case *ast.AssignStmt:
return ctx.mapAssignStmt(s)
case *ast.ExprStmt:
return ctx.mapExprStmt(s)
case *ast.IfStmt:
return ctx.mapIfStmt(s)
case *ast.SwitchStmt:
return ctx.mapSwitchStmt(s)
case *ast.CaseClause:
return ctx.mapCaseClause(s)
case *ast.ForStmt:
return ctx.mapForStmt(s)
case *ast.RangeStmt:
return ctx.mapRangeStmt(s)
case *ast.IncDecStmt:
return ctx.mapIncDecStmt(s)
case *ast.GoStmt:
return ctx.mapGoStmt(s)
case *ast.DeferStmt:
return ctx.mapDeferStmt(s)
case *ast.SendStmt:
return ctx.mapSendStmt(s)
case *ast.BranchStmt:
return ctx.mapBranchStmt(s)
case *ast.LabeledStmt:
return ctx.mapLabeledStmt(s)
case *ast.BlockStmt:
return ctx.mapBlockStmt(s)
case *ast.DeclStmt:
return ctx.mapDeclStmt(s)
case *ast.SelectStmt:
return ctx.mapSelectStmt(s)
case *ast.TypeSwitchStmt:
return ctx.mapTypeSwitchStmt(s)
case *ast.CommClause:
return ctx.mapCommClause(s)
case *ast.EmptyStmt:
return ctx.mapEmptyStmt(s)
default:
return nil
}
}
// mapReturnStmt maps a return statement.
func (ctx *parseContext) mapReturnStmt(stmt *ast.ReturnStmt) *tree.Return {
prefix := ctx.prefixAndSkip(stmt.Pos(), len("return"))
var exprs []tree.RightPadded[tree.Expression]
for i, expr := range stmt.Results {
mapped := ctx.mapExpr(expr)
var after tree.Space
if i < len(stmt.Results)-1 {
commaOffset := ctx.findNext(',')
if commaOffset >= 0 {
after = ctx.prefix(ctx.file.Pos(commaOffset))
ctx.skip(1) // ","
}
}
exprs = append(exprs, tree.RightPadded[tree.Expression]{Element: mapped, After: after})
}
return &tree.Return{ID: uuid.New(), Prefix: prefix, Expressions: exprs}
}
// mapAssignStmt maps an assignment statement.
func (ctx *parseContext) mapAssignStmt(stmt *ast.AssignStmt) tree.Statement {
// Check for compound assignment operators (+=, -=, etc.) — always single LHS/RHS
if len(stmt.Lhs) == 1 && len(stmt.Rhs) == 1 {
if op, ok := mapAssignmentOp(stmt.Tok); ok {
lhs := ctx.mapExpr(stmt.Lhs[0])
opPrefix := ctx.prefix(stmt.TokPos)
ctx.skip(len(stmt.Tok.String()))
rhs := ctx.mapExpr(stmt.Rhs[0])
return &tree.AssignmentOperation{
ID: uuid.New(),
Variable: lhs,
Operator: tree.LeftPadded[tree.AssignmentOperator]{Before: opPrefix, Element: op},
Assignment: rhs,
}
}