Answer the question
In order to leave comments, you need to log in
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;
}
}
}
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
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
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 questionAsk a Question
731 491 924 answers to any question