L
L
Light-Effect2020-06-19 13:37:46
Algorithms
Light-Effect, 2020-06-19 13:37:46

Is there a simple algorithm for parsing blocks of code?

Is there any parsing algorithm for this example:

function testA(a, b) {
    if (a === 1) {
        switch (b) {
            case 1:
                return;
        }
    }
}


The algorithm is interested in getting the content in each curly braces. Example:

1:
{
    if (a === 1) {
        switch (b) {
            case 1:
                return;
        }
    }
}

2.

{
        switch (b) {
            case 1:
                return;
        }
    }

3.

{
            case 1:
                return;
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Shamanov, 2020-06-19
@SilenceOfWinter

js linter is needed to parse into tokens. if you farm, then the simplest algorithm is to split the regular expression into tokens, then look for pairs of brackets in the loop - i.e. each element of the array is the coordinates (string, character) of the beginning and end of the block

W
Wataru, 2020-06-19
@wataru

You need to match each opening parenthesis with a matching closing one.
In the simplest case, this is done in one pass through the text with the stack.
We met an opening bracket - put its position on the stack. We met the closing one - we take out the last position from the stack. The piece from this position to the current one is your code block.
This algorithm in your example will display exactly what you need, but the pieces will be in reverse order, sorted by the right edge. If you need to sort exactly as you indicated, then you need to expand the algorithm - go from the end and put closing brackets on the stack.
You can complicate the algorithm if you need to do some kind of syntax check. Then you will have to, first, split the text into tokens. Secondly, put all sorts of different opening tokens on the stack. For example, '[', '(' in C or "begin" in Pascal will also go there. Then, when any closing token is encountered, you need to check that the correct opening token is at the top of the stack.
It is also important not to forget that with an incorrect input code, you may run out of stack prematurely. For example: "{a};}{". Here, when you get to the second parenthesis, you will have an empty stack. This means that the text is invalid.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question