When you are comparing programming languages to human languages (which the OP is implicitly doing), the best way to think about it is this:
- Syntax is the set of valid words (and correct spelling of those words) that make up a language, and how to identify proper nouns (i.e. names)
- Grammar is how those words should be structured to make sense
In computer science explicitly, source code is tokenized. For example, there may be a single numerical value that represents a keyword, and a separate one for an open parenthesis. Computers are not restricted in what can be considered a token like human languages are.
The string of tokens then has to conform to certain patterns in order to generate the machine code that the CPU understands. For example, the grammar of a language dictates whether object.verb()
is meaningful in the language, and what should happen.
When the parser cannot generate a valid token for any given part of the source code, the parser itself will generate a syntax error. If done well, it will also include enough information to find the offending code (for example a line number).
When you have valid syntax, your lexer will attempt to make sense of those tokens and generate the machine code. If there is an error in this stage, you will commonly get a generic compilation error (hopefully with a line number).