JavaCC的簡單例子

來源:互聯網
上載者:User

 JavaCC附帶的例子是尋找匹配的花括弧個數的,我寫的例子在它的基礎上稍微延伸,可以實現對多行的處理,每行的資訊都能表現出來。

 

options{
 STATIC = false;
 }

PARSER_BEGIN(Simple2)

public class Simple2 {
 public static int lineNumber = 0;

  public static void main(String args[]) throws ParseException {
    Simple2 parser = new Simple2(System.in);
    parser.Run();
    System.out.println("Total Line = "+ (lineNumber+1));//計算行數
  }

}

PARSER_END(Simple2)

SKIP :
{
  " "
| "/t"
| "/r"
}

TOKEN:
{
<NEWLINE : "/n">//考慮到系統不同,僅選擇對/n標記
{
 Simple2.lineNumber++; //因為此處是在TokenManager處理需要標識範圍
}
}

void Run():{}
{
 ( Input() )*<EOF>
}

void Input() :
{
 int count;
}
{
  ( count = MatchedBraces() )+ (<NEWLINE>)*
  {System.out.println("This line:" + count);}
}

int MatchedBraces() :
{ int nested_count = 0;}
{
  "{" [ nested_count = MatchedBraces() ] "}"
  { return ++nested_count; }
}

不足的地方時,如此寫法會出現冗餘代碼,原因在MatchedBraces函數中的花括弧出現,因此待我研究明白LOOKAHEAD之後再做改進。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.