How to pass duration for discriminant ada? - ada

I'm playing around with ADA, trying to get my grips on it. I still have a hard time figuring out the discriminant part though. I have a task with one discriminant, and I'm trying to pass a duration to it. However it tells me:
package Procedures is
task type WhatchDog(dur : Duration := 1.0) is
entry Reset(start : in Time);
entry Sync(timedOut : out Boolean);
end WhatchDog;
end Procedures;
with Procedures;
procedure Main is
watch : Procedures.WhatchDog(dur => 0.5);
begin
null;
end Main;
Discriminants must have a discrete or access type.
When I change my discriminant type to an access type,
task type WhatchDog(dur : access Duration := 1.0) is
it gives me the following warning:
Expected an access type with designated type "Standard Duration"
Found type universal real
I know there are other ways to realize a constructor, such as creating an entry point. But I would like to know what I'm doing wrong here, and understand the error I'm making.
The google work I've done so far doesn't really shine any light on this, and only makes use of real types which seem to work fine. Here for example:
http://www.adaic.org/resources/add_content/docs/95style/html/sec_6/6-1-3.html

In your attempted workaround you're trying to assign a Duration to an Access. The proper assignment would be, if going that way:
task type WatchDog (Dur : access Duration := new Duration'(1.0)) is
at the price of having an allocation that is never deallocated, that is, a minor memory leak. That could be a problem if you create/destroy many instances of the task type during a long-lived program, but in that case you have to also take care of reaping the tasks (at least in Gnat).
In this case, I would either have a first entry to pass the Duration value to the task, or a value in milliseconds (or whatever is appropriate) using a Natural as discriminant, and converting it inside the task. Certainly it is an itch in the language.

I am not sure this is the intended use of discriminants. Here, duration is really a configuration of your instances, but doesn't impact the layout of the type in memory. So I think it would be better (and certainly more usual) to either have a Configure entry that can be called to do the initial setup, or if this really needs to be given when the instance is created, you could try creating a generic with a formal Duration parameter.

The reason that you cannot assign 1.0 to dur (the access discriminant) is that dur is of a pointer type (anonymous, access to Duration) while 1.0 is a numeric literal. In short, you cannot assign a real value to a pointer variable, only a pointer value to a pointer variable. See Alex's answer for one way to get one.
The type Duration is not a discrete type, i.e. neither integral nor enumerated. But discrete is what a discriminant must be if not of an access type, given discriminants' original intent as outlined by manuBriot.
So, to initialize some aspect of task objects by passing a value for dur, you need pointers. The following small rewrite does not use an allocator (new), it uses names for duration values, of which it then takes the pointer using 'Access.
package Procedures is
Duration_By_Default : aliased constant Duration := 1.0;
task type Whatchdog
(dur : access constant Duration := Duration_By_Default'Access)
is
entry Reset(start : in Time);
entry Sync(timedOut : out Boolean);
end WhatchDog;
end Procedures;
with Procedures;
procedure Main is
Desired_Duration : aliased constant Duration := 0.5;
watch : Procedures.WhatchDog(dur => Desired_Duration'Access);
begin
null;
end Main;
Note the implications of having an access value point to a variable duration, instead of a constant duration as shown here.
Alternatively, perform a computation that produces a Duration value from some integer discriminant, named dur_in_msec, say.
task body Whatchdog is
dur : constant Duration := Duration(Float(dur_in_msec) / 1_000.0);

Related

How is the `'Old` attribute in a **Post** contract handled for access types that might got deallocated inside the function or procedure?

Assume having the following setup:
type My is new Integer;
type My_Acc is access My;
procedure Replace(Self : in out My_Acc; New_Int : Integer)
with Pre => New_Int /= Self.all, Post => Self'Old.all /= Self.all;
Note: Code above might not be fully valid, but I hope the concept is understandable.
Now what happens if Unchecked_Deallocation() is used on Self inside Replace
and a new Integer is allocated and set to Self (This should result in Self'Old pointing to a now invalid memory location)?
Does Ada keep kind of a snapshot where Self'Old points to the previous memory location, but before Unchecked_Deallocation() is executed?
If Self'Old would get invalid for use in the Post contract, how could you still access the previous value? Is it possible to create a manual snapshot in the Pre contract that can then be used in Post? Maybe it can be achieved using Ghost_Code?
I want to make everything in Spark, in case that changes something.
Edit: Fixed Self to in out as mentioned by Simon Wright.
Edit: Fixed type of Self to allow null
It may be that the latest versions of SPARK support access types; it used not to, at all.
First, your Not_Null_My_Acc needs to be a subtype of My_Acc, unless you meant it to be a type in its own right.
Second, you can’t deallocate Self inside Replace and allocate a new value; Self is in-mode, & hence not writable.
Third, you can’t apply ’Old to Self, because
warning: attribute "Old" applied to constant has no effect
What you can say is
Post => Self.all'Old /= Self.all;
In ARM 6.1.1(26ff) it says
Each X'Old in a postcondition expression that is enabled denotes a constant that is implicitly declared at the beginning of the subprogram body, entry body, or accept statement.
The implicitly declared entity denoted by each occurrence of X'Old is declared as follows:
...
X'Old : constant S := X;
... in other words, nothing fancy is expected, just a straight copy of (in this case) Self: not Self.all.
So, if your Replace deallocates Self, then Self’Old is a dangling reference, and erroneous.
I suggested previously that changing the postcondition to
Post => Self.all'Old /= Self.all;
would be safe; why wouldn’t that meet your requirements? is there something going on you haven’t told us about?
Note the subtle difference between Self’Old.all and Self.all’Old. The first one takes a copy of Self as it was before the call, which gets dereferenced after the call (by which time it’s pointing into hyperspace), while the second one dereferences the prior Self and copies the integer value it finds there; on return that’s still valid.

Ada deferred constant finalized using complicated calculation; where to put the code?

I needed the result of a rather complex calculation to define a private type, something like this:
generic
top_m : Positive;
package Mystic is
type T is private;
private
type Table is array (Positive range <>) of Positive;
function reallyComplicatedFunction(x : Positive) return Table;
mytable : constant Table := reallyComplicatedFunction(top_m);
-- I will need mytable for calculations later
type T is array (mytable'Range) of Natural;
-- T is very different from Table, except they share their Range
end Mystic;
I needed the type T to depend on generic parameter top_m in a really complicated way, embodied by reallyComplicatedFunction(.). The function is defined in the body of package Mystic, but it does not use anything else declared by the package.
To my surprise this setup works just fine. Maybe I'm just lucky, because as far as I can tell from decyphering the ARM, this kind of invocation of the function is merely 'legal' but it is not guaranteed not to throw a Program_Error. I interpret this as "it would be too restrictive to forbid this sort of stuff entirely, but the compiler can't be expected to determine its feasibility in all cases either, so we'll just allow you to experiment with it". And then there's the rather significant possibility that I'm completely misreading the reference manual. Anyway, books on Ada give rather stern warnings about this sort of thing, typically around the discussion of pragma Elaborate et al., such that I almost didn't try this solution.
I've also tried to put the function in a private child package of Mystic, but I could not resolve circularities between the child implicitly depending on the parent and the parent specification depending on the child. Anyway, this function is not an extension of Mystic but a necessary code to initialize it.
My question would then be: where is the proper place for such a function?
ETA: at the request of Simon Wright, here's the part of the ARM I struggle with: http://www.ada-auth.org/standards/12rm/html/RM-3-11.html entries 9, 10/1 and 14:
For a construct that attempts to use a body, a check
(Elaboration_Check) is performed, as follows:
For a call to a (non-protected) subprogram that has an explicit body, a check is made that the body is already elaborated. This check
and the evaluations of any actual parameters of the call are done in
an arbitrary order.
...
The exception Program_Error is raised if any of these checks fails.
As far as I understand, the construct mytable : constant Table := etc. tries to use the body of reallyComplicatedFunction, so it must check whether it was elaborated or not. I assume - this is a weak point in my reasoning but this is what I understood - that elaboration of the body of reallyComplicatedFunction only occurs during the elaboration of the body of package Mystic, so my function won't be elaborated at the time it is called from the private part of the package specification. Nonetheless, I don't receive the Program_Error as promised when using (an instance of) the package.
ETA2: following a remark from trashgod, I've tried turning package Mystic into a non-generic one; made top_m into a visible constant and removed the genericity part. The compiler now catches the circularity I was worried about from the beginning and the program exits with Program_Error: access before elaboration. It's as if the body of a generic package was elaborated before the first instantiation, or rather before the elaboration of the specification of said package during instantiation. Since I'd expect Ada to cater to this kind of need (of hiding complex calculations needed to instantiate a package in the body of said package), I'd not be surprised if it worked as per the standard, but I don't recall reading anything like this anywhere and would like to know the exact rules. Something very smart is going on because if I make the body of the function dependent on type T, the compiler warns about 'call to Tt may occur before body is seen' at the point of package instantiation (I guess 'Tt' is some internality of type T), and when the program is run, it throws a Program_Error complaining about access before elaboration, pointing to the first place where an object of type T is instantiated by another function I have called by reallyComplicatedFunction for testing purposes.
Edit, reflecting the comment that explain why reallyComplicatedFunction should not be public.
If I understand correctly, the function does not really not depend on Mystic, but reallyComplicatedFunction should be private. In that case, I'd try putting it elsewhere, and keep the dependency on top_m. I have assumed that Table could also be moved, even though formally it is creating a dependence of reallyComplicatedFunction, Table being in its parameter profile.
To resolve, a new private place is created in a hierarchy, a private sibling gets the declarations and will only be used in the private part of original Mystic. Hence, private with in the latter's context clause.
package Top is end;
private generic
top_m : Positive;
package Top.Outsourced is
type Table is array (Positive range <>) of Positive;
function reallyComplicatedFunction(x : Positive) return Table;
end Top.Outsourced;
private with Top.Outsourced;
generic
Top_M : Positive;
package Top.Mystic is
type T is private;
private
package Initializer is new Top.Outsourced (top_m);
subtype Table is Initializer.Table;
mytable : constant Table := Initializer.reallyComplicatedFunction (top_m);
-- I will need mytable for calculations later
type T is array (mytable'Range) of Natural;
-- T is very different from Table, except they share their Range
end Top.Mystic;
package body Top.Outsourced is
function reallyComplicatedFunction(x : Positive) return Table is
Limit : Positive;
begin
Limit := Positive'Min (top_m, 1) + x/2;
return Result : Table (1 .. Limit);
end reallyComplicatedFunction;
end Top.Outsourced;
Assuming (since you didn't specify it) the array returned from reallyComplicatedFunction has the range 1..top_m, you could define a new subtype and use that as the range for both arrays:
subtype My_Range is Positive range 1..m_top
type Table is array (My_Range) of Positive;
type T is array (My_Range) of Natural;
and move both my_table and reallyComplicatedFunction inside the package body.

Ada Function Parameter as Access Type or Not

I am refactoring some code originally written using access types, but not yet tested. I found access types to be troublesome in Ada because they can only refer to dynamically allocated items, and referring to items defined at compile time is apparently not allowed. (This is Ada83.)
But now I come to a function like this one:
function Get_Next(stateInfo : State_Info_Access_Type) return integer;
I know that I can easily pass parameter "contents" of an access type rather than the access pointer itself, so I am considering writing this as
function Get_Next(stateInfoPtr : State_Info_Type) return integer;
where State_Info_Type is the type that State_Info_Access_Type refers to.
With this refactor, for all intents and purposes I think I'm still really passing what amounts to an implicit pointer back to the contents (using the .all) syntax).
I want to refactor and test starting with the lowest level functions, working my way up the call chains. My goal is to push the access types out of the code as I go.
Am I understanding this correctly or am I missing something?
I think original author(s), and possibly OP are missing a point, that is, how Ada parameter modes work.
To quote #T.E.D
Every Ada compiler I know of under the hood passes objects larger than fit in a machine register by reference. It is the compiler, not the details of your parameter passing mechanisim, that enforces not writing data back out of the routine.
Ada does this automatically, and leaves the parameter modes as a way of describing the flow of information (Its NOT the C style reference / value conundrum). See the useful wikibook.
What worries me is that the code you have inherited looks like the author has used the explicit access parameter type as a way of getting functions to have side effects (usually considered a bad thing in Ada - World).
My recommendation is to change your functions to:
function Get_Next(State_Info : in State_Info_Type) return Integer;
and see if the compiler tells you if you are trying to modify State_Info. If so, you may need to change your functions to procedures like this:
procedure Get_Next(State_Info : in out State_Info_Type;
Result : out Integer);
This explicitly shows the flow of information without needing to know the register size or the size of State_Info_Type.
As an aside Ada 2012 Will allow you to have functions that have in out parameters.
To quote #T.E.D,
Every Ada compiler I know of under the hood passes objects larger than fit in a machine register by reference. It is the compiler, not the details of your parameter passing mechanisim, that enforces not writing data back out of the routine.
Since this code hasn’t yet been tested, I think you are completely right to rework what looks like code written with a C mindset. But, you oughtn’t to mention pointers at all; you suggested
function Get_Next(stateInfoPtr : State_Info_Type) return integer;
but this would be better as
function Get_Next(stateInfo : State_Info_Type) return integer;
or even (IMO) as
function Get_Next(State_Info : State_Info_Type) return Integer;
to use more standard Ada styling! My editor (Emacs, but GPS can do this too) will change state_info into State_Info on the fly.
As an afterthought, you might be able to get rid of State_Info_Type_Pointer altogether. You mention .all, so I guess you’ve got
SITP : State_Info_Type_Pointer := new State_Info_Type;
... set up components
Next := Get_Next (SITP.all);
but what about
SIT : State_Info_Type;
... set up components
Next := Get_Next (SIT);
I wouldn't recommend this, but you can get pointers to variables in Ada 83 by using 'Address.
You can then use overlays (again this is all Ada83 stuff) to achieve access...
function something(int_address : Address) return integer
is
x : integer;
for x'address use int_address;
begin
-- play with x as you will.

Ada Actual for this must be a variable in out mode

I am making a program in Ada for Data Structures and Algorithms class.
My current problem is the error 'actual for "this" must be a variable'
I did some looking around and I read about it being because of in out mode, but I'm not entirely grasping why it's happening to me I guess.
The Examples I seen made sense but I guess since it's my coding I'm just not seeing it?
Procedure AddUnmarked(g:Grid; this:Linked_List_Coord.List_Type; c:Cell) is
cNorth : Cell := getCell(g, North(c));
cEast : Cell := getCell(g, East(c));
cSouth : Cell := getCell(g, South(c));
cWest : Cell := getCell(g, West(c));
Begin
if CellExists(g, cNorth) and not cNorth.IsMarked then
Linked_List_Coord.Append(this, cNorth.Coords);
elsif CellExists(g, cEast) and not cEast.IsMarked then
Linked_List_Coord.Append(this, cEast.Coords);
elsif CellExists(g, cSouth) and not cSouth.IsMarked then
Linked_List_Coord.Append(this, cSouth.Coords);
elsif CellExists(g, cWest) and not cWest.IsMarked then
Linked_List_Coord.Append(this, cWest.Coords);
end if;
End AddUnmarked;
before "this" is passed to the function it is a Linked_List of my self defined type Coord (2 integers). It is initialized and has had a Coordinate pair added to it before the list is passed to the function above in my code.
What it means is that the list cannot be modified unless you are passing it as a modifiable parameter, that is, in out.
To elaborate, think of LIST_TYPE as being a handle to a tagged-type object; in order to ensure that LIST_TYPE is valid you need to pass it in via an in parameter (or create/manipulate a local object), but to pass out your results you need an out parameter.
So, in order to do your operations on an already-existing object {and get the results back} you need in out.
In Ada, subroutine parameters all have a usage mode associated with them. The available modes are in, out, and in out*. If you don't specify a mode, (like you didn't in your code), then it defaults to in only.
The modes specify what you can do with that parameter on the inside of the subprogram. If you want to read a value passed in from outside the routine, it must have in on it. If you want to write to the parameter (and/or possibly have it read outside the routine), then it must have out on it.
Since none of your parameters have out on them, you cannot write to any of them.
(* - There's another possible mode: access, but that's an advanced topic).

Trying to make a function generic, but getting hung up

I have a variable in a package (rec in this case) that needs to be set when called from package 3, but it's private. Previously the function set_true only set rec to true, so it wasn't a big deal. But I have another package that does the same processing (I'm giving a simple example, but my literal case is more complex), so I thought, well I could pass in the variable I want modified, and let it get changed. Is the only way to set rec in the below layout, to create a second function in package one, that calls set_true with rec as the parameter? I would like to avoid having to keep creating additional functions to handle the local variables. I can't move the variable to public (spec) as I am trying to follow convention and this "type" of variable isn't public anywhere else, and I don't want anyone to be able to just set it on their own (I want functions to have to set). I don't want to have to create a second function named for example set_local_true, and creating an overloaded function set_true, with no parameters, that calls set_true(value => rec) just seems deceptive, does anyone have any better suggestions with the limitations I have?
My two requirements:
Can't make the local variable public.
Be able to use the function to calculate something both externally and internally.
package one is
procedure set_true(value : out Boolean);
end one;
package body one is
rec : Boolean;
begin
procedure set_true(value : out Boolean)
begin
value := true;
end set_true;
end one;
package body two is
local_rec : Boolean;
begin
procedure call_function is
begin
one.set_true(value => local_rec);
end call_function;
end two;
package body three is
begin
procedure call_function is
begin
one.set_true(value => <PACKAGE ONE'S REC))
end call_function;
end three;
EDIT: Or perhaps, what would be a better naming convention for the functions to specify that they are modifying the variable that is local to that package? Set_Local_True again is deceptive cause if you call it from package 3, you're not setting your local true, you're setting package one's local to true....
First off, this is very silly code. I'll assume it is shorthand for something else. But as presented, I can assure you that your clients can set their own booleans themselves without you writing a routine to do it for them. In fact, they can do it better. For the remainder of this answer, I'll assume you aren't acutally writing variables to set booleans for people, but rather doing something of actual use. If not, ignore the rest of this answer and just delete your silly routines.
Secondly, if you are creating a routine with a single out parameter, then unless the object happens to be very large, you should probably make it a function instead. That will allow your clients to use functional programming if they chose. The way you have it, the poor coder has to stop and create a special variable just to call your routine, even if they only want to do it once.
Thirdly, rather than using a unique set routine for each state, I generally prefer to pass in the requested state.
function Set_Frobnost (New_State : boolean := true) return boolean;
If the state is really and truly boolean (no possible third state in the future), then it is debateable. However, it can be a big advantage to your client if they might already have to store the state in a variable (or loop through it).
Your edit about naming shows me you are on the right track.
You should do one of two things here.
Find the higher-level concept controlled by that variable, and name the "setter" routine after that.
Get the hell out of the way and put the flag variable in the pacakge spec.
If you have to access private variables, you might to do it in a child package.
package One is
procedure Foo (X : Boolean);
private
One_Private : Boolean;
end One;
and then
package body One.Two is
procedure Bar is
One.Foo (One.One_Private);
end Bar;
end One.Two;
Elements in the "private" part of a package are like "protected" entities in C++/Java. Truly private variables (only in package body) are not accessible from anywhere else.

Resources