Skip to content

Commit 5577145

Browse files
fix: add range operator
1 parent 2d1fac9 commit 5577145

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

website/guide/rule-config/atomic-rule.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
ast-grep has three categories of rules. Let's start with the most basic one: atomic rule.
44

5-
Atomic rule defines the most basic matching rule that determines whether one syntax node matches the rule or not. There are four kinds of atomic rule: `pattern`, `kind`, `regex` and `nthChild`.
5+
Atomic rule defines the most basic matching rule that determines whether one syntax node matches the rule or not. There are five kinds of atomic rule: `pattern`, `kind`, `regex`, `nthChild` and `range`.
66

77
## `pattern`
88

@@ -187,7 +187,26 @@ const arr = [ 1, 2, 3, ]
187187
// |- match this number
188188
```
189189

190+
## `range`
190191

192+
`range` is a rule to match nodes based on their position in the source code. It is useful when you want to integrate external tools like compilers or type checkers with ast-grep. External tools can provide the range information of the interested node, and ast-grep can use it to rewrite the code.
193+
194+
`range` rule accepts a range object with `start` and `end` fields. Each field is an object with `line` and `column` fields.
195+
196+
```yaml
197+
rule:
198+
range:
199+
start:
200+
line: 0
201+
column: 0
202+
end:
203+
line: 1
204+
column: 5
205+
```
206+
207+
The above example will match an AST node having the first three characters of the first line like `foo` in `foo.bar()`.
208+
209+
`line` and `column` are 0-based and character-wise, and the `start` is inclusive while the `end` is exclusive.
191210

192211

193212
## Tips for Writing Rules

website/reference/rule.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,28 @@ nthChild:
130130
* nthChild's index is 1-based, not 0-based, as in the CSS selector.
131131
* nthChild's node list only includes named nodes, not unnamed nodes.
132132

133+
134+
### `range`
135+
* type: `RangeObject`
136+
137+
A `RangeObject` is an object with two fields `start` and `end`, each of which is an object with two fields `line` and `column`.
138+
139+
Both `line` and `column` are 0-based and character-based. `start` is inclusive and `end` is exclusive.
140+
141+
**Example:**
142+
143+
```yml
144+
range:
145+
start:
146+
line: 0
147+
column: 0
148+
end:
149+
line: 0
150+
column: 3
151+
```
152+
153+
The above example will match an AST node having the first three characters of the first line like `foo` in `foo.bar()`.
154+
133155
## Relational Rules
134156

135157
### `inside`

0 commit comments

Comments
 (0)