-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursiveDescentParser.js
123 lines (108 loc) · 2.25 KB
/
recursiveDescentParser.js
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
// recursiveDescentParser.js
//
// RECURSIVE DESCENT PARSER
// ========================
// DECLARE VARIABLES
// =================
var input;
var initial;
var errorCount;
// DECLARE FUNCTIONS
// =================
// Main function for grammar organization
function main() {
initial = 0;
errorCount = 0;
input = document.getElementById("button1").value;
if (input[input.length - 1] === "$") {
scanner();
} else {
swal("Error", "String Not Ending in $", "error");
}
}
// Classifies Digits
function digit() {
if ((token() === '0') || (token() === '1') || (token() === '2') || (token() === '3')) {
validater(token());
} else {
errorLint();
}
}
// Non Terminal Factors
function factor() {
if (token() === '(') {
validater(token());
expression();
validater(')');
} else if ((token() === '0') || (token() === '1') || (token() === '2') || (token() === '3')) {
digit();
} else {
errorLint();
}
}
// Non Terminal Terms
function term() {
factor();
while ((token() === '*') || (token() === '/')) {
if (token() === '*') {
validater(token());
factor();
} else if (token() === '/') {
validater(token());
factor();
} else {
errorLint();
}
}
}
// Generates Token for comparison
function token() {
return (input[initial]);
}
// Increments the length
function incrementer() {
if (initial < (input.length - 1)) {
initial++;
}
}
// function to validate token
function validater(t) {
if (t === token()) {
incrementer();
} else {
errorLint();
}
}
// Terminal Expression checker
function expression() {
term();
while ((token() === '+') || (token() === '-')) {
if (token() === '+') {
validater(token());
term();
} else if (token() === '-') {
validater(token());
term();
} else {
errorLint();
}
}
}
// function to start lexical scanning
function scanner() {
expression();
validater('$');
if (errorCount === 0) {
swal("Success", "This is a Legal Expression", "success");
} else {
swal("Error!", "Error Found In Expression", "error");
}
}
// TESTING
// =======
// Linting for Errors
function errorLint() {
swal("Error!", "Error found at position: " + initial, "error");
errorCount = 1;
incrementer();
}