/
codegen.go
executable file
·1758 lines (1632 loc) · 50.1 KB
/
codegen.go
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
// Based on go fix utility copyright (C) 2014 The Go Authors. All rights reserved
// Based on bundle utility authored by Russ Cox
// Based on gocat utility authored by Joseph Naegele, 2015
// Copyright (C) 2022, VigilantDoomer
//
// This file is part of build toolchain for VigilantBSP program.
//
// This program is free software: you can redistribute it
// and/or modify it under the terms of GNU General Public License
// as published by the Free Software Foundation, either version 2 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// The below directive doesn't seem to work (gen executable still being created)
//// +build ignore
// The below one does, but now both cause LiteIDE to print out error trying
// to build, which I need still to verify correctness...
////go:build ignore
package main
// This file is not compiled into VigilantBSP executable ("+build ignore" directive
// should be present above), instead it is intended to be executed as part of
// VigilantBSP build toolchain (via "go generate" specified in Makefile) to
// produce some part of VigilantBSP source code from some other part of it.
// However, this program is still under GNU General Public License v2 or later
// license
// Usage:
// go run codegen.go -- --target=filetogenerate.go --include="file1.go;file2.go;file3.go"
// where:
// 1. first "--" is so that arguments to this program (codegen.go) are not
// mistaken for arguments to "go run"
// 2. --target specifies ONE file to be output (if exists, is overwritten)
// 3. --include specifies LIST of files to be parsed from which target file will
// be generated
// Some code in this file was borrowed from "go fix" utility written by
// Go Authors, as well as gocat utility by Joseph Nagele which itself is a
// modification of bundle utility by Russ Cox which was likewise using borrowed
// "go fix" code. Initially I planned to split borrowed stuff into separate file
// but that destroy the ploy of using "go run" to run it, so I had to put it all
// into one file
// Codegen is not perfect! Some code may be refused or incorrectly translated
// Code known to be refused:
// 1. renamed imports
// 2. Cgo-using code
// ...
// Code that may get incorrectly translated:
// 1. Shadowing functions with local variables
// 2. Same-named methods defined on different objects not all of which need
// conversion, then method calls executed on compound statements
// 3. Field names colliding with methods or functions name
// ...
import (
"bytes"
"flag"
"go/ast"
"go/format"
"go/parser"
"io/ioutil"
"os"
"go/token"
"log"
"strings"
"errors"
"fmt"
"go/printer"
"path"
"strconv"
)
// CODEGEN_SIGN is a mark to be inserted into generated file
// MUST match "^//Code generated .* DO NOT EDIT\.$" regexp as per recommendation
// in go documentation, see also https://github.com/golang/go/issues/13560
const CODEGEN_SIGN = "// Code generated from other source files. DO NOT EDIT.\n"
const COPYRIGHT_STR = `// Copyright (C) 2022-2023, VigilantDoomer
//
// This file is part of VigilantBSP program.
//
// VigilantBSP is free software: you can redistribute it
// and/or modify it under the terms of GNU General Public License
// as published by the Free Software Foundation, either version 2 of
// the License, or (at your option) any later version.
//
// VigilantBSP is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with VigilantBSP. If not, see <https://www.gnu.org/licenses/>.`
var Log = log.New(os.Stdout, "", 0)
const (
PRAGMA_SETPREFIX = iota
PRAGMA_REPLACE_VANILLA
PRAGMA_REPLACE_PROTOTYPE
PRAGMA_INIT
)
const (
TARGET_NOTFOUND = iota
TARGET_FUNCDECL
TARGET_TYPEDECL
TARGET_VARDECL
TARGET_CONSTDECL
)
type PragmaRec struct {
Type int
Op1 string // for replace pragmas, what is replaced
Op2 string // for replace pragmas, the replacement
}
type TypeTracker struct {
Name string
Affected bool // type that needs to be renamed because it is dependent on renamed or replaced type
Pivot bool // type which is replaced directly
Object *ast.Object
}
type TypeRelation struct {
Element *TypeTracker
Containers []*TypeTracker
}
type PrefixOp struct {
value string
renamed map[*ast.Ident]bool
}
type FuncTracker struct {
Name string
Object interface{}
Drop bool // only tracked for destinations
}
type FuncReplaceTask struct {
Source *FuncTracker
Destination *FuncTracker
}
type FuncRenameOperator struct {
funcReplaces []*FuncReplaceTask
funcReplByName map[string]*FuncReplaceTask
}
func main() {
// Check to see if first argument is "--", if so, then remove it
// Why?
// Well, "--" to stop parsing flags is _generic_ "go flag" library behavior
// and NOT specific to "go run" through which this program intends to be run,
// yet the following is to be taken into account:
// 1. I need to pass "--" to "go run" after the name of this program and
// before list of arguments this program will receive, so that "go run"
// itself will not parse these arguments
// 2. But when this program is run, this "--" is passed along too and
// needs to be removed before flag.Parse() happens
if len(os.Args) > 1 {
if os.Args[1] == "--" {
os.Args = append([]string{os.Args[0]}, os.Args[2:]...)
}
}
wd, err := os.Getwd()
if err != nil {
Log.Fatalf("Couldn't get working directory: %s\n", err.Error())
}
Log.Printf("Working directory: %s\n", wd)
var targetFileName string
flag.StringVar(&targetFileName, "target", "", "Name of Go source file to generate")
var includeStr string
flag.StringVar(&includeStr, "include", "",
"List of Go source file names, delimited by ';', from which target is generated")
if len(os.Args) <= 1 {
flag.Usage()
}
flag.Parse()
// flag package doesn't remove quotes for us if strings used them, must do
// ourselves
targetFileName = UnquoteStr(targetFileName)
includeStr = UnquoteStr(includeStr)
if len(targetFileName) == 0 {
Log.Fatalf("Missing --target argument.\n")
}
if len(includeStr) == 0 {
Log.Fatalf("Missing --include argument.\n")
}
incFileNames := strings.Split(includeStr, ";")
pragmas := make([]PragmaRec, 0)
fset := token.NewFileSet()
asts := make([]*ast.File, 0)
for _, fname := range incFileNames {
// Comments are needed to be parsed so that "#pragma" directives can be
// found in any of the specified files. All other comments are ignored
// and they should be never copied to the resulting file
astI, err := parser.ParseFile(fset, fname, nil, parser.ParseComments)
if err != nil {
Log.Fatalf("Error parsing AST of file \"%s\": %s\n", fname, err.Error())
}
asts = append(asts, astI)
ParseFilePragmas(astI.Comments, &pragmas)
/*if fname == "zdefs.go" {
ast.Fprint(os.Stdout, fset, astI, nil)
}*/
}
if len(asts) == 0 {
Log.Fatalf("Need at least one source file to proceed.\n")
}
identsToLookFor := make(map[string]int)
prefix := PrefixOp{value: ""}
for _, pragma := range pragmas {
if pragma.Type == PRAGMA_SETPREFIX {
if prefix.value != "" {
Log.Fatalf("Setting prefix more than once is not allowed (old:%s, new:%s). \n",
prefix.value, pragma.Op1)
}
prefix.value = pragma.Op1
} else {
identsToLookFor[pragma.Op1] = TARGET_NOTFOUND
if pragma.Op2 != "" {
identsToLookFor[pragma.Op2] = TARGET_NOTFOUND
}
}
}
typeToRelation := make(map[string]TypeRelation)
isType := make(map[string]bool)
isTop := make(map[interface{}]bool)
for _, astI := range asts {
// ast.Inspect(astI, func(n ast.Node) bool {
InspectTopLevel(astI, func(n ast.Node, tok *token.Token) bool {
switch x := n.(type) {
case *ast.TypeSpec:
fname := x.Name.Name
rel, exists1 := typeToRelation[fname]
if !exists1 {
rel = TypeRelation{
Element: &TypeTracker{
Name: fname,
Affected: false,
Pivot: false,
Object: x.Name.Obj,
},
Containers: make([]*TypeTracker, 0),
}
}
v, exists2 := identsToLookFor[fname]
if exists2 {
if v != TARGET_NOTFOUND {
Log.Fatalf("Duplicate declaration: %s\n", fname)
}
rel.Element.Pivot = true
identsToLookFor[fname] = TARGET_TYPEDECL
}
typeToRelation[fname] = rel
isType[fname] = true
isTop[x] = true
DetectUsedTypes(rel.Element, x, typeToRelation)
case *ast.ValueSpec:
fname := x.Names[0].Name
v, exists := identsToLookFor[fname]
if exists {
if v != TARGET_NOTFOUND {
Log.Fatalf("Duplicate declaration: %s\n", fname)
}
if tok != nil && *tok == token.CONST {
identsToLookFor[fname] = TARGET_CONSTDECL
} else {
identsToLookFor[fname] = TARGET_VARDECL
}
}
isTop[x] = true
case *ast.FuncDecl:
fname := x.Name.Name
if x.Recv != nil {
// is a method
fname = GetMethodReceiverTypeName(x.Recv.List[0].Type) +
"." + fname
}
v, exists := identsToLookFor[fname]
if exists {
if v != TARGET_NOTFOUND {
Log.Fatalf("Duplicate declaration: %s\n", fname)
}
identsToLookFor[fname] = TARGET_FUNCDECL
}
isTop[x] = true
}
return true
})
}
allFound := true
for k, v := range identsToLookFor {
if v != TARGET_NOTFOUND {
//Log.Printf("Discovered %s [%d]\n", k, v)
} else {
allFound = false
Log.Printf("Target definition \"%s\" not found.\n", k)
}
}
//DebugPrintPragmas(pragmas)
relations := make([]TypeRelation, 0)
for _, v := range typeToRelation {
relations = append(relations, v)
}
for _, v := range relations {
if v.Element.Pivot || v.Element.Affected {
PropagateTypeAffect(v, typeToRelation)
}
}
tpeMapping := make(map[string]string)
for _, pragma := range pragmas {
if pragma.Type == PRAGMA_REPLACE_VANILLA &&
identsToLookFor[pragma.Op1] == TARGET_TYPEDECL {
tpeMapping[pragma.Op1] = pragma.Op2
}
}
funcOp := FuncRenameOperator{
funcReplaces: make([]*FuncReplaceTask, 0),
funcReplByName: make(map[string]*FuncReplaceTask),
}
for _, astI := range asts {
// where top-level declarations get renamed (but not references to
// them)
InspectTopLevel(astI, func(n ast.Node, tok *token.Token) bool {
switch x := n.(type) {
case *ast.TypeSpec:
if typeToRelation[x.Name.Name].Element.Affected {
prefix.Rename(x.Name)
}
case *ast.FuncDecl:
fname := x.Name.Name
if x.Recv != nil {
// is a method, need to qualify its name to match pragma
// notation
fname = GetMethodReceiverTypeName(x.Recv.List[0].Type) +
"." + fname
}
if fname == "init" {
// Don't touch init() functions
} else if identsToLookFor[fname] == TARGET_FUNCDECL {
// function with special treatment (has directive
// referencing it). But which kind exactly?
for _, pragma := range pragmas {
if funcOp.RenameFuncOnPragmaMatch(pragma, fname, x,
typeToRelation, &prefix) {
break
}
}
} else {
// function without special treatment which may still need
// to be renamed
funcOp.RenameArbitraryFunction(fname, x, typeToRelation,
&prefix)
}
}
return true
})
}
// shortFuncRenames will contain only the name of function or method itself
// (without receiver type), and only those that were changed (
// funcOp.funcReplaces will contain sometimes replace records that have
// same name in source and destination)
shortFuncRenames := make(map[string]string)
for _, it := range funcOp.funcReplaces {
if it.Source.Name != it.Destination.Name {
shortFuncRenames[it.Source.Name] = it.Destination.Name
}
}
for _, astI := range asts {
// borrowed from go cat - with necessary modifications
// this renames _references_ to global declarations
walk(astI, func(n interface{}) {
switch x := n.(type) {
case *ast.KeyValueExpr:
id, ok := x.Key.(*ast.Ident)
if ok && prefix.IsRenamed(id) &&
strings.HasPrefix(id.Name, prefix.value) &&
isType[id.Name[len(prefix.value):]] {
// I don't even know when this executes... maybe it is
// supposed to undo renames that happened by accident?
// --VigilantDoomer
id.Name = id.Name[len(prefix.value):]
}
case *ast.Ident:
id := x
repl, ok3 := tpeMapping[id.Name]
if ok3 {
// Type is replaced rather than prefixed
_, ex := typeToRelation[repl]
// if object is linked, make sure it is a top-level object
// and not some local declaration with coinciding name
ex = ex && (id.Obj == nil || isTop[id.Obj.Decl])
if ex {
id.Obj = nil
id.Name = repl
id.Obj = typeToRelation[repl].Element.Object
} else {
// Since it is in tpeMapping, it must be a type
Log.Fatalf("typeRelation not found for types: %s -> %s\n", id.Name, repl)
}
} else {
// normal type (that may need to get prefix)
// or maybe not a type at all
if id.Obj != nil {
typeId, ok2 := id.Obj.Decl.(*ast.TypeSpec)
ok2 = ok2 && isTop[id.Obj.Decl]
if ok2 {
if prefix.IsRenamed(typeId.Name) {
prefix.Rename(id)
}
}
// try as func
funcId, ok2 := id.Obj.Decl.(*ast.FuncDecl)
ok2 = ok2 && isTop[id.Obj.Decl]
if ok2 {
if funcId.Recv == nil {
for _, repl := range funcOp.funcReplaces {
if repl.Source.Name != repl.Destination.Name {
if repl.Source.Object == funcId {
id.Name = repl.Destination.Name
}
}
}
}
}
} else {
// Unfortunately, some conversion require this clause.
// They CAN and, under certain circumstances, WILL
// result in source translated uncorrectly
// When one runs into source code that is translated
// incorrectly due to erroneous rename, the best thing
// that can be done currectly is to edit the original
// source (FROM which the resulting source is generated)
// so that names don't collide between methods of
// different objects, between field names, records,
// functions and methods, etc.
// FIXME find whatever way to contain errors to the best
// possible minimum. Totally eliminating would be
// impossible to do with AST alone, I think, but one
// could add warnings about field name in some structure
// matching method name; not converting ident's name
// if it only matches a function (but not method) name
// but ident is accessed via a SelectorExpt, etc.
rel, ok2 := typeToRelation[id.Name]
if ok2 && rel.Element.Affected {
// Name matches one of renamed types' old name,
// although it may refer to something other than
// that type
prefix.Rename(id)
}
funcDestName, ok2 := shortFuncRenames[id.Name]
if ok2 {
// Name matches one of renamed functions/methods,
// although it may refer to something other object
// that just happens to have the same name
id.Name = funcDestName
}
}
}
}
})
}
for _, astI := range asts {
// Dropping top-level declarations that had not changed from the
// originals
DeleteFromThisLevel(astI, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
if x.Name.Name == "init" && x.Recv == nil {
return false
}
for _, repl := range funcOp.funcReplaces {
if x == repl.Destination.Object && !repl.Destination.Drop {
return false
}
}
return true
case *ast.GenDecl:
DeleteFromThisLevel(n, func(n2 ast.Node) bool {
switch x := n2.(type) {
case *ast.ValueSpec:
// FIXME probably overreaching to delete all variables
// and constants, what if some are typed with affected
// types?
return true
case *ast.TypeSpec:
return !prefix.IsRenamed(x.Name)
}
return false
})
if len(x.Specs) == 0 {
return true
}
return false
}
return false
})
}
// After we have dropped some declarations, it's time to see what kind
// of strings that may refer to an imported package remain referenced
importsToKeep := make([]map[string]bool, len(asts))
for i, astI := range asts {
importsToKeep[i] = make(map[string]bool)
walk(astI, func(n interface{}) {
switch x := n.(type) {
case *ast.SelectorExpr:
id, ok := x.X.(*ast.Ident)
if ok { // MAY be an import, or something else
importsToKeep[i][id.Name] = true
}
}
})
}
for i, astI := range asts {
// Dropping unused imports now
DeleteFromThisLevel(astI, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.GenDecl:
DeleteFromThisLevel(n, func(n2 ast.Node) bool {
switch x := n2.(type) {
case *ast.ImportSpec:
keep := importsToKeep[i][tailImportName(x)]
if !keep {
// Another structure that keeps track of imports,
// oh wow
for j, _ := range astI.Imports {
if astI.Imports[j] == x {
astI.Imports = append(astI.Imports[:j], astI.Imports[j+1:]...)
break
}
}
}
return !keep
}
return false
})
if len(x.Specs) == 0 {
return true
}
return false
}
return false
})
}
initFunc := makeInit(pragmas, funcOp.funcReplByName)
if initFunc != nil {
// add it to the end of last one, so it is easier to find it in the
// resulting file
lastAst := asts[len(asts)-1]
lastAst.Decls = append(lastAst.Decls, initFunc)
}
Log.Printf("Files parsed successfully.\n")
if allFound {
Log.Printf("All target definitions were found successfully.\n")
} else {
Log.Fatalf("Some target definitions were not found - see above.\n")
}
/*for _, v := range relations {
if v.Element.Affected {
Log.Printf("Type \"%s\" is derived from a replaced type.\n", v.Element.Name)
}
}*/
Log.Printf("Merging (in memory).\n")
bundledAST, err := ConcatAST(fset, asts, fset, targetFileName)
if err != nil {
Log.Fatalf("Concat failed: %s\n", err.Error())
} else {
Log.Printf("Concatenation succeeded.\n")
}
var buf bytes.Buffer
buf.WriteString(CODEGEN_SIGN)
buf.WriteString(COPYRIGHT_STR)
buf.WriteString("\n")
if err := format.Node(&buf, fset, bundledAST); err != nil {
Log.Fatalf("Format failed: %s\n", err.Error())
} else {
Log.Printf("Formatting succeeded.\n")
}
Log.Printf("Writing %s...\n", targetFileName)
ioutil.WriteFile(targetFileName, buf.Bytes(), os.ModeExclusive|os.ModePerm)
}
func tailImportName(s *ast.ImportSpec) string {
fname := importPath(s)
ns := strings.Split(fname, "/")
return ns[len(ns)-1]
}
// InspectTopLevel - unlike ast.Inspect - shall find only *global* variables,
// methods, functions, but not any that are local to some function
func InspectTopLevel(node ast.Node, f func(ast.Node, *token.Token) bool) {
switch n := node.(type) {
case *ast.File:
for _, decl := range n.Decls {
if !f(decl, nil) {
return
}
// Unlike functions and methods, declarations such as variables,
// constants, types and imports are wrapped in GenDecl-type node
// rather than being directly children of file's AST
InspectTopLevel(decl, f)
}
case *ast.GenDecl:
for _, decl := range n.Specs {
if !f(decl, &n.Tok) {
return
}
}
}
}
// DeleteFromThisLevel traverses over global declarations (if passed a file) or
// a "generic declaration" children (if passed a GenDecl), calling a function on
// each one that tells whether to delete this declaration (true means delete,
// false means keep)
func DeleteFromThisLevel(node ast.Node, f func(ast.Node) bool) {
switch n := node.(type) {
case *ast.File:
l := len(n.Decls)
for i := 0; i < l; i++ {
if f(n.Decls[i]) {
n.Decls = append(n.Decls[:i], n.Decls[i+1:]...)
i--
l--
}
}
case *ast.GenDecl:
l := len(n.Specs)
for i := 0; i < l; i++ {
if f(n.Specs[i]) {
n.Specs = append(n.Specs[:i], n.Specs[i+1:]...)
i--
l--
}
}
}
}
// GetMethodReceiverTypeName returns name of the object type on which method
// is called, including "*" operands (can distinguish *NodeGen, NodeGen,
// **NodeGen, etc.)
func GetMethodReceiverTypeName(x ast.Expr) string {
switch xx := x.(type) {
case *ast.StarExpr:
return "*" + GetMethodReceiverTypeName(xx.X)
case *ast.Ident:
return xx.Name
default:
Log.Fatalf("Cannot identify method receiver type: unknown expression type\n")
return ""
}
}
// ParseFilePragmas navigates through all comments, searches for "#pragma ..."
// directives (a made up syntax for this CODEGEN program), parses them into,
// appends their internal representation to the collection
func ParseFilePragmas(cgroup []*ast.CommentGroup, collector *[]PragmaRec) {
for _, item := range cgroup {
if item.List == nil {
continue
}
for _, comment := range item.List {
ParseComment(*comment, collector)
}
}
}
// ParseComment parses one comment for special directives
func ParseComment(comment ast.Comment, collector *[]PragmaRec) {
if !strings.HasPrefix(comment.Text, "//") {
return // only "//" comments can issue pragmas, but not "/*" comments
}
body := []byte(comment.Text)[2:]
body = bytes.TrimSpace(body)
if !bytes.HasPrefix(body, []byte("#pragma ")) {
return
}
directive := bytes.Split(body, []byte(" "))
directive = directive[1:] // already know #pragma is there, but what follows?
rec := ParsePragma(directive)
//Log.Println(comment.Text) // debug
if rec == nil {
// TODO better error handling, this method probably should just return
// an indicator and not exit program directly, exiting to be handled
// in the calling tree - print filename and position
Log.Fatalf("Couldn't parse the following pragma: <%s>\n", comment.Text)
}
*collector = append(*collector, *rec)
}
// ParsePragma performs recognition of specific directive used
func ParsePragma(pragma [][]byte) *PragmaRec {
if len(pragma) == 0 {
return nil // invalid
}
if bytes.Equal(pragma[0], []byte("setprefix")) {
if len(pragma) != 2 {
return nil
}
return &PragmaRec{
Type: PRAGMA_SETPREFIX,
Op1: UnquoteStr(string(pragma[1])),
Op2: "",
}
}
if bytes.Equal(pragma[0], []byte("init")) {
if len(pragma) != 5 || !bytes.Equal(pragma[2], []byte("with")) ||
!bytes.Equal(pragma[3], []byte("morphed")) {
return nil
}
return &PragmaRec{
Type: PRAGMA_INIT,
Op1: string(pragma[1]),
Op2: string(pragma[4]),
}
}
if bytes.Equal(pragma[0], []byte("replace")) {
if len(pragma) != 4 || !bytes.Equal(pragma[2], []byte("with")) {
return nil
}
return &PragmaRec{
Type: PRAGMA_REPLACE_VANILLA,
Op1: string(pragma[1]),
Op2: string(pragma[3]),
}
}
if bytes.Equal(pragma[0], []byte("replace_prototype")) {
if len(pragma) != 4 || !bytes.Equal(pragma[2], []byte("with")) {
return nil
}
return &PragmaRec{
Type: PRAGMA_REPLACE_PROTOTYPE,
Op1: string(pragma[1]),
Op2: string(pragma[3]),
}
}
return nil
}
func DebugPrintPragmas(pragmas []PragmaRec) {
for _, pragma := range pragmas {
Log.Printf("[Type: %d, Op1: \"%s\", Op2: \"%s\"]\n",
pragma.Type, pragma.Op1, pragma.Op2)
}
}
// UnquoteStr removes trailing quotes if string is wrapped in quotes
func UnquoteStr(s string) string {
if IsQuoted(s) {
es := len(s) - 1
return s[1:es]
}
return s
}
// IsQuoted returns whether argument string begins AND ends with the same quote
// character
func IsQuoted(s string) bool {
es := len(s) - 1
if len(s) < 2 {
return false
}
return (s[0] == '"' && s[es] == '"') ||
(s[0] == '\'' && s[es] == '\'')
}
// DetectUsedTypes for type denoted by ptype and spec, creates mappings from
// all types referenced by it to ptype. Say, passing a struct will make
// rels[<fieldtypename>]<fieldtypeToStructRelation> for every field struct has
func DetectUsedTypes(ptype *TypeTracker, spec *ast.TypeSpec,
rels map[string]TypeRelation) {
all := GetAllTypes(spec.Type)
for _, elem := range all {
rel, exists := rels[elem]
if !exists {
rel = TypeRelation{
Element: &TypeTracker{
Name: elem,
Affected: false,
Pivot: false,
},
Containers: []*TypeTracker{ptype},
}
} else {
fnd := false
for _, cont := range rel.Containers {
if cont == ptype {
fnd = true
break
}
}
if !fnd {
rel.Containers = append(rel.Containers, ptype)
}
}
rels[elem] = rel
}
}
// GetAllTypes parses potentially complex/compound type declaration (struct,
// map, pointers, whatever) to obtain type idents uses in it. So that
// map[string]bool will produce {"string","bool"} etc.
func GetAllTypes(typeNotation ast.Expr) []string {
switch t := typeNotation.(type) {
case *ast.Ident:
return []string{t.Name}
case *ast.StarExpr:
return GetAllTypes(t.X)
case *ast.ArrayType:
return GetAllTypes(t.Elt)
case *ast.MapType:
return append(GetAllTypes(t.Key), GetAllTypes(t.Value)...)
case *ast.ChanType:
return GetAllTypes(t.Value)
case *ast.StructType: // nested structs without type name are possible
res := []string{}
CollectFieldTypes(t.Fields, &res)
return res
case *ast.FuncType:
res := []string{}
// TypeParams - not supported before Go1.18,
// syntax is not used in VigilantBSP code
// CollectFieldTypes(t.TypeParams, &res)
CollectFieldTypes(t.Params, &res)
CollectFieldTypes(t.Results, &res)
return res
case *ast.InterfaceType:
res := []string{}
// Not sure what stuff is there to begin with, and if it can be
// represented as a type
CollectFieldTypes(t.Methods, &res)
return res
case *ast.SelectorExpr:
// types defined as imports from elsewhere, for example
// "reflect.SelectCase". Can't return them properly
return []string{}
case *ast.Ellipsis:
return GetAllTypes(t.Elt)
// TODO this may be incomplete. Be prepared to implement new clauses as
// required
}
Log.Fatalf("Unhandled type notation.\n", typeNotation)
return []string{}
}
func CollectFieldTypes(fl *ast.FieldList, collector *[]string) {
if fl == nil {
return
}
for _, f := range fl.List {
names := GetAllTypes(f.Type)
*collector = append(*collector, names...)
}
}
func PropagateTypeAffect(rec TypeRelation, tracker map[string]TypeRelation) {
for _, cont := range rec.Containers {
if cont.Pivot {
Log.Fatalf("Error: a compound type \"%s\" is derived from a replaced type but has an explicit replacement at the same time.\n",
cont.Name)
}
if !cont.Affected {
cont.Affected = true
rec, exists := tracker[cont.Name]
if exists {
PropagateTypeAffect(rec, tracker)
}
}
}
}
func (p *PrefixOp) IsRenamed(ident *ast.Ident) bool {
if p.renamed == nil {
p.renamed = make(map[*ast.Ident]bool)
}
return p.renamed[ident]
}
func (p *PrefixOp) Rename(id *ast.Ident) {
if id != nil && !p.IsRenamed(id) && id.Name != "_" && id.Name != "" {
id.Name = p.value + id.Name
p.renamed[id] = true
}
}
// CheckFuncAffected returns two values:
// 1. Whether function uses any renamed/converted type at all
// 2. Whether function needs to keep its name, which means either the preceeding
// is false, or the function is a method (has a receiver) and receiver is
// renamed/converted
func CheckFuncAffected(rmap map[string]TypeRelation, x *ast.FuncDecl) (bool, bool) {
recvConv := FieldListHasType(rmap, x.Recv)
restConv := FieldListHasType(rmap, x.Type.Params) ||
// TypeParams - not supported before Go1.18,
// syntax is not used in VigilantBSP code
// FieldListHasType(rmap, x.Type.TypeParams) ||
FieldListHasType(rmap, x.Type.Results)
conv := recvConv || restConv
return conv, !conv || (x.Recv != nil && recvConv)
}
func FieldListHasType(rmap map[string]TypeRelation, fl *ast.FieldList) bool {
if fl == nil {
return false
}
for _, f := range fl.List {
names := GetAllTypes(f.Type)
for _, n := range names {
rel, ok := rmap[n]
if ok {
if rel.Element.Affected || rel.Element.Pivot {
return true
}
}
}
}
return false
}
// GetMethodFuncName returns only function name without receiver type and dot
func GetMethodFuncName(methodName string) string {
tmp := strings.Split(methodName, ".")
return tmp[len(tmp)-1]
}
// RenameFuncOnPragmaMatch identifies if directive pragma applies to current
// function (with qualified name fname and object x), if so, the action depends
// on both which kind of pragma and kind of function/method is processed, with
// following outcomes:
// 1. Function is pragma-init destination => prefixed unconditionally. Methods
// are not allowed
// 2. Function is pragma-replace source, it is scheduled to be dropped from
// source code, and to have all references to it replaced by references to
// pragma-replace destination name.
// 3. Function is pragma-replace destination, it is scheduled to be dropped from
// source code (this is fine, because its declaration will persist in original
// source files, and thus the dropping from generated source is necessary to
// avoid duplicate declaration discovered by compiler)
// 4. Function is pragma-prototype source, then pragma-prototype
// destination name is derived from prefixed source name and is
// assigned to pragma-prototype destination, (the sources
// declaration is dropped). Once again, references to it will
// be replaced to pragma-prototype destination. Here the
// condition destination and source can have the same (method)
// name is not expected and not checked, thus no special
// treatment coded for it
// 5. if function is pragma-prototype destination, see previous
// !!! Methods (as opposed to functions) get renamed only if receiver types
// is not renamed/converted