Last active
June 6, 2023 18:59
-
-
Save Adib23704/6feeda10b96c0b9c486e77f4f698697f to your computer and use it in GitHub Desktop.
LL(1) Grammer Parser Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LL1Parser { | |
| constructor() { | |
| this.index = 0; | |
| } | |
| parse(input) { | |
| this.tokens = input.split(' '); | |
| this.index = 0; | |
| try { | |
| this.S(); | |
| if (this.index === this.tokens.length) { | |
| console.log(`\nResult: "${input}" is a valid syntax which parsed successfully.`); | |
| } else { | |
| throw new Error('Invalid input'); | |
| } | |
| } catch (error) { | |
| console.error(`\nResult: "${input}" is not a valid syntax. Parsing error: ${error.message}`); | |
| } | |
| } | |
| match(token) { | |
| if (this.tokens[this.index] === token) { | |
| this.index++; | |
| console.log(`Matched ${token}`); | |
| } else { | |
| throw new Error(`Expected ${token} but found ${this.tokens[this.index]}`); | |
| } | |
| } | |
| S() { | |
| console.log('S -> E'); | |
| this.E(); | |
| } | |
| E() { | |
| console.log('E -> T EPrime'); | |
| this.T(); | |
| this.EPrime(); | |
| } | |
| EPrime() { | |
| if (this.tokens[this.index] === '+') { | |
| console.log('EPrime -> + T EPrime'); | |
| this.match('+'); | |
| this.T(); | |
| this.EPrime(); | |
| } else { | |
| console.log('EPrime -> ε'); | |
| } | |
| } | |
| T() { | |
| console.log('T -> F TPrime'); | |
| this.F(); | |
| this.TPrime(); | |
| } | |
| TPrime() { | |
| if (this.tokens[this.index] === '*') { | |
| console.log('TPrime -> * F TPrime'); | |
| this.match('*'); | |
| this.F(); | |
| this.TPrime(); | |
| } else { | |
| console.log('TPrime -> ε'); | |
| } | |
| } | |
| F() { | |
| if (this.tokens[this.index] === '(') { | |
| console.log('F -> ( E )'); | |
| this.match('('); | |
| this.E(); | |
| this.match(')'); | |
| } else if (this.tokens[this.index] === 'id') { | |
| console.log('F -> id'); | |
| this.match('id'); | |
| } else { | |
| throw new Error('Invalid input'); | |
| } | |
| } | |
| // Method to print the grammar table | |
| printGrammarTable() { | |
| console.log('Grammar Table:'); | |
| console.log('--------------\n'); | |
| console.log('Non-Terminals: S, E, EPrime, T, TPrime, F'); | |
| console.log('Productions: E, T EPrime, + T EPrime | ε,\n\t\t\t F TPrime, * F TPrime | ε,\n\t\t\t (E) | id'); | |
| console.log('Terminals: id, +, *, (, )\n'); | |
| } | |
| } | |
| // Usage example | |
| const parser = new LL1Parser(); | |
| const input = 'id + id * id'; | |
| parser.printGrammarTable(); // Print the grammar table | |
| console.log('Parsing Steps:'); | |
| console.log('--------------\n'); | |
| parser.parse(input); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Converted to Python