-
Notifications
You must be signed in to change notification settings - Fork 9
/
tokenizer.go
179 lines (161 loc) · 5.16 KB
/
tokenizer.go
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// go port of https://github.com/github/linguist/blob/master/lib/linguist/tokenizer.rb
//
// in their words:
//
// # Generic programming language tokenizer.
// #
// # Tokens are designed for use in the language bayes classifier.
// # It strips any data strings or comments and preserves significant
// # language symbols.
//
package tokenizer
import (
"bufio"
"bytes"
"regexp"
)
var (
// Maximum input length for Tokenize()
ByteLimit = 100000
// NOTE(tso): these string slices are turned into their regexp slice counterparts
// by this package's init() function.
StartLineComments = []string{
"\"", // Vim
"%", // Tex
}
SingleLineComments = []string{
"//", // C
"--", // Ada, Haskell, AppleScript
"#", // Perl, Bash, Ruby
}
MultiLineComments = [][]string{
[]string{"/*", "*/"}, // C
[]string{"<!--", "-->"}, // XML
[]string{"{-", "-}"}, // Haskell
[]string{"(*", "*)"}, // Coq
[]string{`"""`, `"""`}, // Python
[]string{"'''", "'''"}, // Python
[]string{"#`(", ")"}, // Perl6
}
StartLineComment []*regexp.Regexp
BeginSingleLineComment []*regexp.Regexp
BeginMultiLineComment []*regexp.Regexp
EndMultiLineComment []*regexp.Regexp
String = regexp.MustCompile(`[^\\]*(["'` + "`])")
Shebang = regexp.MustCompile(`#!.*$`)
Number = regexp.MustCompile(`(0x[0-9a-f]([0-9a-f]|\.)*|\d(\d|\.)*)([uU][lL]{0,2}|([eE][-+]\d*)?[fFlL]*)`)
)
func init() {
for _, st := range append(StartLineComments, SingleLineComments...) {
StartLineComment = append(StartLineComment, regexp.MustCompile(`^\s*`+regexp.QuoteMeta(st)))
}
for _, sl := range SingleLineComments {
BeginSingleLineComment = append(BeginSingleLineComment, regexp.MustCompile(regexp.QuoteMeta(sl)))
}
for _, ml := range MultiLineComments {
BeginMultiLineComment = append(BeginMultiLineComment, regexp.MustCompile(regexp.QuoteMeta(ml[0])))
EndMultiLineComment = append(EndMultiLineComment, regexp.MustCompile(regexp.QuoteMeta(ml[1])))
}
}
// If the given token matches the start of a multi-line comment,
// this function will return true and a regex for the corresponding closing token,
// otherwise false and nil.
func FindMultiLineComment(token []byte) (matched bool, terminator *regexp.Regexp) {
for idx, re := range BeginMultiLineComment {
if re.Match(token) {
return true, EndMultiLineComment[idx]
}
}
return false, nil
}
// Simple tokenizer that uses bufio.Scanner to process lines and individual words
// and matches them against regular expressions to filter out comments, strings, and numerals
// in a manner very similar to github's linguist (see https://github.com/github/linguist/blob/master/lib/linguist/tokenizer.rb)
//
// The intention is to merely retrieve significant tokens from a piece of source code
// in order to identify the programming language using statistical analysis
// and NOT to be used as any part of the process of compilation whatsoever.
//
// NOTE(tso): The tokens produced by this function may be of a dubious quality due to the approach taken.
// Feedback and alternate implementations welcome :)
func Tokenize(input []byte) (tokens []string) {
if len(input) == 0 {
return tokens
}
if len(input) >= ByteLimit {
input = input[:ByteLimit]
}
var (
ml_in = false // in a multiline comment
ml_end *regexp.Regexp // closing token regexp
str_in = false // in a string literal
str_end byte = 0 // closing token byte to be found by the String regexp
)
buf := bytes.NewBuffer(input)
scanlines := bufio.NewScanner(buf)
scanlines.Split(bufio.ScanLines)
// NOTE(tso): the use of goto here is probably interchangable with continue
line:
for scanlines.Scan() {
ln := scanlines.Bytes()
for _, re := range StartLineComment {
if re.Match(ln) {
goto line
}
}
// NOTE(tso): bufio.Scanner.Split(bufio.ScanWords) seems to just split on whitespace
// this may yield inaccurate results where there is a lack of sufficient
// whitespace for the approaches taken here, i.e. jumping straight to the
// next word/line boundary.
ln_buf := bytes.NewBuffer(ln)
scanwords := bufio.NewScanner(ln_buf)
scanwords.Split(bufio.ScanWords)
word:
for scanwords.Scan() {
tk_b := scanwords.Bytes()
tk_s := scanwords.Text()
// find end of multi-line comment
if ml_in {
if ml_end.Match(tk_b) {
ml_in = false
ml_end = nil
}
goto word
}
// find end of string literal
if str_in {
s := String.FindSubmatch(tk_b)
if s != nil && s[1][0] == str_end {
str_in = false
str_end = 0
}
goto word
}
// find single-line comment
for _, re := range BeginSingleLineComment {
if re.Match(tk_b) {
goto line
}
}
// find start of multi-line comment
if matched, terminator := FindMultiLineComment(tk_b); matched {
ml_in = true
ml_end = terminator
goto word
}
// find start of string literal
if s := String.FindSubmatch(tk_b); s != nil {
str_in = true
str_end = s[1][0]
goto word
}
// find numeric literal
if n := Number.Find(tk_b); n != nil {
goto word
}
// add valid tokens to result set
tokens = append(tokens, tk_s)
}
}
return tokens
}