-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCFG1.html
81 lines (69 loc) · 1.58 KB
/
CFG1.html
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
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>CFG for Addition </title>
</head>
<body>
<h2 id=title></h2>
<p>Context-free grammar for unary addition</p>
w = <input id=input type=text value="aa+aa=aaaa"
onChange="test()">
<pre id=out></pre>
<hr />
<b>Grammar</b>
<style>
#cfg {
margin: 10px 50px;
color: blue;
font-weight: bold;
}
</style>
<div id=cfg>
S → aSa | +aEa <br>
E → aEa | =
</div>
<pre id=sample></pre>
<hr />
<!--p>Ref: <a href="https:xxx"
target="ExternalDocument">xxx</a>
</p-->
<script>
"use strict";
function delta(c, p) { // Unary addition
if (c=='a' && p=='S') return "aSa";
if (c=='+' && p=='S') return "+aEa";
if (c=='a' && p=='E') return "aEa";
if (c=='=' && p=='E') return "=";
return ''; //default -- no transition
}
function generate(w, init='S') {
//w: input String
//init: start symbol
//g: generated String
let txt = init, g = init
for (let i=0; i<w.length; i++) {
let c = w[i], p = g[i]
if (c == p) continue
let d = delta(c, p)
if (d == '') {
input.selectionStart = i
input.selectionEnd = i+1
break
}
g = g.replace(p, d)
txt += "\n=> "+g
}
return txt+'\n'+(w==g ? "Accept" : "Reject")
}
function test() {
let s = generate(input.value);
console.log(s); out.innerHTML = s
}
title.innerText = document.title;
sample.innerText = delta+'\n'+generate;
test();
</script>
</body>
</html>