Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell equivalent of C's __LINE__

Is there a way to get line-number/traceback information in Haskell?

(like C's __LINE__ macro or Python's traceback.extract_stack())

That would be of use for me for writing Haskell program that generates C++ code, which would be notated with comments telling which Haskell line is responsible for which C++ line.

Haskell example:

LINE "#include <foo.h>" -- this is line 12
: INDENT "void Foo::bar() {" "}"
    [ LINE $ "blah(m_" ++ x ++ ", \"" ++ x ++ "\");"
    | x <- ["Potato", "Avocado"]
    ]

will generate this C++ code:

#include <foo.h>                  // gen.hs:12
void Foo::bar() {                 // gen.hs:13
  blah(m_Potato, "Potato");       // gen.hs:14
  blah(m_Avocado, "Avocado");     // gen.hs:14
}                                 // gen.hs:13
like image 472
yairchu Avatar asked Feb 22 '10 20:02

yairchu


People also ask

What is __ LINE __ in C?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

How do you get the value of the current line of the source code in runtime C++?

Using __LINE__ Macro The standard solution to find the current line number in C++ is using the predefined macro __LINE__ . It returns the integer value representing the current line in the source code file being compiled. The preprocessor will simply replace the __LINE__ macro with the current line number.


1 Answers

You can actually use the CPP __LINE__ pragma in Haskell.

{-# LANGUAGE CPP #-}

main = do
    print "one"
    print __LINE__


$ runhaskell A.hs
"one"
5

Also, the Control.Exception.assert function will emit a line number if its condition fails.

import Control.Exception

main = do
    print "one"
    assert False $
        print "two"


$ runhaskell A.hs
"one"
A.hs: A.hs:5:5-10: Assertion failed
like image 63
Don Stewart Avatar answered Nov 01 '22 14:11

Don Stewart