allow adding #line directives
Jesse Luehrs [Wed, 20 Oct 2010 21:59:21 +0000 (16:59 -0500)]
lib/Eval/Closure.pm
t/03-description.t [new file with mode: 0644]

index c2a4387..5094d0a 100644 (file)
@@ -17,6 +17,9 @@ sub eval_closure {
     $args{source} = _canonicalize_source($args{source});
     _validate_env($args{environment} ||= {});
 
+    $args{source} = _line_directive($args{description}) . $args{source}
+        if defined $args{description};
+
     my ($code, $e) = _clean_eval_closure(@args{qw(source environment name)});
 
     croak("Failed to compile source: $e\n\nsource:\n$args{source}")
@@ -65,6 +68,12 @@ sub _validate_env {
     }
 }
 
+sub _line_directive {
+    my ($description) = @_;
+
+    return qq{#line 1 "$description"\n};
+}
+
 sub _clean_eval_closure {
     # my ($source, $__captures, $name) = @_
     my $__captures = $_[1];
diff --git a/t/03-description.t b/t/03-description.t
new file mode 100644 (file)
index 0000000..781ec72
--- /dev/null
@@ -0,0 +1,38 @@
+#!/usr/bin/env perl
+use strict;
+use warnings;
+use Test::More;
+use Test::Exception;
+
+use Eval::Closure;
+
+my $source = <<'SOURCE';
+sub {
+    Carp::confess("foo")
+}
+SOURCE
+
+{
+    my $code = eval_closure(
+        source => $source,
+    );
+
+    throws_ok {
+        $code->();
+    } qr/^foo at \(eval \d+\) line 2\n/,
+      "no location info if context isn't passed";
+}
+
+{
+    my $code = eval_closure(
+        source      => $source,
+        description => 'accessor foo (defined at Class.pm line 282)',
+    );
+
+    throws_ok {
+        $code->();
+    } qr/^foo at accessor foo \(defined at Class\.pm line 282\) line 2\n/,
+      "description is set";
+}
+
+done_testing;