函式名:Parle\RLexer::insertMacro()
適用版本:Parle 0.7.1 及以上版本
用法:Parle\RLexer::insertMacro() 函式用於向詞法分析器中插入宏定義。宏定義是一種將特定的輸入序列替換為指定的輸出序列的規則。透過插入宏定義,可以在詞法分析過程中對輸入進行預處理,從而簡化後續的詞法分析工作。
引數:
- $symbol (string):宏定義的名稱。
- $expansion (string):宏定義的替換序列。
示例:
// 建立詞法分析器
$lexer = new Parle\RLexer();
// 插入宏定義
$lexer->insertMacro('VERSION', '1.0');
$lexer->insertMacro('GREETING', 'Hello, world!');
$lexer->insertMacro('MULTIPLY', '2 * 3');
// 使用插入的宏定義
$input = 'The current version is VERSION.';
$input = $lexer->expandMacros($input);
echo $input; // 輸出:The current version is 1.0.
$input = 'Say GREETING.';
$input = $lexer->expandMacros($input);
echo $input; // 輸出:Say Hello, world!.
$input = '2 * 3 equals MULTIPLY.';
$input = $lexer->expandMacros($input);
echo $input; // 輸出:2 * 3 equals 6.
注意事項:
- 插入的宏定義可以是任意字串,可以包含變數、函式呼叫等。
- 插入的宏定義會在詞法分析過程中被替換為對應的替換序列。
- 可以使用 Parle\RLexer::expandMacros() 方法對輸入進行宏展開,得到替換後的結果。
- 插入的宏定義僅在當前的詞法分析器物件中有效,不會影響其他詞法分析器物件。
- 如果需要移除已插入的宏定義,可以使用 Parle\RLexer::removeMacro() 方法。