Search code examples
haskellparsec

Understanding SourceName in Parsec


I have a question regarding the meaning of SourceName in parse function in Parsec. It seems that all books/blogs/tutorials I read just skip what it is and use "stdin", "(stdin)" or an arbitrary string such as "test parser". Does it make any difference what is specified as a SourceName?

I tried to read the source code of Parsec and it seems that it is used for creating a position. But why does it matter what source it is (as a String indeed). It sounds that I do not need to worry about it in most cases.

Thanks in advance!


Solution

  • In Parsec, SourceName is a String that's used for generating error messages. When in the REPL, this is not very important:

    λ> parse expression "<stdin>" ")"
    Left "<stdin>" (line 1, column 1):
    unexpected ")"
    expecting expression
    

    If we used "foo" instead of "<stdin>", if would look like this instead:

    Left "foo" (line 1, column 1):
    unexpected ")"
    expecting expression
    

    This is useful when writing a program that takes multiple files as input, like a compiler or interpreter. For example, in my interpreter, I have the following function:

    runFile :: FilePath -> IO ()
    runFile path = do code  <- readFile path
                      start <- prelude
                      evalString path start code >>= putStrLn
    

    Here I'm passing path—the path of the file you're running—into the function which parses the expression. This way, the error message will tell you which file has the parse error, along with the line numbers.

    λ> runFile "/Users/tikhon/tmp/foo.tpl"
    Error: "/Users/tikhon/tmp/foo.tpl" (line 1, column 1):
    unexpected ')'
    expecting expression or end of input!