❌ About FreshRSS

Normal view

There are new articles available, click to refresh the page.
Before yesterdayNewest questions tagged ada - Stack Overflow

How to Overload the Subscript/Subprogram Call Operator in Ada

We all know and love Ada.Containers.Vectors. Here's an example of its usage:

with Ada.Text_IO;
with Ada.Containers.Vectors;

procedure Example is
   use Ada.Text_IO;

   package Vectors_Integer is new Ada.Containers.Vectors (Natural, Integer);
   use Vectors_Integer;

   My_Vec : Vector := 1 & 2 & 3;
   Put_Line (Integer'Image (My_Vec (0)));
end Example;

My question is simple: how does My_Vec (0) work, and how can I recreate this behavior in a type of my own?

I have been searching the internet for a while but I can't find to seem any explanation for how this expression works. The subscript operator, which uses the same syntax as the function call operator, cannot be overloaded using the normal syntax for operator overloading. I've read the package specification for Ada.Containers.Vectors, and there doesn't seem to be any explicit means through which Vector overloads this operator. I had guessed that the Element function might have something to do with it, but have been unable to use it to define a type of my own that replicates Vector's behavior. I'm at a complete loss on how to overload the subscript operator, even though it is clear that it is possible.

Ada design by contracts critical software

I have a question related to applying contracts in a critical environment.

Imagine I have the following function to divide:

function div (dividend, divisor : Float) return Float
with Pre => divisor /= 0;

Well, for me the pre-condition is part of the signature of the function and every client must be aware of the contract, if a client pass a zero to the divisor argument is its fault bacause he is violating the contract and thus the function will fail. In testing, with pre-conditions activated, the code will fail showing a contract violation and, in production with pre-conditions deactivated, would fail raising a constraint.

As a constraint error is not acceptable in a critical environment, this is what the client is requiring me for the implementation, to call a module that manages inconsistencies:

function div (dividend, divisor : Float) return Float is
  if divisor = 0 then
    InconsistencyManager.inconsistency ("Some Log"); --It firstly logs a message and then does an infinite loop

  return dividend / divisor; --If everything is ok, return the division
end div;

For me this side effect for a function its quite weird, and for me violating a contract is like passing the wrong type to a subprogram, the difference is that this kind of error is caught at compilation time and the contract violation, if there aren't enough tests, could stop the execution of the program when is already installed.

Do you really has to protect against human stupidity like this? Do you really has to penalize the function execution making always that question?

How to initialize a record with a list element in ada

By: bal
10 November 2023 at 22:53

When trying to instantiate a list element in a record my program does not work. I get the following error in the declaration of the subtype list_unbounded: hear.adb:25:65: error: prefix must not be a generic package hear.adb:25:65: error: use package instantiation as prefix instead hear.adb:25:70: error: incorrect constraint for this kind of type gnatmake: "hear.adb" compilation error

Procedure hear is:
    ind : Integer;
    Subtype List_Unbounded is Ada.Containers.Doubly_Linked_Lists.List(ELement_Type => Ada.Strings.UNbounded.Unbounded_String);
    Type T_Node is record
        Name : Ada.Strings.Unbounded.UNbounded_String;
        N_List : List_Unbounded;
    end record;

Trying to compile a simple Ada program, getting GNAT compiling error in OS 14.1 (23B73) on a M2 MBP

❯ alr build
β“˜ Building myproj/myproj.gpr...
   [link]         myproj.adb
0  0x10034af43  __assert_rtn + 64
1  0x10024cf43  ld::AtomPlacement::findAtom(unsigned char, unsigned long long, ld::AtomPlacement::AtomLoc const*&, long long&) const + 1411
2  0x100269431  ld::InputFiles::SliceParser::parseObjectFile(mach_o::Header const*) const + 19745
3  0x100279e44  ld::InputFiles::parseAllFiles(void (ld::AtomFile const*) block_pointer)::$_7::operator()(unsigned long, ld::FileInfo const&) const + 1380
4  0x7ff8051315cd  _dispatch_client_callout2 + 8
5  0x7ff805141e3e  _dispatch_apply_invoke + 214
6  0x7ff80513159a  _dispatch_client_callout + 8
7  0x7ff80514099d  _dispatch_root_queue_drain + 879
8  0x7ff805140f22  _dispatch_worker_thread2 + 152
9  0x7ff8052d5c06  _pthread_wqthread + 262
ld: Assertion failed: (resultIndex < sectData.atoms.size()), function findAtom, file Relocations.cpp, line 1336.
collect2: error: ld returned 1 exit status
gprbuild: link of myproj.adb failed
gprbuild: failed command was: /users/sdey02/.config/alire/cache/dependencies/gnat_native_13.2.1_c21501ad/bin/gcc myproj.o b__myproj.o -L/Users/sdey02/myproj/obj/development/ -L/Users/sdey02/myproj/obj/development/ -L/users/sdey02/.config/alire/cache/dependencies/gnat_native_13.2.1_c21501ad/lib/gcc/x86_64-apple-darwin21.6.0/13.2.0/adalib/ /users/sdey02/.config/alire/cache/dependencies/gnat_native_13.2.1_c21501ad/lib/gcc/x86_64-apple-darwin21.6.0/13.2.0/adalib/libgnat.a -Wl,-rpath,@executable_path/..//obj/development -Wl,-rpath,@executable_path/../..//.config/alire/cache/dependencies/gnat_native_13.2.1_c21501ad/lib/gcc/x86_64-apple-darwin21.6.0/13.2.0/adalib -o /Users/sdey02/myproj/bin//myproj
error: Command ["gprbuild", "-s", "-j0", "-p", "-P", "/Users/sdey02/myproj/myproj.gpr"] exited with code 4
error: Compilation failed.

Error seems to be this: ld: Assertion failed: (resultIndex < sectData.atoms.size()), function findAtom, file Relocations.cpp, line 1336.

I ran the alr build command and expected the crate to build but instead got an exited with code 4 error.

I checked other threads and it seems to be an issue with the latest version of cmd line tools. What are my options to fix this?

I am trying to implement this using a circular queue. My program executes but says terminated succesfully when build&ran

LinkSort.adb file

with Ada.Text_IO; use Ada.Text_IO;

procedure LinkSort is

  type JobType is (Accountant, Analysist, Manager, Manufacturing, Programmer, Inventory, Sales, SoftwareEnginner);
  package JobTypeIO is new Ada.Text_IO.Enumeration_IO(JobType); use JobTypeIO;

  type EmpName is (Ben, Betty, Bob, Damon, Darlene, David, Desire, Donald, Dustin, Jerry, Kevin, Mary, Marty, Sable, Sam, Sara, Teddy, Tom);
  package EmpNameIO is new Ada.Text_IO.Enumeration_IO(EmpName); use EmpNameIO;

  type LegalResponce is (yup, y, yes, affirmative, nope, no, n, negative);
  subtype PositiveResponce is LegalResponce range yup..affirmative;
  package LegalIO is new Ada.Text_IO.Enumeration_IO(LegalResponce); use LegalIO;

  package IntIO is new Ada.Text_IO.Integer_IO(Integer); use IntIO;

  type Emp is record
    Name: EmpName;
    Job: JobType;
    age: integer;
  end record;

  SortByJob: Array(JobType) of integer := (others =\> 0);

  SortSpace: Array(1..200) of Emp;
  Avail: integer := 1; -- Dynamic storage allocator.
  Pt: integer;

  Again: LegalResponce := affirmative;


  while (Again in PositiveResponce) loop
    put("Enter name: "); get(SortSpace(Avail).Name); --Get emp info.
    put("Enter Job type: "); get(SortSpace(Avail).Job);
    -- Insert in appropriate list (by job).
    SortSpace(Avail).Next := SortByJob(SortSpace(Avail).Job);
    SortByJob(SortSpace(Avail).Job) := Avail;
    -- Prepare for next dynamically allocated node.
    Avail := Avail + 1; --Using static array allocation as opposed dynamic linked list.
    put("Enter another name (yup or nope): "); get(Again);
  end loop;

  -- Sort by job type.

  for I in JobType loop
    new_line; put("Job Type = "); put (I); new_line;
    Pt := SortByJob(I); -- Point to first node in job list.
    while Pt /= 0 loop
      put(SortSpace(Pt).Name); put(" "); put(SortSpace(Pt).Job);
      put(" link = "); put(SortSpace(Pt).Next,4); new_line;
      Pt := SortSpace(Pt).Next; -- Move down list.
    end loop;
  end loop;

end LinkSort;

main.adb file

procedure Main is
end Main;

Stuck on what I should do next? I've tried to implement everything in the Ada.Text_IO in the main.adb file but errors occurred. I know i need to move something into the main file in order for the program to execute after it has been built. The output statement should be name, job type then sort space number.

Error: declarations must come before begins (Ada) [closed]

procedure Main is


--  Insert code here.procedure LinkSort ;

  type JobType is (Accountant, Analysist, Manager, Manufacturing, Programmer,
             Inventory, Sales, SoftwareEnginner);
package JobTypeIO is new Ada.Text_IO.Enumeration_IO(JobType); use JobTypeIO;

type EmpName is (Ben, Betty, Bob, Damon, Darlene, David, Desire, Donald, Dustin,Jerry, Kevin, Mary, Marty, Sable, Sam, Sara, Teddy, Tom);package EmpNameIO is new Ada.Text_IO.Enumeration_IO(EmpName); use EmpNameIO;

type LegalResponce is (yup, y, yes, affirmative, nope, no, n, negative);subtype PositiveResponce is LegalResponce range yup..affirmative;package LegalIO is new Ada.Text_IO.Enumeration_IO(LegalResponce); use LegalIO;

package IntIO is new Ada.Text_IO.Integer_IO(Integer); use IntIO;null;end Main;

I've tried to insert declarations before begin but more errors pop up. This is supposed to use IO-redirection but I cannot figure out what I am missing.

Can I instantiate a generic within the same unit in Ada?

It doesn't seem like this is possible, but I haven't seen a definitive answer. What I want to do is define a generic subprogram with some generic formal parameters and instantiate it in the same package, like the following simplified and untested example:

    Proc_Address : access System.Address;
    type Param_1_Type (<>) is private;
procedure Procedure_IP(Param_1 : Param_1_Type);

Instance_1_Address : System.Address := ...
procedure Instance_1 is new Procedure_IP(Instance_1_Address, type_1);
Instance_2_Address : System.Address := ...
procedure Instance_2 is new Procedure_IP(Instance_2_Address, type_2);

But this kind of thing keeps resulting in those "access before elaboration" errors. I can't seem to find any pragmas that will affect elaboration of a single subprogram; seems it has to be the whole package. Attempts to move the generic subprogram into a separate package have proven more troublesome than I had hoped because the specific stuff I want the function to do is closely related to other things happening in the same package.

Is there any way to resolve the elaboration order issue, so that I can keep the declaration and instantiations in the same package?

Option B is to rework this in a different way, like maybe passing a function pointer to a non-generic function or something, but doing it as a generic seems to be the cleanest way to go about it, especially since I'll need to refer to each of the intended instances a lot.

Does Ada have a type equivalent to Pascal's set?

I'm learning Ada as a spare-time activity and, while I realise that it is greatly inspired by Pascal, I can't find a type that is similar to Pascal's set.

set is built into the Pascal language itself and uses one bit per element. So, for example, var a: set of char; declares a (typically) 256-bit data type that can hold any set of characters.

In Ada, I can see that it has sets as part of its library (not a built-in language feature) but those are more like Java's HashSet or C++'s unordered_set and take up much more memory than 1 bit per element. Am I missing something?

macOS Sonoma GtkAda installed, but Gnat Studio and others do not see it

I have Macs with macOS Sonoma and I have successfully compiled and installed GtkAda from source that I got from AdaCore, with no errors. It's installed at /usr/local/lib/gnat and /usr/local/lib/gtkada, but nothing sees it. I use Gnat Studio and of course it complains about not finding "gtkada" compiling from the command line has the same issue. I have not updated the LD_LIBRARY_PATH, and related because I don't know how if that's the issue. This works on Linux and Windows very easily, but I'm not sure what else to do at this point. I have listed my Macs with Sonoma, but I've actually never had it work with Ventura either, so I don't think that has anything to do with it. I know I'm missing something, and probably something simple.

Unbounded string `ENCODING_ERROR : bad input at Item`

Why is the following code failing ?

I have picked Characters.Latin_1.Reserved_128 on purpose.

-- File 'print_non_graphic_character.adb'
with Ada.Characters.Latin_1;
with Ada.Text_IO;
with Ada.Strings.Unbounded;

procedure Print_Non_Graphic_Character is
   Text_String : constant String := "Non Graphic Character: " & Ada.Characters.Latin_1.Reserved_128;
   Text_Unbounded_String : constant Ada.Strings.Unbounded.Unbounded_String :=
      Ada.Strings.Unbounded.To_Unbounded_String (Text_String);
   Ada.Text_IO.Put_Line (Text_String);
   Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.To_String (Text_Unbounded_String));
   Ada.Text_IO.Put_Line (Text_Unbounded_String'Image);
end Print_Non_Graphic_Character;

Note that it also fails with:

Ada.Text_IO.Put_Line (Ada.Strings.Unbounded.Unbounded_String'Image (Text_Unbounded_String));
-- File 'print_non_graphic_character.gpr'
project Print_Non_Graphic_Character is
   for Main use ("print_non_graphic_character.adb");
   for Object_Dir use ".objs";

   package Compiler is
      -- "-Og" -- Optimize for debug
      -- "-g" -- Generate debug info
      for Default_Switches ("Ada") use ("-g", "-gnat2020", "-Og");
   end Compiler;

   package Binder is
      for Switches ("Ada") use ("-Es"); --  Symbolic traceback
   end Binder;
end Print_Non_Graphic_Character;

It gives me with GNAT 12.2.0

Non Graphic Character: οΏ½
Non Graphic Character: οΏ½

raised ADA.STRINGS.UTF_ENCODING.ENCODING_ERROR : bad input at Item (25)
0x40e8fb Ada.Strings.Utf_Encoding.Raise_Encoding_Error at a-stuten.adb:126
0x40f38b Ada.Strings.Utf_Encoding.Strings.Decode at a-suenst.adb:163
0x4049a8 Print_Non_Graphic_Character at print_non_graphic_character.adb:13
0x404efa Main at b__print_non_graphic_character.adb:279
0x404658 _start at ???

It is annoying because, when I want to print a record which is commposed with Unbounded_String, I cannot use the 'Image attribute because of the above error and have to print each field and use To_String for Unbounded_String (which is annoying to have when I couple that with generic functions/packages).

Ada interfacing C++: instance destroyed

I want to use a C++ library that implements the Factory Method design pattern.

Below you can see a minimal reproducibable example, including C++ sources and the Ada adapter.

  • Item.h:

    // Product interface
    #ifndef _ITEM_H_
    #define _ITEM_H_
    class Item {
      virtual ~Item() = default;
      virtual void do_something() = 0;
  • ConcreteItem.h:

    #ifndef _CONCRETEITEM_H_
    #define _CONCRETEITEM_H_
    #include "Item.h"
    class ConcreteItem : public Item {
      void do_something();
  • ConcreteItem.cpp:

    #include <stdlib.h>
    #include <iostream>
    #include "ConcreteItem.h"
    void ConcreteItem::do_something() {
      std::cout << "Doing stuff \n";
    ConcreteItem::ConcreteItem() {
      std::cout << "Concrete Item created \n";
      std::cout << "Concrete Item destroyed \n";
  • Factory.h:

    #ifndef _FACTORY_H_
    #define _FACTORY_H_
    #include "Item.h"
    class Factory {
      static Item* get_configured_item ();
      Factory(Factory& other) = delete;
      static Factory* factory;
      static Item* config_item;
  • Factory.cpp:

    #include "Factory.h"
    #include "ConcreteItem.h"
    Factory* Factory::factory = nullptr;
    Item* Factory::config_item = nullptr;
    Item *Factory::get_configured_item() {
      if (Factory::factory == nullptr) {
        Factory::factory = new Factory();
        if (Factory::config_item == nullptr) {
          Factory::config_item = new ConcreteItem();
      return Factory::config_item;
    Factory::~Factory() {
      delete Factory::config_item;

And here I have the Ada files that imports C++ symbols, generated with a call to g++ -c -fdump-ada-spec -C ./Factory.h and doing some modifications to suite my taste:

  • Factory_h.ads:
    limited with Item_h;
    package Factory_h is
      type Factory is limited record
      end record
        with Import => True,
        Convention => CPP;
      function get_configured_item return access Item_h.Item'Class  -- ./Factory.h:9
        with Import => True, 
        Convention => CPP, 
        External_Name => "_ZN7Factory19get_configured_itemEv";
    end Factory_h;
  • Item_h.ads:
    with Interfaces.C;
    package Item_h is
      type Item is limited interface
        with Import => True,
        Convention => CPP;
      --  procedure Delete_Item (this : access Item) is abstract;-- ./Item.h:8
      --  procedure Delete_And_Free_Item (this : access Item) is abstract; -- ./Item.h:8;
      procedure do_something (this : access Item) is abstract;  -- ./Item.h:9
    end Item_h;

And finaly an Ada main to test this silly example:

with Factory_h;
with Item_h;

procedure main is
  configured_item : constant access Item_h.Item'Class :=

end main;

Do you know why if I comment out the Item primitives Delete_Item and Delete_And_Free_Item the call to do_something is never done and the item is destroyed?

If I uncomment them everything works.

Thanks in advance!

Linking erros xerces-c on GNAT

I have to use a C++ library that uses xerces-c. Then I have an Ada project that imports two symbols from the previously mentioned C++ library. When I try to build the main of the Ada project, a bunch of undefined references arises, so I suppose I'm not linking correctly to xerces-c. I've ensured y have the libxerces-c.a and the headers in my path (I'm using CentOS).

This is the package Linker I'm using in my gpr, which I found by googling post of people having similar link errors:

package Linker is
  for Linker_Options use ("-Wl", "-Bstatic", "-lxerces-c", "-Wl", "-Bdynamic");
end Linker;

This is an example of one of the linking erros: undefined reference to `xercesc_3_2::XMLPlatformUtils::Initialize(char const*, char const*, xercesc_3_2::PanicHandler*, xercesc_3_2::MemoryManager*)'

I'm solving the problems for now by creating a gpr library project for xerces-c with for Externally_Built use "True"; and placing the libxerces-c.a manually in the lib directory of that project, but it really sounds weird to me. This way the linking erros disappear and everything seems to work.

Has anybody faced similar problems?

Gcc 13.1.0 macOS Sonoma not compiling Ada or any languages on Intel or M1 Macs

I just upgraded to macOS Sonoma on my Intel and M1 Macs, and Gcc and Alire cannot compile simple Ada programs or any others so I suspect it's a compatibility issue. I am using Gcc 13.1.0 aarch64 and x86_64 on the MacBook Pro/Air M1 and MacBook Pro Core i9 respectively. The error I see among others is "-macosx_version_min has been renamed to -macosx_version_min" also: "exited with code 4" Since I cannot compile Ada programs which is most important, is there a workaround or hack until there are upgraded versions to fix it? The same errors are present on both the Intel and M1 Macs, and I had no issues at all on macOS Ventura.

I tried using Gcc 13.1.0 aarch64 and x86_64 on my MacBook M1s and only the x86_64 version on my Intel MacBook Pro Core i9. I tried using Alire with it's native compilers on both type Macs and its matching gprbuild version. The same errors are present using the terminal editing with "nano" and compiling with "gnatmake" or Gnat Studio using the Gcc 13.1.0 toolchain. It obviously is a compatibility issue between Gcc/Alire and macOS Sonoma. It's not just Ada "Hello, World!", but C and C++ "Hello, World!"

Java Itext7 ADA Issues - setTagged method on PdfDocument increasing the size drastically for pdf pages

I'm using Itext 7.1.7 to generate the pdf and now for ADA Complience, I had to use setTagged method for setting tags on each element. But I'm seeing some issues after making those chagnes when it comes to memory and size. Pleae find the below example code snippet.

BufferedOutputStream bos = new bufferedOutputStream(ostream);
PdfWriter writer = new PdfWriter(bos, (new WriterProperties().setFullCompressionMode(true)).addUAXmpMetadata().setPdfVersion(PdfVersion.PDF_1_7)
OutputStream over = writer.getOutputStream();
PdfDocument pdf = new PdfDocument(new PdfWriter(over));

Document document = new Document(pdf, PageSize
document = document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));

Here we had to create pages that are exceeding 500 Pages and what I observed is, for comply withtoA, when I use pdf.setTwagged(), It's taking log of memory to trocess the page and eneach up downloading the page with larger size. For e.g, if I don't have pdf.sidTaguse for a 500 pag()es file, the size is like 10mb but hen I use pdf.setTagged(), it's going upto 300+mb.

So how can I gdoes the size impacts when I use setTagged?ehe pdf with the same size yet ADAmeeting the Complience?

Get call stack in string format

Is there a way to print call stack when printing a message ?

I have a procedure:

procedure DoSomething (myParameter : in MyType)
  isOk : Boolean := False;
  isOk := FunctionReturningFalseWhenError(myParameter);
  if not isOk
    MyDisplayFunction(GNAT.Source_Info.File & ":" & Positive'Image(GNAT.Source_Info.Line) & ": Error with DoSomething");
  end if;
end DoSomething;

This procedure is called many times and I want to have more information to print (like call stack).

Ada: (gpr)install package with multiple shared libraries

I have an Ada library project creating a shared library that has dependencies on other prebuilt shared libraries (c/c++). Unfortunately the prebuilt libraries can’t be installed system wide and I am looking for a project setup without user specific library path’s.

Therefor I want to create a GPR project that β€œconfigures/installs” the Ada library and its dependencies with β€˜gprinstall’ so the Ada library can be use out-of-the-box in any Ada executable project.

I figured out that I can make a separate β€œexternally_built” Ada library project for every dependency there is and run a recursive gprinstall on the Ada library project. This will work but adds more packages to the Ada environment than I like so I want to know if there is a better/elegant way to include (extra) shared libraries in a Ada project? (1)

Form the Ada (library) project standpoint the external built libraries kinda belong together, so it would be great if they can be bundled together in one package and installed with gprinstall.

Although I am not sure if this is the way to go, I am trying to get the externally built libraries to piggy-bag with the gprinstall of the Ada library project but without success, maybe someone has an idea how to do this? (2) It’s seems gprbuild can only output one object, is this so? (3)

Thanks in advance and for your time, Ingmar

Initialise type from address

I want to initialise a type from a System.address. For example :

    type T_Generic is private;
package MyPackage is
    G_Addr : System.Address;
    procedure Register (myAddr : System.address);
    procedure MyProcedure (myAddr : System.address);
end MyPackage;

package body MyPackage is
    procedure Register(myAddr : System.address)
        G_Addr := myAddr;
    end MyProcedure;

    procedure MyProcedure (myAddr : System.address)
        myVar : T_Generic with address => myAddr;
        if (myAddr = G_Addr)
            -- work with myVar 
        end if;
    end MyProcedure;
end MyPackage;

But I cannot compile this piece of code myVar : T_Generic with address => myAddr; :

aspect specification is an Ada 2012 feature

unit must be compiled with -gnat2012 switch

I cannot change compilation's options, how can I do ?