Allow Whitespace sections ANTLR4

醉酒当歌 提交于 2019-11-27 09:10:48

This is how I solved the problem at the end:

The idea is to enable/disable whitespace in a parser rule:

 templateBody : {enableWs();} templateChunk* {disableWs();};

So we will have to define enableWs and disableWs in our parser base class:

public void enableWs() {
    if (_input instanceof MultiChannelTokenStream) {
        ((MultiChannelTokenStream) _input).enable(HIDDEN);
    }
}

public void disableWs() {
    if (_input instanceof MultiChannelTokenStream) {
        ((MultiChannelTokenStream) _input).disable(HIDDEN);
    }
}

Now what is this MultiChannelTokenStream?

  • Antlr4 defines a CommonTokenStream which is a token stream reading only from one channel.
  • MultiChannelTokenStream is a token stream reading from the enabled channels. For implementation I took the source code of CommonTokenStream and replaced each reference to the channel by channels (equality comparison gets contains comparison)

An example implementation with the grammar above could be found at antlr4multichannel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!