MCPcopy Create free account
hub / github.com/coder/guts / parseExpression

Function parseExpression

single.go:17–59  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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.
17func 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}

Callers 2

IncludeCustomMethod · 0.85
TestParseSingleFunction · 0.85

Calls 2

parseMethod · 0.95
NewGolangParserFunction · 0.85

Tested by 1

TestParseSingleFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…