Syntax Analysis
Syntax analysis is the compilation stage that immediately follows lexical analysis. Once tokens have been assigned to the code elements, the compiler checks that the tokens are in the correct order and that they follow the rules of the programming language being used.
Rules of language
In Python, the command print(user_name)
is syntactically correct because it follows the rules for a print statement:
- Print in lower case
- Immediately followed by a left-hand bracket
- Followed by an identifier
- Closed by a right-hand bracket
This is no different from natural languages like English. For example, the sentence “he Moved wearily” fails on three syntax points:
- Start with a capital letter
- Followed by lower case letters
- End with a full stop
The syntax rules for programming languages are limited, but must be followed.
Syntax rules differ between languages:
if a > b:
is syntactically correct in Pythonif a > b
is not syntactically correct in Python — the rule for using a colon is brokenif (a == b)
is syntactically correct in Javaif (a = b)
is not syntactically correct in Java — a single equals sign is not a conditional operator