debugModerate
Break keyword outside a loop is syntax error or semantic error?
Viewed 0 times
errorkeywordloopsyntaxoutsidesemanticbreak
Problem
I am designing a simple compiler for my university project. In my programming language, the break keyword is allowed.
I want to know whether break keyword occurs outside a loop should be a syntax error or semantic error. I want to know what is the best approach.
If it is a syntax error I can do it in the grammar file. But if it is a semantic one then I can do it in a pass. But I don't know which one is the better approach.
I want to know whether break keyword occurs outside a loop should be a syntax error or semantic error. I want to know what is the best approach.
If it is a syntax error I can do it in the grammar file. But if it is a semantic one then I can do it in a pass. But I don't know which one is the better approach.
Solution
Both work, so how you do it is up to you. But there are a couple of reasons to consider doing it during a post-parse analysis:
-
While it is certainly possible to define two different types of
-
Detecting the error in a post-parse scan will allow you to produce better error messages. Rather than just presenting the user with some kind of
-
While it is certainly possible to define two different types of
block, one in which break is legal and the other one in which it isn't, the result is a lot of duplication in the grammar, and a certain complication because you have to allow break inside blocks which are themselves contained inside a looping construct. If you allow compound statements without explicit blocks, like if (condition) break;, then you also need to define different if statements, etc. This rapidly gets out of hand unless you have a tagged formalism like that used in ECMAScript.-
Detecting the error in a post-parse scan will allow you to produce better error messages. Rather than just presenting the user with some kind of
syntax error message (which might be "unexpected token 'break'"), you can actually provide a meaningful error message like "'break' statement cannot be used outside of a loop."Context
StackExchange Computer Science Q#136292, answer score: 13
Revisions (0)
No revisions yet.