Why does the Ada compiler allow a range violation? Why does my type declare a runtime object?

Why does the Ada compiler allow a range violation? He gives a warning, but why does he allow him to pass if it is a mistake anyway? Is there a practical scenario in which this is a useful behavior?

And most importantly: why is the type declaration an instance of the runtime? I mean, the 3rd line of sample code is what I expect to be evaluated ahead of time. I thought that only the 5th line would “make” it in the executable file. Why not? Is this something useful? Am I missing something or misunderstood?

with Ada.Text_IO; procedure question is subtype Test is Natural range -1 .. 10; begin Ada.Text_IO.Put_Line ("foobar"); end; 

Note. The result is identical to "type Test is new Natural range -1..10;"

Note: GNAT 4.6

+3
source share
1 answer

This comp.lang.ada post assumes that you need at least -gnato -fstack-check command-line options for Gnat as an Ada compatible compiler.

However, this is not a problem: the compiler warns of a range error; with gnat i get:

 gnatmake -gnato -fstack-check question question.adb:3:35: warning: static value out of range of type "Standard.Natural" question.adb:3:35: warning: "Constraint_Error" will be raised at run time 

and obvious runtime error.

In this case, since the range is static, the compiler could catch an error; but, as you might imagine, in the general case, the type cannot be completely determined until runtime, as in the following example.

 with Ada.Text_IO; with Ada.Command_Line; procedure question is subtype Arguments is Natural range 1 .. Ada.Command_Line.Argument_Count; begin for i in Arguments loop Ada.Text_IO.Put_Line ("Argument " & integer'image(i) & " is " & Ada.Command_Line.Argument(i)); declare OneArg : constant String := Ada.Command_Line.Argument(i); subtype Characters is Natural range OneArg'range; begin null; -- process the string here end; end loop; end; 

None of the subtypes are known here until you run the program.

The declare block shows the corresponding template, which I find very useful, which allows us to use not only the [sub] variables, but also selects objects with a variable size on the stack so that they automatically return and change at each iteration of the loop. (You could allocate "new" and free with "unchecked_deallocation", as in other languages, but very often, since there is simply no need here)

+7
source

Source: https://habr.com/ru/post/1273594/


All Articles