- Learn Type:Driven Development
- Yawar Amin Kamon Ayeva
- 371字
- 2021-07-02 14:41:26
Syntax errors
Syntax errors are a basic kind of error and happen when the compiler literally can't make sense of the source code, for example:
type person = {id: int; name: string};
Can you spot the error in the preceding code? If you compare it with the person definition in src/Ch02/Ch02_Demo.re, you should be able to. In any case, the compiler will tell you (usually fairly accurately) where to look. The only problem is you'll have to learn to sift through the compiler output to find the exact error, as follows:
(Output from bsb -w)
>>>> Start compiling
Rebuilding since [ [ 'change', 'Ch02_Demo.re' ] ]
ninja: Entering directory `lib/bs'
[1/2] Building src/Ch02/Ch02_Demo.mlast
FAILED: src/Ch02/Ch02_Demo.mlast
/usr/local/lib/node_modules/bs-platform/lib/bsc.exe -pp "/usr/local/lib/node_modules/bs-platform/lib/refmt3.exe –print binary" -w -30-40+6+7+27+32..39+44+45+101 -warn-error +3 -bs-suffix -nostdlib -I '/Users/yawar/src/learning-tydd-reason/node_modules/bs-platform/lib/ocaml' -no-alias-deps -color always -c -o src/Ch02/Ch02_Demo.mlast -bs-syntax-only -bs-binary-ast -impl /Users/yawar/src/learning-tydd-reason/src/Ch02/Ch02_Demo.re
File "/Users/yawar/src/learning-tydd-reason/src/Ch02/Ch02_Demo.re", line 2, characters 23-24:
Error: 438: <UNKNOWN SYNTAX ERROR>
File "/Users/yawar/src/learning-tydd-reason/src/Ch02/Ch02_Demo.re", line 1, characters 0-0:
Error: Error while running external preprocessor
Command line: /usr/local/lib/node_modules/bs-platform/lib/refmt3.exe –print binary '/Users/yawar/src/learning-tydd-reason/src/Ch02/Ch02_Demo.re' > /var/folders/xg/6jbw_1bj5h35b4lt7rygs12w0000gn/T/ocamlppf72c18
ninja: error: rebuilding 'build.ninja': subcommand failed
>>>> Finish compiling(exit: 1)
Syntax errors start with the text File "/path/to/file", line L, characters C1-C2: (where L, C1, and C2 are the actual line and character numbers). The error message, <UNKNOWN SYNTAX ERROR>, is not too helpful, but the line and character positions pinpoint the location pretty well. Confusingly, there is also another error message starting in the same way, but this time with line 1 and characters 0-0: Error while running external preprocessor. This is Reason's way of redundantly saying it couldn't understand the code, and is hopefully going away soon!
In our example, the error points at the 23rd and 24th characters, where you see a semicolon and space; if you compare that with the correct version of the code, you see that it should be a comma and space.
When you're starting out with Reason, you should expect to see more of these syntax errors, and to spend some time working through exactly why they're happening. As you learn the syntax, you can expect to be able to tell just by looking at it that a piece of code doesn't contain the correct syntax. The correct syntax is available in Reason's excellent reference documentation.