I need to count the number of classes in correct C# source file. I wrote the following grammar:
grammar CSharpClassGrammar;
options
{
language=CSharp2;
}
@parser::namespace { CSharpClassGrammar.Generated }
@lexer::namespace { CSharpClassGrammar.Generated }
@header
{
using System;
using System.Collections.Generic;
}
@members
{
private List<string> _classCollector = new List<string>();
public List<string> ClassCollector { get { return
_classCollector; } }
}
/*------------------------------------------------------------------
* PARSER RULES
*------------------------------------------------------------------*/
csfile : class_declaration* EOF
;
class_declaration
: (ACCESSLEVEL | MODIFIERS)* PARTIAL? class CLASSNAME
class_body
; ?
{ _classCollector.Add($CLASSNAME.text); }
;
class_body
: { class_declaration* }
;
/*------------------------------------------------------------------
* LEXER RULES
*------------------------------------------------------------------*/
ACCESSLEVEL
: public | internal | protected | private | protected
internal
;
MODIFIERS
: static | sealed | abstract
;
PARTIAL
: partial
;
CLASSNAME
: ( a .. z | A .. Z | _ ) ( a .. z | A .. Z | 0 .. 9 | _ )*
;
COMMENT
: // ~(
|
)* {$channel=HIDDEN;}
| /* ( options {greedy=false;} : . )* */ {$channel=HIDDEN;}
;
WHITESPACE
: ( | |
|
| u000C )+ { $channel = HIDDEN; }
;
此解析器正确地计算具有空类主体的空类(以及嵌套类):
internal class DeclarationClass1
{
class DeclarationClass2
{
public class DeclarationClass3
{
abstract class DeclarationClass4
{
}
}
}
}
我需要计算不为空的类,例如:
class TestClass
{
int a = 42;
class Nested { }
}
I need to somehow ignore all the code that is "not a class declaration". In the example above ignore
int a = 42;
How can I do this? May be example for other language?
Please, help!