TXL solution to [[TIL Chairmarks]] #2.1, declaring "for" statement to nondeclaring "for" statement. -- Main.JamesCordy - 10 Oct 2005 _File "TILfordeclare.Txl"_ % TXL transformation to adapt existing "declaring for" semantics TIL programs % to a proposed new semantics in which "for" control variables must be declared % Jim Cordy, October 2005 % Note: In this program all keywords of TIL are quoted in patterns and replacements - % this is not strictly necessary, but is conventional style in modern TXL programs. % Based on the TIL base grammar include "TIL.Grm" % Preserve comments, we're probably going to maintain the result include "TILCommentOverrides.Grm" % Transformation rule to correct all for loops. % Default rewrite rule semantics in TXL are compositional fixed point, % which for most transformations is the desired semantics. However, % this transformation has no syntactic compositional fixed point. % So the alternatives are either a semantically-guarded transformation, % a grammar override, or an explicit once-over traversal. % This solution uses the last of these, not because it is the best solution % but because this example gives us an opportunity to demonstrate that possibility. function main % This is a function transformer, so it applies only once unless explicitly % reapplied. The "replace *" allows it to search deeply for its pattern. % The replacement reapplies it twice to implement an explicit traversal. replace * [statement*] 'for Id [id] := Expn1 [expression] 'to Expn2 [expression] 'do Statements [statement*] 'end MoreStatements [statement*] by 'var Id; 'for Id := Expn1 'to Expn2 'do Statements [main] 'end MoreStatements [main] end function _Example run:_ cat multiples.til // Test of declaring for loop in TIL // Output first 10 multiples of numbers 1 through 9 for i := 1 to 9 do for j := 1 to 10 do write i*j; end end txl multiples.til TILfordeclare.Txl TXL v10.4a (15.6.05) (c)1988-2005 Queen's University at Kingston Compiling TILfordeclare.Txl ... Parsing multiples.til ... Transforming ... // Test of declaring for loop in TIL // Output first 10 multiples of numbers 1 through 9 var i; for i := 1 to 9 do var j; for j := 1 to 10 do write i * j; end end