-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtokenizer.js
More file actions
91 lines (83 loc) · 2.95 KB
/
Copy pathtokenizer.js
File metadata and controls
91 lines (83 loc) · 2.95 KB
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
/**
* Tokenizer - Performs lexical analysis on DevLang source code
*
* @version 1.0.0
* @license MIT
*/
const { TokenTypes } = require('./tokenTypes');
const { Token } = require('./token');
/**
* Tokenizer - Performs lexical analysis on DevLang source code
*/
class Tokenizer {
constructor(code) {
this.code = code;
this.tokens = [];
this.keywords = new Set(['bolo', 'dekho', 'puchoo', 'nhi_toh']);
this.arithmeticOps = new Set(['+', '-', '*', '/', '%']);
this.comparisonOps = new Set(['==', '!=', '>', '<', '>=', '<=']);
this.logicalOps = new Set(['&&', '||', '!']);
this.parentheses = new Set(['(', ')']);
this.curlyBraces = new Set(['{', '}']);
this.tokenize();
}
tokenize() {
// Correct pattern: includes string literals
const pattern = /"(?:\\.|[^"\\])*"|[A-Za-z_]\w*|\d+|==|!=|>=|<=|&&|\|\||[+\-*/%]=?|[(){};,]|[<>]|=/g;
const matches = this.code.match(pattern) || [];
for (const match of matches) {
// String literal (e.g. "hello world")
if (match.startsWith('"') && match.endsWith('"')) {
this.tokens.push(new Token(TokenTypes.STRING_LITERAL, match.slice(1, -1)));
}
// Keyword (bolo, dekho, puchoo, nhi_toh)
else if (this.keywords.has(match)) {
this.tokens.push(new Token(TokenTypes.KEYWORD, match));
}
// Identifier (e.g. name, age)
else if (/^[A-Za-z_]\w*$/.test(match)) {
this.tokens.push(new Token(TokenTypes.IDENTIFIER, match));
}
// Assignment operator (=)
else if (match === '=') {
this.tokens.push(new Token(TokenTypes.ASSIGNMENT_OP, match));
}
// Integer literal
else if (/^\d+$/.test(match)) {
this.tokens.push(new Token(TokenTypes.INT_LITERAL, match));
}
// Arithmetic operators
else if (this.arithmeticOps.has(match)) {
this.tokens.push(new Token(TokenTypes.ARITHMETIC_OP, match));
}
// Comparison operators
else if (this.comparisonOps.has(match)) {
this.tokens.push(new Token(TokenTypes.COMPARISON_OP, match));
}
// Logical operators
else if (this.logicalOps.has(match)) {
this.tokens.push(new Token(TokenTypes.LOGICAL_OP, match));
}
// Parentheses
else if (this.parentheses.has(match)) {
this.tokens.push(new Token(TokenTypes.PARENTHESIS, match));
}
// Curly braces
else if (this.curlyBraces.has(match)) {
this.tokens.push(new Token(TokenTypes.CURLY_BRACE, match));
}
// Semicolon
else if (match === ';') {
this.tokens.push(new Token(TokenTypes.SEMICOLON, match));
}
// Unknown token
else {
console.warn(`Unrecognized token: ${match}`);
}
}
}
getTokens() {
return this.tokens;
}
}
module.exports = { Tokenizer };