parseExpression feels a bit janky, however it enables the caller to send in a golang expression, eg `map[string]string`, and get back a Typescript type.
(expr string)
| 15 | // parseExpression feels a bit janky, however it enables the caller to send in |
| 16 | // a golang expression, eg `map[string]string`, and get back a Typescript type. |
| 17 | func parseExpression(expr string) (bindings.ExpressionType, error) { |
| 18 | fs := token.NewFileSet() |
| 19 | // This line means the expression must be an expression type, not a statement. |
| 20 | // This removes the ability for things like generics. If there is a reason |
| 21 | // to allow a larger subset of golang expressions and statements, this |
| 22 | // can be changed. |
| 23 | src := fmt.Sprintf(`package main; type check = %s;`, expr) |
| 24 | |
| 25 | asFile, err := parser.ParseFile(fs, "main.go", []byte(src), 0) |
| 26 | if err != nil { |
| 27 | return nil, xerrors.Errorf("parse expression: %w", err) |
| 28 | } |
| 29 | |
| 30 | config := types.Config{} |
| 31 | pkg, err := config.Check("main.go", fs, []*ast.File{asFile}, nil) |
| 32 | if err != nil { |
| 33 | return nil, xerrors.Errorf("check types: %w", err) |
| 34 | } |
| 35 | |
| 36 | goParser, _ := NewGolangParser() |
| 37 | goParser.fileSet = fs |
| 38 | ts := Typescript{ |
| 39 | typescriptNodes: make(map[string]*typescriptNode), |
| 40 | parsed: goParser, // Intentionally empty |
| 41 | serialized: false, |
| 42 | } |
| 43 | err = ts.parse(pkg.Scope().Lookup("check")) |
| 44 | if err != nil { |
| 45 | return nil, xerrors.Errorf("parse: %w", err) |
| 46 | } |
| 47 | |
| 48 | check, ok := ts.typescriptNodes["check"] |
| 49 | if !ok { |
| 50 | return nil, xerrors.Errorf("no check node") |
| 51 | } |
| 52 | |
| 53 | alias, ok := check.Node.(*bindings.Alias) |
| 54 | if !ok { |
| 55 | return nil, xerrors.Errorf("expected alias, got %T", check) |
| 56 | } |
| 57 | |
| 58 | return alias.Type, nil |
| 59 | } |
searching dependent graphs…