Constant Pain

Trelane was complaining about Image::Imlib2 the other day. Apparently, it accepts any method call without error. i.e. it’s a blackhole object.

A quick inspection of the source revealed two things:

  1. An AUTOLOAD() method, to resolve unknown method calls.
  2. A constant() function in the XS to resolve names to constant values. This was being called from AUTOLOAD().

As it turned out there was a bug in constant()—it wasn’t correctly reporting constants that didn’t exist. But, a one line patch fixed things:

  diff -ruN Image-Imlib2-1.08/lib/Image/Imlib2.xs Image-Imlib2-1.08-dom/lib/Image/Imlib2.xs
  --- Image-Imlib2-1.08/lib/Image/Imlib2.xs       2006-03-01 19:11:15.000000000 +0000
  +++ Image-Imlib2-1.08-dom/lib/Image/Imlib2.xs   2006-06-17 17:25:56.000000000 +0100
  @@ -25,6 +25,7 @@
           if (strEQ(name, "TEXT_TO_ANGLE")) return IMLIB_TEXT_TO_ANGLE;
           break;
       }
  +    errno = ENOENT;
       return 0;

   not_there:

But when questioned, the author (acme) didn’t know much about why the constant() function was there at all. And it turns out both constant() and AUTOLOAD() are created automatically by h2xs. Newer versions use ExtUtils::Constant instead of doing things directly.

However, the fact is that we’re still using AUTOLOAD() to load in a bunch of things that we already know. Kind of pointless. Thankfully, Trelane was slightly more determined that I am, and wrote a proper patch getting rid of AUTOLOAD() entirely and creating individual functions for each constant. As a result, we now have Image::Imlib2 1.09.

What’s the moral of this tale? Always question code that gets autogenerated for you. You absolutely have to understand what it’s doing for you. Don’t assume that the person who wrote the generator knew more about your problem than you do.