-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathclassparser.go
More file actions
391 lines (311 loc) · 9.82 KB
/
classparser.go
File metadata and controls
391 lines (311 loc) · 9.82 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
package extgen
import (
"bufio"
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"regexp"
"strings"
)
var phpClassRegex = regexp.MustCompile(`//\s*export_php:class\s+(\w+)`)
var phpMethodRegex = regexp.MustCompile(`//\s*export_php:method\s+(\w+)::([^{}\n]+)(?:\s*{\s*})?`)
var methodSignatureRegex = regexp.MustCompile(`(\w+)\s*\(([^)]*)\)\s*:\s*(\??[\w|]+)`)
var methodParamTypeNameRegex = regexp.MustCompile(`(\??[\w|]+)\s+\$?(\w+)`)
type exportDirective struct {
line int
className string
}
type classParser struct{}
func (cp *classParser) Parse(filename string) ([]phpClass, error) {
return cp.parse(filename)
}
func (cp *classParser) parse(filename string) (classes []phpClass, err error) {
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, filename, nil, parser.ParseComments)
if err != nil {
return nil, fmt.Errorf("parsing file: %w", err)
}
validator := Validator{}
exportDirectives := cp.collectExportDirectives(node, fset)
methods, err := cp.parseMethods(filename)
if err != nil {
return nil, fmt.Errorf("parsing methods: %w", err)
}
// match structs to directives
matchedDirectives := make(map[int]bool)
var genDecl *ast.GenDecl
var ok bool
for _, decl := range node.Decls {
if genDecl, ok = decl.(*ast.GenDecl); !ok || genDecl.Tok != token.TYPE {
continue
}
for _, spec := range genDecl.Specs {
var typeSpec *ast.TypeSpec
if typeSpec, ok = spec.(*ast.TypeSpec); !ok {
continue
}
var structType *ast.StructType
if structType, ok = typeSpec.Type.(*ast.StructType); !ok {
continue
}
var phpCl string
var directiveLine int
if phpCl, directiveLine = cp.extractPHPClassCommentWithLine(genDecl.Doc, fset); phpCl == "" {
continue
}
matchedDirectives[directiveLine] = true
class := phpClass{
Name: phpCl,
GoStruct: typeSpec.Name.Name,
}
class.Properties = cp.parseStructFields(structType.Fields.List)
// associate methods with this class
for _, method := range methods {
if method.ClassName == phpCl {
class.Methods = append(class.Methods, method)
}
}
if err := validator.validateClass(class); err != nil {
fmt.Printf("Warning: Invalid class '%s': %v\n", class.Name, err)
continue
}
classes = append(classes, class)
}
}
for _, directive := range exportDirectives {
if !matchedDirectives[directive.line] {
return nil, fmt.Errorf("//export_php class directive at line %d is not followed by a struct declaration", directive.line)
}
}
return classes, nil
}
func (cp *classParser) collectExportDirectives(node *ast.File, fset *token.FileSet) []exportDirective {
var directives []exportDirective
for _, commentGroup := range node.Comments {
for _, comment := range commentGroup.List {
if matches := phpClassRegex.FindStringSubmatch(comment.Text); matches != nil {
pos := fset.Position(comment.Pos())
directives = append(directives, exportDirective{
line: pos.Line,
className: matches[1],
})
}
}
}
return directives
}
func (cp *classParser) extractPHPClassCommentWithLine(commentGroup *ast.CommentGroup, fset *token.FileSet) (string, int) {
if commentGroup == nil {
return "", 0
}
for _, comment := range commentGroup.List {
if matches := phpClassRegex.FindStringSubmatch(comment.Text); matches != nil {
pos := fset.Position(comment.Pos())
return matches[1], pos.Line
}
}
return "", 0
}
func (cp *classParser) parseStructFields(fields []*ast.Field) []phpClassProperty {
var properties []phpClassProperty
for _, field := range fields {
for _, name := range field.Names {
prop := cp.parseStructField(name.Name, field)
properties = append(properties, prop)
}
}
return properties
}
func (cp *classParser) parseStructField(fieldName string, field *ast.Field) phpClassProperty {
prop := phpClassProperty{Name: fieldName}
// check if field is a pointer (nullable)
if starExpr, isPointer := field.Type.(*ast.StarExpr); isPointer {
prop.IsNullable = true
prop.GoType = cp.typeToString(starExpr.X)
} else {
prop.IsNullable = false
prop.GoType = cp.typeToString(field.Type)
}
prop.PhpType = cp.goTypeToPHPType(prop.GoType)
return prop
}
func (cp *classParser) typeToString(expr ast.Expr) string {
switch t := expr.(type) {
case *ast.Ident:
return t.Name
case *ast.StarExpr:
return "*" + cp.typeToString(t.X)
case *ast.ArrayType:
return "[]" + cp.typeToString(t.Elt)
case *ast.MapType:
return "map[" + cp.typeToString(t.Key) + "]" + cp.typeToString(t.Value)
default:
return "any"
}
}
var goToPhpTypeMap = map[string]phpType{
"string": phpString,
"int": phpInt, "int64": phpInt, "int32": phpInt, "int16": phpInt, "int8": phpInt,
"uint": phpInt, "uint64": phpInt, "uint32": phpInt, "uint16": phpInt, "uint8": phpInt,
"float64": phpFloat, "float32": phpFloat,
"bool": phpBool,
"any": phpMixed,
}
func (cp *classParser) goTypeToPHPType(goType string) phpType {
goType = strings.TrimPrefix(goType, "*")
if phpType, exists := goToPhpTypeMap[goType]; exists {
return phpType
}
if strings.HasPrefix(goType, "[]") || strings.HasPrefix(goType, "map[") {
return phpArray
}
return phpMixed
}
func (cp *classParser) parseMethods(filename string) (methods []phpClassMethod, err error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer func() {
e := file.Close()
if err == nil {
err = e
}
}()
scanner := bufio.NewScanner(file)
var currentMethod *phpClassMethod
lineNumber := 0
for scanner.Scan() {
lineNumber++
line := strings.TrimSpace(scanner.Text())
if matches := phpMethodRegex.FindStringSubmatch(line); matches != nil {
className := strings.TrimSpace(matches[1])
signature := strings.TrimSpace(matches[2])
method, err := cp.parseMethodSignature(className, signature)
if err != nil {
fmt.Printf("Warning: Error parsing method signature %q: %v\n", signature, err)
continue
}
validator := Validator{}
phpFunc := phpFunction{
Name: method.Name,
Signature: method.Signature,
Params: method.Params,
ReturnType: method.ReturnType,
IsReturnNullable: method.isReturnNullable,
}
if err := validator.validateTypes(phpFunc); err != nil {
fmt.Printf("Warning: Method \"%s::%s\" uses unsupported types: %v\n", className, method.Name, err)
continue
}
method.lineNumber = lineNumber
currentMethod = method
}
if currentMethod != nil && strings.HasPrefix(line, "func ") {
goFunc, err := cp.extractGoMethodFunction(scanner, line)
if err != nil {
return nil, fmt.Errorf("extracting Go method function: %w", err)
}
currentMethod.GoFunction = goFunc
validator := Validator{}
phpFunc := phpFunction{
Name: currentMethod.Name,
Signature: currentMethod.Signature,
GoFunction: currentMethod.GoFunction,
Params: currentMethod.Params,
ReturnType: currentMethod.ReturnType,
IsReturnNullable: currentMethod.isReturnNullable,
}
if err := validator.validateGoFunctionSignatureWithOptions(phpFunc, true); err != nil {
fmt.Printf("Warning: Go method signature mismatch for '%s::%s': %v\n", currentMethod.ClassName, currentMethod.Name, err)
currentMethod = nil
continue
}
methods = append(methods, *currentMethod)
currentMethod = nil
}
}
if currentMethod != nil {
return nil, fmt.Errorf("//export_php:method directive at line %d is not followed by a function declaration", currentMethod.lineNumber)
}
return methods, scanner.Err()
}
func (cp *classParser) parseMethodSignature(className, signature string) (*phpClassMethod, error) {
matches := methodSignatureRegex.FindStringSubmatch(signature)
if len(matches) != 4 {
return nil, fmt.Errorf("invalid method signature format")
}
methodName := matches[1]
paramsStr := strings.TrimSpace(matches[2])
returnTypeStr := strings.TrimSpace(matches[3])
isReturnNullable := strings.HasPrefix(returnTypeStr, "?")
returnType := strings.TrimPrefix(returnTypeStr, "?")
var params []phpParameter
if paramsStr != "" {
paramParts := strings.SplitSeq(paramsStr, ",")
for part := range paramParts {
param, err := cp.parseMethodParameter(strings.TrimSpace(part))
if err != nil {
return nil, fmt.Errorf("parsing parameter '%s': %w", part, err)
}
params = append(params, param)
}
}
return &phpClassMethod{
Name: methodName,
PhpName: methodName,
ClassName: className,
Signature: signature,
Params: params,
ReturnType: phpType(returnType),
isReturnNullable: isReturnNullable,
}, nil
}
func (cp *classParser) parseMethodParameter(paramStr string) (phpParameter, error) {
parts := strings.Split(paramStr, "=")
typePart := strings.TrimSpace(parts[0])
param := phpParameter{HasDefault: len(parts) > 1}
if param.HasDefault {
param.DefaultValue = cp.sanitizeDefaultValue(strings.TrimSpace(parts[1]))
}
matches := methodParamTypeNameRegex.FindStringSubmatch(typePart)
if len(matches) < 3 {
return phpParameter{}, fmt.Errorf("invalid parameter format: %s", paramStr)
}
typeStr := strings.TrimSpace(matches[1])
param.Name = strings.TrimSpace(matches[2])
param.IsNullable = strings.HasPrefix(typeStr, "?")
param.PhpType = phpType(strings.TrimPrefix(typeStr, "?"))
return param, nil
}
func (cp *classParser) sanitizeDefaultValue(value string) string {
if strings.HasPrefix(value, "[") && strings.HasSuffix(value, "]") {
return value
}
if strings.ToLower(value) == "null" {
return "null"
}
return strings.Trim(value, `'"`)
}
func (cp *classParser) extractGoMethodFunction(scanner *bufio.Scanner, firstLine string) (string, error) {
goFunc := firstLine + "\n"
braceCount := 1
for scanner.Scan() {
line := scanner.Text()
goFunc += line + "\n"
for _, char := range line {
switch char {
case '{':
braceCount++
case '}':
braceCount--
}
}
if braceCount == 0 {
break
}
}
return goFunc, nil
}