Class: Linguist::Tokenizer

Inherits:
Object
  • Object
show all
Defined in:
lib/linguist/tokenizer.rb,
ext/linguist/linguist.c

Overview

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.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.tokenize(data) ⇒ Object

Public: Extract tokens from data

data - String to tokenize

Returns Array of token Strings.



16
17
18
# File 'lib/linguist/tokenizer.rb', line 16

def self.tokenize(data)
  new.extract_tokens(data)
end

Instance Method Details

#extract_tokens(rb_data) ⇒ Object



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
# File 'ext/linguist/linguist.c', line 12

static VALUE rb_tokenizer_extract_tokens(VALUE self, VALUE rb_data) {
	YY_BUFFER_STATE buf;
	yyscan_t scanner;
	struct tokenizer_extra extra;
	VALUE ary, s;
	long len;
	int r;

	Check_Type(rb_data, T_STRING);

	len = RSTRING_LEN(rb_data);
	if (len > 100000)
		len = 100000;

	linguist_yylex_init_extra(&extra, &scanner);
	buf = linguist_yy_scan_bytes(RSTRING_PTR(rb_data), (int) len, scanner);

	ary = rb_ary_new();
	do {
		extra.type = NO_ACTION;
		extra.token = NULL;
		r = linguist_yylex(scanner);
		switch (extra.type) {
		case NO_ACTION:
			break;
		case REGULAR_TOKEN:
			len = strlen(extra.token);
			if (len <= MAX_TOKEN_LEN)
				rb_ary_push(ary, rb_str_new(extra.token, len));
			free(extra.token);
			break;
		case SHEBANG_TOKEN:
			len = strlen(extra.token);
			if (len <= MAX_TOKEN_LEN) {
				s = rb_str_new2("SHEBANG#!");
				rb_str_cat(s, extra.token, len);
				rb_ary_push(ary, s);
			}
			free(extra.token);
			break;
		case SGML_TOKEN:
			len = strlen(extra.token);
			if (len <= MAX_TOKEN_LEN) {
				s = rb_str_new(extra.token, len);
				rb_str_cat2(s, ">");
				rb_ary_push(ary, s);
			}
			free(extra.token);
			break;
		}
	} while (r);

	linguist_yy_delete_buffer(buf, scanner);
	linguist_yylex_destroy(scanner);

	return ary;
}