473,609 Members | 1,900 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Emulating nested function behaviour

If you know languages like Python or D you know, that nested
functions can be really handy.

Though some compilers (looking at GCC) provide the extension of
nested functions, I wonder, how one could implement an
equivalent behaviour with plain C (in this case I'm thinking of
the language I'm developing, which shall be converted into C for
target compilation). So far I didn't touch the topic "nested
functions", since I just don't see an elegant way to implement
them, but I want them, .

The problem is, that a nested functions resides within the scope
of the enclosing function and thus sees all variables of that.
Of course, if I were not seeking for portability, I could just
fiddle around with assembler on the stack. But I'd like to do as
much in C as possible.

So far the "best" solution I came up with was to create a struct
for each function, containing all it's variables:

struct _foo_variables {
int a;
int b;
short c;
/* ... */
};

static void _nest_foo_bar(s truct _foo_variables * const
_foo_variables)
{
}

void foo()
{
struct _foo_variables _variables;
/* ... */
_nest_foo_bar(& _variables);
}

But this doesn't look very elegant.

By nature nested functions can only be called from within the
scope of the enclosing function. I wonder if there's a more
elegant way, to access a calling function's variables from the
called function. I presume not, but maybe I'm wrong. I'm most
concerned about the performance impact due to the need of
dereferencing stuff - most architectures are more efficient in
addressing stuff on the stack, than from arbitrary pointers,
even if they point on the stack. I don't know how good compilers
are nowadays to figure out what's going on, and optimizing this
into frame pointer relative access. Yeah, I know "premature
optimization... "

lambda expressions were implemented quite easyly using the ffcall
library; lambdas (how I specified them for my language) can't
access variables outside the scope anyway, since they're first
class objects to be passed around.

Of course I could just omit the whole idea of nested functions,
but they're so damn usefull in some occasions.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber .org, ICQ: 134682867

Dec 27 '07 #1
4 2302
Harald van Dijk wrote:
The problem isn't just that a nested function sees the
variables of the enclosing function, but that it sees the
variables of the specific call of the enclosing function, which
can be different from the most recent call if the function is
recursive.
Of course, but doing tricks like unwiding the stack would take
this into account. But C does not define anything about stacks,
and I want the generated code to be as generic as possible.
>By nature nested functions can only be called from within the
scope of the enclosing function.

Within the execution of the enclosing function. Because of
function pointers, it might be from outside of the enclosing
function's scope.
Yes of course. But the C code is supposed to be generated and not
modified directly. And all "nested" functions are declared
static, so it should be impossible to get a function pointer to
them from outside code - the code generator will definitely not
assign nested functions to function pointers that are outside
the scope of the containing function.

Well, nobody's supposed to see/touch the generated code under
normal conditions. I'm still thinking about, how I can get debug
information, which is referencing the "original" source code,
from which the C code is generated. Probably I've to fiddle
around with the DWARF data on the link level, but that's a
different problem and not related to C.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber .org, ICQ: 134682867

Dec 27 '07 #2
Wolfgang Draxinger <wd********@dar kstargames.dewr ites:
If you know languages like Python or D you know, that nested
functions can be really handy.

Though some compilers (looking at GCC) provide the extension of
nested functions, I wonder, how one could implement an
equivalent behaviour with plain C (in this case I'm thinking of
the language I'm developing, which shall be converted into C for
target compilation). So far I didn't touch the topic "nested
functions", since I just don't see an elegant way to implement
them, but I want them, .
[...]

I don't have any concrete suggestions, just an observation. The fact
that you're (thinking of) writing a compiler that uses C as an
intermediate language gives you an advantage: the generated C doesn't
have to be particularly easy to read, as long as it's correct.

Using C as a target language is not uncommon. I'm sure there are
existing implementations for languages that support nested
subroutines. Many of those are likely to be open source; even those
that aren't are likely to let you see the generated C code. (Eiffel
is one likely example that springs to mind.) You can get ideas from
other people's work.

You might also have better luck in comp.compilers. Note that it's a
moderated group; responses aren't likely to be fast, especially at
this time of year.

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
[...]
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 27 '07 #3
On Thu, 27 Dec 2007 21:56:29 +0100, Wolfgang Draxinger wrote:
Harald van Dijk wrote:
>The problem isn't just that a nested function sees the variables of the
enclosing function, but that it sees the variables of the specific call
of the enclosing function, which can be different from the most recent
call if the function is recursive.

Of course, but doing tricks like unwiding the stack would take this into
account. But C does not define anything about stacks, and I want the
generated code to be as generic as possible.
No, that's just it: unwinding the stack wouldn't take that into account,
because unwinding the stack would leave you at the innermost call to the
outer function. The example function I gave would generate the exact
opposite result this way.
>>By nature nested functions can only be called from within the scope of
the enclosing function.

Within the execution of the enclosing function. Because of function
pointers, it might be from outside of the enclosing function's scope.

Yes of course. But the C code is supposed to be generated and not
modified directly. And all "nested" functions are declared static, so it
should be impossible to get a function pointer to them from outside code
- the code generator will definitely not assign nested functions to
function pointers that are outside the scope of the containing function.
That will save you from a lot of problems. In that case, might I suggest
transforming what would become

int f(void) {
int data;

int nested(void) {
/* do things with data */
}
}

into

static int f_nested(void);
struct f_data {
int data;
} *f_data;

int f(void) {
struct f_data data, *prev_data;

prev_data = f_data;
f_data = &data;

/* ... */

f_data = prev_data;
}

static int f_nested(void) {
/* do things with f_data->data */
}

? This way, f_nested will have access to the data from the most recent
call to f, and even if f calls itself recursively, you won't invalidate
pointers to the local data. You just need to make sure to restore the
pointer after you return from f, that's all.
Dec 27 '07 #4
Harald van Dijk wrote:
On Thu, 27 Dec 2007 21:56:29 +0100, Wolfgang Draxinger wrote:
>Harald van Dijk wrote:
>>The problem isn't just that a nested function sees the variables of the
enclosing function, but that it sees the variables of the specific call
of the enclosing function, which can be different from the most recent
call if the function is recursive.
Of course, but doing tricks like unwiding the stack would take this into
account. But C does not define anything about stacks, and I want the
generated code to be as generic as possible.

No, that's just it: unwinding the stack wouldn't take that into account,
because unwinding the stack would leave you at the innermost call to the
outer function. The example function I gave would generate the exact
opposite result this way.
>>>By nature nested functions can only be called from within the scope of
the enclosing function.
Within the execution of the enclosing function. Because of function
pointers, it might be from outside of the enclosing function's scope.
Yes of course. But the C code is supposed to be generated and not
modified directly. And all "nested" functions are declared static, so it
should be impossible to get a function pointer to them from outside code
- the code generator will definitely not assign nested functions to
function pointers that are outside the scope of the containing function.

That will save you from a lot of problems. In that case, might I suggest
transforming what would become

int f(void) {
int data;

int nested(void) {
/* do things with data */
}
}

into

static int f_nested(void);
struct f_data {
int data;
} *f_data;

int f(void) {
struct f_data data, *prev_data;

prev_data = f_data;
f_data = &data;

/* ... */

f_data = prev_data;
}

static int f_nested(void) {
/* do things with f_data->data */
}
I was following up to the point where Harald suggested "in that case" with
the recommendation of using the most recent. Wolfgang's statement that
>so it should be impossible to get a function pointer to them from
outside code
does not eliminate the problem with Harald's recursive example where the
address is taken from /within/ the outer function, then passed to itself or
an outside function which saves the pointer, calls f and, in a nested
context, uses the earlier saved pointer.

Wolfgang, are you saying that a pointer to the nested function cannot be taken?
--
Thad
Dec 28 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1257
by: Kamilche | last post by:
""" Emulating Python inheritance manually. By loading it from disk at run time, you can create new custom types without programmer intervention, and reload them on demand, without breaking anything. The only time programmer intervention is required, is when new functions are added. It works well for data... I can use 'chicken.color' to access that attribute, but not for functions. I can't say 'chicken.printme()',
5
1797
by: Dave Benjamin | last post by:
I ran into an odd little edge case while experimenting with functions that create classes on the fly (don't ask me why): >>> def f(x): ... class C(object): ... x = x ... print C.x ... >>> f(5) Traceback (most recent call last):
10
1935
by: Brendan | last post by:
Hi everyone I'm new to Python, so forgive me if the solution to my question should have been obvious. I have a function, call it F(x), which asks for two other functions as arguments, say A(x) and B(x). A and B are most efficiently evaluated at once, since they share much of the same math, ie, A, B = AB(x), but F wants to call them independantly (it's part of a third party library, so I can't change this behaviour easily). My...
1
2600
by: Niall Smart | last post by:
Hi I'm trying to emulate a "following-sibling-or-self" XPath axis without using the union operator. The XML looks like this: <deeply-nested> <select> <option value="1">One</option> <option value="2" selected="selected">Two</option> <option value="3">Three</option>
2
2594
by: Bart | last post by:
Hi there, Since you've all told me that frames ar evil, I'm planning to disguard frames in favour of CSS "pseudo-frames" for my personal website. While trying to "emulate frames" (that is I want a 2 column layout, with the menu in the left column) I came up with this: http://home-1.tiscali.nl/~knmg0017/css_frames_1.htm
11
1986
by: Alfonso Morra | last post by:
Hi, I have the ff data types : typedef enum { VAL_LONG , VAL_DOUBLE , VAL_STRING , VAL_DATASET }ValueTypeEnum ;
5
2254
by: Stephan Schaem | last post by:
How does one write an unmanaged function that perform this functionality? In short I want to turn off/on visual style in my app... Thanks, Stephan PS: two people have been looking for some time, and no solution aside putting the manifest in a file, and renaming the file before startup was found... very ugly hack ...
37
2763
by: Tim N. van der Leeuw | last post by:
Hi, The following might be documented somewhere, but it hit me unexpectedly and I couldn't exactly find this in the manual either. Problem is, that I cannot use augmented assignment operators in a nested scope, on variables from the outer scope: PythonWin 2.4.3 (#69, Mar 29 2006, 17:35:34) on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond@skippinet.com.au) -
3
1899
by: Dieter Maurer | last post by:
I met the following surprising behaviour .... for i in range(3): .... def gen1(): .... yield i .... yield i, gen1() .... .... 0 0 1 1
0
8129
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8074
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8535
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8220
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8404
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6997
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6056
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4080
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1667
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.