index.jison
%lex
%%
/* 词法分析 */
"$$" return 'DOLLAR'
"$" return 'DEFINE'
"(" return '('
")" return ')'
"{" return '{'
"}" return '}'
":" return ':'
"," return ','
";" return ';'
(\r\n|\n|\r) return 'EOL'
[ \t\v\b\f]+ return 'SPACES'
[_a-zA-Z0-9]+ return 'KEYWORDS'
[^{] return '^{'
[^$\r\n]+ return 'WORDS'
/lex
/* 语法定义 */
%start document
%%
/* 语法分析 */
document:
statements {
console.log($$);
}
;
statements:
statement {
$$ = $1;
}
| statements statement {
$$ = $1 + $2;
}
;
statement:
function
| DOLLAR {
$$ = "$";
}
| '(' | ')'
| '{' | '}' | '^{'
| ':' | ';' | ',' | EOL
| KEYWORDS | WORDS {
$$ = yytext;
}
;
function:
/* 替换标记1 */
DEFINE KEYWORDS ';' {
if(funs.has($2)) {
$$ = funs.get($2)();
} else {
$$ = "----Undefined function " + $2 + "!----";
}
}
/* 替换标记2 */
| DEFINE KEYWORDS '(' ')' {
// fun = $2
// arg = $4
if(funs.has($2)) {
$$ = funs.get($2)();
} else {
$$ = "----Undefined function " + $2 + "!----";
}
}
/* 行内标记 */
| DEFINE KEYWORDS '(' parameter ')' '^{' {
// fun = $2
// arg = $4
// more = $6
if(funs.has($2)) {
$$ = funs.get($2)($4) + $6;
} else {
$$ = $6 + "----Undefined function " + $2 + "!----";
}
}
/* 块标记 */
| DEFINE KEYWORDS '(' parameter ')' '{' content '}' {
// fun = $2
// arg = $4
// content = $7
if(funs.has($2)) {
$$ = funs.get($2)($4, $7);
} else {
$$ = "----Undefined function " + $2 + "!----";
}
}
;
parameter:
KEYWORDS {
$$ = yytext;
}
;
content:
text {
$$ = $1;
}
| content text {
$$ = $1 + $2;
}
;
text:
'^{'
| KEYWORDS
| WORDS
| SPACES
| EOL {
$$ = yytext;
}
;
input.txt
--------------
$$
(){}:;
_abc
--------------
123$name()456
123$name;456
123$name2()456
123$name2;456
--------------
***$meta(abc)***
--------------
$head(1233){
内
容
}
--------------
package.json
{
"name": "hello_jison",
"scripts": {
"build_text": "jison src/text/index.jison -o dist/text.js",
"dev_text": "node dist/text.js src/text/input.txt"
}
}