[comp.lang.c] Porting programs from Modula 2

fangchin@portia.Stanford.EDU (Chin Fang) (01/12/91)

paul@tredysvr.Tredydev.Unisys.COM (Paul Siu) writes:
>I have a program that I need to port from modula-2.  Modula contain two
>datatypes that are not supported in C: sets and subranges.  Does anyone know
>how I could simulate them in C or work around it?

Just a thought, how is Dave Gillespie's p2c performing in this case?  
I never tried it for translating Modula-2.  But it always a very good
translator as far as Pascal is concerned.  The document of p2c claims it
supports Modula-2 syntax as well.

Regards,

Chin Fang
Mechanical Engineering Department
Stanford University
fangchin@portia.stanford.edu

brandis@inf.ethz.ch (Marc Brandis) (01/15/91)

In article <646@caslon.cs.arizona.edu> dave@cs.arizona.edu (Dave P. Schaumann) writes:
>As for sets, you will have to write a group of subroutines to deal with that.
>The traditional way is to use an array of character (one for each set element),
>or a bit-vector (if space is a critical issue).
>

The bit-vector solution is the preferable solution even if space is not a
critical issue. It is neither simpler nor faster to use the array of character
approach. The operations "+", "*", "-", "/" on SETs as well as the comparison
become a loop with the array solution, while they are simple operations when
the bit-vector approach is used. Look at the following case for "+":

	Modula-2:
	
	VAR a, b, c: SET;
	BEGIN
	  a := b+c

	C with array approach:

	char a[n], b[n], c[n];
	int i;

	for (i = 0; i < n; i++) a[i] = b[i] | c[i];

	C with bit vector approach:

	unsigned long a, b, c;

	a = b | c;

The same holds for the assignment of SETs. The other set of operations, INCL,
EXCL and the test IN can be coded as follows (example for IN):

	Modula-2:

	VAR a: SET; i: INTEGER;
	BEGIN
	  IF i IN a THEN ...

	C with array approach:

	char a[n]; int i;
	
	if (a[i]) ...

	C with bit vector approach:

	unsigned long a; int i;

	if ((1 << i) & a) ...

The array approach will typically be translated to an indexed load followed
by a compare against zero followed by a branch. The bit-vector approach will
translate to the load of an immediate value followed by a shift, an and and 
a branch (if all operands are in register, which is reasonable for modern
machines and compilers). On many machines, the second sequence will not be
slower than the first one. Depending on the architecture of the machine, the
bit-vector version can be even improved. If the shift operation sets a 
condition code bit for a special bit in the word (e.g. the sign bit or the 
least significant bit), you can directly shift a and get the result.


Marc-Michael Brandis
Computer Systems Laboratory, ETH-Zentrum (Swiss Federal Institute of Technology)
CH-8092 Zurich, Switzerland
email: brandis@inf.ethz.ch