You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/compiler/scanner.md
+30-4
Original file line number
Diff line number
Diff line change
@@ -10,6 +10,7 @@ There is a *singleton* `scanner` created in `parser.ts` to avoid the cost of cre
10
10
11
11
Here is a *simplied* version of the actual code in the parser that you can run demonstrating this concept:
12
12
13
+
`code/compiler/scanner/runScanner.ts`
13
14
```ts
14
15
import*astsfrom"ntypescript";
15
16
@@ -29,7 +30,7 @@ function initializeState(text: string) {
29
30
// Sample usage
30
31
initializeState(`
31
32
var foo = 123;
32
-
`);
33
+
`.trim());
33
34
34
35
// Start the scanning
35
36
var token =scanner.scan();
@@ -50,9 +51,34 @@ SemicolonToken
50
51
```
51
52
52
53
### Scanner State
53
-
After you call `scan` the scanner updates its local state (position in the scan, current token details etc). The scanner provides a bunch of utility functions to get the current scanner state.
54
+
After you call `scan` the scanner updates its local state (position in the scan, current token details etc). The scanner provides a bunch of utility functions to get the current scanner state. In the below sample we create a scanner and then use it to identify the tokens as well as their positions in the code.
54
55
55
-
// TODO: document a few of these and provide a sample.
56
+
`code/compiler/scanner/runScannerWithPosition.ts`
57
+
```ts
58
+
// Sample usage
59
+
initializeState(`
60
+
var foo = 123;
61
+
`.trim());
62
+
63
+
// Start the scanning
64
+
var token =scanner.scan();
65
+
while (token!=ts.SyntaxKind.EndOfFileToken) {
66
+
let currentToken =ts.syntaxKindToName(token);
67
+
let tokenStart =scanner.getStartPos();
68
+
token=scanner.scan();
69
+
let tokenEnd =scanner.getStartPos();
70
+
console.log(currentToken, tokenStart, tokenEnd);
71
+
}
72
+
```
73
+
74
+
This will print out the following:
75
+
```
76
+
VarKeyword 0 3
77
+
Identifier 3 7
78
+
FirstAssignment 7 9
79
+
FirstLiteralToken 9 13
80
+
SemicolonToken 13 14
81
+
```
56
82
57
83
### Standalone scanner
58
-
Even though the parser has a singleton scanner you can create a standalone scanner using `createScanner` and use its `setText`/`setTextPos` to scan at different points in a file for your amusement.
84
+
Even though the typescript parser has a singleton scanner you can create a standalone scanner using `createScanner` and use its `setText`/`setTextPos` to scan at different points in a file for your amusement.
0 commit comments