[m-dev.] interpreting C datastructures as Mercury terms

Peter Schachte pets at students.cs.mu.OZ.AU
Thu May 7 16:31:55 AEST 1998


On Thu, 7 May 1998, Thomas Charles CONWAY wrote:

> 2) List-like structures.
> There are a number of structures that are of the form:
> typedef struct BAR {
> 	strcut BAR	*next;
> 	Word		*this;
> 	Word		*that;
> } Bar;
> 
> Now, you could write the following type declaration:
> 
> :- type bar
> 	--->	bar(bar, this_type, that_type)
> 	;	nil.
> 
> However, the tag assignment rules mean that all the recursive pointers
> need to be tagged which is a pain in C.  If we could convince the compiler
> to use the opposite to the usual tag assignment (ie 0 to bar/n and 1 to nil)
> the problem would go away - rather than using NULL to represent the empty
> list of Bars, we use 1 (appropriately macroized and cast of course) and
> the bar-pointers can be used without explicit tagging.

While you're at this, it would be very good if the technology you implement
would also work for (at least some) existing C types, as well, where you
don't have control over all the code that uses the type.  For this, you
really want the representation of nil to be NULL (ie, 0). 

One way to get this is to define in each platform's configuration the
smallest memory address that you could ever get ahold of.  Then you can, for
types that ask for it, allocate zero-arity constructors the numbers from 0
through that number-1 (I think it should be pretty safe to guarantee that
the number will always be at least 1) and assign tags starting with 0 to the
non-zero arity constructurs.  Using this tag assignment (well actually tag
and value assignment) scheme, the C type Bar and Mercury type bar would have
the same representation.

Hmmmm.  I just had another thought.  Why can't you do what you want right
now by defining an abstract type and defining different modes of constructor
functions as pragma C code?  Should be simple enough.  Then it'll look to
the user pretty much like an ordinary discriminated union type, even though
it isn't implemented that way.


-Peter Schachte               | How does a project get to be a year late?
mailto:pets at cs.mu.OZ.AU       | ... One day at a time. -- Frederick Brooks,
http://www.cs.mu.oz.au/~pets/ | Jr., The Mythical Man Month 
PGP: finger pets at 128.250.37.3 | 




More information about the developers mailing list