簡體   English   中英

使用ANTLR解析JavaScript正則表達式

[英]Parsing JavaScript regex with ANTLR

我有一個ANTLR JavaScript語法(取自Internet),它似乎支持除正則表達式文字之外的所有內容。

正則表達式文字的問題在於你有兩個規則,基本上:

multiplicativeExpression
    : unaryExpression (LT!* ('*' | '/' | '%')^ LT!* unaryExpression)*

regexLiteral
    : '/' RegexLiteralChar* '/'

規則RegexLiteralChar使用不同於正常表達式的詞法規則(例如,雙引號不會終止它)。

這意味着我需要以某種方式從我的解析器中改變某種詞法分析器狀態。 我怎樣才能做到這一點? 它甚至可能嗎?

看看Bart Kiers 評論中提到的語法,你可以看到這個評論,

定義這種語法面臨的主要挑戰是:

-1-與乘法表達式和正則表達式文字相關的DIV符號周圍的歧義。 這是通過一些詞法分析器驅動的魔法來解決的:門控語義謂詞根據RegularExpressionsEnabled屬性的值打開或關閉正則表達式的識別。 啟用正則表達式時,它們優先於除法表達式。 是否啟用正則表達式的決定是基於前一個令牌可被視為除法的左側操作數的最后一個令牌的啟發式算法。

...

areRegularExpressionsEnabled()函數定義為,

private final boolean areRegularExpressionsEnabled()
{
    if (last == null)
    {
        return true;
    }
    switch (last.getType())
    {
    // identifier
        case Identifier:
    // literals
        case NULL:
        case TRUE:
        case FALSE:
        case THIS:
        case OctalIntegerLiteral:
        case DecimalLiteral:
        case HexIntegerLiteral:
        case StringLiteral:
    // member access ending 
        case RBRACK:
    // function call or nested expression ending
        case RPAREN:
            return false;
    // otherwise OK
        default:
            return true;
    }
}

然后該函數用於RegularExpressionLiteral表達式,

RegularExpressionLiteral
    : { areRegularExpressionsEnabled() }?=> DIV RegularExpressionFirstChar RegularExpressionChar* DIV IdentifierPart*
    ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM