変数サポート

This commit is contained in:
syuilo 2017-02-09 20:13:44 +09:00
parent 21b72f7854
commit df5a8768ec
2 changed files with 64 additions and 8 deletions

View File

@ -80,6 +80,14 @@ const symbols = [
'~'
];
// 変数宣言
const varDef = [
'var',
'const',
'let',
'mut'
];
const elements = [
// comment
code => {
@ -122,6 +130,45 @@ const elements = [
}
},
// extract vars
(code, i, source, vars) => {
const prev = source[i - 1];
if (prev && /[a-zA-Z]/.test(prev)) return null;
const match = varDef.filter(v => code.substr(0, v.length + 1) == v + ' ')[0];
if (match) {
const bar = code.substr(match.length + 1).match(/^[a-zA-Z0-9_-]+/);
if (bar) {
if (!keywords.some(k => k == bar)) {
console.log(bar[0]);
vars.push(bar[0]);
}
}
}
return null;
},
// vars
(code, i, source, vars) => {
const prev = source[i - 1];
if (prev && /[a-zA-Z]/.test(prev)) return null;
const match = vars.sort((a, b) => b.length - a.length)
.filter(v => code.substr(0, v.length) == v)[0];
if (match) {
if (/^[a-zA-Z]/.test(code.substr(match.length))) return null;
return {
html: `<span class="var">${match}</span>`,
next: match.length
};
} else {
return null;
}
},
// number
(code, i, source) => {
const prev = source[i - 1];
@ -139,7 +186,10 @@ const elements = [
},
// keyword
code => {
(code, i, source) => {
const prev = source[i - 1];
if (prev && /[a-zA-Z]/.test(prev)) return null;
const match = keywords.filter(k => code.substr(0, k.length) == k)[0];
if (match) {
if (/^[a-zA-Z]/.test(code.substr(match.length))) return null;
@ -171,16 +221,19 @@ function genHtml(source, lang) {
let code = source;
let html = '';
function push(token) {
html += token.html;
code = code.substr(token.next);
}
let vars = [];
let i = 0;
function push(token) {
html += token.html;
code = code.substr(token.next);
i += token.next;
}
while (code != '') {
const parsed = elements.some(el => {
const e = el(code, i, source);
const e = el(code, i, source, vars);
if (e) {
push(e);
return true;
@ -193,8 +246,6 @@ function genHtml(source, lang) {
next: 1
});
}
i++;
}
return html;

View File

@ -130,6 +130,11 @@ pre > code
.number
color #ae81ff
.var:not(.keyword)
font-weight bold
font-style italic
//text-decoration underline
mk-locker
display block
position fixed