JavaScript实现词法分析
所用软件
Visual Studio Code
or
Hbuilder-X
代码块
<!DOCTYPE html
>
<html
>
<head
>
<meta charset
="UTF-8">
<title
>词法分析(
JS实现)
</title
>
<link href
="https://fonts.googleapis.com/css?family=Noto+Serif+SC" rel
="stylesheet">
</head
>
<body
>
<p
class="only">JavaScript实现简易词法分析
</p
>
<main
>
<textarea name
="input" rows
="20" cols
="40"></textarea
>
<textarea name
="output" rows
="20" cols
="40"></textarea
>
<button name
="compile">Lexical Analysis
</button
>
</main
>
<script
>
let inputBox
= document
.querySelector("textarea[name=input]");
let outputBox
= document
.querySelector("textarea[name=output]");
let btnCompile
= document
.querySelector("button[name=compile]");
btnCompile
.addEventListener("click", event
=> {
let inputCode
= inputBox
.value
;
outputBox
.value
= JSON.stringify(Lexical_Analysis(inputCode
));
});
const reservedWords
= ['if', 'int', 'for', 'while', 'do', 'return', 'break', 'continue'];
const operators
= ['+', '-', '*', '/', '=', '<', '>', '!', '>=', '<=', '!='];
const separators
= [',', ';', '{', '}', '(', ')'];
function Lexical_Analysis(str
) {
let cur
= 0;
let tokens
= [];
while (cur
< str
.length
) {
if (/\s/.test(str
[cur
])) {
cur
++;
} else if (/[a-z]/i.test(str
[cur
])) {
debugger;
let word
= "" + str
[cur
++];
while (cur
< str
.length
&& /[a-z]/i.test(str
[cur
])) {
word
+= str
[cur
++];
}
if (reservedWords
.includes(word
)) {
tokens
.push({
type
: 1,
value
: word
,
});
} else {
tokens
.push({
type
: 2,
value
: word
,
});
}
} else if (separators
.includes(str
[cur
])) {
tokens
.push({
type
: 5,
value
: str
[cur
++],
});
} else if (operators
.includes(str
[cur
])) {
let operator
= "" + str
[cur
++];
if (['>', '<', '!'].includes(operator
)) {
if (str
[cur
] = '=') {
operator
+= str
[cur
++];
}
}
tokens
.push({
type
: 4,
value
: operator
,
});
} else if (/[0-9]/.test(str
[cur
])) {
let val
= "" + str
[cur
++];
while (cur
< str
.length
&& /[0-9]/.test(str
[cur
])) {
val
+= str
[cur
++];
}
tokens
.push({
type
: 3,
value
: val
,
});
} else {
return "包含非法字符:" + str
[cur
];
}
}
return tokens
;
}
</script
>
</body
>
<style
>
p
.only
{
text
-align
: center
;
font
-size
: 2.5em
;
color
: #ce1818
;
}
main
{
display
: flex
;
flex
-wrap
: wrap
;
justify
-content
: center
;
}
textarea
,
button
{
font
-family
: 'Noto Serif SC', STFangSong
, serif
;
font
-size
: 17px
;
}
</style
>
</html
>
使用方法
直接创建一个html文件,复制粘贴代码块,然后打开html文件即可。
效果图
转载请注明原文地址:https://blackberry.8miu.com/read-41516.html