XTRAN Example — Translate Pascal Array Subscripts to C
The following example uses the standard set of XTRAN rules for parsing Pascal and translating it to C. This is complicated by the fact that Pascal allows nonzero lower bounds on array dimensions, whereas C does not. (And, of course, if a Pascal array dimension has no lower bound, it defaults to 1.) XTRAN handles this as follows, for each array dimension with a nonzero lower bound:
- XTRAN translates the C declaration's dimension
to
<upper-bound> - <lower-bound> + 1.
If both bounds are integers, XTRAN does the arithmetic and generates the appropriate integer; otherwise it generates the expression. - For each reference to the array in the code, XTRAN subtracts the lower bound from the corresponding subscript in the reference. If both the lower bound and the reference's subscript are integers, XTRAN does the arithmetic and adjusts the subscript to the difference; otherwise it generates the expression.
NOTE that the translation shown below was done with default conditions. XTRAN provides many options for controlling the way it translates.
Process Flowchart
Here is a flowchart for this process, in which the elements are color coded:
- BLUE for XTRAN versions (runnable programs)
- ORANGE for XTRAN rules (text files)
- RED for
code
Input to XTRAN:
TYPE arrtyp1 = ARRAY [3..5, 8] OF INTEGER; { arrtyp1 = ARRAY [3..5, 8] OF INTEGER; } arrtyp2 = ARRAY [2..10, 5..12] OF REAL; { arrtyp2 = ARRAY [2..10, 5..12] OF REAL; } VAR p_arr1, p_arr2 : ARRAY [2..5] OF REAL; { p_arr1, p_arr2 : ARRAY [2..5] OF REAL; } pp_arr3 : ARRAY [10] OF ^INTEGER; { pp_arr3 : ARRAY [10] OF ^INTEGER; } pp_arr4 : ARRAY [6, 2..5] OF INTEGER; { pp_arr4 : ARRAY [6, 2..5] OF INTEGER; } p_arr5 : arrtyp1; { p_arr5 : arrtyp1; } p_arr6, p_arr7 : arrtyp2; { p_arr6, p_arr7 : arrtyp2; } i, j : INTEGER; { i, j : INTEGER; } BEGIN i := 2; { i := 2; } j := 1; { j := 1; } p_arr1[i] := p_arr2[2]; { p_arr1[i] := p_arr2[2]; } pp_arr3[i] := ^(pp_arr4[4, i]); { pp_arr3[i] := ^(pp_arr4[4, i]); } p_arr5[i, j] := p_arr5[4, 4]; { p_arr5[i, j] := p_arr5[4, 4]; } p_arr6[2, i] := p_arr7[j, 8] { p_arr6[2, i] := p_arr7[j, 8] } END;
Output from XTRAN:
typedef long Arrtyp1[3][8]; /* arrtyp1 = ARRAY [3..5, 8] OF INTEGER; */ typedef float Arrtyp2[9][8]; /* arrtyp2 = ARRAY [2..10, 5..12] OF REAL; */ float p_arr1[4], p_arr2[4]; /* p_arr1, p_arr2 : ARRAY [2..5] OF REAL; */ long *pp_arr3[10]; /* pp_arr3 : ARRAY [10] OF ^INTEGER; */ long pp_arr4[6][4]; /* pp_arr4 : ARRAY [6, 2..5] OF INTEGER; */ Arrtyp1 p_arr5; /* p_arr5 : arrtyp1; */ Arrtyp2 p_arr6, p_arr7; /* p_arr6, p_arr7 : arrtyp2; */ long i, j; /* i, j : INTEGER; */ i = 2; /* i := 2; */ j = 1; /* j := 1; */ p_arr1[i - 2] = p_arr2[0]; /* p_arr1[i] := p_arr2[2]; */ pp_arr3[i - 1] = &pp_arr4[3][i - 2]; /* pp_arr3[i] := ^(pp_arr4[4, i]); */ p_arr5[i - 3][j - 1] = p_arr5[1][3]; /* p_arr5[i, j] := p_arr5[4, 4]; */ p_arr6[0][i - 5] = p_arr7[j - 2][3]; /* p_arr6[2, i] := p_arr7[j, 8] */