Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3874010
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T22:06:11+00:00 2026-05-19T22:06:11+00:00

I need to count the number of classes in correct C# source file. I

  • 0

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
        : '//' ~('\n'|'\r')* {$channel=HIDDEN;}
        |   '/*' ( options {greedy=false;} : . )* '*/' {$channel=HIDDEN;}
        ;

WHITESPACE
        : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; }
        ; 

This parser correctly count empty classes (and nested classes too) with empty class-body:

internal class DeclarationClass1
{
    class DeclarationClass2
    {
        public class DeclarationClass3
        {
            abstract class DeclarationClass4
            {
            }
        }
    }
}

I need to count classes with not empty body, such as:

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T22:06:11+00:00Added an answer on May 19, 2026 at 10:06 pm

    When you’re only interested in certain parts of a source file, you could set filter=true in your options { … } sections. This will enable you to only define those tokens you’re interested in, and what you don’t define, is ignored by the lexer.

    Note that this only works with lexer grammars, not in combined (or parser) grammars.

    A little demo:

    lexer grammar CSharpClassLexer;
    
    options {
      language=CSharp2;
      filter=true;
    }
    
    @namespace { Demo }
    
    Comment
      :  '//' ~('\r' | '\n')*
      |  '/*' .* '*/'
      ;
    
    String
      :  '"' ('\\' . | ~('"' | '\\' | '\r' | '\n'))* '"'
      |  '@' '"' ('"' '"' | ~'"')* '"'
      ;
    
    Class
      :  'class' Space+ Identifier 
         {Console.WriteLine("Found class: " + $Identifier.text);}
      ;
    
    Space
      :  ' ' | '\t' | '\r' | '\n'
      ;
    
    Identifier
      :  ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*
      ;
    

    It’s important you leave the Identifier in there because you don’t want Xclass Foo to be tokenized as: ['X', 'class', 'Foo']. With the Identifier in there, Xclass will become the entire identifier.

    The grammar can be tested with the following class:

    using System;
    using Antlr.Runtime;
    
    namespace Demo
    {
        class MainClass
        {
            public static void Main (string[] args)
            {
                string source = 
    @"class TestClass
    {
        int a = 42;
    
        string _class = ""inside a string literal: class FooBar {}..."";
    
        class Nested { 
            /* class NotAClass {} */
    
            // class X { }
    
            class DoubleNested {
                string str = @""
                    multi line string 
                    class Bar {}
                "";
            }
        }
    }";
                Console.WriteLine("source=\n" + source + "\n-------------------------");
                ANTLRStringStream Input = new ANTLRStringStream(source);
                CSharpClassLexer Lexer = new CSharpClassLexer(Input);
                CommonTokenStream Tokens = new CommonTokenStream(Lexer);
                Tokens.GetTokens();
            }
        }
    }
    

    which produces the following output:

    source=
    class TestClass
    {
        int a = 42;
    
        string _class = "inside a string literal: class FooBar {}...";
    
        class Nested { 
            /* class NotAClass {} */
    
            // class X { }
    
            class DoubleNested {
                string str = @"
                    multi line string 
                    class Bar {}
                ";
            }
        }
    }
    -------------------------
    Found class: TestClass
    Found class: Nested
    Found class: DoubleNested
    

    Note that this is just a quick demo, I am not sure if I handled the proper string literals in the grammar (I am unfamiliar with C#), but this demo should give you a start.

    Good luck!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to read a large space-seperated text file and count the number of
I need to count the number of lines in a file, in a UNIX
I need to count the number of rows returned from database.By using following code
I need to get a count of the number of files in a directory.
I need to pass a variable number of strings to instantiate different classes. I
I need to count number of words including special characters like % ,$ in
I need to count the number of characters rendered in an H1 tag. Is
I need to count the number of views of an asset, this asset being
I need a function count_permutations() that returns the number of permutations of a given
Essentially I need a count of each Entries Comments: SELECT e.*, COUNT(c.id) as comments

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.