How does Ada programming language implement packages? Does it use a struct? a record? and where can I find an example of this implementation if possible?
2 Answers
The language doesn't really specify how the underlying implementation should be done. That is left up to the compiler vendor. I doubt they use a struct or record. Any answer you find will be vendor specific and not so much language specific. It's worth noting that the most common compiler, GNAT, is open source, so the source code is available to view and try and make out how they do it. Again, that is just one potential implementation. Other compilers may do it differently.
If you just mean what does an example of a package potentially look like:
empty my_package.ads:
package My_Package is
-- Empty package
end My_Package;
my_package.ads with a "class" like type:
package My_Package is
type My_Type is tagged private;
function Get_Value(Self : My_Type) return Integer;
private
type My_Type is tagged record
Value : Integer := 2;
end record;
end My_Package;
my_package.adb with definitions of operations:
package body My_Package is
function Get_Value(Self : My_Type) return Integer is
begin
return Self.Value;
end Get_Value;
end My_Package;
As you can see, packages can be empty. They can have types, operations, or both. Packages are where encapsulation is handled (as opposed to the type like C++ and Java do). So you can have private types and operations in a package, but not do any traditional object oriented programming.
An Ada package is mainly just a namespace, and so has no effect on the executable code emitted by a compiler.
Let me try to illustrate this.
The Ada:
...
A := B;
...
might emit code such as:
...
CPY B, A
...
The Ada:
package P is
B: Integer;
...
end;
...
A := P.B;
...
might emit exactly the same code. The fact that B is now inside a package does not change the emitted code.
A package can have initialisation code, which will be implemented very like a procedure. An instantiation of a generic package might be implemented like a record (whose components hold the generic parameters), or it might be expanded in-place, in which case the situation is the same as with a non-generic package.
Interesting question! Why do you ask?