OCaml中#符号含义咨询:生成文件内#代码解析
# Lines in Your Generated OCaml Lexer File Hey there! Let's clear up the confusion around those strange #-prefixed lines in your generated lexer file. First, let's properly format the code snippet you shared to make it easier to parse:
match Lexing.engine __ocaml_lex_tables __ocaml_lex_state lexbuf with | 0 -> # 81 "lexer.mll" ( TOK_EOF ) # 239 "lexer.ml" | 1 -> # 82 "lexer.mll" ( new_line lexbuf; TOK_WHITE ) # 244 "lexer.ml"
What do those # directives mean?
These are compiler position markers automatically generated by ocamllex (the OCaml lexer generator) when it translates your .mll source file into a .ml implementation file. Here's a breakdown of each part:
# 81 "lexer.mll"tells the OCaml compiler: "The code that follows corresponds to line 81 of the originallexer.mllsource file".- The code between these markers (like
(TOK_EOF)or(new_line lexbuf; TOK_WHITE)) is the actual logic you wrote in your.mllfile's lexing rules. # 239 "lexer.ml"switches the compiler's position tracking back to line 239 of the generated.mlfile, whereocamllexinserts its own internal code to handle the lexer engine.
Why are they there?
The key purpose is error reporting clarity. When your lexer has a compile-time error or a runtime issue, these markers let the compiler point you directly to the line in your original .mll file (the one you actually edit) instead of the auto-generated .ml file. Without these markers, error messages would reference lines in the messy, machine-written .ml file, making it way harder to track down problems.
Are they expected?
Absolutely! These are normal, automatic output from ocamllex. You never need to edit these lines manually—just ignore them and focus on your .mll source file.
内容的提问来源于stack exchange,提问作者Enrico Borba

