前言
前些天偶然看到以前寫的一份代碼,注意有一段塵封的代碼,被我遺忘了,這段代碼是一個簡單的決議器,當時是為了決議日志而做的,最初決議日志時,我只是簡單的正則加上分割,寫著寫著,我想,能不能用一個簡單的方案做個決議器,這樣可以決議多種日志,于是就有了這段代碼,后來日志決議完了,沒有決議其它日志就給忘了,再次看到這段代碼,用非常簡單易讀的代碼就實作了一個決議器,覺得非常值得分享,
思路
言歸正傳,這個簡單的決議器是怎么構思的呢?那要先從模式匹配開始,決議與模式匹配有很多相似之處,比如決議一個整數,跟匹配一個整數就是相似的,都需要根據整數的文法 0|[1-9]\d* 把文本中滿足文法的部分找出來,不同的是,當說到決議整數的時候,我們希望得到的結果是一個整數,而不是一段文本,更進一步,如果我們已經知道如何決議整數,那么決議加減運算式又可以看到一些相似性,加減運算式的文法可以表示為 num ('+'|'-' num)*,就像文本模式匹配一樣,需要對一些“東西”的到達順序、重復次數、分支進行匹配,
從上面的描述可以看出,我們要做的是某種模式匹配,模式匹配的明星非正則運算式莫數,觀察正則運算式,我們基本的需求都有啥?比如有,匹配一個字符或者按順序出現的字符,好了,就從這兩點出發,我們可以設計兩個函式,一個 match 函式用來匹配單個字符,一個 seq 函式表示按順序匹配,顯然,多個 match 就可以形成 seq,seq 是一個高階函式,但是,seq 是直接組合 match 嗎?當然不是,因為 match 需要一個引數,表示需要匹配的字符是哪個,所以 match 也是一個高階函式,而 seq 需要 match 產生的函陣列合成新函式,即 seq([match('a'), match('b'), match('c')]),那 match 和 seq 生成的函式是什么?答案是匹配器,允許我們直接對文本進行匹配:
const match_a = match('a');
match_a('abc');
const match_abc = seq([match('a'), match('b'), match('c')]);
match_abc('abc');
由于我們要組合函式,所以匹配器不是只簡單回傳 bool 值,這樣組合程序中,狀態會丟失,我們讓匹配器回傳兩個值:一個是匹配后剩余的字串;一個是匹配是否成功,于是我們就有了:
declare type Matcher = (src: string) => [string, bool];
function match(ch): Matcher {
return src =https://www.cnblogs.com/1bite/archive/2023/03/26/> {
if (src.startsWith(ch)) return [src.substring(1), true];
return [src, false];
};
}
// 順序匹配,其中一個失敗則整體失敗
function seq(steps: Matcher[]): Matcher {
return src => {
for (const step of steps) {
const [rest, ok] = step(src);
if (!ok) return [src, false];
src = rest;
}
return [src, true];
};
}
試試看,
const match_a = match('a');
console.log(...match_a('abc')); // "bc" true
console.log(...match_a('def')); // "def" false
const match_abc = seq([match('a'), match('b'), match('c')]);
match_abc('abc');
console.log(...match_abc('abc')); // "" true
console.log(...match_abc('abd')); // "abd" false
妙極了!

擁抱正則運算式
接下來,我們可以在這個基礎上實作正則運算式的其它模式,比如:
alt,候選串列,串列中有一個匹配成功則成功,一個失敗則整體失敗,對應正則運算式中是|和[],opt,可選,對應正則表達的?模式,many,多次重復,對應正則運算式中的*模式,
其它不一一列舉,如果繼續下去,應該能實作一個自己的正則運算式,但不是我們的目標,我想先回到“決議”上,
觀察 match 函式,它只能匹配一個字符,如果要匹配多個則要使用 seq 進行組合,不是很方便,既然正則運算式可以進行文本匹配,我們沒有必要重復正則運算式的作業,直接利用它就好,所以,我們可以把正則運算式作為 match 的引數:
function match(pattern: RegExp): Matcher {
// ...
}
決議
前面說過,決議整數的結果是整數而不是長得像整數的字串,因此,Matcher 不能回傳 bool,而應該是某個“結果”,所以 Matcher 的簽名應該是 (src: string) => [string, any],怎么把文本變成那個“結果”呢,可以在 match 后面加一個回呼,表示匹配到了文本后,應該如何處理這個文本,顯然,這個回呼的輸入引數是匹配到的文本,輸出是“結果”,即 (token: string) => any,我們把這個回呼函式取名為 Action,
如果現在嘗試去改 match 函式,就會發現一個問題,seq 函式也回傳 Matcher,但這個匹配器執行后應該回傳什么“結果”呢?為解決這個問題,我們也需要給 seq 函式添加 Action,只不過 seq 函式的 Action 的輸入引數是一個串列,還有,匹配成功后,我也可以不做任何動作,此時把匹配的文本繼續往下傳即可,現在我們再修改代碼:
declare type Matcher = (src: string) => [string, any];
declare type Action = (val: any) => any;
function noop(tok: any){ return tok; }
// 用 `pattern` 匹配文本的開頭
function match(pattern: RegExp, action: Action = noop): Matcher {
return src =https://www.cnblogs.com/1bite/archive/2023/03/26/> {
const m = pattern.exec(src);
if (!m || m.index !== 0) throw new Error(`unexpected token'${src[0]}'`);
const rest = src.substring(m[0].length);
return [rest, action(m[0])];
};
}
// 順序匹配,其中一個失敗則整體失敗
function seq(steps: Matcher[], action: Action = noop): Matcher {
return src =https://www.cnblogs.com/1bite/archive/2023/03/26/> {
const list: any[] = [];
for (const step of steps) {
const [rest, val] = step(src); // `step` 函式會 `throw`,因此一個失敗整體就會失敗
src = rest;
list.push(val);
}
return [src, action(list)];
};
}
玩玩看:
const match_helloworld = seq([match(/hello/), match(/ /), match(/world/)]);
console.log(...match_helloworld('hello world')); // "" ["hello", " ", "world"]
console.log(...match_helloworld('helloworld')); // Error: unexpected token 'w'
還是妙,但目前為止還算常規,跟正則運算式差不多,那么,接下來看下面這個例子:
const int = match(/0|[1-9]\d*/, Number); // 用整數的文法匹配文本,并把匹配到的文本直接轉成 js 的 `number`
// 根據文法 `int('+'|'-')int` 進行匹配,并根據中間 token 進行計算
const Exp = seq([int, match(/\+|\-/), int], toks => {
if (toks[1] === '+') return toks[0] + toks[2]; // 因為 `int` 函式回傳的是 `number`,所以這里可以直接進行計算!
if (toks[1] === '-') return toks[0] - toks[2];
return toks;
});
console.log(...Exp('1+2')); // "" 3
console.log(...Exp('5-3')); // "" 2
現在是不是更妙了,

完全體
光有 seq 可不能滿足決議的全部需求,還得要把其它模式加進來,我就不一一說明其它模式的實作方法了,直接給出全部代碼,相信看代碼也很好理解:
declare type Matcher = (src: string) => [string, any];
declare type Action = (val: any) => any;
function noop(tok: any){ return tok; }
// 原來的 `match` 函式,改了個名字
function token(pattern: string|RegExp, action: Action = noop): Matcher {
if (pattern instanceof RegExp) {
return (src) => {
if (src.length === 0) throw new SyntaxError("Unexpected EOS");
const regex = new RegExp(pattern.source[0] === '^' ? pattern.source : '^' + pattern.source);
const m = regex.exec(src);
if (!m || m.index !== 0)
throw new SyntaxError(`Unexpected token '${src[0]}', expected: ${pattern}`);
const rest = src.substring(m[0].length);
return [rest, action(m[0])];
};
} else if (typeof pattern === "string") {
return (src) => {
if (src.length === 0) throw new SyntaxError("Unexpected EOS");
if (!src.startsWith(pattern))
throw new SyntaxError(`Unexpected token '${src[0]}', expected: ${pattern}`);
const rest = src.substring(pattern.length);
if (action) return [rest, action(pattern)];
return [rest, pattern];
};
}
throw Error("pattern must to be instance of string or RegExp");
}
// 順序匹配,其中一個失敗則整體失敗
function seq(steps: Matcher[], action: Action = noop): Matcher {
return src =https://www.cnblogs.com/1bite/archive/2023/03/26/> {
const list: any[] = [];
for (const step of steps) {
const [rest, val] = step(src); // `step` 函式會 `throw`,因此一個失敗整體就會失敗
src = rest;
list.push(val);
}
return [src, action(list)];
};
}
// 可選匹配
function opt(step: Matcher, action: Action = noop): Matcher {
return (src) => {
try {
const [rest, v] = step(src);
return [rest, action(v)];
} catch (err) {
return [src, undefined]; // 也許這里可以改成 `return [src, action("")]`;
}
};
}
// 候選串列匹配,串列中其中一個匹配即可
function alt(steps: Matcher[], action: Action = noop): Matcher {
return (src) => {
for (const step of steps) {
try {
const [rest, v] = step(src);
return [rest, action(v)];
} catch (_) {
// mute
}
}
throw new Error(`unknown token ${src[0]}`);
};
}
// 重復任意次數
function many(item: Matcher, action: (vals: any[]) => any = noop): Matcher {
return src =https://www.cnblogs.com/1bite/archive/2023/03/26/> {
let list: any[] = [];
let val = undefined;
while (true) {
try {
[src, val] = item(src);
list.push(val);
} catch (_) {
break;
}
}
return [src, action(list)];
};
}
// 帶分隔符的重復,即滿足 `item (sep item)*` 這種文法的
function many_sep(sep: Matcher, item: Matcher, action: (vals: any[]) => any = noop): Matcher {
const etc = seq([sep, item], vs => vs[1]);
return (src) => {
let list: any[] = [];
let val = undefined;
try {
[src, val] = item(src);
list.push(val);
} catch (_) {
return [src, action(list)];
}
// 以下邏輯也可通過呼叫 `many` 實作
while (true) {
try {
[src, val] = etc(src);
list.push(val);
} catch (_) {
break;
}
}
return [src, action(list)];
};
}
好了,直接攢個大活兒,咱們用這些東西決議 JSON 看看:
const ws = token(/\s*/);
const Sep = seq([token(','), opt(ws)], v => v[0]); // 也可以簡寫為 `token(/,\s*/)`
const Str = token(/"([^\\"]|\\[\\\/bfrtn]|\\u[0-9a-fA-F]{0})*"/, JSON.parse); // 這里使用 `JSON.parse` 算是作弊,不過用它讓演示代碼縮短了不少
const Num = token(/-?(0|[1-9]\d*)(\.\d+)?([eE][\+\-]?\d+)?/, Number);
// Elems = Val (',' Val)*
const Elems = many_sep(Sep, src =https://www.cnblogs.com/1bite/archive/2023/03/26/> Val(src));
// KVs = KV (',' KV)*
const KVs = many_sep(Sep, src =https://www.cnblogs.com/1bite/archive/2023/03/26/> KV(src));
// js 中可以直接使用 `Object.fromEntries`
function objFromKVs(kvs: [string, any][]) {
return kvs.reduce((obj, [k, v]) => { obj[k] = v; return obj; }, {} as any);
}
// Val = Str | Num |'true' | 'false' | 'null' | '[' ws Elems ws ']' | '{' ws KVs ws '}'
const Val = alt([
Str,
Num,
token(/true|false/, token => token === 'true'),
token(/null/, _ => null),
seq([token('['), ws, Elems, ws, token(']')], v => v[2]), // '[' ws Elems ws ']'
seq([token('{'), ws, KVs, ws, token('}')], v => objFromKVs(v[2] as any[])) // '{' ws KVs ws '}'
]);
// KV = Str ws ':' ws Val
const KV = seq([
Str,
ws,
token(':'),
ws,
Val,
], kv => [kv[0], kv[4]]); // 匹配 KV 串列,并轉換成 `[[key, val]...]` 的形式
// 演示
console.log(...Val('[1, 2.3e4, true, null, "\\t"]')); // "" [1, 23000, true, null, " "]
console.log(...Val('{ "k1": 123, "k2": true }')); // "" {k1: 123, k2: true}
怎么樣,相當不錯吧!!!

接下來再演示下進階版本的運算式決議與求值,支持加、減、乘、除和括號:
// Factor = '(' ws Exp ws ')' | Num
const Factor = alt([
seq([token('('), ws, src =https://www.cnblogs.com/1bite/archive/2023/03/26/> Exp(src), ws, token(')')], vals => vals[2]),
Num,
]);
// Term = Factor (ws '*|/' ws Factor)*
const Term = seq([Factor, many(seq([ws, token(/\*|\//), ws, Factor]))], ([head, tail]) => {
return (tail as any[]).reduce((acc, x) => {
if (x[1] === '*') return acc * x[3];
if (x[1] === '/') return acc / x[3];
return acc;
}, head);
});
// Exp = Term (ws '+|-' ws Term)*
const Exp = seq([Term, many(seq([ws, token(/\+|-/), ws, Term]))], ([head, tail]) => {
return (tail as any[]).reduce((acc, x) => {
if (x[1] === '+') return acc + x[3];
if (x[1] === '-') return acc - x[3];
return acc;
}, head);
});
console.log(...Exp('( 1 + 2 * 5 ) * 3')); // "" 33
總結
本文使用簡單易懂的代碼,實作了一組可以構造決議器的函式,相信通過本文的演示,你應該對決議器的基本作業原理有了一個淺淺的了解,實際上,我們實作的這一組函式是一種領域特定語言,即 DSL,雖然實作方式簡單,但不妨礙這種 DSL 的實用性,在日常的小腳本中,更加體現它的小巧、易懂、功能強大,不過也要注意的是,我是以小巧、簡易為目標實作的,所以性能不是首要目標,將本文的實作用于性能挑剔的場合肯定是不合適的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/548250.html
標籤:其他
上一篇:前端設計模式——計算屬性模式
下一篇:前端設計模式——路由模式
