Search code examples
c#compiler-construction

Checking open parenthesis close parenthesis in c#


I am creating a compiler.

When I write input code for my compiler, if there is a missing parenthesis, the compiler should show an error. For that I use this code:

Stack<int> openingbraces = new Stack<int>();
string output = string.Empty;

for (int i = 0; i < MELEdtior.Length; i++)
{
    if (MELEdtior[i] == '{')
    {
        openingbraces.Push(i);
        output="close braces missing";
    }
    else if (MELEdtior[i] == '}')
    {
        openingbraces.Push(i);
        output = "Open Braces missing";
    }   
}
if(openingbraces.Count==2)
{
    output = "Build Successfull";
}
else
{
    output = "brace missing";
}`

When I give simple input like function{} it works perfectly. But my input is:

{global gHCIRCIN = OBSNOW("Head circumf")}
{IF gHCIRCCM <> "" AND HeadCircsDifferrev()  THEN
OBSNOW("Head circumf",str(rnd(ConvertCMtoIN(gHCIRCCM),2)))  ELSE "" ENDIF }

Here my compiler should check the correctness of all parentheses, and show an error message.

My idea to achieve this is to separate opening and closing parentheses first and then pair them, if any pair is missing, my compiler should throw an error message. How can I implement this?


Solution

  • Here is a mini program solving the problem. Based on o_weisman's comment.

    class Program {
        static void Main(string[] args) {
    
            int currentOpenBracketNum = 0;
            string message = "Brackets OK";
            string input = @"{globa} }{IF gHCIRCCM <> """" AND HeadCircsDifferrev() THEN OBSNOW(""Head circumf"",str(rnd(ConvertCMtoIN(gHCIRCCM),2))) ELSE """" ENDIF }";
    
            foreach (char c in input) {
                if (c.Equals('{')) currentOpenBracketNum++;
                else if (c.Equals('}')) {
                    if (currentOpenBracketNum > 0) {
                        currentOpenBracketNum--;
                    } else {
                        message = "Missing open bracket";
                    }
                }
            }
    
            if (currentOpenBracketNum > 0) {
                message = "Missing close bracket";
            }
    
            Console.WriteLine(message);
            Console.ReadKey(); // suspend screen
        }
    }
    

    Note: You could track if you are within " characters and exclude counting of those which is considered as string, if you want to solve the coming issue what xanatos is pointing out.