Astronomize
Astronomize

Reputation: 31

Is it possible to get the closing curly bracket for an opening curly bracket from a list of strings/tokens?

I am trying to make a programming language in c#, so I have a list of tokens. I loop through that list of tokens to find grammar, and in doing this, upon discovering an opening curly bracket, I would like to find the most accurate closing bracket to match the opening bracket.

For this example there would be a list of tokens of every symbol and keyword, knowing that, let's move on...

Here is the example:

The red arrow is what would happen if I got the nearest closing bracket, and the green arrow would be what would happen if I found a way to accurately find a closing curly bracket.

Does anyone know how I would go about doing this?

please keep in mind my project is in C# so if you have any samples in C# that would be great, thanks!

Upvotes: 1

Views: 172

Answers (1)

Cee McSharpface
Cee McSharpface

Reputation: 8725

The internal representation of your language's source code needs to (as all software does) model reality. Your example is nesting blocks delimited by braces. So the next step is to build a syntax tree. The matching closing bracket (if represented in the abstract syntax tree at all) would then always be the last node in each subtree at the same level as the first:

compilation_unit  
  class_definition
  block_start[1]
    method_definition
    block_start[2]
      conditional_expression
      block_start[3]
        function_call
      block_end[3]
    block_end[2]
  block_end[1]

Upvotes: 1

Related Questions