@@ -7,6 +7,13 @@ https://github.com/ast-grep/ast-grep/issues/48
7
7
8
8
It guides one to write comprehensive AST code (in case people forget to handle some cases)
9
9
10
+ # What are good TypeScript types?
11
+
12
+ * Correct: reject invalid code and accept valid code
13
+ * Concise: easy to read, especially in hover and completion
14
+ * Robust: easy to refactor
15
+ * Performant: fast to compile
16
+
10
17
# TreeSitter's types
11
18
12
19
Tree-Sitter's official API is untyped. However it provides static node types in json
@@ -33,36 +40,72 @@ For example `+`/`-`/`*`/`/` is too noisy for a general AST library
33
40
34
41
Use type script to resolve type alias
35
42
36
- ## ` NodeKinds <M>`
43
+ ## ` Kinds <M>`
37
44
38
- 1 . string literal completion with string
45
+ 1 . string literal completion with ` LowPriorityString `
39
46
2 . lenient
40
47
41
48
Problem?
42
49
43
50
https://github.com/microsoft/TypeScript/issues/33471
44
51
https://github.com/microsoft/TypeScript/issues/26277
45
52
46
- ## Distinguish general ` string ` and specific kinds
47
- ` RefinedNode<> `
53
+ ## Distinguish general ` string ` ly kinds and specific kinds
54
+
55
+ Note ` SgNode<'expression' | 'type'> ` is different from ` SgNode<'expression'> | SgNode<'type'> `
56
+
57
+ ast-grep uses a trick via the type ` RefineNode<> ` to let you switch between the two
48
58
49
59
50
60
## Refine Node, Manually
51
61
52
62
1.via ` sgNode.find<"KIND"> `
53
63
2.via ` sgNode.is<"KIND"> ` , One time type narrowing
54
64
65
+ Using the intersting overloading feature of TypeScript
66
+
67
+ ``` typescript
68
+ interface NodeMethod <K > {
69
+ (): SgNode
70
+ <T extends K >(): SgNode <T >
71
+ }
72
+ ```
73
+
55
74
## Refine Node, Automatically
56
75
57
- ` sgNode.field("kind") `
76
+ ` sgNode.field("kind") ` will
77
+
58
78
79
+ ## Exhaustive Checking via ` sgNode.kindToRefine `
59
80
60
- ## Exhaustive Checking via ` sgNode.kindForRefinement `
81
+ Only available for node with specific kinds
61
82
62
- Only available specific kinds
83
+ ``` typescript
84
+ const func: SgNode <' function_declaration' > | SgNode <' arrow_function' >
85
+
86
+ switch (func .kindToRefine ) {
87
+ case ' function_declaration' :
88
+ func .kindToRefine // narrow to 'function_declaration'
89
+ break
90
+ case ' arrow_function' :
91
+ func .kindToRefine // narrow to 'arrow_function'
92
+ break
93
+ default :
94
+ func satisfies never // exhaustive check!
95
+ }
96
+ ```
63
97
64
98
## Typed Rule!
65
99
100
+ ``` typescript
101
+ sgNode .find ({
102
+ rule: {
103
+ // kind: 'invalid_kind', // error!
104
+ kind: ' function_declaration' , // typed!
105
+ }
106
+ })
107
+ ```
108
+
66
109
## Opt-in refinement for better compile time performance
67
110
68
111
# Ending
0 commit comments