Need C-->Pascal conversion program

Dave Gillespie daveg at near.cs.caltech.edu
Tue Mar 20 09:36:14 AEST 1990


On 17 Mar 90 01:37:14 GMT, mccaugh at sunb0.cs.uiuc.edu (Scott McCaughrin) said:
> If you are going to convert from PASCAl to C, how do you propose to
> handle arbitrarily nested PROCs/FUNCTIONs? Scope-nesting can get
> arbitrarily complex in PASCAL - not so in C.

The solution I used in my Pascal to C translator, p2c, was to collect all
the variables of the parent procedure that were used by sub-procedures
into a struct; the parent passes a pointer to this struct to each
sub-procedure.  If these in turn have sub-sub-procedures which need
their grandparent's variables, the sub-procedure's struct will include
a pointer to the parent's struct.

  procedure p1;
    var v1 : integer;
    procedure p2;
      var v2 : integer;
      procedure p3;
        var v3 : integer;
        begin
          v3 := 3;
          writeln(v1, v2, v3);
          p3; p2; p1
        end; {p3}
      begin {p2}
        v2 := 2;
        p3
      end; {p2}
    begin {p1}
      v1 := 1;
      p2
    end; {p1}

translates to something like (assuming ANSI C)

  struct loc_p1 { int v1; };
  struct loc_p2 { struct loc_p1 *LINK; int v2; };
  void p3(struct loc_p2 *LINK) {
    int v3;
    v3 = 3;
    printf("%d%d%d\n", LINK->LINK->v1, LINK->v2, v3);
    p3(LINK); p2(LINK->LINK); p1();
  }
  void p2(struct loc_p1 *LINK) {
    struct loc_p2 v;
    v.LINK = LINK;
    v.v2 = 2;
    p3(&v);
  }
  void p1() {
    struct loc_p1 v;
    v.v1 = 1;
    p2(&v);
  }

(I just wrote this off the top of my head; I haven't checked with p2c.)

Of course in the simple case that only one variable is referenced, it
would be easier to pass a pointer to the variable itself.  I haven't had
time to teach p2c to do this yet.

Accessing a grandparent's variable with this approach involves chasing
down N links, as in "LINK->LINK->v1".  A "display" would eliminate this
in this example by modifying p3 like this:

  void p3(struct loc_p2 *LINK) {
    struct loc_p1 *LINK_p1 = LINK->LINK;
    ...
    printf("%d%d%d", LINK_p1->v1, LINK->v2, v3);
    ...
  }

This is a win if each call to p3 is going to refer to v1 many times.
The current version of p2c doesn't do this, either.  In my experience
few real programs need it.

(You can get p2c from FTP on csvax.caltech.edu.  It will be posted in
comp.sources.unix when that group comes back on-line.)

								-- Dave
--
Dave Gillespie
  256-80 Caltech Pasadena CA USA 91125
  daveg at csvax.caltech.edu, ...!cit-vax!daveg



More information about the Comp.lang.c mailing list