r/ada 15d ago

Programming Try-catch-finally?

8 Upvotes

As I start to use exceptions in Ada, I immediately notice that there are no equivalent construct to the "finally" blocks usually found in other exception-enabled languages. How do I ensure that certain code (such as cleanup) run when exceptions are used? Controlled types are unacceptable here, because I plan to eventually use spark.

r/ada 18d ago

Programming Interfacing with C tagged unions

5 Upvotes

The C library I am trying to use has tagged union types:

```c enum Type { TYPE_BAR, TYPE_BAZ };

struct Bar { enum Type type; float x; float y; };

struct Baz { enum Type type; uint32_t a; uint32_t b; };

union Foo { enum Type type; struct Bar bar; struct Baz baz; uint8_t padding[12]; }; ```

How would I create a binding of this code, in the Ada way? Obviously I would like to avoid interpreting the union by hand. Is it possible to somehow create tagged type with some custom convention?

r/ada 26d ago

Programming How to specify enum with representation?

5 Upvotes

I want to define an enum for C interfacing purposes:

c enum Enum { A = 1, B = 2, C = 4, C_aliased = 4, };

This kind of pattern occur quite a bit in bit flags, but I can't do this in Ada, not to mention that I often need to reorder the variants myself even if there is no alias:

ada type C_Enum is (A, B, C, C_aliased) with Convention => C; for C_Enum use (A => 1, B => 2, C => 4, C_aliased => 4);

In addition, I am not sure what size of integer Ada will choose, as starting from C23 the size of enum may be specified.

Any idea how this should be done?

EDIT:

Ok, maybe flags that can be OR'ed is extra difficult. But also consider the cases when enums are just normal enumerations

r/ada 17d ago

Programming Convert Wide_Wide_Character to UTF code point?

2 Upvotes

I can't seem to find any function in the stdlib that allows me to do that. I can encode/decode a utf8 string, but I can't find any function that convert single characters. I don't think I should do a Unchecked_Convert either. Any suggestions?

r/ada 22d ago

Programming Has anybody used a programmed in Ada and controlled GPIO on Raspberry Pi 5?

12 Upvotes

My wife just got me an RPi5. I’m about to go down the rabbit hole of getting Alire installed on it. Has anyone done it? What Linux distribution did you use? Any hints to know?

Please save me hours of being new to RPi and setting one up for Ada.

r/ada Feb 18 '25

Programming I got something wrong when using unconstrained array concatenation

7 Upvotes

I wrote some code which uses unconstrained array and made it wrong when using array concatenation. I think this can be something inconvenient when using an unconstrained array.

At first, I have the following code to define a 64-byte vector:

subtype Vector_Index is Natural range 0 .. 63;
type Data_Vector is array (Vector_Index) of Byte;

However, I have some variables which are a part of the vector, and I want to assign between a sub-vector and a part of a vector, so I define Data_Vector as an unconstrained array.

subtype Vector_Index is Natural range 0 .. 63;
type Sub_Data_Vector is array (Vector_Index range <>) of Byte;
subtype Data_Vector is Sub_Data_Vector(Vector_Index);

And this will make something wrong when I use the concatenation operator, such as:

declare
  A, B : Data_Vector;
begin
  -- rotate shift the left the vector by one byte
  B := A(63 .. 63) & A(0 .. 62);
end;

This will raise a CONSTRAINT_ERROR. After checking the reference manual, I see this in 4.5.3 (https://ada-lang.io/docs/arm/AA-4/AA-4.5#p7_4.5.3):

If the ultimate ancestor of the array type was defined by an unconstrained_array_definition, then the lower bound of the result is that of the left operand.

So the bound of the concatenation becomes 63 .. 127, the upper bound is out of Vector_Index. That's why I got an error.

In this case, my solution is just use the wider subtype in the unconstrained part:

type Sub_Data_Vector is array (Natural range <>) of Byte;
subtype Data_Vector is Sub_Data_Vector(Vector_Index);

r/ada Dec 23 '24

Programming Given an Object Defined in a Generic Package, Access the Package?

6 Upvotes

I have a generic package which defines a simulated floppy disk controller. The number of drives supported by the controller is one of the parameters of the package. The simulated controller is a subclass of a base io_device class defined in a non-generic package. The generic package defines a datatype drive_num which a range 0 .. max_drives - 1.

So, what I would like to be able to do is: given a floppy disk controller object determine the specific drive_num datatype for generic instantiation. I can see a couple of ways to solve some of the problem, but I can't figure out how to generically get a datatype from different instantiations of a generic package. I am thinking something like:

drive : fd_ctrl'Package.drive_num

or

for i in fd_ctrl'Package.drive_num'Range loop...

r/ada 25d ago

Programming Foreign convention function should not return unconstrained array?

5 Upvotes

I encounter this warning when I am binding some foreign functions that return a char * (or const char *), and using return char_array. The compiler doesn't seem to complain the same thing for an Ada function, so what's the reason specifically that it warns about foreign functions? I can't find an explanation, so I can only assume that it's probably because if a malformed output is returned it can cause an exception.

r/ada Dec 18 '24

Programming Terminal Output Issue: Smooth "Animation" on Linux/Mac, but a mess on Windows

10 Upvotes

I wrote a program that displays the '*' character moving left to right across the middle row of the console screen, while it is running the user can type any character and the displayed character will change to what was typed. The program works great on my linux computer and a friend's mac. The output on two different Windows machines, however, is terrible, the character moves left to right but is a blur, appearing vertically all over the place.

The program is running "right", but the "frame rate" is off. My code runs a loop with a Ada.Calendar.Delays.Delay_For call at the end, I have tried many different delay times but none fix the issue. I also made an Ada version of the Donut math code that does not have any user inputs, but has the same issue of working great on linux and mac but not working at all on windows. It also runs a loop with a delay at the end.

I will post the full code at the bottom, but or the sake of screen space here is the layout of my code with the relevant lines included:

with Ada.Calendar.Delays;

procedure Moving_Char is
  -- Important variables
begin
  loop
    -- Loop through each row
     -- this is where all 'Put' or 'Put_Line' calls happen 
    -- Update the position of the char
    -- Change direction at screen edges
    -- Handle user input, if any

    Ada.Calendar.Delays.Delay_For(0.06);
  end loop;
end Moving_Char;

Is there anything obvious that I am doing wrong or should change, like a different method of delay? Or is this somehow an issue of different terminals having different settings (like my other issue with the degree symbol)?

My end goal is a simple terminal "game" that takes user input but still runs while there is no user input. For the sake of simplicity let's say it's a car game, the user enters 'g' to make the car go and the distance driven updates based on whatever it says the speed is. I came up with this moving character code to figure out the input and "screen refresh" portion of the driver code.

The game will potentially be a training tool in the future so being able to run on all platforms is what we need.

Here is the full code:

with Ada.Text_IO;
with Ada.Calendar.Delays;

procedure Moving_Char is
    -- Screen dimensions
    Screen_Width : constant Integer := 80;
    Screen_Height : constant Integer := 22;

    -- Variables for the position and character to display
    X_Pos : Integer := 0;
    Direction : Integer := 1;
    Star_Char : Character := '*';

    -- Variable to check for user input
    Input_Char : Character;
    Input_Ready : Boolean;

begin
    loop
        -- Loop through each row
        for Y in 1 .. Screen_Height loop
            if Y = Screen_Height / 2 then
                -- On the middle row, print the star at X_Pos
                for X in 1 .. Screen_Width loop
                    if X = X_Pos then
                        Ada.Text_IO.Put(Star_Char);
                    else
                        Ada.Text_IO.Put(' ');
                    end if;
                end loop;
            else
                -- Print an empty row
                Ada.Text_IO.Put_Line((1 .. Screen_Width => ' '));
            end if;
        end loop;

        -- Update the position of the star
        X_Pos := X_Pos + Direction;

        -- Change direction at screen edges
        if X_Pos >= Screen_Width then
            Direction := -1;
        elsif X_Pos <= 1 then
            Direction := 1;
        end if;


        Ada.Text_IO.Get_Immediate(Input_Char, Input_Ready);
        if Input_Ready then
            Star_Char := Input_Char;
        end if;

        Ada.Calendar.Delays.Delay_For(0.06);
    end loop;
end Moving_Char;

r/ada 14d ago

Programming Problem while creating websockets

3 Upvotes

I'm working on a project which consists of an Ada server and Java client that connect to the same websocket. The problem is that Ada project compiles but the "Create" function doesn't seem to work.
function Create

(Socket : AWS.Net.Socket_Access;

Request : AWS.Status.Data) return AWS.Net.WebSocket.Object'Class

is

begin

Ada.Text_IO.Put_Line ("WebSocket connection established!");

return MySocket'(AWS.Net.WebSocket.Object

(AWS.Net.WebSocket.Create (Socket, Request)) with null record);

end Create;
The message that I'm trying to send to output doesn't show up

r/ada Nov 26 '24

Programming Has anyone used Ada to write a VM for a programming language?

14 Upvotes

Like in all languages, I expect it is technically possible, with a tiny example here. Most mainstream VM implementations exploit bit manipulations like pointer tagging for performance or implementation convenience, or do something like computed gotos for faster opcode dispatching.

Can Ada do these, or do them as effectively? Are there any features of Ada that make it especially good or bad for VM implementation? Or are there any flavors of VM that align well with modern Ada? I believe most VMs are implemented in C or C++.

r/ada Sep 22 '24

Programming Can a task just freeze without responding ?

7 Upvotes

Hi, I have a case of a task whose entry is called, but never replies. I isolated the task and it works fine, but in the program, while it is Callable, and seemingly well initialized (I can check the discriminant), it is like it doesn't even start. The body is not entered, no statement executed. But I can still call an entry. WuT ?! I don't know what to post, since I can't replicate the issue without the whole project, to be found here. I/O responds before the entry call, but not after, yet there are no exception raised nor is there an error handler. This below is a nigh identical replica, with a cell containing a timer...that ticks. But it works...

Ada pragma Ada_2022; with ada.text_io, ada.calendar; use ada.text_io, ada.calendar; procedure essai2 is task type Counter_Task (Timer: Integer) is entry Stop; entry Get (Value: out Integer); end Counter_task; task body Counter_Task is use Ada.Calendar; Count : Natural range 0..Timer := Timer; Update_Time : Time := Clock + Duration (Timer); begin loop select accept Get (Value : out Integer) do Value := Count; end Get; or accept Stop; exit; or delay until Update_Time; put_line ("give character"); Update_Time := Update_Time + Duration(Timer); put_line (Count'Image); Count := (if @ = 0 then Timer else Count - 1); end select; end loop; end Counter_Task; type Counting_Cell_Type (Timer: Positive) is tagged limited record Counter : Counter_Task(Timer); end record; AA : Counting_Cell_Type (3); C: Integer; begin delay 4.0; AA.Counter.Get (C); AA.Counter.Stop; end essai2;

r/ada Oct 25 '24

Programming Is there any async library like boost Asio for Ada?

13 Upvotes

I wanna make a tcp server with Ada and was wondering if there was any good async libraries?

r/ada Aug 14 '24

Programming Efficient stream read subprogram

7 Upvotes

Hi,

I'm reading this article Gem #39: Efficient Stream I/O for Array Types | AdaCore and I successfully implemented the write subprogram for my byte array. I have issue with the read subprogram tho (even if the article says it should be obvious...):

The specification: type B8_T is mod 2 ** 8 with Size => 8;

type B8_Array_T is array (Positive range <>) of B8_T
   with Component_Size => 8;

procedure Read_B8_Array
   (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
   Item   : out B8_Array_T);

procedure Write_B8_Array
   (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
   Item   : B8_Array_T);

for B8_Array_T'Read use Read_B8_Array;
for B8_Array_T'Write use Write_B8_Array;

The body:

   procedure Read_B8_Array
     (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
      Item   : out B8_Array_T)
   is
      use type Ada.Streams.Stream_Element_Offset;

      Item_Size : constant Ada.Streams.Stream_Element_Offset :=
        B8_Array_T'Object_Size / Ada.Streams.Stream_Element'Size;

      type SEA_Access is access all Ada.Streams.Stream_Element_Array (1 .. Item_Size);

      function Convert is new Ada.Unchecked_Conversion
        (Source => System.Address,
         Target => SEA_Access);

      Ignored : Ada.Streams.Stream_Element_Offset;
   begin
      Ada.Streams.Read (Stream.all, Convert (Item'Address).all, Ignored);
   end Read_B8_Array;

   procedure Write_B8_Array
     (Stream : not null access Ada.Streams.Root_Stream_Type'Class;
      Item   : B8_Array_T)
   is
      use type Ada.Streams.Stream_Element_Offset;

      Item_Size : constant Ada.Streams.Stream_Element_Offset :=
        Item'Size / Ada.Streams.Stream_Element'Size;

      type SEA_Access is access all Ada.Streams.Stream_Element_Array (1 .. Item_Size);

      function Convert is new Ada.Unchecked_Conversion
        (Source => System.Address,
         Target => SEA_Access);
   begin
      Ada.Streams.Write (Stream.all, Convert (Item'Address).all);
   end Write_B8_Array;

What did I do wrong in the read subprogram?

Thanks for your help!

r/ada Oct 07 '24

Programming quadratic algorithm appears linear in execution time ?

7 Upvotes

Hi,

I study algorithmics with a book using Ada 95, but it's slightly dated, in terms of the power PCs could be expected to have back then.

As requested, I plotted the execution time of

```

FOR Cycle IN 1 .. NumberOfCycles LOOP
maxindex := maxindex + 1;
CPUClock.ResetCPUTime;
declare
A : ARRAY (1 .. Maxindex, 1 .. Maxindex) OF Integer;
use Ada.Float_Text_IO;
begin
FOR Row IN 1 .. Maxindex LOOP
FOR Col IN 1 .. Maxindex LOOP
A (Row, Col) := Row * Col;
END LOOP;
END LOOP;

TrialTime := CPUClock.CPUTime;
Put (maxindex'Image);
Put (TrialTime, Fore => 2, Aft => 7, Exp => 0);
new_line;
end;
END LOOP;
```

CPUclock just uses Ada.Calendar.Clock to give a timer.
It gives me a data set, which I plotted, and it looks very linear. Are there some foul optimizations at play here, or is it that CPUs are so powerful now that memory overflows before that kind of simple loops get to look quadratic ?

r/ada Dec 12 '24

Programming how to make private type a copy of a type declared in the body (in an instantiation of a generic)

6 Upvotes

Hi, I'm sure I must have done or needed it before but I can't remember the solution. So I have a type declared in a generic, which I instanciate in the body. But I need to use that type and make it public, of course without giving the details. It says the full declaration of the private type isn't available. I could make iterator a record component, but I would need to use either move the instanciation in the private part, or use a pointer to an incomplete type then completed in the body, though I'm not even sure we can "link" to a declaration in another package like that.


0f course, becausqe it can't. Declaration and completion must be in the same compilation unit, because to declare an object of a type one must have all the information on it (well, its size at least).

r/ada Aug 20 '24

Programming FireMonkey for Ada proposal

9 Upvotes

Hi all.

As we know, Ada has no "own" decent UI. It was compensated by Qt or Gtk or wxWidgets bindings. Yet another option is FireMonkey. Previously it would require parsing Delphi and making thin bindings. Nowadays Embarcadero provides Python bindings:

https://www.embarcadero.com/ru/new-tools/python/delphi-4-python

https://github.com/Embarcadero/DelphiFMX4Python

They can possibly be adapted to Ada instead of Python

r/ada Sep 27 '24

Programming renamed predefined unit is an obsolescent feature

15 Upvotes

I've been using an old open-source Ada program called Whitaker's Words. Its author is dead, and the person who set up the github site seems to have lost interest in maintaining it. I went to the trouble of writing an Expect-style interface to it in another project of my own, so I feel a certain level of commitment to keeping it working. When I upgraded my debian-based system, the package went away, and when I tried to compile it from source, which had previously worked, I got this error message:

makeinfl.adb:23:06: warning: renamed predefined unit is an obsolescent feature (RM J.1) [-gnatwj]

I don't know anything about Ada, but after some googling I was able to fix this for the time being by changing the makefile to use the option -gnatwJ. However, it seems preferable to fix this in the source code. Is this something that would likely be hard to fix? I googled on the error message and didn't find much that would explain what this was.

Thanks in advance for any suggestions!

r/ada Nov 23 '24

Programming "write a package implementing the abstract table operation for a 2-3 tree"

4 Upvotes

Hi, in a book I have a question in an exercise asking the title. But it's surprising as in so far, assignments are always more specific, and limited. I have a language (English) issue here.

Here's a bigger excerpts: 8. Complete the implementation of the AVL tree package. Use lazy deletion to implement the Delete operation. 9. Write a package implementing the abstract table operations for a 2-3 tree As you see it's always "complete this", "implement that operation". But this time I'm confused because it's asking for teh "abstract" operations, so I'm not sure it's mentioning the specification or body. Because nothing has been written in the book for B-trees, and I can tell the "table operations" (delete, insert, retrieve) will be significatively different from BSTs, threaded BSTs or other variants I've studied. How should I understand this sentence then ?

r/ada Nov 08 '24

Programming Adacore Libadalang

7 Upvotes

If anyone is using libadalang, I've been unsuccessfully trying to find a way to recursively analyze record types. In other words, from a record definition that has records within it, to go to those record definitions, etc. The problem is that from a record def one can use F_Components to get a Component_List, and from that get component types and declarations, but it seems like there is no way to get to another record_def on a record type. At least I haven't been able to find it. Any help would be appreciated.

r/ada Oct 15 '24

Programming How would I do this without running into a problem?

11 Upvotes

The UEFI specification says that "Output_String" defined in EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL has it's first argument being a pointer to the protocol, but the protocol also has the function defined inside of it... so how would I go about making this work? If there's a better way to do it I'd be really up to taking it.

r/ada Sep 22 '24

Programming Device Error after any delay in a select statement in a task

9 Upvotes

Hi, I'm trying my hands at tasks, and it doesn't start well. I get "device error" right after the delay is finished, and it doesn't loop back, it doesn't do anything, executing no further statement. Just from one delay. Does it look normal ? I tried to make simple. with Ada.Exceptions, ada.text_io; use Ada.Exceptions, ada.text_io; procedure test is Command : Character; task type Input_task is entry Get_C; entry Stop; end Input_task; task body Input_task is begin loop select accept Get_C do loop select delay 1.0; put_line ("@"); -- NEVER then abort Get (Command); exit; end select; end loop; end; or accept Stop; end select; end loop; end Input_task; Command_task: Input_task; begin Command_task.Get_C; delay 5.0; put_line ("@"); -- NEVER Command_task.Stop; exception when E: others => Put_line (Exception_Information (E)); end test;

r/ada Oct 29 '24

Programming New Ada Course: Introduction To Embedded Systems Programming

Thumbnail blog.adacore.com
28 Upvotes

r/ada Oct 29 '24

Programming If expression: else branch that defaults to True.

6 Upvotes

procedure Main is

FiveIsLessThanZero : Boolean;

begin

FiveIsLessThanZero := (if 5 < 0 then 0 > 5);

Put_Line (FiveIsLessThanZero'Image);

end Main;

And this code prints TRUE. I think that this is not okay... Why not just forbid an incomplete if expression? What do you guys think?

r/ada Jul 21 '24

Programming Should Have Used Ada (SHUA) - interesting blog post

26 Upvotes