编译原理 #02# 简易递归下降分析程序(JavaScript实现)

// 实验存档

截图:

代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <link href="https://fonts.googleapis.com/css?family=Noto+Serif+SC" rel="stylesheet">
    <style>
        main {
            /*对子元素开启弹性布局*/
            display: flex;
            /*弹性元素在必要的时候换行*/
            flex-wrap: wrap;
            /*将弹性元素居中*/
            justify-content: center;
        }

        textarea,
        button {
            font-family: 'Noto Serif SC', STFangSong, serif;
            font-size: 17px;
        }
    </style>
</head>

<body>
    <main>
        <textarea name="input" rows="20" cols="40"></textarea>
        <textarea name="output" rows="20" cols="40"></textarea>
        <button name="execute">Execute</button>
    </main>

    <script>
        let inputBox = document.querySelector("textarea[name=input]");
        let outputBox = document.querySelector("textarea[name=output]");
        let btnExecute = document.querySelector("button[name=execute]");

        btnExecute.addEventListener("click", event => {            
            startAnalyzing(inputBox.value);
        });

        /*
            对下列文法,用递归下降分析法对任意输入的符号串进行分析:
            (1)E->eBaA
            (2)A->a|bAcB
            (3)B->dEd|aC
            (4)C->e|dC
            输入一以#结束的符号串,例如eadeaa#为合法符号串
         */

function startAnalyzing(s) { str = s; cur = 0; E(); outputBox.value = str + "为合法符号串!"; } function E() { // E->eBaA# match('e'); B(); match('a'); A(); match('#'); } function A() { // A->a|bAcB if (str[cur] === 'a') { match('a'); } else if (str[cur] === 'b') { match('b'); A(); match('c'); B(); } else { report("存在语法错误,字符位置为:" + cur); } } function B() { // B->dEd|aC if (str[cur] === 'd') { match('d'); E(); match('d'); } else if (str[cur] === 'a') { match('a'); C(); } else { report("存在语法错误,字符位置为:" + cur); } } function C() { // C->e|dC if (str[cur] === 'e') { match('e'); } else if (str[cur] === 'd') { match('d'); C(); } else { report("存在语法错误,字符位置为:" + cur); } } function match(ch) { if (cur < str.length && str[cur] === ch) ++cur; else report("存在语法错误,字符位置为:" + cur); } function report(s) { outputBox.value = s; throw new Error(s); } </script> </body> </html>
原文地址:https://www.cnblogs.com/xkxf/p/10670705.html