In TXL, all parsers are also pretty printers, so see the TIL Parser Using TXL if comments are not an issue. Because the TXL solution to preserving formatting and comments in a transformation is Source Factoring, comments are not normally handled using TXL itself.

However, in TXL it is also possible to handle comments by parsing them, either as disciplined comments (those appearing in predicted places, which of course is possible using any system), or using Robust Parsing techniques.

TXL allows for the addition of disciplined comments to an existing base grammar using Grammar Overrides. The example below is based on the TXL base grammar for TIL given on the TIL Parser Using TXL page, and implements a pretty printer for TIL with discplined comment handling.

-- JamesCordy - 17 Aug 2005 (revised JamesCordy - 10 Oct 2005)

File "TILpretty.Txl"

% TXL parser / pretty-printer for Tiny Imperative Language,
% with disciplined comment handling
include "TIL.Grm"

#define COMMENTS

% Add optional grammar overrides for disciplined end-of-line comments
% in the C++ style.  You can either control this either by commenting/uncommenting
% the #define above, or by using -d COMMENTS on the TXL command line
#if COMMENTS then
    include "TILCommentOverrides.Grm"
#end if

% No need to do anything except recognize the input, since the grammar
% includes the formatting cues
function main
    match [program]
        _ [program]
end function

File "TILCommentOverrides.Grm"

% Grammar overrides to allow for disciplined TIL comments in the C++ style.
% (Handling more general undisciplined comments is more complicated,
%  see the TXL C grammar.)

#pragma -comment

comments
    //
end comments

redefine statement
        ...
    |  [comment_statement]
end redefine

define comment_statement
    [repeat comment_NL+]
end define

define comment_NL
    [comment] [NL]
end define

Example run:

<linux> cat factors.til
// Factor an input number
var n; write "Input n please"; read n;
write 
"The factors of n are"; var f; f := 2;
while n != 1 do while (n / f) * f = n do
        // Got one - print it!
        write f; n := n / f;
end
    f := f + 1;
        end
<linux> txl factors.til TILpretty.Txl
TXL v10.4a (15.6.05) (c)1988-2005 Queen's University at Kingston
Compiling TILpretty.Txl ... 
Parsing factors.til ...
Transforming ...
// Factor an input number
var n;
write "Input n please";
read n;
write "The factors of n are";
var f;
f := 2;
while n != 1 do
    while (n / f) * f = n do
        // Got one - print it!
        write f;
        n := n / f;
    end
    f := f + 1;
end
<linux> 

Revision: r1.2 - 10 Oct 2005 - 15:25 - JamesCordy
Sts > StsBench > TILChairmarks > TILPrettyPrinterUsingTXL
Copyright © 1999-2020 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback