Automated function and procedure names

Is there a built in string in Ada that gives you the name of a function? I am looking for the equivalent of __FUNCTION __ in C.

When I start wrting a program, I create all the function names and instead of null; I use put_line(functtion_name); For instance, instead of

procedure fred(x: integer) is
begin
    put_line("fred");
end fred;

I’d like to use

procedure fred(x: integer) is
begin
    put_line(__FUNCTION__);
end fred;

Also, when logging, I’d like to do something like

put_line(
    file=>logfile,
    item=>__FUNCTION__ & ": " &  ....);

Sometimes, during the design phase, I change procedure names and very often forget to change the put_line. Search and replace doesn’t always work because the procedure name can be embedded in a middle of a word, which often leads to weird logging or comments and possibly compilation errors.

The GNAT.Source_Info library (specific to only GNAT) provides this functionality among others: The source file of the library can be found in gcc.gnu.org Git - gcc.git/blob - gcc/ada/libgnat/g-souinf.ads

The actual procedure name you are looking for from the library is Enclosing_Entity

Best regards,
Fer

3 Likes

You can get this portably with PragmARC.Reflection.

3 Likes

@Irvise Your solution works. Just needs

with GNAT.Source_Info; use GNAT.Source_Info;
...
    put_line(Enclosing_Entity);

This will print the module name and the function name.

@JC001 Looks like I need to download the whole package to get this to work. I can’t just download pragmarc.reflection.ads

You could if there were a file by that name:

  1. Go to the repo main page: GitHub - jrcarter/PragmARC: The PragmAda Reusable Components
  2. Click on the file name: pragmarc-reflection.ads
  3. Above on the right side of the code box is a button with a downward-pointing arrow; when you put the cursor over it, you get a pop-up reading “Download raw file”. Clicking on this button will download the file.

Of course, you’ll also have to download the spec of package PragmARC and the spec and body of package PragmARC.Mixed_Case, so you might find it easier to just download the zip file.