F# and Line/File/Directory macros

I learned how to program in C a long time ago (maybe 1992?). When diagnosing issues, I got accustomed to being able to have an exception or other message targeted at a developer to explain where the message came from. I could review the logs an know where the message was printed in the build of the system that the user had running. Using this power, I could get context with an otherwise uninformative message like

got here __FILE__:__LINE__

In 2001, I moved into .NET full time. I got garbage collection, assemblies, reflection, and so much else. I lost __FILE__ and __LINE__. I learned to push out PDBs to get file and line information when I needed it in exceptions. But, I couldn’t push those files out to production. I learned to use SOS with WinDBG and a collection of symbols to debug production issues, and I moved on. As I write this, I’m reading the F# spec. Guess what I saw in section 3.11 of the spec?

The following identifiers are automatically replaced by values in F# code:

__SOURCE_DIRECTORY__ replaced by a literal verbatim string, e.g. C:source
__SOURCE_FILE__ replaced by a literal verbatim string of the filename as given to the command line compiler or on a load line, e.g. sourcefile.fs, after taking into account adjustments from line directives.
__LINE__ replaced by a literal string giving the line number in the source file, after taking into account adjustments from line directives.

Here is an example of printing these values to the console.


    1 #light


    3 printfn “Source Directory: %s”  __SOURCE_DIRECTORY__

    4 printfn “Source File: %s” __SOURCE_FILE__

    5 printfn “Line: %s” __LINE__

The resulting output:

Source Directory: C:UsersScott SeelyDocumentsVisual Studio 2008ProjectsCloudService1TestApp
Source File: C:UsersScott SeelyDocumentsVisual Studio 2008ProjectsCloudService1TestAppProgram.fs
Line: 5

This is too freaking awesome! It is such a simple tool for diagnostics and it does so much. I was worried that the whole exercise in learning F# would really be some form of mental masturbation. So far, I’m seeing some real plusses. I’m also having fun.

%d bloggers like this: