开发者

Line numbers with template toolkit

开发者 https://www.devze.com 2022-12-13 14:36 出处:网络
I am using the Perl Template Toolkit to generate C files. I dearly want to be able to include #line directives in my C code so that error messages from the C compiler send me to the right place (the t

I am using the Perl Template Toolkit to generate C files. I dearly want to be able to include #line directives in my C code so that error messages from the C compiler send me to the right place (the template file) rather than the wrong pl开发者_StackOverflowace (the template output). However, I don't know how to do this. The only result I got from Google was an unanswered message on the Template Toolkit mailing list.

I can imagine a tortured solution like reading the template file myself and adding line numbers, but does anyone have a trick or even a sensible method of getting the line numbers of the original file in Template Toolkit?


Looks to me like Template::Parser's location method returns a suitable #line directive, but there isn't any built in function I see to include that in the output. You'd have to extend Template Toolkit to make it do so.


Since number and "filename" are totally made up (whatever you want) in the #line directive, I suggest putting #line directives in the template using a slightly different context.

Rather than counting lines in the template yourself, which you could do, even using a template pre-processor. I would 'invent' file names for the different sections of the template and number thos lines with small numbers that you can count.

Then an error message might say "... in line 2 of div id='topleft'"


It doesn't look like Template::Toolkit natively supports this. One thing that you could do is make your program also write a mapping of generated lines to their lines in the appropriate template, so that you can look the errors up the errors with a simple script.


A brute-force solution:

#!/usr/local/bin/perl
use warnings;
use strict;
my $file = "something.c";
open my $input, "<", $file or die $!;
while (<$input>) {
    print "#line $. \"$file\"\n";
    print;
}
close $input or die $!;

Even better, test for [% on the line and only print #lines where necessary.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号