Last active
April 23, 2024 23:26
-
-
Save eduardvercaemer/f93ff51d61058d57e81746e04e4f5d4c to your computer and use it in GitHub Desktop.
Tampermonkey, Convert SLR Parser to C matrix.
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
// ==UserScript== | |
// @name Export SLR Parser Automata to C | |
// @namespace http://tampermonkey.net/ | |
// @version 2024-04-23 | |
// @description Export SLR Parser Automata to C | |
// @author Ed | |
// @match https://jsmachines.sourceforge.net/machines/slr.html | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=sourceforge.net | |
// @grant none | |
// ==/UserScript== | |
/** | |
* https://jsmachines.sourceforge.net/machines/slr.html | |
* Export your parser automata to a plain C array | |
*/ | |
(function() { | |
'use strict'; | |
const button = document.createElement('button') | |
button.innerText = 'EXPORT AUTOMATA TO C' | |
button.addEventListener('click', exportAutomata) | |
document.body.prepend(button) | |
})(); | |
function exportAutomata() { | |
console.debug('exporting automata...') | |
const thead = window.lrTableView.childNodes[0].childNodes[0].getElementsByTagName('tr')[1] | |
const [_, ACTION, GOTO] = thead.getElementsByTagName('th') | |
const actions = parseInt(ACTION.getAttribute('colspan')) | |
const gotos = parseInt(GOTO.getAttribute('colspan')) | |
const tbody = window.lrTableView.childNodes[0].childNodes[1] | |
const rows = Array.from(tbody.getElementsByTagName('tr')) | |
const mat = rows.map(r => { | |
const cols = Array.from(r.getElementsByTagName('td')) | |
return cols.slice(1).map(c => { | |
const text = c.innerText | |
const match = /[sr](\d+)/.exec(text) | |
if (match) { | |
const value = parseInt(match[1]) | |
return text.startsWith('s') ? value | |
: value + 512 | |
} | |
const number = /\d+/.exec(text) | |
if (number) { | |
return parseInt(number) | |
} | |
if (text === 'acc') { | |
return 512 | |
} | |
return -1 | |
}) | |
}) | |
const cdef = `int const mat[${mat.length}][${actions + gotos}] = {\n ` + mat.map(r => `{${r.join(', ')}}`).join(',\n ') + '\n};'; | |
const blob = new Blob([cdef], {type:'text'}) | |
const url = URL.createObjectURL(blob) | |
const anchor = document.createElement('a') | |
anchor.setAttribute('href', url) | |
anchor.setAttribute('download', 'mat.c') | |
document.body.appendChild(anchor) | |
anchor.click() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment