Trouble implementing a standard library -- Calling C functions from within my language

noitalmost <noitalmost@cox.net>
Wed, 19 Mar 2014 18:28:13 -0400

          From comp.compilers

Related articles
Trouble implementing a standard library -- Calling C functions from wi noitalmost@cox.net (noitalmost) (2014-03-19)
Re: Trouble implementing a standard library -- Calling C functions fro DrDiettrich1@aol.com (Hans-Peter Diettrich) (2014-03-20)
Re: Trouble implementing a standard library -- Calling C functions fro alexfrunews@gmail.com (2014-03-19)
Re: Trouble implementing a standard library -- Calling C functions fro noitalmost@cox.net (noitalmost) (2014-03-21)
| List of all articles for this month |
From: noitalmost <noitalmost@cox.net>
Newsgroups: comp.compilers
Date: Wed, 19 Mar 2014 18:28:13 -0400
Organization: Compilers Central
Keywords: code, question
Posted-Date: 19 Mar 2014 20:13:14 EDT

I need some small-scale examples, like a toy compiler would do if it
needed access to some libc functions.


Let's say I have a module (library) called Std that provides
procedure ln (x : float) float;
procedure open(fname : string; mode : int) int;
procedure read(fd : int; buf : ^byte; cnt : int) bool;


On a Linux system, I want to just wrap the libc functions
double log(double x);
int open(const char *fname, int mode);
ssize_t read(int fd, void *buf, int cnt);


In prior projects, I always output assembly and just did system calls.
This time it's different. First, I have an intermediate form that can
produce C source code. Second, I want to be able to access functions
(say from math.h) that aren't Linux system calls.


I don't think the intermediate form matters for this discussion. It
can be assumed that module Std gets parsed into an AST, and that I can
walk the AST to generate C code.


How is this usually handled? I could put a CCall node in my AST and have the
parser recognize
procedure ln (x : float) :
    return CCall( ln, x );
end ln;


And then have
class CCall : public Expr
{
    CCall(string name, vector<Expr*> params);
    string genC();
    ...
}


where, Expr is a AstNode. But CCall::genC() would be a really
complicated list of special cases. Maybe I also need to pass the C
return type and the C types of the parameters? And I'm on my way
toward an Ada-style foreign-function interface. Eek! Isn't there a
simpler way?


Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.