-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathtokens.ts
99 lines (93 loc) · 2.54 KB
/
tokens.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { Token as AntlrToken } from 'antlr4'
import { Token, TokenizeOptions } from './types'
import { tokens } from './antlr/solidity-tokens'
import type { Comment, Location } from './ast-types'
const TYPE_TOKENS = [
'var',
'bool',
'address',
'string',
'Int',
'Uint',
'Byte',
'Fixed',
'UFixed',
]
function getTokenType(value: string) {
if (value === 'Identifier' || value === 'from') {
return 'Identifier'
} else if (value === 'TrueLiteral' || value === 'FalseLiteral') {
return 'Boolean'
} else if (value === 'VersionLiteral') {
return 'Version'
} else if (value === 'StringLiteral') {
return 'String'
} else if (TYPE_TOKENS.includes(value)) {
return 'Type'
} else if (value === 'NumberUnit') {
return 'Subdenomination'
} else if (value === 'DecimalNumber') {
return 'Numeric'
} else if (value === 'HexLiteral') {
return 'Hex'
} else if (value === 'ReservedKeyword') {
return 'Reserved'
} else if (/^\W+$/.test(value)) {
return 'Punctuator'
} else {
return 'Keyword'
}
}
function range(token: AntlrToken): [number, number] {
return [token.start, token.stop + 1]
}
function loc(token: AntlrToken): Location {
const tokenText = token.text ?? ''
const textInLines = tokenText.split(/\r?\n/)
const numberOfNewLines = textInLines.length - 1
return {
start: { line: token.line, column: token.column },
end: {
line: token.line + numberOfNewLines,
column:
textInLines[numberOfNewLines].length +
(numberOfNewLines === 0 ? token.column : 0),
},
}
}
export function buildTokenList(
tokensArg: AntlrToken[],
options: TokenizeOptions
): Token[] {
return tokensArg.map((token) => {
const type = getTokenType(tokens[token.type.toString()])
const node: Token = { type, value: token.text }
if (options.range === true) {
node.range = range(token)
}
if (options.loc === true) {
node.loc = loc(token)
}
return node
})
}
export function buildCommentList(
tokensArg: AntlrToken[],
commentsChannelId: number,
options: TokenizeOptions
): Comment[] {
return tokensArg
.filter((token) => token.channel === commentsChannelId)
.map((token) => {
const comment: Comment = token.text.startsWith('//')
? { type: 'LineComment', value: token.text.slice(2) }
: { type: 'BlockComment', value: token.text.slice(2, -2) }
if (options.range === true) {
comment.range = range(token)
}
if (options.loc === true) {
comment.loc = loc(token)
}
return comment
})
}