text
stringlengths 437
491k
| meta
dict |
|---|---|
with datos; use datos;
with rotar_derecha;
procedure insertar_elemento_en_pos (num, pos: in Integer; R: in out Lista_Enteros) is
-- pre: la posicion de insercion sera menor o igual
-- que el numero de elementos que contenga la lista +1
-- post: el elemento quedara insertado en la posicion de insercion
-- y el resto de los elementos quedaran desplazados hacia la derecha
Aux: Integer;
begin
R.Cont := R.Cont + 1;
Aux := R.Numeros(pos);
R.Numeros(pos) := num;
R := rotar_derecha(pos, R);
R.Numeros(pos+1) := Aux;
end insertar_elemento_en_pos;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
WITH Ada.Text_Io; USE Ada.Text_Io;
procedure Ver_Substring_Opcional is
-- salida: 11 booleanos(SE)
-- post: corresponden a cada uno de los casos de pruebas dise�ados.
-- pre: { True }
function Substring_Sub(
S : String;
Sub : String)
return Boolean is
-- EJERCICIO 3- ESPECIFICA E IMPLEMENTA recursivamente el subprograma
-- Substring_aa que decide si el string S contiene el substring 'aa'.
BEGIN
-- Completar
if S'Size < Sub'Size then
return False;
end if;
if S(S'First .. S'First + 1) = Sub then
return True;
end if;
return Substring_Sub(S(S'First + 1 .. S'Last), Sub);
end Substring_Sub;
-- post: { True <=> Substring(S, Sub) }
begin
Put_Line("-------------------------------------");
Put("La palabra vacia no contiene el string 'aa': ");
Put(Boolean'Image(Substring_Sub("", "aa")));
New_Line;
New_Line;
New_Line;
Put_Line("-------------------------------------");
Put_Line("Palabras de 1 caracter");
Put("-- La palabra de 1 caracter 'a' no contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("a", "aa")));
New_Line;
Put("-- La palabra de 1 caracter 'b' no contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("b", "aa")));
New_Line;
New_Line;
New_Line;
Put_Line("-------------------------------------");
Put_Line("Palabras de varios caracteres");
Put("-- 'aaaa' contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("aaaa", "aa")));
New_Line;
Put("-- 'bbbb' no contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("bbbb", "aa")));
New_Line;
Put("-- 'abab' no contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("abab", "aa")));
New_Line;
Put("-- 'baba' no contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("baba", "aa")));
New_Line;
Put("-- 'abba' no contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("abba", "aa")));
New_Line;
Put("-- 'aabb' contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("aabb", "aa")));
New_Line;
Put("-- 'baab' contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("baab", "aa")));
New_Line;
Put("-- 'bbaa' contiene el substring 'aa': ");
Put(Boolean'Image(Substring_Sub("bbaa", "aa")));
New_Line;
Put_Line("-------------------------------------");
end Ver_Substring_Opcional;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with System.Native_Time;
with C.winbase;
with C.windef;
package body System.Native_Execution_Time is
use type C.windef.WINBOOL;
-- implementation
function Clock return CPU_Time is
CreationTime : aliased C.windef.FILETIME;
ExitTime : aliased C.windef.FILETIME;
KernelTime : aliased C.windef.FILETIME;
UserTime : aliased C.windef.FILETIME;
begin
if C.winbase.GetProcessTimes (
C.winbase.GetCurrentProcess,
CreationTime'Access,
ExitTime'Access,
KernelTime'Access,
UserTime'Access) =
C.windef.FALSE
then
raise Program_Error; -- ???
else
return Native_Time.To_Duration (UserTime);
end if;
end Clock;
end System.Native_Execution_Time;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Ada.Finalization;
generic
type Resolve_Element is private;
-- Type for reolving a promise
type Reject_Element is private;
-- Type for rejecting a promise
package Network.Generic_Promises is
pragma Preelaborate;
type Listener is limited interface;
-- A listener on promise events
type Listener_Access is access all Listener'Class with Storage_Size => 0;
not overriding procedure On_Resolve
(Self : in out Listener;
Value : Resolve_Element) is abstract;
-- The promise is resolved with a Value
not overriding procedure On_Reject
(Self : in out Listener;
Value : Reject_Element) is abstract;
-- The promise is rejected with a value
type Promise is tagged private;
-- Promise is an object to be resolved or rejected with some value
function Is_Attached (Self : Promise'Class) return Boolean;
-- The promise has a corresponding controlling part
function Is_Pending (Self : Promise'Class) return Boolean
with Pre => Self.Is_Attached;
-- The promise has not resolved nor rejected yet
function Is_Resolved (Self : Promise'Class) return Boolean
with Pre => Self.Is_Attached;
-- The promise has been resolved
function Is_Rejected (Self : Promise'Class) return Boolean
with Pre => Self.Is_Attached;
-- The promise has been rejected
procedure Add_Listener
(Self : in out Promise'Class;
Value : not null Listener_Access);
-- Let a listener to be notified when the promise is settled
procedure Remove_Listener
(Self : in out Promise'Class;
Value : not null Listener_Access);
-- Let a listener to be notified when the promise is settled
type Controller is tagged limited private;
-- Controlling part of the promise
function Is_Pending (Self : Controller'Class) return Boolean;
-- The promise has not resolved nor rejected yet
function Is_Resolved (Self : Controller'Class) return Boolean;
-- The promise has been resolved
function Is_Rejected (Self : Controller'Class) return Boolean;
-- The promise has been rejected
function To_Promise (Self : access Controller'Class) return Promise
with Post => To_Promise'Result.Is_Attached;
procedure Resolve
(Self : in out Controller'Class;
Value : Resolve_Element)
with Pre => Self.To_Promise.Is_Pending,
Post => Self.To_Promise.Is_Resolved;
-- Resolve the promise and notify listeners
procedure Reject
(Self : in out Controller'Class;
Value : Reject_Element)
with Pre => Self.To_Promise.Is_Pending,
Post => Self.To_Promise.Is_Rejected;
-- Reject the promise. This will notify the listener
private
type List_Node;
type List_Node_Access is access List_Node;
type List_Node is record
Item : not null Listener_Access;
Next : List_Node_Access;
end record;
type Promise_State is (Pending, Resolved, Rejected);
type Promise_Data (State : Promise_State := Pending) is record
case State is
when Pending =>
Listeners : List_Node_Access;
Callback : Listener_Access;
when Resolved =>
Resolve_Value : Resolve_Element;
when Rejected =>
Reject_Value : Reject_Element;
end case;
end record;
type Controller is new Ada.Finalization.Limited_Controlled with record
Data : Promise_Data;
end record;
overriding procedure Finalize (Self : in out Controller);
type Controller_Access is access all Controller'Class
with Storage_Size => 0;
type Promise is tagged record
Parent : Controller_Access;
end record;
end Network.Generic_Promises;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
local json = require("json")
name = "C99"
type = "api"
function start()
set_rate_limit(10)
end
function check()
local c
local cfg = datasrc_config()
if cfg ~= nil then
c = cfg.credentials
end
if (c ~= nil and c.key ~= nil and c.key ~= "") then
return true
end
return false
end
function vertical(ctx, domain)
local c
local cfg = datasrc_config()
if cfg ~= nil then
c = cfg.credentials
end
if (c == nil or c.key == nil or c.key == "") then
return
end
local resp, err = request(ctx, {['url']=build_url(domain, c.key)})
if (err ~= nil and err ~= "") then
log(ctx, "vertical request to service failed: " .. err)
return
end
local d = json.decode(resp)
if (d == nil or d.success ~= true or #(d.subdomains) == 0) then
return
end
for i, s in pairs(d.subdomains) do
new_name(ctx, s.subdomain)
end
end
function build_url(domain, key)
return "https://api.c99.nl/subdomainfinder?key=" .. key .. "&domain=" .. domain .. "&json"
end
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- Test Jacobi Eigendecomposition of real valued square matrices.
-- Uses Intel's 18 digit Real to estimate eigval err in 15 digit real,
-- so not very portable.
with Jacobi_Eigen;
with Test_Matrices;
with Text_IO; use Text_IO;
procedure jacobi_eigen_tst_2 is
type Index is range 1 .. 138;
-- the test matrix is square-shaped matrix on: Index x Index.
-- eg Hilbert's matrix is a square matrix with unique elements on the range
-- Index'First .. Index'Last. However, you have the option or using any
-- diagonal sub-block of the matrix defined by Index x Index
Starting_Col : constant Index := Index'First + 0;
Final_Col : constant Index := Index'Last - 0;
-- Can't change:
Final_Row : constant Index := Final_Col;
type Real is digits 18;
type Matrix is array(Index, Index) of Real;
--pragma Convention (Fortran, Matrix); --No! prefers Ada convention.
package Eig is new Jacobi_Eigen
(Real => Real,
Index => Index,
Matrix => Matrix);
use Eig;
-- Eig exports Col_Vector
package rio is new Float_IO(Real);
use rio;
type Real_15 is digits 15;
type Matrix_15 is array(Index, Index) of Real_15;
A : Matrix_15;
--pragma Convention (Fortran, Matrix); --No! prefers Ada convention.
package Eig_15 is new Jacobi_Eigen
(Real => Real_15,
Index => Index,
Matrix => Matrix_15);
-- Eig exports Eig_15.Col_Vector
package Make_Square_Matrix is new Test_Matrices (Real_15, Index, Matrix_15);
use Make_Square_Matrix;
Eig_vals_15 : Col_Vector := (others => 0.0);
procedure d15
(A : in Matrix_15;
Eigval : out Col_Vector) is
Q_tr, A_tmp : Matrix_15;
Eigenvalues : Eig_15.Col_Vector := (others => 0.0);
No_of_Sweeps_Done, No_of_Rotations : Natural;
begin
A_tmp := A;
Eig_15.Eigen_Decompose
(A => A_tmp, -- A_tmp is destroyed
Q_tr => Q_tr,
Eigenvals => Eigenvalues,
No_of_Sweeps_Performed => No_of_Sweeps_Done,
Total_No_of_Rotations => No_of_Rotations,
Final_Col => Final_Col,
Start_Col => Starting_Col,
Eigenvectors_Desired => True);
Eig_15.Sort_Eigs
(Eigenvals => Eigenvalues,
Q_tr => Q_tr,
Start_Col => Starting_Col,
Final_Col => Final_Col,
Sort_Eigvecs_Also => True);
for i in Starting_Col .. Final_Col loop
Eigval(i) := Real (Eigenvalues(i));
end loop;
end d15;
Zero : constant Real := +0.0;
B, Q_tr : Matrix := (others => (others => Zero));
Eigenvals : Col_Vector;
Err, Ave_Err, Max_Err, Max_Val : Real;
Min_Allowed_Real : constant Real := +2.0 **(Real'Machine_Emin + 32);
No_of_Sweeps_Done, No_of_Rotations : Natural;
-----------
-- Pause --
-----------
procedure Pause (s0,s1,s2,s3,s4,s5,s6,s7,s8,s9 : string := "") is
Continue : Character := ' ';
begin
new_line;
if S0 /= "" then put_line (S0); end if;
if S1 /= "" then put_line (S1); end if;
if S2 /= "" then put_line (S2); end if;
if S3 /= "" then put_line (S3); end if;
if S4 /= "" then put_line (S4); end if;
if S5 /= "" then put_line (S5); end if;
if S6 /= "" then put_line (S6); end if;
if S7 /= "" then put_line (S7); end if;
if S8 /= "" then put_line (S8); end if;
if S9 /= "" then put_line (S9); end if;
new_line;
begin
put ("Type a character to continue: ");
get_immediate (Continue);
exception
when others => null;
end;
end pause;
begin
Pause (
"The test uses Intel's 18 digit Reals to estimate eigenval error in the",
"15 digit calculation, so only works on Intel/AMD hardware."
);
for Pass_id in 1 .. 2 loop
for Chosen_Matrix in Matrix_Id loop
Init_Matrix (A, Chosen_Matrix, Starting_Col, Final_Col);
-- Usually A is not symmetric. Eigen_Decompose doesn't care about
-- that. It uses the upper triangle of A, and pretends that A is
-- symmetric. But for subsequent analysis, we symmetrize:
if Pass_id = 1 then -- use lower triangle of A to make a fully symmetric A:
for Col in Starting_Col .. Final_Col loop
for Row in Col .. Final_Row loop
A(Col, Row) := A(Row, Col); -- write lower triangle of A to upper triangle
end loop;
end loop;
else -- use upper triangle of A to make a fully symmetric A:
for Col in Starting_Col .. Final_Col loop
for Row in Starting_Col .. Col loop
A(Col, Row) := A(Row, Col); -- write lower triangle of A to upper triangle
end loop;
end loop;
end if;
d15 (A, Eig_vals_15);
for i in Starting_Col .. Final_Col loop
for j in Starting_Col .. Final_Row loop
B(i,j) := Real (A(i,j));
end loop;
end loop;
Eigen_Decompose
(A => B,
Q_tr => Q_tr,
Eigenvals => Eigenvals,
No_of_Sweeps_Performed => No_of_Sweeps_Done,
Total_No_of_Rotations => No_of_Rotations,
Final_Col => Final_Col,
Start_Col => Starting_Col,
Eigenvectors_Desired => True);
Sort_Eigs
(Eigenvals => Eigenvals,
Q_tr => Q_tr,
Start_Col => Starting_Col,
Final_Col => Final_Col,
Sort_Eigvecs_Also => True);
Max_Err := Zero;
Ave_Err := Zero;
for I in Starting_Col .. Final_Col loop
Err := Abs (Eigenvals(I) - Eig_vals_15(I));
if Err > Max_Err then Max_Err := Err; end if;
Ave_Err := Ave_Err + Err;
end loop;
Max_Val := Zero;
for I in Starting_Col .. Final_Col loop
if Abs (Eigenvals(I)) > Max_Val then Max_Val := Abs (Eigenvals(I)); end if;
end loop;
new_line;
put("For matrix A of type "); put(Matrix_id'Image(Chosen_Matrix));
new_line;
put(" Max err:");
put(Max_Err / (Max_Val + Min_Allowed_Real));
put(" Ave err:");
put(Ave_Err / ((Real(Final_Col)-Real(Starting_Col)+1.0)*(Max_Val+Min_Allowed_Real)));
end loop;
end loop;
end;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body GEL
is
function to_Asset (Self : in String) return asset_Name
is
the_Name : String (asset_Name'Range);
begin
the_Name (1 .. Self'Length) := Self;
the_Name (Self'Length + 1 .. the_Name'Last) := (others => ' ');
return asset_Name (the_Name);
end to_Asset;
function to_String (Self : in asset_Name) return String
is
begin
for i in reverse Self'Range
loop
if Self (i) /= ' '
then
return String (Self (1 .. i));
end if;
end loop;
return "";
end to_String;
end GEL;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with
ada.Numerics.generic_elementary_Functions;
generic
type Float_type is digits <>;
type Matrix_2x2_type is private;
with package float_elementary_Functions is new ada.Numerics.generic_elementary_Functions (Float_type);
with function to_Matrix_2x2 (m11, m12,
m21, m22 : Float_type) return Matrix_2x2_type;
slot_Count : Standard.Positive;
package cached_Rotation
--
-- Caches 2x2 rotation matrices of angles for speed at the cost of precision.
--
is
pragma Optimize (Time);
function to_Rotation (Angle : in Float_type) return access constant Matrix_2x2_type;
private
pragma Inline_Always (to_Rotation);
end cached_Rotation;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Unchecked_Conversion;
with Ada.Unchecked_Deallocation;
package body YAML is
use type C_Int;
procedure Deallocate is new Ada.Unchecked_Deallocation
(String, String_Access);
procedure Deallocate is new Ada.Unchecked_Deallocation
(Document_Type, Document_Access);
----------------------
-- C symbol imports --
----------------------
procedure C_Document_Delete (Document : in out C_Document_T)
with Import, Convention => C, External_Name => "yaml_document_delete";
function C_Document_Get_Root_Node
(Document : C_Document_Access) return C_Node_Access
with
Import,
Convention => C,
External_Name => "yaml_document_get_root_node";
function C_Document_Get_Node
(Document : C_Document_Access;
Index : C_Int) return C_Node_Access
with
Import, Convention => C, External_Name => "yaml_document_get_node";
function C_Parser_Initialize (Parser : C_Parser_Access) return C_Int
with Import, Convention => C, External_Name => "yaml_parser_initialize";
function Allocate_Parser return C_Parser_Access
with Import, Convention => C, External_Name => "yaml__allocate_parser";
function C_Parser_Load
(Parser : C_Parser_Access; Document : C_Document_Access) return C_Int
with Import, Convention => C, External_Name => "yaml_parser_load";
procedure C_Parser_Set_Input_String
(Parser : C_Parser_Access;
Input : C_Char_Access;
Size : Interfaces.C.size_t)
with
Import,
Convention => C,
External_Name => "yaml_parser_set_input_string";
procedure C_Parser_Set_Input_File
(Parser : C_Parser_Access;
File : C_File_Ptr)
with Import,
Convention => C,
External_Name => "yaml_parser_set_input_file";
procedure C_Parser_Delete (Parser : C_Parser_Access)
with Import, Convention => C, External_Name => "yaml_parser_delete";
procedure Deallocate_Parser (Parser : C_Parser_Access)
with Import, Convention => C, External_Name => "yaml__deallocate_parser";
function C_Fopen
(Path, Mode : Interfaces.C.Strings.chars_ptr) return C_File_Ptr
with Import, Convention => C, External_Name => "fopen";
function C_Fclose (Stream : C_File_Ptr) return C_Int
with Import, Convention => C, External_Name => "fclose";
-------------
-- Helpers --
-------------
function Convert (S : String_Access) return C_Char_Access;
procedure Discard_Input
(Parser : in out Parser_Type'Class;
Re_Initialize : Boolean);
-- Free input holders in parser and delete the C YAML parser. If
-- Re_Initialize, also call Initialize_After_Allocation.
function Get_Node
(Document : Document_Type'Class; Index : C_Int) return Node_Ref;
-- Wrapper around C_Document_Get_Node. Raise a Constraint_Error if Index is
-- out of range.
procedure Initialize_After_Allocation (Parser : in out Parser_Type'Class);
-- Initialize the C YAML parser and assign proper defaults to input holders
-- in Parser.
function Wrap
(Document : Document_Type'Class; N : C_Node_Access) return Node_Ref
is
((Node => N, Document => Document'Unrestricted_Access));
function Wrap (M : C_Mark_T) return Mark_Type is
((Line => Natural (M.Line) + 1, Column => Natural (M.Column) + 1));
function Wrap (Error_View : C_Parser_Error_View) return Error_Type;
function Convert (S : String_Access) return C_Char_Access is
Char_Array : C_Char_Array with Address => S.all'Address;
begin
return Char_Array'Unrestricted_Access;
end Convert;
function Get_Node
(Document : Document_Type'Class; Index : C_Int) return Node_Ref
is
N : constant C_Node_Access :=
C_Document_Get_Node (Document.C_Doc'Unrestricted_Access, Index);
begin
if N = null then
raise Constraint_Error;
end if;
return Wrap (Document, N);
end Get_Node;
procedure Initialize_After_Allocation (Parser : in out Parser_Type'Class) is
begin
if C_Parser_Initialize (Parser.C_Parser) /= 1 then
-- TODO: determine a good error handling scheme
raise Program_Error;
end if;
Parser.Input_Encoding := Any_Encoding;
Parser.Input_String := null;
Parser.Input_File := No_File_Ptr;
end Initialize_After_Allocation;
procedure Discard_Input
(Parser : in out Parser_Type'Class;
Re_Initialize : Boolean) is
begin
C_Parser_Delete (Parser.C_Parser);
Deallocate (Parser.Input_String);
if Parser.Input_File /= No_File_Ptr
and then C_Fclose (Parser.Input_File) /= 0
then
raise File_Error;
end if;
if Re_Initialize then
Initialize_After_Allocation (Parser);
end if;
end Discard_Input;
function Wrap (Error_View : C_Parser_Error_View) return Error_Type is
function Convert
(S : Interfaces.C.Strings.chars_ptr)
return Ada.Strings.Unbounded.Unbounded_String
is (Ada.Strings.Unbounded.To_Unbounded_String
(Interfaces.C.Strings.Value (S)));
Kind : Error_Kind renames Error_View.Error;
Problem : constant Ada.Strings.Unbounded.Unbounded_String :=
Convert (Error_View.Problem);
Problem_Offset : Natural;
Problem_Value : Integer;
Context : Ada.Strings.Unbounded.Unbounded_String;
Context_Mark, Problem_Mark : Mark_Type;
begin
case Kind is
when Reader_Error =>
Problem_Offset := Natural (Error_View.Problem_Offset);
Problem_Value := Integer (Error_View.Problem_Value);
when Scanner_Error | Parser_Error =>
Context := Convert (Error_View.Context);
Context_Mark := Wrap (Error_View.Context_Mark);
Problem_Mark := Wrap (Error_View.Problem_Mark);
when others =>
null;
end case;
case Kind is
when No_Error =>
return (No_Error, Problem);
when Composer_Error =>
return (Composer_Error, Problem);
when Memory_Error =>
return (Memory_Error, Problem);
when Writer_Error =>
return (Writer_Error, Problem);
when Emitter_Error =>
return (Emitter_Error, Problem);
when Reader_Error =>
return (Reader_Error, Problem, Problem_Offset, Problem_Value);
when Scanner_Error =>
return (Scanner_Error,
Problem, Context, Context_Mark, Problem_Mark);
when Parser_Error =>
return (Parser_Error,
Problem, Context, Context_Mark, Problem_Mark);
end case;
end Wrap;
----------
-- Misc --
----------
overriding procedure Initialize (Document : in out Document_Type) is
begin
Document.Ref_Count := 0;
Document.To_Delete := False;
end Initialize;
overriding procedure Finalize (Document : in out Document_Type) is
begin
if Document.To_Delete then
C_Document_Delete (Document.C_Doc);
Document.To_Delete := False;
end if;
end Finalize;
overriding procedure Adjust (Handle : in out Document_Handle) is
begin
Handle.Inc_Ref;
end Adjust;
overriding procedure Finalize (Handle : in out Document_Handle) is
begin
Handle.Dec_Ref;
end Finalize;
procedure Inc_Ref (Handle : in out Document_Handle'Class) is
begin
if Handle /= No_Document_Handle then
Handle.Document.Ref_Count := Handle.Document.Ref_Count + 1;
end if;
end Inc_Ref;
procedure Dec_Ref (Handle : in out Document_Handle'Class) is
begin
if Handle /= No_Document_Handle then
declare
D : Document_Access := Handle.Document;
begin
D.Ref_Count := D.Ref_Count - 1;
if D.Ref_Count = 0 then
Deallocate (D);
end if;
end;
end if;
end Dec_Ref;
overriding procedure Initialize (Parser : in out Parser_Type) is
begin
Parser.C_Parser := Allocate_Parser;
Initialize_After_Allocation (Parser);
end Initialize;
overriding procedure Finalize (Parser : in out Parser_Type) is
begin
Discard_Input (Parser, False);
Deallocate_Parser (Parser.C_Parser);
end Finalize;
-----------------------
-- Public interface --
-----------------------
function Create return Document_Handle is
D : constant Document_Access := new Document_Type;
begin
D.Ref_Count := 1;
return (Ada.Finalization.Controlled with Document => D);
end Create;
function Root_Node (Document : Document_Type'Class) return Node_Ref is
begin
return Wrap
(Document,
C_Document_Get_Root_Node (Document.C_Doc'Unrestricted_Access));
end Root_Node;
function Start_Mark (Document : Document_Type'Class) return Mark_Type is
begin
return Wrap (Document.C_Doc.Start_Mark);
end Start_Mark;
function End_Mark (Document : Document_Type'Class) return Mark_Type is
begin
return Wrap (Document.C_Doc.End_Mark);
end End_Mark;
function Kind (Node : Node_Ref'Class) return Node_Kind is
begin
return Node.Node.Kind;
end Kind;
function Start_Mark (Node : Node_Ref'Class) return Mark_Type is
begin
return Wrap (Node.Node.Start_Mark);
end Start_Mark;
function End_Mark (Node : Node_Ref'Class) return Mark_Type is
begin
return Wrap (Node.Node.End_Mark);
end End_Mark;
function Value (Node : Node_Ref'Class) return UTF8_String is
Data : C_Node_Data renames Node.Node.Data;
Result : UTF8_String (1 .. Natural (Data.Scalar.Length))
with Address => Data.Scalar.Value.all'Address;
begin
return Result;
end Value;
function Length (Node : Node_Ref'Class) return Natural is
use C_Node_Item_Accesses, C_Node_Pair_Accesses;
Data : C_Node_Data renames Node.Node.Data;
begin
return
(case Kind (Node) is
when Sequence_Node => Natural
(Data.Sequence.Items.Seq_Top - Data.Sequence.Items.Seq_Start),
when Mapping_Node => Natural
(Data.Mapping.Pairs.Map_Top - Data.Mapping.Pairs.Map_Start),
when others => raise Program_Error);
end Length;
function Item (Node : Node_Ref'Class; Index : Positive) return Node_Ref
is
use C_Node_Item_Accesses;
Data : C_Node_Data renames Node.Node.Data;
Item : constant C_Node_Item_Access :=
Data.Sequence.Items.Seq_Start + C_Ptr_Diff (Index - 1);
begin
return Get_Node (Node.Document.all, Item.all);
end Item;
function Item (Node : Node_Ref'Class; Index : Positive) return Node_Pair
is
use C_Node_Pair_Accesses;
Data : C_Node_Data renames Node.Node.Data;
Pair : constant C_Node_Pair_Access :=
Data.Mapping.Pairs.Map_Start + C_Ptr_Diff (Index - 1);
begin
return (Key => Get_Node (Node.Document.all, Pair.Key),
Value => Get_Node (Node.Document.all, Pair.Value));
end Item;
function Item (Node : Node_Ref'Class; Key : UTF8_String) return Node_Ref
is
begin
for I in 1 .. Length (Node) loop
declare
Pair : constant Node_Pair := Item (Node, I);
begin
if Kind (Pair.Key) = Scalar_Node
and then Value (Pair.Key) = Key
then
return Pair.Value;
end if;
end;
end loop;
return No_Node_Ref;
end Item;
function Image (Error : Error_Type) return String is
function "+" (US : Ada.Strings.Unbounded.Unbounded_String) return String
renames Ada.Strings.Unbounded.To_String;
function Problem_Image
(Text : Ada.Strings.Unbounded.Unbounded_String;
Mark : Mark_Type) return String
is (+Text & " " & "at line" & Natural'Image (Mark.Line)
& ", column" & Natural'Image (Mark.Column));
begin
case Error.Kind is
when No_Error =>
return "no error";
when Reader_Error =>
declare
Value : constant String :=
(if Error.Problem_Value /= -1
then Integer'Image (Error.Problem_Value)
else "");
begin
return "reader error: " & (+Error.Problem) & ":" & Value
& " at offset" & Natural'Image (Error.Problem_Offset);
end;
when Scanner_Error | Parser_Error =>
declare
Kind : constant String :=
(case Error.Kind is
when Scanner_Error => "scanner error",
when Parser_Error => "parser error",
when others => raise Program_Error);
Context : constant String :=
(if Ada.Strings.Unbounded.Length (Error.Context) > 0
then Problem_Image (Error.Context, Error.Context_Mark) & ": "
else "");
begin
return Kind & ": " & Context
& Problem_Image (Error.Problem, Error.Problem_Mark);
end;
when Composer_Error =>
return "composer error";
when Memory_Error =>
return "memory error";
when Writer_Error =>
return "writer error";
when Emitter_Error =>
return "emitter error";
end case;
end Image;
function Has_Input (P : Parser_Type'Class) return Boolean is
begin
return P.Input_String /= null or else P.Input_File /= No_File_Ptr;
end Has_Input;
procedure Set_Input_String
(Parser : in out Parser_Type'Class;
Input : String;
Encoding : Encoding_Type)
is
begin
Parser.Input_Encoding := Encoding;
Deallocate (Parser.Input_String);
Parser.Input_String := new String'(Input);
C_Parser_Set_Input_String
(Parser.C_Parser,
Convert (Parser.Input_String),
Parser.Input_String'Length);
end Set_Input_String;
procedure Set_Input_File
(Parser : in out Parser_Type'Class;
Filename : String;
Encoding : Encoding_Type)
is
use Interfaces.C.Strings;
C_Mode : chars_ptr := New_String ("r");
C_Filename : chars_ptr := New_String (Filename);
File : constant C_File_Ptr := C_Fopen (C_Filename, C_Mode);
begin
Free (C_Mode);
Free (C_Filename);
if File = No_File_Ptr then
raise File_Error;
end if;
Deallocate (Parser.Input_String);
Parser.Input_Encoding := Encoding;
Parser.Input_File := File;
C_Parser_Set_Input_File (Parser.C_Parser, Parser.Input_File);
end Set_Input_File;
procedure Discard_Input (Parser : in out Parser_Type'Class) is
begin
Discard_Input (Parser, True);
end Discard_Input;
procedure Load
(Parser : in out Parser_Type'Class;
Error : out Error_Type;
Document : in out Document_Type'Class) is
begin
Document.Finalize;
if C_Parser_Load
(Parser.C_Parser, Document.C_Doc'Unrestricted_Access) /= 1
then
declare
Error_View_Address : constant System.Address :=
System.Address (Parser.C_Parser);
Error_View : C_Parser_Error_View
with Import => True,
Convention => Ada,
Address => Error_View_Address;
begin
Error := Wrap (Error_View);
end;
end if;
Document.To_Delete := True;
end Load;
end YAML;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.text_io; use Ada.Text_IO;
procedure main is
task type Server_Task is
entry A;
entry B;
end Server_Task;
task body Server_Task is
begin
loop
Put_Line("Server starts next cycle");
select
accept A do
Put_Line("A start");
delay 1.5;
Put_Line("A end");
end A;
or
accept B do
Put_Line("B start");
delay 0.1;
Put_Line("B end");
end B;
end select;
delay 0.9; -- server is doing something else beyond just serving A and B
Put_Line("Server finished cycle");
end loop;
end Server_Task;
Server : Server_Task; -- create server instance
-- a task that only calls Server.A, blocking.
task type Client_A is
end Client_A;
task body Client_A is
begin
loop
Server.A;
end loop;
end Client_A;
-- a different task, that calls Server.B, but waits no more than 2 seconds.
task type Client_B;
task body Client_B is
begin
loop
select
Server.B;
or
delay 2.0;
Put_Line("timeout B");
end select;
end loop;
end Client_B;
TA : Client_A;
TB : Client_B;
begin
null;
end main;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- -----------------------------------------------------------------------------
-- Mapcode management
with Mapcode_Utils.As_U;
private with Countries;
package Mapcodes is
Mapcode_C_Version : constant String := "2.0.2";
Mapcode_Data_Version : constant String := "2.3.0";
Mapcode_Ada_Version : constant String := "1.1.5/Data"
& Mapcode_Data_Version;
-- Real type (for latitude and longitude)
type Real is digits 15 range -1.79E308 .. 1.79E308;
-----------------
-- TERRITORIES --
-----------------
-- Valid territory identifier
type Territories is private;
-- Given an ISO 3166 alphacode (such as "US-AL" or "FRA"), return the
-- corresponding territory identifier or raise Unknown_Territory
-- A Context territory helps to interpret ambiguous (abbreviated)
-- alphacodes, such as "BR" or "US" for the subdivision "AL"
-- Territory_Code can also be the number of the territory (ex "364" for US-AL)
-- Raise, if Territory or Context is not known, or if Territory is ambiguous
-- and no contextex is provided:
Unknown_Territory : exception;
function Get_Territory (Territory_Code : String;
Context : String := "") return Territories;
-- Note about aliases and ambiguity: The check for ambiguity is strict among
-- subdivisions but does not apply to aliases. As a consequence, "TAM"
-- corresponds to "MX-TAM" without error despite "RU-TAM is also an alias
-- for "RU-TT". (Aliases are not ambiguous among them, but would it be
-- the case then Get_Territory would return one of them without error).
-- Return the number of a territory ("0" for Vatican to "532" for
-- International)
-- See package Countries, field Num of the territory definition
function Get_Territory_Number (Territory : Territories) return String;
-- Return the alphacode (usually an ISO 3166 code) of a territory
-- Format: Local (often ambiguous), International (full and unambiguous,
-- DEFAULT), or Shortest
type Territory_Formats is (Local, International, Shortest);
function Get_Territory_Alpha_Code (
Territory : Territories;
Format : Territory_Formats := International) return String;
-- Return the full readable name of a territory (e.g. "France")
-- This is the first part of the Name (see package Countries), before the
-- first " (" if any
function Get_Territory_Fullname (Territory : Territories) return String;
-- Return the parent country of a subdivision (e.g. "US" for "US-AL")
-- Raise, if Territory is not a subdivision:
Not_A_Subdivision : exception;
function Get_Parent_Of (Territory : Territories) return Territories;
-- Return True if Territory is a subdivision (state)
function Is_Subdivision (Territory : Territories) return Boolean;
-- Return True if Territory is a country that has states
function Has_Subdivision (Territory : Territories) return Boolean;
-- Given a subdivision name, return the array (possibly empty) of territory
-- subdivisions with the same name
-- Ex: given "AL" return the array (318 (BR-AL), 482 (RU-AL), 364 (US-AL))
type Territories_Array is array (Positive range <>) of Territories;
function Get_Subdivisions_With (Subdivision : String)
return Territories_Array;
--------------------------
-- Encoding to mapcodes --
--------------------------
-- Coordinate in fraction of degrees
subtype Lat_Range is Real range -90.0 .. 90.0;
subtype Lon_Range is Real range -180.0 .. 180.0;
type Coordinate is record
Lat : Lat_Range;
Lon : Lon_Range;
end record;
-- One mapcode-related information bloc
type Mapcode_Info is record
-- Territory code (AAA for Earth)
Territory_Alpha_Code : Mapcode_Utils.As_U.Asu_Us;
-- Simple mapcode
Mapcode : Mapcode_Utils.As_U.Asu_Us;
-- Territory, then a space and the mapcode,
-- or simple mapcode if it is valid on Earth
Full_Mapcode : Mapcode_Utils.As_U.Asu_Us;
-- Territory
Territory : Territories;
end record;
type Mapcode_Infos is array (Positive range <>) of Mapcode_Info;
-- Encode a coordinate
-- Return an array of mapcodes, each representing the specified coordinate.
-- If a Territory alphacode or num is specified, then only mapcodes (if any)
-- within that territory are returned. If Earth is provided as territory,
-- then only the 9-letter "international" mapcode is returned
-- If Shortest is set, then at most one mapcode (the "default" and
-- "shortest possible" mapcode) in any territory are returned
-- The Precision option leads to produce mapcodes extended with high-precision
-- letters (the parameter specifies how many letters, 0 to 8, after a '-')
-- The resulting array is always organized by territories: all the mapcodes
-- of a territory follow each other and in order of increasing length.
-- If Sort is set, then the returned array contains first the shortest
-- mapcode, then possibly the other mapcodes for the same territory,
-- then possibly mapcodes for other territories, then possibly the
-- international (Earth) mapcode
-- Otherwise the territories appear in the crescent order of Territory_Range
-- (see package Countries)
-- As a consequence, if it appears then the international mapcode is always
-- the last
subtype Precisions is Natural range 0 .. 8;
Earth : constant String := "AAA";
function Encode (Coord : Coordinate;
Territory_Code : String := "";
Shortest : Boolean := False;
Precision : Precisions := 0;
Sort : Boolean := False) return Mapcode_Infos;
------------------------
-- Decoding a mapcode --
------------------------
-- Decode a string containing a mapcode
-- The optional Context territory alphacode shall be set if the mapcode is
-- ambiguous (not "international")
-- Return a coordinate or, if the mapcode is incorrect or ambiguous, raise:
Decode_Error : exception;
function Decode (Mapcode, Context : String) return Coordinate;
private
type Territories is new Natural range 0 .. Countries.Territories_Def'Last - 1;
-- Operation exported to child package Languages
-- Packing and unpacking to avoid full digits mapcodes
function Aeu_Pack (R : Mapcode_Utils.As_U.Asu_Us;
Short : Boolean) return String;
function Aeu_Unpack (Str : String) return String;
-- Decode and encode a char
function Decode_A_Char (C : Natural) return Integer;
function Encode_A_Char (C : Natural) return Character;
end Mapcodes;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with Sf.Window.Window; use Sf, Sf.Window, Sf.Window.Window;
with Sf.Window.VideoMode; use Sf.Window.VideoMode;
with Sf.Window.Event; use Sf.Window.Event;
with Sf.Window.Keyboard; use Sf.Window.Keyboard;
with Sf.System.Sleep; use Sf.System.Sleep;
with Sf.System.Time; use Sf.System.Time;
with Sf.Window.Cursor;
with Sf.Graphics.RenderWindow; use Sf.Graphics, Sf.Graphics.RenderWindow;
with Sf.Graphics.Sprite; use Sf.Graphics.Sprite;
with Sf.Graphics.Image; use Sf.Graphics.Image;
with Sf.Graphics.BlendMode; use Sf.Graphics.BlendMode;
with Sf.Graphics.Text; use Sf.Graphics.Text;
with Sf.Graphics.Texture; use Sf.Graphics.Texture;
with Sf.Graphics.Color; use Sf.Graphics.Color;
with Sf.Graphics.Font; use Sf.Graphics.Font;
procedure Main is
Window : sfRenderWindow_Ptr;
Mode : sfVideoMode := (640, 480, 32);
Params : sfContextSettings := sfDefaultContextSettings;
Event : sfEvent;
CursorHand : Sf.Window.sfCursor_Ptr := Cursor.createFromSystem(Cursor.sfCursorHand);
Sprite : sfSprite_Ptr;
Img : sfTexture_Ptr;
Icon : sfImage_Ptr;
Str : sfText_Ptr;
Font : sfFont_Ptr;
begin
Img := CreateFromFile ("logo.png");
if Img = null then
Put_Line ("Could not open image");
return;
end if;
Icon := CreateFromFile ("sfml-icon.png");
if Icon = null then
Put_Line ("Could not open icon");
Destroy (Img);
return;
end if;
Sprite := Create;
if Sprite = null then
Put_Line ("Could not create sprite");
Destroy (Img);
return;
end if;
SetTexture (Sprite, Img);
SetPosition (Sprite,
(x => Float (sfUint32 (Mode.Width) / 2 - GetSize (Img).x / 2),
y => Float (sfUint32 (Mode.Height) / 2 - GetSize (Img).y / 2)));
--sfSprite_SetBlendMode (Sprite, sfBlendAlpha);
Font := CreateFromFile("aerial.ttf");
if Font = null then
Put_Line ("Could not get font");
Destroy (Sprite);
Destroy (Img);
return;
end if;
Str := Create;
if Str = null then
Put_Line ("Could not create string");
Destroy (Sprite);
Destroy (Img);
Destroy(Font);
return;
end if;
SetFont (Str, Font);
SetString (Str, "The SFML Logo" & Character'Val (10) & "In Aerial Font");
--sfText_SetSize(Str, 20.0);
SetPosition (Str, (Float (Mode.Width / 2) - (GetGlobalBounds (Str).Width) / 2.0,
Float (Mode.Height / 2) + 60.0));
SetColor (Str, sfBlue);
Window := Create (Mode, "Ada SFML Window", sfResize or sfClose, Params);
if Window = null then
Put_Line ("Failed to create window");
return;
end if;
setMouseCursor (Window, CursorHand);
SetFramerateLimit (Window, 32);
SetVerticalSyncEnabled (Window, sfFalse);
SetVisible (Window, sfTrue);
SetIcon (Window, GetSize (Icon).x, GetSize (Icon).y,
GetPixelsPtr (Icon));
while IsOpen (Window) = sfTrue loop
while PollEvent (Window, Event) = sfTrue loop
if Event.eventType = sfEvtClosed then
Close (Window);
Put_Line ("Attempting to close");
end if;
if Event.eventType = sfEvtKeyPressed
and then Event.key.code = sfKeyEscape then
Close (Window);
Put_Line ("Attempting to close");
end if;
end loop;
Clear (Window, sfWhite);
DrawSprite (Window, Sprite);
DrawText (Window, Str);
Display (Window);
sfSleep (sfSeconds (0.001));
end loop;
Destroy (Window);
Destroy (Sprite);
Destroy (Img);
Destroy (Icon);
Destroy (Str);
Destroy(Font);
end Main;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Program.Compilation_Unit_Vectors;
with Program.Compilation_Units;
with Program.Library_Items;
with Program.Library_Unit_Bodies;
package Program.Library_Unit_Declarations is
pragma Pure;
type Library_Unit_Declaration is limited interface
and Program.Library_Items.Library_Item;
-- library_unit_declaration is a compilation unit that is the declaration
-- or renaming of a library unit.
type Library_Unit_Declaration_Access is
access all Library_Unit_Declaration'Class
with Storage_Size => 0;
not overriding function Corresponding_Body
(Self : access Library_Unit_Declaration)
return Program.Library_Unit_Bodies.Library_Unit_Body_Access
is abstract;
-- Returns the corresponding library_unit_body, if any, for the
-- library_unit_declaration. The corresponding library_unit_body is the
-- unit that depends semantically on the library_unit_declaration.
--
-- Returns null for library_unit_declaration arguments that
-- do not have a corresponding library_unit_body contained in the Context.
not overriding function Corresponding_Childern
(Self : access Library_Unit_Declaration)
return Program.Compilation_Unit_Vectors.Compilation_Unit_Vector_Access
is abstract;
-- with Post'Class =>
-- (Corresponding_Childern'Result.Is_Empty
-- or else (for all X in Corresponding_Childern'Result.Each_Unit
-- => X.Unit.Is_Library_Item));
-- Returns a list of the child units for the given parent library unit.
--
-- Both the declaration and body (if any) of each child unit are returned.
-- Descendants beyond immediate children (i.e., children of children) are
-- not returned by this query.
end Program.Library_Unit_Declarations;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Servlet.Core;
with Servlet.Requests;
with Servlet.Responses;
with servlet.Streams;
package Upload_Servlet is
use Servlet;
type File_Type is (IMAGE, PDF, TAR_GZ, TAR, ZIP, UNKNOWN);
-- Guess a file type depending on a content type or a file name.
function Get_File_Type (Content_Type : in String;
Name : in String) return File_Type;
-- Execute a command and write the result to the output stream.
procedure Execute (Command : in String;
Output : in out Streams.Print_Stream);
-- The <b>Servlet</b> represents the component that will handle
-- an HTTP request received by the server.
type Servlet is new Core.Servlet with null record;
-- Called by the servlet container when a GET request is received.
-- Display the upload form page.
procedure Do_Get (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class);
-- Called by the servlet container when a POST request is received.
-- Receives the uploaded files and identify them using some external command.
procedure Do_Post (Server : in Servlet;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class);
private
-- Write the upload form page with an optional response message.
procedure Write (Response : in out Responses.Response'Class;
Message : in String);
end Upload_Servlet;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- { dg-do compile }
procedure Entry_Queues2 is
F1 : Integer := 17;
generic
type T is limited private;
procedure Check;
procedure Check is
begin
declare
type Poe is new T;
begin
declare
type Arr is array (1 .. 2) of Poe;
X : Arr;
pragma Unreferenced (X);
begin
null;
end;
end;
end;
begin
declare
protected type Poe (D3 : Integer := F1) is
entry E (D3 .. F1); -- F1 evaluated
end Poe;
protected body Poe is
entry E (for I in D3 .. F1) when True is
begin
null;
end E;
end Poe;
procedure Chk is new Check (Poe);
begin
Chk;
end;
end;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
package ASF.Components.Html.Links is
-- ------------------------------
-- Output Link Component
-- ------------------------------
type UIOutputLink is new UIHtmlComponent with private;
-- Get the link to be rendered in the <b>href</b> attribute.
function Get_Link (UI : in UIOutputLink;
Context : in Faces_Context'Class) return String;
-- Get the value to write on the output.
function Get_Value (UI : in UIOutputLink) return EL.Objects.Object;
-- Set the value to write on the output.
procedure Set_Value (UI : in out UIOutputLink;
Value : in EL.Objects.Object);
-- Encode the begining of the link.
procedure Encode_Begin (UI : in UIOutputLink;
Context : in out Faces_Context'Class);
-- Encode the end of the link.
procedure Encode_End (UI : in UIOutputLink;
Context : in out Faces_Context'Class);
private
type UIOutputLink is new UIHtmlComponent with record
Value : EL.Objects.Object;
end record;
end ASF.Components.Html.Links;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body BSSNBase.ADM_BSSN is
----------------------------------------------------------------------------
-- from BSSN to ADM
function adm_gab (gBar : MetricPointArray;
phi : Real)
return MetricPointArray
is
begin
return exp(4.0*phi) * gBar;
end;
function adm_Kab (ABar : ExtcurvPointArray;
gBar : MetricPointArray;
phi : Real;
trK : Real)
return ExtcurvPointArray
is
begin
return exp(4.0*phi)*(ABar + ExtcurvPointArray(trK*gBar/3.0));
end;
----------------------------------------------------------------------------
-- from ADM to BSSN
function bssn_phi (gab : MetricPointArray)
return Real
is
g : Real := symm_det (gab);
begin
return log(g)/12.0;
end;
function bssn_trK (Kab : ExtcurvPointArray;
gab : MetricpointArray)
return Real
is
iab : MetricPointArray := symm_inverse (gab);
begin
return symm_trace (Kab, iab);
end;
function bssn_gBar (gab : MetricPointArray)
return MetricPointArray
is
g : Real := symm_det (gab);
begin
return gab / (g**(1.0/3.0));
end;
function bssn_ABar (Kab : ExtcurvPointArray;
gab : MetricPointArray)
return ExtcurvPointArray
is
g : Real := symm_det (gab);
trK : Real := bssn_trK (Kab, gab);
begin
return (Kab - ExtcurvPointArray(trK*gab/3.0))/(g**(1.0/3.0));
end;
end BSSNBase.ADM_BSSN;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with ASF.Sessions;
with ASF.Applications.Messages.Utils;
package body ASF.Contexts.Flash is
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Flash : in out Flash_Context;
Name : in String;
Value : in Util.Beans.Objects.Object) is
Instance : Flash_Bean_Access;
begin
Flash.Get_Execute_Flash (Instance);
if Util.Beans.Objects.Is_Null (Value) then
Instance.Attributes.Delete (Name);
else
Instance.Attributes.Include (Name, Value);
end if;
end Set_Attribute;
-- ------------------------------
-- Set the attribute having given name with the value.
-- ------------------------------
procedure Set_Attribute (Flash : in out Flash_Context;
Name : in Unbounded_String;
Value : in Util.Beans.Objects.Object) is
begin
Flash.Set_Attribute (To_String (Name), Value);
end Set_Attribute;
-- ------------------------------
-- Get the attribute with the given name from the 'previous' flash context.
-- ------------------------------
function Get_Attribute (Flash : in Flash_Context;
Name : in String) return Util.Beans.Objects.Object is
begin
if Flash.Previous = null then
return Util.Beans.Objects.Null_Object;
else
declare
Pos : constant Util.Beans.Objects.Maps.Cursor := Flash.Previous.Attributes.Find (Name);
begin
if Util.Beans.Objects.Maps.Has_Element (Pos) then
return Util.Beans.Objects.Maps.Element (Pos);
else
return Util.Beans.Objects.Null_Object;
end if;
end;
end if;
end Get_Attribute;
-- Keep in the flash context the request attribute identified by the name <b>Name</b>.
procedure Keep (Flash : in out Flash_Context;
Name : in String) is
begin
null;
end Keep;
-- ------------------------------
-- Returns True if the <b>Redirect</b> property was set on the previous flash instance.
-- ------------------------------
function Is_Redirect (Flash : in Flash_Context) return Boolean is
begin
return Flash.Previous /= null and then Flash.Previous.Redirect;
end Is_Redirect;
-- Set this property to True to indicate to the next request on this session will be
-- a redirect. After this call, the next request will return the <b>Redirect</b> value
-- when the <b>Is_Redirect</b> function will be called.
procedure Set_Redirect (Flash : in out Flash_Context;
Redirect : in Boolean) is
begin
null;
end Set_Redirect;
-- ------------------------------
-- Returns True if the faces messages that are queued in the faces context must be
-- preserved so they are accessible through the flash instance at the next request.
-- ------------------------------
function Is_Keep_Messages (Flash : in Flash_Context) return Boolean is
begin
return Flash.Keep_Messages;
end Is_Keep_Messages;
-- ------------------------------
-- Set the keep messages property which controlls whether the faces messages
-- that are queued in the faces context must be preserved so they are accessible through
-- the flash instance at the next request.
-- ------------------------------
procedure Set_Keep_Messages (Flash : in out Flash_Context;
Value : in Boolean) is
begin
Flash.Keep_Messages := Value;
end Set_Keep_Messages;
-- ------------------------------
-- Perform any specific action before processing the phase referenced by <b>Phase</b>.
-- This operation is used to restore the flash context for a new request.
-- ------------------------------
procedure Do_Pre_Phase_Actions (Flash : in out Flash_Context;
Phase : in ASF.Events.Phases.Phase_Type;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Events.Phases.Phase_Type;
use type Util.Beans.Basic.Readonly_Bean_Access;
begin
-- Restore the flash bean instance from the session if there is one.
if Phase = ASF.Events.Phases.RESTORE_VIEW then
declare
S : constant ASF.Sessions.Session := Context.Get_Session;
B : access Util.Beans.Basic.Readonly_Bean'Class;
begin
if S.Is_Valid then
Flash.Object := S.Get_Attribute ("asf.flash.bean");
B := Util.Beans.Objects.To_Bean (Flash.Object);
if B /= null and then B.all in Flash_Bean'Class then
Flash.Previous := Flash_Bean'Class (B.all)'Unchecked_Access;
Context.Add_Messages ("", Flash.Previous.Messages);
end if;
end if;
end;
end if;
end Do_Pre_Phase_Actions;
-- ------------------------------
-- Perform any specific action after processing the phase referenced by <b>Phase</b>.
-- This operation is used to save the flash context
-- ------------------------------
procedure Do_Post_Phase_Actions (Flash : in out Flash_Context;
Phase : in ASF.Events.Phases.Phase_Type;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
use type ASF.Events.Phases.Phase_Type;
begin
if (Phase = ASF.Events.Phases.INVOKE_APPLICATION
or Phase = ASF.Events.Phases.RENDER_RESPONSE) and then not Flash.Last_Phase_Done then
Flash.Do_Last_Phase_Actions (Context);
end if;
end Do_Post_Phase_Actions;
-- ------------------------------
-- Perform the last actions that must be made to save the flash context in the session.
-- ------------------------------
procedure Do_Last_Phase_Actions (Flash : in out Flash_Context;
Context : in out ASF.Contexts.Faces.Faces_Context'Class) is
S : ASF.Sessions.Session := Context.Get_Session;
begin
-- If we have to keep the messages, save them in the flash bean context if there are any.
if Flash.Keep_Messages then
declare
Messages : constant Applications.Messages.Vectors.Cursor := Context.Get_Messages ("");
begin
if ASF.Applications.Messages.Vectors.Has_Element (Messages) then
if Flash.Next = null then
Flash.Next := new Flash_Bean;
end if;
ASF.Applications.Messages.Utils.Copy (Flash.Next.Messages, Messages);
end if;
end;
end if;
if S.Is_Valid then
S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.Null_Object);
elsif Flash.Next /= null then
S := Context.Get_Session (Create => True);
end if;
if Flash.Next /= null then
S.Set_Attribute ("asf.flash.bean", Util.Beans.Objects.To_Object (Flash.Next.all'Access));
end if;
Flash.Last_Phase_Done := True;
end Do_Last_Phase_Actions;
procedure Get_Active_Flash (Flash : in out Flash_Context;
Result : out Flash_Bean_Access) is
begin
if Flash.Previous = null then
null;
end if;
Result := Flash.Previous;
end Get_Active_Flash;
procedure Get_Execute_Flash (Flash : in out Flash_Context;
Result : out Flash_Bean_Access) is
begin
if Flash.Next = null then
Flash.Next := new Flash_Bean;
end if;
Result := Flash.Next;
end Get_Execute_Flash;
-- Get the value identified by the name.
-- If the name cannot be found, the method should return the Null object.
function Get_Value (From : in Flash_Bean;
Name : in String) return Util.Beans.Objects.Object is
pragma Unreferenced (From, Name);
begin
return Util.Beans.Objects.Null_Object;
end Get_Value;
end ASF.Contexts.Flash;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Ada_2012;
with Interfaces;
with System;
package body PBKDF2_Generic is
function PBKDF2
(Password : String; Salt : String; Iterations : Positive;
Derived_Key_Length : Index) return Element_Array
is
Password_Buffer : Element_Array
(Index (Password'First) .. Index (Password'Last));
for Password_Buffer'Address use Password'Address;
pragma Import (Ada, Password_Buffer);
Salt_Buffer : Element_Array (Index (Salt'First) .. Index (Salt'Last));
for Salt_Buffer'Address use Salt'Address;
pragma Import (Ada, Salt_Buffer);
begin
return
PBKDF2 (Password_Buffer, Salt_Buffer, Iterations, Derived_Key_Length);
end PBKDF2;
function PBKDF2
(Password : Element_Array; Salt : Element_Array; Iterations : Positive;
Derived_Key_Length : Index) return Element_Array
is
Result : Element_Array (0 .. Derived_Key_Length - 1);
Current : Index := Result'First;
Blocks_Needed : constant Index :=
Index
(Float'Ceiling (Float (Derived_Key_Length) / Float (Hash_Length)));
begin
for I in 1 .. Blocks_Needed loop
declare
Ctx : Hash_Context := Hash_Initialize (Password);
Temporary, Last : Element_Array (0 .. Hash_Length - 1);
begin
-- First iteration
Hash_Update (Ctx, Salt);
Hash_Update (Ctx, Write_Big_Endian (I));
Temporary := Hash_Finalize (Ctx);
Last := Temporary;
-- Subsequent iterations
for Unused in 2 .. Iterations loop
Ctx := Hash_Initialize (Password);
Hash_Update (Ctx, Last);
Last := Hash_Finalize (Ctx);
XOR_In_Place (Temporary, Last);
end loop;
declare
Bytes_To_Copy : constant Index :=
Index'Min
(Index'Min (Derived_Key_Length, Hash_Length),
Result'Last - Current + 1);
begin
Result (Current .. Current + Bytes_To_Copy - 1) :=
Temporary (0 .. Bytes_To_Copy - 1);
Current := Current + Bytes_To_Copy;
end;
end;
end loop;
return Result;
end PBKDF2;
function Write_Big_Endian (Input : Index) return Element_Array is
use Interfaces;
use System;
Int : constant Unsigned_32 := Unsigned_32 (Input);
begin
if Default_Bit_Order = High_Order_First then
return
(0 => Element (Int and 16#FF#),
1 => Element (Shift_Right (Int, 8) and 16#FF#),
2 => Element (Shift_Right (Int, 16) and 16#FF#),
3 => Element (Shift_Right (Int, 24) and 16#FF#));
else
return
(0 => Element (Shift_Right (Int, 24) and 16#FF#),
1 => Element (Shift_Right (Int, 16) and 16#FF#),
2 => Element (Shift_Right (Int, 8) and 16#FF#),
3 => Element (Int and 16#FF#));
end if;
end Write_Big_Endian;
procedure XOR_In_Place (L : in out Element_Array; R : Element_Array) is
begin
pragma Assert (L'Length = R'Length);
for I in L'Range loop
L (I) := L (I) xor R (I);
end loop;
end XOR_In_Place;
end PBKDF2_Generic;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Buffer_Package; use Buffer_Package;
with Utilities_Package; use Utilities_Package;
package Editor_Package is
type KEYSTROKE is record
O : ERR_TYPE;
C : Character;
end record;
type Editor is record
Name : Unbounded_String;
Doc : Integer;
Cmd : Integer;
Doc_View : View;
Focus_View : View;
Running : Boolean;
Error: Unbounded_String;
end record;
function Open_Editor
(Name : Unbounded_String; Doc : Integer; Cmd : Integer) return Editor;
procedure Load_File (File_Name : Unbounded_String; E : in out Editor);
procedure Run_Startup (Name : String);
procedure Run_Startup_Files (File_Name : Unbounded_String);
procedure Run (E : Editor);
procedure Status_Callback (E : Editor; V : View);
procedure Redisplay (V : View);
procedure Fix_Loc (E : Editor);
function Get_Key_Stroke (E : Editor; D : Boolean) return KEYSTROKE;
procedure Dispatch (E : Editor; F : View; K : KEYSTROKE);
end Editor_Package;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Containers.Generic_Array_Sort;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Vectors;
with Ada.Strings.Unbounded.Hash;
with Ada.Unchecked_Deallocation;
with TOML.Generic_Dump;
with TOML.Generic_Parse;
package body TOML is
use Ada.Strings.Unbounded;
procedure Dump_To_String is new TOML.Generic_Dump
(Output_Stream => Unbounded_UTF8_String,
Put => Append);
procedure Sort_Keys is new Ada.Containers.Generic_Array_Sort
(Index_Type => Positive,
Element_Type => Unbounded_UTF8_String,
Array_Type => Key_Array);
package TOML_Maps is new Ada.Containers.Hashed_Maps
(Key_Type => Unbounded_String,
Element_Type => TOML_Value,
Hash => Hash,
Equivalent_Keys => "=");
package TOML_Vectors is new Ada.Containers.Vectors (Positive, TOML_Value);
type TOML_Value_Record (Kind : Any_Value_Kind) is limited record
Ref_Count : Natural;
case Kind is
when TOML_Table =>
Map_Value : TOML_Maps.Map;
when TOML_Array =>
Item_Kind_Set : Boolean;
-- Whether the kind for array items have been determined
Item_Kind : Any_Value_Kind;
-- Kind for all items in this array. Valid iff Item_Kind_Set is
-- true.
Array_Value : TOML_Vectors.Vector;
-- List of values for all items
when TOML_String =>
String_Value : Unbounded_String;
when TOML_Integer =>
Integer_Value : Any_Integer;
when TOML_Float =>
Float_Value : Any_Float;
when TOML_Boolean =>
Boolean_Value : Boolean;
when TOML_Offset_Date_Time => null;
when TOML_Local_Date_Time => null;
when TOML_Local_Date => null;
when TOML_Local_Time => null;
end case;
end record;
procedure Free is new Ada.Unchecked_Deallocation
(TOML_Value_Record, TOML_Value_Record_Access);
function Create_Value (Rec : TOML_Value_Record_Access) return TOML_Value;
-- Wrap a value record in a value. This resets its ref-count to 1.
procedure Set_Item_Kind (Value : TOML_Value; Item : TOML_Value)
with Pre => Value.Kind = TOML_Array;
-- If Value (an array) has its item kind set, do nothing. Otherwise, set it
-- to Item's kind.
------------------
-- Create_Value --
------------------
function Create_Value (Rec : TOML_Value_Record_Access) return TOML_Value is
begin
return Result : TOML_Value do
Rec.Ref_Count := 1;
Result.Value := Rec;
end return;
end Create_Value;
------------------
-- Create_Error --
------------------
function Create_Error
(Message : String; Location : Source_Location) return Read_Result is
begin
return
(Success => False,
Message => To_Unbounded_String (Message),
Location => Location);
end Create_Error;
-------------
-- Is_Null --
-------------
function Is_Null (Value : TOML_Value) return Boolean is
begin
return Value.Value = null;
end Is_Null;
----------
-- Kind --
----------
function Kind (Value : TOML_Value) return Any_Value_Kind is
begin
return Value.Value.Kind;
end Kind;
------------
-- Equals --
------------
function Equals (Left, Right : TOML_Value) return Boolean is
begin
-- If Left and Right refer to the same document, they are obviously
-- equivalent (X is equivalent to X). If they don't have the same kind,
-- they are obviously not equivalent.
if Left = Right then
return True;
elsif Left.Kind /= Right.Kind then
return False;
end if;
case Left.Kind is
when TOML_Table =>
declare
Left_Keys : constant Key_Array := Left.Keys;
Right_Keys : constant Key_Array := Right.Keys;
begin
if Left_Keys /= Right_Keys then
return False;
end if;
for K of Left_Keys loop
if not Equals (Left.Get (K), Right.Get (K)) then
return False;
end if;
end loop;
end;
when TOML_Array =>
if Left.Length /= Right.Length then
return False;
end if;
for I in 1 .. Left.Length loop
if not Equals (Left.Item (I), Right.Item (I)) then
return False;
end if;
end loop;
when TOML_String =>
return Left.Value.String_Value = Right.Value.String_Value;
when TOML_Integer =>
return Left.Value.Integer_Value = Right.Value.Integer_Value;
when TOML_Boolean =>
return Left.Value.Boolean_Value = Right.Value.Boolean_Value;
when TOML_Float | TOML_Offset_Date_Time .. TOML_Local_Time =>
raise Program_Error;
end case;
return True;
end Equals;
-----------
-- Clone --
-----------
function Clone (Value : TOML_Value) return TOML_Value is
Result : TOML_Value;
begin
case Value.Kind is
when TOML_Table =>
Result := Create_Table;
for Key of Value.Keys loop
Result.Set (Key, Value.Get (Key).Clone);
end loop;
when TOML_Array =>
Result := Create_Array;
for I in 1 .. Value.Length loop
Result.Append (Value.Item (I));
end loop;
when TOML_String =>
Result := Create_String (Value.Value.String_Value);
when TOML_Integer =>
Result := Create_Integer (Value.Value.Integer_Value);
when TOML_Boolean =>
Result := Create_Boolean (Value.Value.Boolean_Value);
when TOML_Float | TOML_Offset_Date_Time .. TOML_Local_Time =>
raise Program_Error;
end case;
return Result;
end Clone;
----------------
-- As_Boolean --
----------------
function As_Boolean (Value : TOML_Value) return Boolean is
begin
return Value.Value.Boolean_Value;
end As_Boolean;
----------------
-- As_Integer --
----------------
function As_Integer (Value : TOML_Value) return Any_Integer is
begin
return Value.Value.Integer_Value;
end As_Integer;
---------------
-- As_String --
---------------
function As_String (Value : TOML_Value) return String is
begin
return To_String (Value.As_Unbounded_String);
end As_String;
-------------------------
-- As_Unbounded_String --
-------------------------
function As_Unbounded_String
(Value : TOML_Value) return Ada.Strings.Unbounded.Unbounded_String is
begin
return Value.Value.String_Value;
end As_Unbounded_String;
---------
-- Has --
---------
function Has (Value : TOML_Value; Key : String) return Boolean is
begin
return Value.Has (To_Unbounded_String (Key));
end Has;
---------
-- Has --
---------
function Has
(Value : TOML_Value; Key : Unbounded_UTF8_String) return Boolean is
begin
return Value.Value.Map_Value.Contains (Key);
end Has;
----------
-- Keys --
----------
function Keys (Value : TOML_Value) return Key_Array is
use TOML_Maps;
Map : TOML_Maps.Map renames Value.Value.Map_Value;
I : Positive := 1;
begin
return Result : Key_Array (1 .. Natural (Map.Length)) do
for Position in Map.Iterate loop
Result (I) := Key (Position);
I := I + 1;
end loop;
Sort_Keys (Result);
end return;
end Keys;
---------
-- Get --
---------
function Get (Value : TOML_Value; Key : String) return TOML_Value is
begin
return Value.Get (To_Unbounded_String (Key));
end Get;
---------
-- Get --
---------
function Get
(Value : TOML_Value; Key : Unbounded_UTF8_String) return TOML_Value is
begin
return Value.Value.Map_Value.Element (Key);
end Get;
-----------------
-- Get_Or_Null --
-----------------
function Get_Or_Null (Value : TOML_Value; Key : String) return TOML_Value
is
begin
return Value.Get_Or_Null (To_Unbounded_String (Key));
end Get_Or_Null;
-----------------
-- Get_Or_Null --
-----------------
function Get_Or_Null
(Value : TOML_Value; Key : Unbounded_UTF8_String) return TOML_Value
is
use TOML_Maps;
Position : constant Cursor := Value.Value.Map_Value.Find (Key);
begin
return (if Has_Element (Position)
then Element (Position)
else No_TOML_Value);
end Get_Or_Null;
----------------------
-- Iterate_On_Table --
----------------------
function Iterate_On_Table (Value : TOML_Value) return Table_Entry_Array is
Keys : constant Key_Array := Value.Keys;
begin
return Result : Table_Entry_Array (Keys'Range) do
for I In Keys'Range loop
Result (I) := (Keys (I), Value.Get (Keys (I)));
end loop;
end return;
end Iterate_On_Table;
------------
-- Length --
------------
function Length (Value : TOML_Value) return Natural is
begin
return Natural (Value.Value.Array_Value.Length);
end Length;
-------------------
-- Item_Kind_Set --
-------------------
function Item_Kind_Set (Value : TOML_Value) return Boolean is
begin
return Value.Value.Item_Kind_Set;
end Item_Kind_Set;
---------------
-- Item_Kind --
---------------
function Item_Kind (Value : TOML_Value) return Any_Value_Kind is
begin
return Value.Value.Item_Kind;
end Item_Kind;
----------
-- Item --
----------
function Item (Value : TOML_Value; Index : Positive) return TOML_Value is
begin
return Value.Value.Array_Value.Element (Index);
end Item;
--------------------
-- Create_Boolean --
--------------------
function Create_Boolean (Value : Boolean) return TOML_Value is
begin
return Create_Value (new TOML_Value_Record'
(Kind => TOML_Boolean, Ref_Count => 1, Boolean_Value => Value));
end Create_Boolean;
--------------------
-- Create_Integer --
--------------------
function Create_Integer (Value : Any_Integer) return TOML_Value is
begin
return Create_Value (new TOML_Value_Record'
(Kind => TOML_Integer, Ref_Count => 1, Integer_Value => Value));
end Create_Integer;
-------------------
-- Create_String --
-------------------
function Create_String (Value : String) return TOML_Value is
begin
return Create_String (To_Unbounded_String (Value));
end Create_String;
-------------------
-- Create_String --
-------------------
function Create_String (Value : Unbounded_UTF8_String) return TOML_Value is
begin
return Create_Value (new TOML_Value_Record'
(Kind => TOML_String,
Ref_Count => 1,
String_Value => Value));
end Create_String;
------------------
-- Create_Table --
------------------
function Create_Table return TOML_Value is
begin
return Create_Value (new TOML_Value_Record'
(Kind => TOML_Table, Ref_Count => 1, Map_Value => <>));
end Create_Table;
---------
-- Set --
---------
procedure Set (Value : TOML_Value; Key : String; Entry_Value : TOML_Value)
is
begin
Value.Set (To_Unbounded_String (Key), Entry_Value);
end Set;
---------
-- Set --
---------
procedure Set
(Value : TOML_Value;
Key : Unbounded_UTF8_String;
Entry_Value : TOML_Value)
is
begin
Value.Value.Map_Value.Include (Key, Entry_Value);
end Set;
-----------------
-- Set_Default --
-----------------
procedure Set_Default
(Value : TOML_Value; Key : String; Entry_Value : TOML_Value)
is
begin
Value.Set_Default (To_Unbounded_String (Key), Entry_Value);
end Set_Default;
-----------------
-- Set_Default --
-----------------
procedure Set_Default
(Value : TOML_Value;
Key : Unbounded_UTF8_String;
Entry_Value : TOML_Value)
is
use TOML_Maps;
Dummy_Position : Cursor;
Dummy_Inserted : Boolean;
begin
Value.Value.Map_Value.Insert
(Key, Entry_Value, Dummy_Position, Dummy_Inserted);
end Set_Default;
-----------
-- Unset --
-----------
procedure Unset (Value : TOML_Value; Key : String) is
begin
Value.Unset (To_Unbounded_String (Key));
end Unset;
-----------
-- Unset --
-----------
procedure Unset (Value : TOML_Value; Key : Unbounded_UTF8_String) is
begin
Value.Value.Map_Value.Delete (Key);
end Unset;
------------------
-- Create_Array --
------------------
function Create_Array (Item_Kind : Any_Value_Kind) return TOML_Value is
begin
return Create_Value (new TOML_Value_Record'
(Kind => TOML_Array,
Ref_Count => 1,
Item_Kind_Set => True,
Item_Kind => Item_Kind,
Array_Value => <>));
end Create_Array;
------------------
-- Create_Array --
------------------
function Create_Array return TOML_Value is
begin
return Create_Value (new TOML_Value_Record'
(Kind => TOML_Array,
Ref_Count => 1,
Item_Kind_Set => False,
Item_Kind => <>,
Array_Value => <>));
end Create_Array;
-------------------
-- Set_Item_Kind --
-------------------
procedure Set_Item_Kind (Value : TOML_Value; Item : TOML_Value) is
begin
if not Value.Item_Kind_Set then
Value.Value.Item_Kind_Set := True;
Value.Value.Item_Kind := Item.Kind;
end if;
end Set_Item_Kind;
---------
-- Set --
---------
procedure Set (Value : TOML_Value; Index : Positive; Item : TOML_Value) is
begin
Set_Item_Kind (Value, Item);
Value.Value.Array_Value (Index) := Item;
end Set;
------------
-- Append --
------------
procedure Append (Value, Item : TOML_Value) is
begin
Set_Item_Kind (Value, Item);
Value.Value.Array_Value.Append (Item);
end Append;
-------------------
-- Insert_Before --
-------------------
procedure Insert_Before
(Value : TOML_Value; Index : Positive; Item : TOML_Value)
is
begin
Set_Item_Kind (Value, Item);
Value.Value.Array_Value.Insert (Index, Item);
end Insert_Before;
-----------------
-- Load_String --
-----------------
function Load_String (Content : String) return Read_Result is
type Input_Stream is record
Next_Character : Positive;
-- Index of the next character in Content that Get must return
end record;
procedure Get
(Stream : in out Input_Stream;
EOF : out Boolean;
Byte : out Character);
-- Callback for Parse_String
---------
-- Get --
---------
procedure Get
(Stream : in out Input_Stream;
EOF : out Boolean;
Byte : out Character) is
begin
if Stream.Next_Character > Content'Length then
EOF := True;
else
EOF := False;
Byte := Content (Stream.Next_Character);
Stream.Next_Character := Stream.Next_Character + 1;
end if;
end Get;
function Parse_String is new TOML.Generic_Parse (Input_Stream, Get);
Stream : Input_Stream := (Next_Character => Content'First);
begin
return Parse_String (Stream);
end Load_String;
--------------------
-- Dump_As_String --
--------------------
function Dump_As_String (Value : TOML_Value) return String is
begin
return To_String (Dump_As_Unbounded (Value));
end Dump_As_String;
-----------------------
-- Dump_As_Unbounded --
-----------------------
function Dump_As_Unbounded
(Value : TOML_Value) return Unbounded_UTF8_String is
begin
return Result : Unbounded_UTF8_String do
Dump_To_String (Result, Value);
end return;
end Dump_As_Unbounded;
------------------
-- Format_Error --
------------------
function Format_Error (Result : Read_Result) return String is
Formatted : Unbounded_UTF8_String;
begin
if Result.Location.Line /= 0 then
declare
L : constant String := Result.Location.Line'Image;
C : constant String := Result.Location.Column'Image;
begin
Append (Formatted, L (L'First + 1 .. L'Last));
Append (Formatted, ":");
Append (Formatted, C (C'First + 1 .. C'Last));
Append (Formatted, ": ");
end;
end if;
Append (Formatted, Result.Message);
return To_String (Formatted);
end Format_Error;
------------
-- Adjust --
------------
overriding procedure Adjust (Self : in out TOML_Value) is
begin
if Self.Value = null then
return;
end if;
Self.Value.Ref_Count := Self.Value.Ref_Count + 1;
end Adjust;
--------------
-- Finalize --
--------------
overriding procedure Finalize (Self : in out TOML_Value) is
begin
if Self.Value = null then
return;
end if;
declare
V : TOML_Value_Record renames Self.Value.all;
begin
-- Decrement the ref-count. If no-one references V anymore,
-- deallocate it.
V.Ref_Count := V.Ref_Count - 1;
if V.Ref_Count > 0 then
return;
end if;
end;
Free (Self.Value);
end Finalize;
end TOML;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Numerics, Ada.Text_IO, Chebyshev, Dense_AD, Dense_AD.Integrator;
use Numerics, Ada.Text_IO, Chebyshev;
procedure Henon_Heiles is
use Int_IO, Real_IO, Real_Functions;
N : constant Nat := 2;
K : constant Nat := 13;
package AD_Package is new Dense_AD (2 * N);
package Integrator is new AD_Package.Integrator (K);
use AD_Package, Integrator;
-----------------------------------------------
Control : Control_Type := New_Control_Type (Tol => 1.0e-7);
function KE (Q : in AD_Vector) return AD_Type is
begin
return 0.5 * (Q (3) ** 2 + Q (4) ** 2);
end KE;
function PE (Q : in AD_Vector) return AD_Type is
begin
return 0.5 * (Q (1) ** 2 + Q (2) ** 2)
+ Q (1) ** 2 * Q (2) - Q (2) ** 3 / 3.0;
end PE;
function Lagrangian (T : in Real;
X : in Vector) return AD_Type is
Q : constant AD_Vector := Var (X);
begin
return KE (Q) - PE (Q);
end Lagrangian;
function Hamiltonian (T : in Real;
X : in Vector) return AD_Type is
Q : constant AD_Vector := Var (X);
begin
return KE (Q) + PE (Q);
end Hamiltonian;
-----------------------------------------------
function Get_IC (X : in Vector;
E : in Real) return Vector is
use Real_IO;
Y : Vector := X;
G : Vector;
H : AD_Type;
F, Dw : Real := 1.0;
W : Real renames Y (3); -- Y(3) is ω_t
begin
-- use Newton's method to solve for E - H = 0
W := 1.0;
while abs (F) > 1.0e-14 loop
H := Hamiltonian (0.0, Y);
F := E - Val (H);
G := Grad (H);
Dw := (E - Val (H)) / G (3); -- G(3) is \partial H / \partial ω_t
W := W + Dw;
end loop;
H := Hamiltonian (0.0, Y);
F := E - Val (H);
return Y;
end Get_IC;
function Func (X : in Vector) return Real is
begin
return X (1);
end Func;
function Sgn (X : in Real) return Real is
begin
if X >= 0.0 then return 1.0;
else return -1.0;
end if;
end Sgn;
function Find_State_At_Level (Level : in Real;
A : in Array_Of_Vectors;
T : in Real;
Dt : in Real;
Lower : in out Real;
Upper : in out Real;
Func : not null access function (X : Vector)
return Real) return Variable is
Guess : Variable;
Est : Real := 1.0e10;
Sign : constant Real := Sgn (Func (Interpolate (A, Upper, T, T + Dt)) -
Func (Interpolate (A, Lower, T, T + Dt)));
begin
while abs (Est - Level) > 1.0e-10 loop
Guess.T := 0.5 * (Lower + Upper);
Guess.X := Interpolate (A, Guess.T, T, T + Dt);
Est := Func (Guess.X);
if Est * sign > 0.0 then Upper := Guess.T;
else Lower := Guess.T; end if;
end loop;
return Guess;
end Find_State_At_Level;
-- Initial Conditions ----
Var, State, Guess : Variable := (0.0, (0.0, -0.1, 1.0, 0.0));
X : Vector renames Var.X;
T : Real renames Var.T;
-------------------------------
Y : Real_Vector (1 .. 2 * N * K);
A, Q : Array_Of_Vectors;
Fcsv : File_Type;
H0 : constant Real := 1.0 / 8.0;
T_Final : constant Real := 400_000.0;
Lower, Upper : Real;
AD : AD_Type;
begin
Control.Max_Dt := 10.0;
X := Get_IC (X, H0);
AD := Hamiltonian (0.0, X);
State := Var;
for Item of X loop
Put (Item); New_Line;
end loop;
Put (Val (AD)); New_Line;
Create (Fcsv, Name => "out.csv");
Put_Line (Fcsv, "t, q1, q2, q_dot1, q_dot2, p1, p2, E");
Print_Lagrangian (Fcsv, Var, Lagrangian'Access);
while T < T_Final loop
Put (Var.T); Put (" "); Put (Control.Dt); New_Line;
Y := Update (Lagrangian'Access, Var, Control, Sparse);
A := Chebyshev_Transform (Y);
Q := Split (Y);
for I in 2 .. K loop
if Q (1) (I - 1) * Q (1) (I) < 0.0 then -- If there's a zero, bisect
Lower := Var.T + Control.Dt * Grid (I - 1);
Upper := Var.T + Control.Dt * Grid (I);
Guess := Find_State_At_Level
(0.0, A, Var.T, Control.Dt, Lower, Upper, Func'Access);
----------------------------------------------------------------
if Guess.X (3) > 0.0 then
Print_Lagrangian (Fcsv, Guess, Lagrangian'Access);
end if;
end if;
end loop;
-- Put (Var.T); New_Line;
-- Print_Lagrangian (Fcsv, Var, Lagrangian'Access);
Update (Var => Var, Y => Y, Dt => Control.Dt); -- Update variable Var
end loop;
Close (Fcsv);
end Henon_Heiles;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body Node is
procedure SleepForSomeTime (maxSleep: Natural; intervals: Natural := 1) is
gen: RAF.Generator;
fraction: Float;
begin
RAF.Reset(gen);
fraction := 1.0 / Float(maxSleep);
delay Duration(fraction * RAF.Random(gen) * Float(intervals));
end SleepForSomeTime;
task body NodeTask is
target: pNodeObj;
neighbours: pArray_pNodeObj;
stash: pMessage;
exitTask: Boolean := False;
trapActive: Boolean := False;
begin
loop
select
accept SendMessage(message: in pMessage) do
logger.LogMessageInTransit(message.all.content, self.all.id);
stash := message;
if trapActive then
logger.Log("→→→ message" & Natural'Image(stash.all.content) & " fell into plunderer’s trap");
stash := null;
receiver.all.ReceiveMessage;
trapActive := False;
end if;
SleepForSomeTime(maxSleep);
if stash /= null and isLast then
-- allow receiving the message only if the node is the last node
logger.Log("→→→ message" & Natural'Image(stash.all.content) & " received");
stash := null;
receiver.all.ReceiveMessage;
end if;
if stash /= null then
stash.all.health := Natural'Pred(stash.all.health);
if stash.all.health = 0 then
-- message has exhausted its health
logger.Log("→→→ message" & Natural'Image(stash.all.content) & " died of exhaustion");
stash := null;
receiver.all.ReceiveMessage;
end if;
end if;
-- logger.Log("message" & Natural'Image(message.all.content) & " has" & Natural'Image(message.all.health) & " health" & " node" & Natural'Image(self.all.id));
end SendMessage;
or
accept SetupTrap do
trapActive := True;
end SetupTrap;
or
accept Stop do
exitTask := True;
end Stop;
else
SleepForSomeTime(maxSleep);
end select;
if stash /= null then
neighbours := self.all.neighbours;
target := neighbours.all(RAD.Next(neighbours'Length));
-- logger.Log("message" & Natural'Image(stash.all.content) & " is about to be sent from node" & Natural'Image(self.all.id) & " to node" & Natural'Image(target.all.id));
target.all.nodeStash.all.SendMessage(stash);
-- logger.Log("message" & Natural'Image(stash.all.content) & " sent from node" & Natural'Image(self.all.id) );
stash := null;
end if;
if exitTask then
exit;
end if;
end loop;
end NodeTask;
task body NodeStash is
exitTask: Boolean := False;
stash: pMessage;
begin
loop
select
accept SendMessage(message: in pMessage) do
stash := message;
end SendMessage;
or
accept Stop do
exitTask := True;
end Stop;
end select;
if stash /= null then
self.all.nodeTask.all.SendMessage(stash);
stash := null;
end if;
if exitTask then
exit;
end if;
end loop;
end NodeStash;
task body NodeTaskGrimReaper is
begin
node.all.nodeTask.Stop;
node.all.nodeStash.Stop;
end NodeTaskGrimReaper;
end Node;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package GL.Low_Level.Enums is
pragma Preelaborate;
-- Unlike GL.Enums, this package is not private and hosts enum types that may
-- be needed by third-party code or wrappers.
type Texture_Kind is (Texture_1D, Texture_2D, Proxy_Texture_1D,
Proxy_Texture_2D, Texture_3D, Proxy_Texture_3D,
Texture_Cube_Map, Texture_Cube_Map_Positive_X,
Texture_Cube_Map_Negative_X,
Texture_Cube_Map_Positive_Y,
Texture_Cube_Map_Negative_Y,
Texture_Cube_Map_Positive_Z,
Texture_Cube_Map_Negative_Z,
Proxy_Texture_Cube_Map,
Texture_1D_Array,
Proxy_Texture_1D_Array, Texture_2D_Array,
Proxy_Texture_2D_Array, Texture_Buffer);
type Renderbuffer_Kind is (Renderbuffer);
type Framebuffer_Kind is (Read, Draw, Read_Draw);
type Buffer_Kind is (Array_Buffer, Element_Array_Buffer, Pixel_Pack_Buffer,
Pixel_Unpack_Buffer, Uniform_Buffer, Texture_Buffer,
Transform_Feedback_Buffer, Transform_Feedback,
Copy_Read_Buffer, Copy_Write_Buffer,
Draw_Indirect_Buffer, Shader_Storage_Buffer,
Atomic_Counter_Buffer);
type Draw_Buffer_Index is (DB0, DB1, DB2, DB3, DB4, DB5, DB6, DB7,
DB8, DB9, DB10, DB11, DB12, DB13, DB14, DB15);
type Only_Depth_Buffer is (Depth_Buffer);
type Only_Stencil_Buffer is (Stencil);
type Only_Depth_Stencil_Buffer is (Depth_Stencil);
type Only_Color_Buffer is (Color);
type Query_Param is (Time_Elapsed, Samples_Passed, Any_Samples_Passed,
Transform_Feedback_Primitives_Written);
type Query_Results is (Query_Result, Query_Result_Available);
private
for Texture_Kind use (Texture_1D => 16#0DE0#,
Texture_2D => 16#0DE1#,
Proxy_Texture_1D => 16#8063#,
Proxy_Texture_2D => 16#8064#,
Texture_3D => 16#806F#,
Proxy_Texture_3D => 16#8070#,
Texture_Cube_Map => 16#8513#,
Texture_Cube_Map_Positive_X => 16#8515#,
Texture_Cube_Map_Negative_X => 16#8516#,
Texture_Cube_Map_Positive_Y => 16#8517#,
Texture_Cube_Map_Negative_Y => 16#8518#,
Texture_Cube_Map_Positive_Z => 16#8519#,
Texture_Cube_Map_Negative_Z => 16#851A#,
Proxy_Texture_Cube_Map => 16#851B#,
Texture_1D_Array => 16#8C18#,
Proxy_Texture_1D_Array => 16#8C19#,
Texture_2D_Array => 16#8C1A#,
Proxy_Texture_2D_Array => 16#8C1B#,
Texture_Buffer => 16#8C2A#);
for Texture_Kind'Size use Enum'Size;
for Renderbuffer_Kind use (Renderbuffer => 16#8D41#);
for Renderbuffer_Kind'Size use Enum'Size;
for Framebuffer_Kind use (Read => 16#8CA8#,
Draw => 16#8CA9#,
Read_Draw => 16#8D40#);
for Framebuffer_Kind'Size use Enum'Size;
for Buffer_Kind use (Array_Buffer => 16#8892#,
Element_Array_Buffer => 16#8893#,
Pixel_Pack_Buffer => 16#88EB#,
Pixel_Unpack_Buffer => 16#88EC#,
Uniform_Buffer => 16#8A11#,
Texture_Buffer => 16#8C2A#,
Transform_Feedback_Buffer => 16#8C8E#,
Transform_Feedback => 16#8E22#,
Copy_Read_Buffer => 16#8F36#,
Copy_Write_Buffer => 16#8F37#,
Draw_Indirect_Buffer => 16#8F3F#,
Shader_Storage_Buffer => 16#90D2#,
Atomic_Counter_Buffer => 16#92C0#);
for Buffer_Kind'Size use Enum'Size;
for Draw_Buffer_Index use (DB0 => 16#8825#,
DB1 => 16#8826#,
DB2 => 16#8827#,
DB3 => 16#8828#,
DB4 => 16#8829#,
DB5 => 16#882A#,
DB6 => 16#882B#,
DB7 => 16#882C#,
DB8 => 16#882D#,
DB9 => 16#882E#,
DB10 => 16#882F#,
DB11 => 16#8830#,
DB12 => 16#8831#,
DB13 => 16#8832#,
DB14 => 16#8833#,
DB15 => 16#8834#);
for Draw_Buffer_Index'Size use Int'Size;
for Only_Depth_Buffer use (Depth_Buffer => 16#1801#);
for Only_Depth_Buffer'Size use Enum'Size;
for Only_Stencil_Buffer use (Stencil => 16#1802#);
for Only_Stencil_Buffer'Size use Enum'Size;
for Only_Depth_Stencil_Buffer use (Depth_Stencil => 16#84F9#);
for Only_Depth_Stencil_Buffer'Size use Enum'Size;
for Only_Color_Buffer use (Color => 16#1800#);
for Only_Color_Buffer'Size use Enum'Size;
for Query_Param use (Time_Elapsed => 16#88BF#,
Samples_Passed => 16#8914#,
Any_Samples_Passed => 16#8C2F#,
Transform_Feedback_Primitives_Written => 16#8C88#);
for Query_Param'Size use Low_Level.Enum'Size;
for Query_Results use (Query_Result => 16#8866#,
Query_Result_Available => 16#8867#);
for Query_Results'Size use Low_Level.Enum'Size;
end GL.Low_Level.Enums;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Beans.Objects.Maps;
with Util.Beans.Objects.Vectors;
with Util.Serialize.IO;
with Util.Stacks;
with Util.Log;
package Util.Beans.Objects.Readers is
type Reader is limited new Util.Serialize.IO.Reader with private;
-- Start a document.
overriding
procedure Start_Document (Handler : in out Reader);
-- Start a new object associated with the given name. This is called when
-- the '{' is reached. The reader must be updated so that the next
-- <b>Set_Member</b> procedure will associate the name/value pair on the
-- new object.
overriding
procedure Start_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class);
-- Finish an object associated with the given name. The reader must be
-- updated to be associated with the previous object.
overriding
procedure Finish_Object (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class);
overriding
procedure Start_Array (Handler : in out Reader;
Name : in String;
Logger : in out Util.Log.Logging'Class);
overriding
procedure Finish_Array (Handler : in out Reader;
Name : in String;
Count : in Natural;
Logger : in out Util.Log.Logging'Class);
-- Set the name/value pair on the current object. For each active mapping,
-- find whether a rule matches our name and execute it.
overriding
procedure Set_Member (Handler : in out Reader;
Name : in String;
Value : in Util.Beans.Objects.Object;
Logger : in out Util.Log.Logging'Class;
Attribute : in Boolean := False);
-- Get the root object.
function Get_Root (Handler : in Reader) return Object;
private
type Object_Context is record
Map : Util.Beans.Objects.Maps.Map_Bean_Access;
List : Util.Beans.Objects.Vectors.Vector_Bean_Access;
end record;
type Object_Context_Access is access all Object_Context;
package Object_Stack is new Util.Stacks (Element_Type => Object_Context,
Element_Type_Access => Object_Context_Access);
type Reader is limited new Util.Serialize.IO.Reader with record
Context : Object_Stack.Stack;
Root : Util.Beans.Objects.Object;
end record;
end Util.Beans.Objects.Readers;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with MPFR.Root_FR.Inside;
with System;
with C.mpfr;
with C.string;
package body MPC.Root_C is
use type C.signed_int;
procedure memcpy (dst, src : System.Address; n : C.size_t)
with Import, Convention => Intrinsic, External_Name => "__builtin_memcpy";
-- implementation
function Re (X : MP_Complex) return MPFR.Root_FR.MP_Float is
Source : C.mpfr.mpfr_t renames Controlled.Constant_Reference (X).re;
Dummy : C.signed_int;
begin
return Result :
MPFR.Root_FR.MP_Float (
MPFR.Precision (C.mpfr.mpfr_get_prec (Source (0)'Access)))
do
Dummy :=
C.mpfr.mpfr_set4 (
MPFR.Root_FR.Inside.Reference (Result),
Source (0)'Access,
C.mpfr.MPFR_RNDN,
C.mpfr.mpfr_sgn (Source (0)'Access));
end return;
end Re;
function Im (X : MP_Complex) return MPFR.Root_FR.MP_Float is
Source : C.mpfr.mpfr_t renames Controlled.Constant_Reference (X).im;
Dummy : C.signed_int;
begin
return Result :
MPFR.Root_FR.MP_Float (
MPFR.Precision (C.mpfr.mpfr_get_prec (Source (0)'Access)))
do
Dummy :=
C.mpfr.mpfr_set4 (
MPFR.Root_FR.Inside.Reference (Result),
Source (0)'Access,
C.mpfr.MPFR_RNDN,
C.mpfr.mpfr_sgn (Source (0)'Access));
end return;
end Im;
function Compose (Re, Im : MPFR.Root_FR.MP_Float) return MP_Complex is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Re.Precision, Im.Precision) do
Dummy :=
C.mpc.mpc_set_fr_fr (
Controlled.Reference (Result),
MPFR.Root_FR.Inside.Constant_Reference (Re),
MPFR.Root_FR.Inside.Constant_Reference (Im),
C.mpc.MPC_RNDNN);
end return;
end Compose;
function Compose (
Re : Long_Long_Float;
Real_Precision : MPFR.Precision;
Im : MPFR.Root_FR.MP_Float)
return MP_Complex
is
Im_Source : constant not null access constant C.mpfr.mpfr_struct :=
MPFR.Root_FR.Inside.Constant_Reference (Im);
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Im.Precision) do
declare
Raw_Result : constant not null access C.mpc.mpc_struct :=
Controlled.Reference (Result);
begin
Dummy :=
C.mpfr.mpfr_set_ld (
Raw_Result.re (0)'Access,
C.long_double (Re),
C.mpfr.MPFR_RNDN);
Dummy :=
C.mpfr.mpfr_set4 (
Raw_Result.im (0)'Access,
Im_Source,
C.mpfr.MPFR_RNDN,
C.mpfr.mpfr_sgn (Im_Source));
end;
end return;
end Compose;
function Image (
Value : MP_Complex;
Base : Number_Base := 10;
Rounding : MPC.Rounding)
return String
is
Image : constant C.char_ptr :=
C.mpc.mpc_get_str (
C.signed_int (Base),
0,
Controlled.Constant_Reference (Value),
C.mpc.mpc_rnd_t (Rounding));
Length : constant Natural := Integer (C.string.strlen (Image));
Ada_Image : String (1 .. Length);
for Ada_Image'Address use Image.all'Address;
begin
return Result : String (1 .. Length) do
Result := Ada_Image;
C.mpc.mpc_free_str (Image);
end return;
end Image;
function Value (
Image : String;
Base : Number_Base := 10;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Image_Length : constant C.size_t := Image'Length;
C_Image : C.char_array (0 .. Image_Length); -- NUL
begin
memcpy (C_Image'Address, Image'Address, Image_Length);
C_Image (Image_Length) := C.char'Val (0);
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
if C.mpc.mpc_set_str (
Controlled.Reference (Result),
C_Image (C_Image'First)'Access,
C.signed_int (Base),
C.mpc.mpc_rnd_t (Rounding)) < 0
then
raise Constraint_Error;
end if;
end return;
end Value;
function "=" (Left, Right : MP_Complex) return Boolean is
begin
return C.mpc.mpc_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) = 0;
end "=";
function "<" (Left, Right : MP_Complex) return Boolean is
begin
return C.mpc.mpc_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) < 0;
end "<";
function ">" (Left, Right : MP_Complex) return Boolean is
begin
return C.mpc.mpc_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) > 0;
end ">";
function "<=" (Left, Right : MP_Complex) return Boolean is
begin
return C.mpc.mpc_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) <= 0;
end "<=";
function ">=" (Left, Right : MP_Complex) return Boolean is
begin
return C.mpc.mpc_cmp (
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right)) >= 0;
end ">=";
function Copy (
Right : MP_Complex;
Real_Precision : MPFR.Precision := MPFR.Default_Precision;
Imaginary_Precision : MPFR.Precision := MPFR.Default_Precision;
Rounding : MPC.Rounding := Default_Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_set (
Controlled.Reference (Result),
Controlled.Constant_Reference (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Copy;
function Negative (
Right : MP_Complex;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_neg (
Controlled.Reference (Result),
Controlled.Constant_Reference (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Negative;
function Add (
Left, Right : MP_Complex;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_add (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Add;
function Subtract (
Left, Right : MP_Complex;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_sub (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Subtract;
function Multiply (
Left, Right : MP_Complex;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_mul (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Multiply;
function Divide (
Left, Right : MP_Complex;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_div (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
Controlled.Constant_Reference (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Divide;
function Power (
Left : MP_Complex;
Right : Integer;
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision;
Rounding : MPC.Rounding)
return MP_Complex
is
Dummy : C.signed_int;
begin
return Result : MP_Complex (Real_Precision, Imaginary_Precision) do
Dummy :=
C.mpc.mpc_pow_si (
Controlled.Reference (Result),
Controlled.Constant_Reference (Left),
C.signed_long (Right),
C.mpc.mpc_rnd_t (Rounding));
end return;
end Power;
package body Controlled is
function Create (
Real_Precision : MPFR.Precision;
Imaginary_Precision : MPFR.Precision)
return MP_Complex is
begin
return Result : MP_Complex := (Ada.Finalization.Controlled with Raw => <>) do
C.mpc.mpc_init3 (
Result.Raw (0)'Access,
C.mpfr.mpfr_prec_t (Real_Precision),
C.mpfr.mpfr_prec_t (Imaginary_Precision));
end return;
end Create;
function Reference (Item : in out Root_C.MP_Complex)
return not null access C.mpc.mpc_struct is
begin
return Item.Data.Raw (0)'Unchecked_Access;
end Reference;
function Constant_Reference (Item : Root_C.MP_Complex)
return not null access constant C.mpc.mpc_struct is
begin
return Item.Data.Raw (0)'Unchecked_Access;
end Constant_Reference;
overriding procedure Initialize (Object : in out MP_Complex) is
begin
raise Program_Error;
end Initialize;
overriding procedure Adjust (Object : in out MP_Complex) is
Source : constant C.mpc.mpc_t := Object.Raw; -- move
Dummy : C.signed_int;
begin
C.mpc.mpc_init3 (
Object.Raw (0)'Access,
C.mpfr.mpfr_get_prec (Source (0).re (0)'Access),
C.mpfr.mpfr_get_prec (Source (0).im (0)'Access));
Dummy :=
C.mpc.mpc_set (Object.Raw (0)'Access, Source (0)'Access, C.mpc.MPC_RNDNN);
end Adjust;
overriding procedure Finalize (Object : in out MP_Complex) is
begin
C.mpc.mpc_clear (Object.Raw (0)'Access);
end Finalize;
end Controlled;
end MPC.Root_C;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- --
pragma Ada_2012;
with Ada.Containers;
with Ada.Containers.Doubly_Linked_Lists;
with Ada.Containers.Hashed_Maps;
with Ada.Containers.Hashed_Sets;
with Ada.Containers.Vectors;
with Skill.Types;
with Skill.Hashes; use Skill.Hashes;
with Skill.Types.Pools;
with Skill.Containers.Arrays;
with Skill.Containers.Sets;
with Skill.Containers.Maps;
package body Skill.Field_Types.Builtin is
use type Skill.Types.v64;
use type Skill.Types.Uv64;
use type Skill.Containers.Boxed_Array;
use type Skill.Types.Boxed_List;
use type Skill.Containers.Boxed_Set;
use type Skill.Types.Boxed_Map;
function Offset_Single_V64 (Input : Types.v64) return Types.v64 is
function Cast is new Ada.Unchecked_Conversion
(Skill.Types.v64,
Skill.Types.Uv64);
V : constant Skill.Types.Uv64 := Cast (Input);
begin
if 0 = (V and 16#FFFFFFFFFFFFFF80#) then
return 1;
elsif 0 = (V and 16#FFFFFFFFFFFFC000#) then
return 2;
elsif 0 = (V and 16#FFFFFFFFFFE00000#) then
return 3;
elsif 0 = (V and 16#FFFFFFFFF0000000#) then
return 4;
elsif 0 = (V and 16#FFFFFFF800000000#) then
return 5;
elsif 0 = (V and 16#FFFFFC0000000000#) then
return 6;
elsif 0 = (V and 16#FFFE000000000000#) then
return 7;
elsif 0 = (V and 16#FF00000000000000#) then
return 8;
else
return 9;
end if;
end Offset_Single_V64;
procedure Insert
(This : in out Skill.Containers.Boxed_Array;
E : in Types.Box)
is
begin
This.Append (E);
end Insert;
package body Annotation_Type_P is
use type Types.Annotation;
procedure Fix_Types (This : access Field_Type_T) is
procedure Add (P : Types.Pools.Pool) is
begin
This.Types_By_Name.Include (P.Skill_Name, P);
end Add;
begin
This.Types.Foreach (Add'Access);
end Fix_Types;
overriding function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box
is
T : Types.v64 := Input.V64;
Idx : Types.v64 := Input.V64;
begin
if 0 = T then
return Boxed (null);
else
declare
Data : Types.Annotation_Array :=
This.Types.Element (Integer (T - 1)).Base.Data;
begin
return Boxed (Data (Integer (Idx)));
end;
end if;
end Read_Box;
overriding function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.v64
is
type T is access all String;
function Cast is new Ada.Unchecked_Conversion
(T,
Types.String_Access);
Ref : Types.Annotation := Unboxed (Target);
begin
if null = Ref then
return 2;
else
return Offset_Single_V64
(Types.v64
(1 +
This.Types_By_Name.Element
(Ref.Dynamic.Skill_Name).Pool_Offset)) +
Offset_Single_V64 (Types.v64 (Ref.Skill_ID));
end if;
end Offset_Box;
overriding procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream;
Target : Types.Box)
is
type T is access all String;
function Cast is new Ada.Unchecked_Conversion
(T,
Types.String_Access);
Ref : Types.Annotation := Unboxed (Target);
begin
if null = Ref then
Output.I16 (0);
else
Output.V64
(Types.v64
(1 +
This.Types_By_Name.Element
(Ref.Dynamic.Skill_Name).Pool_Offset));
Output.V64 (Types.v64 (Ref.Skill_ID));
end if;
end Write_Box;
end Annotation_Type_P;
package Arrays_P is new Skill.Containers.Arrays (Types.Box);
package body Const_Arrays_P is
pragma Warnings (Off);
function Boxed
(This : access Containers.Boxed_Array_T'Class) return Types.Box
is
type X is access all Containers.Boxed_Array_T'Class;
function Cast is new Ada.Unchecked_Conversion (X, Types.Box);
begin
return Cast (X (This));
end Boxed;
function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box
is
Count : Types.v64 := This.Length;
Result : Containers.Boxed_Array :=
Containers.Boxed_Array (Arrays_P.Make);
begin
for I in 1 .. Count loop
Insert (Result, This.Base.Read_Box (Input));
end loop;
return Boxed (Result);
end Read_Box;
function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.v64
is
Result : Types.v64 := 0;
Count : Natural := Natural (This.Length);
begin
for I in 1 .. Count loop
Result :=
Result + This.Base.Offset_Box (Unboxed (Target).Get (I - 1));
end loop;
return Result;
end Offset_Box;
procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream;
Target : Types.Box)
is
Length : Natural := Natural (This.Length);
begin
for I in 1 .. Length loop
This.Base.Write_Box (Output, Unboxed (Target).Get (I - 1));
end loop;
end Write_Box;
end Const_Arrays_P;
package body Var_Arrays_P is
function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box
is
Count : Types.v64 := Input.V64;
Result : Containers.Boxed_Array :=
Containers.Boxed_Array (Arrays_P.Make);
begin
for I in 1 .. Count loop
Insert (Result, This.Base.Read_Box (Input));
end loop;
return Boxed (Result);
end Read_Box;
function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.v64
is
Result : Types.v64;
Arr : Containers.Boxed_Array := Unboxed (Target);
Count : Natural := Natural (Arr.Length);
begin
if null = Arr then
return 1;
end if;
Result := Offset_Single_V64 (Types.v64 (Count));
for I in 1 .. Count loop
Result := Result + This.Base.Offset_Box (Arr.Get (I - 1));
end loop;
return Result;
end Offset_Box;
procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream;
Target : Types.Box)
is
Arr : Containers.Boxed_Array := Unboxed (Target);
Length : Natural := Natural (Arr.Length);
begin
if null = Arr then
Output.I8 (0);
return;
end if;
Output.V64 (Types.v64 (Length));
for I in 1 .. Length loop
This.Base.Write_Box (Output, Arr.Get (I - 1));
end loop;
end Write_Box;
end Var_Arrays_P;
package body List_Type_P is
function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box
is
Count : Types.v64 := Input.V64;
Result : Containers.Boxed_Array :=
Containers.Boxed_Array (Arrays_P.Make);
begin
for I in 1 .. Count loop
Insert (Result, This.Base.Read_Box (Input));
end loop;
return Boxed (Result);
end Read_Box;
function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.v64
is
Result : Types.v64;
Arr : Containers.Boxed_Array := Unboxed (Target);
Count : Natural := Natural (Arr.Length);
begin
if null = Arr then
return 1;
end if;
Result := Offset_Single_V64 (Types.v64 (Count));
for I in 1 .. Count loop
Result := Result + This.Base.Offset_Box (Arr.Get (I - 1));
end loop;
return Result;
end Offset_Box;
procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream;
Target : Types.Box)
is
Arr : Containers.Boxed_Array := Unboxed (Target);
Length : Natural := Natural (Arr.Length);
begin
if null = Arr then
Output.I8 (0);
return;
end if;
Output.V64 (Types.v64 (Length));
for I in 1 .. Length loop
This.Base.Write_Box (Output, Arr.Get (I - 1));
end loop;
end Write_Box;
end List_Type_P;
package Sets_P is new Skill.Containers.Sets (Types.Box, Types.Hash, "=");
package body Set_Type_P is
function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box
is
Count : Types.v64 := Input.V64;
Result : Containers.Boxed_Set := Containers.Boxed_Set (Sets_P.Make);
begin
for I in 1 .. Count loop
Result.Add (This.Base.Read_Box (Input));
end loop;
return Boxed (Result);
end Read_Box;
function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.v64
is
Result : Types.v64;
Set : Containers.Boxed_Set := Unboxed (Target);
Count : Natural := Natural (Set.Length);
Iter : Containers.Set_Iterator;
begin
if null = Set then
return 1;
end if;
Result := Offset_Single_V64 (Types.v64 (Count));
Iter := Set.Iterator;
while Iter.Has_Next loop
Result := Result + This.Base.Offset_Box (Iter.Next);
end loop;
Iter.Free;
return Result;
end Offset_Box;
procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream;
Target : Types.Box)
is
Set : Containers.Boxed_Set := Unboxed (Target);
Length : Natural := Natural (Set.Length);
Iter : Containers.Set_Iterator;
begin
if null = Set then
Output.I8 (0);
return;
end if;
Output.V64 (Types.v64 (Length));
Iter := Set.Iterator;
while Iter.Has_Next loop
This.Base.Write_Box (Output, Iter.Next);
end loop;
Iter.Free;
end Write_Box;
end Set_Type_P;
package Maps_P is new Skill.Containers.Maps(Types.Box, Types.Box, Types.Hash, "=", "=");
package body Map_Type_P is
function Read_Box
(This : access Field_Type_T;
Input : Streams.Reader.Stream) return Types.Box
is
Count : Types.v64 := Input.V64;
Result : Types.Boxed_Map := Types.Boxed_Map (Maps_P.Make);
K, V : Types.Box;
begin
for I in 1 .. Count loop
K := This.Key.Read_Box (Input);
V := This.Value.Read_Box (Input);
Result.Update (K, V);
end loop;
return Boxed (Result);
end Read_Box;
function Offset_Box
(This : access Field_Type_T;
Target : Types.Box) return Types.v64
is
Map : Containers.Boxed_Map := Unboxed (Target);
Iter : Containers.Map_Iterator;
Result : Types.v64;
Count : Natural := Natural (Map.Length);
begin
if null = Map or 0 = Count then
return 1;
end if;
Result := Offset_Single_V64 (Types.v64 (Count));
Iter := Map.Iterator;
while Iter.Has_Next loop
Result := Result
+ This.Key.Offset_Box (Iter.Key)
+ This.Value.Offset_Box (Iter.Value);
Iter.Advance;
end loop;
Iter.Free;
return Result;
end Offset_Box;
procedure Write_Box
(This : access Field_Type_T;
Output : Streams.Writer.Sub_Stream;
Target : Types.Box)
is
Map : Types.Boxed_Map := Unboxed (Target);
Iter : Containers.Map_Iterator;
Length : Natural := Natural (Map.Length);
begin
if null = Map or 0 = Length then
Output.I8 (0);
return;
end if;
Output.V64 (Types.v64 (Length));
Iter := Map.Iterator;
while Iter.Has_Next loop
This.Key.Write_Box (Output, Iter.Key);
This.Value.Write_Box (Output, Iter.Value);
Iter.Advance;
end loop;
Iter.Free;
end Write_Box;
end Map_Type_P;
end Skill.Field_Types.Builtin;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- @summary String functions
package body MyStrings with SPARK_Mode is
procedure StrCpySpace (outstring : out String; instring : String) is
begin
if instring'Length >= outstring'Length then
-- trim
outstring := instring (instring'First .. instring'First - 1 + outstring'Length);
else
-- pad
declare
lastidx : constant Natural := outstring'First + instring'Length - 1;
begin
outstring := (others => ' ');
outstring (outstring'First .. lastidx) := instring;
end;
end if;
end StrCpySpace;
function RTrim (S : String) return String is
begin
for J in reverse S'Range loop
if S (J) /= ' ' then
return S (S'First .. J);
end if;
end loop;
return "";
end RTrim;
function LTrim (S : String) return String is
begin
for J in S'Range loop
if S (J) /= ' ' then
return S (J .. S'Last);
end if;
end loop;
return "";
end LTrim;
function Trim (S : String) return String is
begin
return LTrim (RTrim (S));
end Trim;
function StrChr (S : String; C : Character) return Integer is
begin
for idx in S'Range loop
if S (idx) = C then
return idx;
end if;
end loop;
return S'Last + 1;
end StrChr;
function Is_AlNum (c : Character) return Boolean is
begin
return (c in 'a' .. 'z') or (c in 'A' .. 'Z') or (c in '0' .. '9');
end Is_AlNum;
function Strip_Non_Alphanum (s : String) return String with SPARK_Mode => Off is
tmp : String (1 .. s'Length) := s;
len : Integer := 0;
begin
for c in s'Range loop
if Is_AlNum (s (c)) then
len := len + 1;
tmp (len) := s (c);
end if;
end loop;
declare
ret : constant String (1 .. len) := tmp (1 .. len); -- SPARK: "subtype constraint cannot depend on len"
begin
return ret;
end;
end Strip_Non_Alphanum;
end MyStrings;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- http://www.adapower.com/index.php?Command=Class&ClassID=Patterns&CID=288
-- This is because in Ada, generic functions cannot be overloaded, so we
-- cannot follow Bob's implementation
type Ast_Printer is new Visitor with
record
Image : L_String := To_Bounded_String ("");
end record;
function Print (V : Ast_Printer) return String;
function Print (The_Expr : Expr'Class) return String;
overriding
procedure visit_Binary_Expr (Self : in out Ast_Printer; The_Expr : Binary) with
Global => (input => Exprs.State);
overriding
procedure visit_Grouping_Expr (Self : in out Ast_Printer; The_Expr : Grouping);
overriding
procedure visit_Float_Literal_Expr (Self : in out Ast_Printer; The_Expr : Float_Literal);
overriding
procedure visit_Num_Literal_Expr (Self : in out Ast_Printer; The_Expr : Num_Literal);
overriding
procedure visit_Str_Literal_Expr (Self : in out Ast_Printer; The_Expr : Str_Literal);
overriding
procedure visit_Unary_Expr (Self : in out Ast_Printer; The_Expr : Unary);
private
function Print (The_Expr : Binary) return String;
function Print (The_Expr : Grouping) return String;
function Print (The_Expr : Float_Literal) return String;
function Print (The_Expr : Num_Literal) return String;
function Print (The_Expr : Str_Literal) return String;
function Print (The_Expr : Unary) return String;
end Ast_Printers;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
function To_tv_nsec (X : Nanosecond_Number) return C.signed_long_long
with Convention => Intrinsic;
-- Linux (x32)
pragma Inline_Always (To_tv_nsec);
pragma Warnings (On, "is not referenced");
function To_tv_nsec (X : Nanosecond_Number) return C.signed_long is
begin
return C.signed_long (X);
end To_tv_nsec;
function To_tv_nsec (X : Nanosecond_Number) return C.signed_long_long is
begin
return C.signed_long_long (X);
end To_tv_nsec;
-- implementation
function To_timespec (D : C.sys.time.struct_timeval)
return C.time.struct_timespec is
begin
return (
tv_sec => D.tv_sec,
tv_nsec => To_tv_nsec (Nanosecond_Number (D.tv_usec) * 1_000));
end To_timespec;
function To_timespec (D : Duration) return C.time.struct_timespec is
Nanosecond : constant Nanosecond_Number :=
Nanosecond_Number'Integer_Value (D);
Sub_Second : constant Nanosecond_Number := Nanosecond mod 1_000_000_000;
begin
return (
tv_sec =>
C.sys.types.time_t ((Nanosecond - Sub_Second) / 1_000_000_000),
tv_nsec => To_tv_nsec (Sub_Second));
end To_timespec;
function To_Duration (D : C.time.struct_timespec) return Duration is
begin
return Duration'Fixed_Value (
Nanosecond_Number'Integer_Value (To_Duration (D.tv_sec))
+ Nanosecond_Number (D.tv_nsec));
end To_Duration;
function To_Duration (D : C.sys.types.time_t) return Duration is
begin
return Duration'Fixed_Value (
(Nanosecond_Number (D)) * 1_000_000_000);
end To_Duration;
procedure Simple_Delay_For (D : Duration) is
Req_T : aliased C.time.struct_timespec := To_timespec (D);
begin
loop
declare
Rem_T : aliased C.time.struct_timespec;
R : C.signed_int;
begin
R := C.time.nanosleep (Req_T'Access, Rem_T'Access);
exit when not (R < 0);
Req_T := Rem_T;
end;
end loop;
end Simple_Delay_For;
procedure Delay_For (D : Duration) is
begin
if D >= 0.0 then
Delay_For_Hook.all (D);
end if;
end Delay_For;
end System.Native_Time;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--*
-- OBJECTIVE:
-- CHECK THAT THE IDENTIFIERS "BOOLEAN, TRUE, AND FALSE" AND THE
-- IDENTIFIERS "INTEGER, NATURAL, AND POSITIVE" ARE DECLARED IN
-- THE PACKAGE "STANDARD", ALONG WITH THE OPERATORS OF THE TYPE
-- BOOLEAN AND THE TYPE INTEGER.
-- HISTORY:
-- DTN 04/15/92 CONSOLIDATION OF C86006A AND C86006B.
WITH REPORT; USE REPORT;
PROCEDURE C86006I IS
ABOOL, BBOOL : STANDARD.BOOLEAN := STANDARD.FALSE;
CBOOL : STANDARD.BOOLEAN := STANDARD.TRUE;
INT1 : STANDARD.INTEGER := -2;
NAT1 : STANDARD.NATURAL := 0;
POS1, POS2 : STANDARD.POSITIVE := 2;
BEGIN
TEST("C86006I", "CHECK THAT THE IDENTIFIERS ""BOOLEAN, TRUE, AND " &
"FALSE"" AND THE IDENTIFIERS ""INTEGER, NATURAL, " &
"AND POSITIVE"" ARE DECLARED IN THE PACKAGE " &
"""STANDARD"", ALONG WITH THE OPERATORS OF THE " &
"TYPE BOOLEAN AND THE TYPE INTEGER");
-- STANDARD.">" OPERATOR.
IF STANDARD.">"(ABOOL,BBOOL) THEN
FAILED("STANDARD.> FAILED FOR BOOLEAN TYPE");
END IF;
IF STANDARD.">"(INT1,NAT1) THEN
FAILED("STANDARD.> FAILED FOR INTEGER-NATURAL TYPE");
END IF;
-- STANDARD."/=" OPERATOR.
IF STANDARD."/="(ABOOL,BBOOL) THEN
FAILED("STANDARD./= FAILED FOR BOOLEAN TYPE");
END IF;
IF STANDARD."/="(POS1,POS2) THEN
FAILED("STANDARD./= FAILED FOR INTEGER-POSITIVE TYPE");
END IF;
-- STANDARD."AND" OPERATOR.
IF STANDARD."AND"(CBOOL,ABOOL) THEN
FAILED("STANDARD.AND FAILED");
END IF;
-- STANDARD."-" BINARY OPERATOR.
IF STANDARD."-"(INT1,POS1) /= IDENT_INT(-4) THEN
FAILED("STANDARD.- FAILED");
END IF;
-- STANDARD."-" UNARY OPERATOR.
IF STANDARD."-"(INT1) /= IDENT_INT(2) THEN
FAILED("STANDARD.UNARY - FAILED");
END IF;
-- STANDARD."REM" OPERATOR.
IF STANDARD."REM"(IDENT_INT(14),IDENT_INT(5)) /= IDENT_INT(4) THEN
FAILED("STANDARD.REM (++=+) FAILED");
END IF;
-- STANDARD."MOD" OPERATOR.
IF STANDARD."MOD"(IDENT_INT(14),IDENT_INT(-5)) /= IDENT_INT(-1) THEN
FAILED("STANDARD.MOD (+-=-) FAILED");
END IF;
RESULT;
END C86006I;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
with Real_Type; use Real_Type;
package Quaternions is
type Quaternion_Real is record
w, x, y, z : Real;
end record;
function "abs" (Quad : Quaternion_Real) return Real;
function Unit (Quad : Quaternion_Real) return Quaternion_Real;
function Conj (Quad : Quaternion_Real) return Quaternion_Real;
function "-" (Quad : Quaternion_Real) return Quaternion_Real;
function "+" (Left, Right : Quaternion_Real) return Quaternion_Real;
function "-" (Left, Right : Quaternion_Real) return Quaternion_Real;
function "*" (Left, Right : Quaternion_Real) return Quaternion_Real;
function "/" (Left, Right : Quaternion_Real) return Quaternion_Real;
function "*" (Left : Quaternion_Real; Right : Real) return Quaternion_Real;
function "/" (Left : Quaternion_Real; Right : Real) return Quaternion_Real;
function "*" (Left : Real; Right : Quaternion_Real) return Quaternion_Real;
function "/" (Left : Real; Right : Quaternion_Real) return Quaternion_Real;
function Image (Quad : Quaternion_Real) return String;
end Quaternions;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Servlet.Requests;
with Servlet.Responses;
with Servlet.Core;
-- The <b>Servlet.Filters</b> package defines the servlet filter
-- interface described in Java Servlet Specification, JSR 315, 6. Filtering.
--
package Servlet.Filters is
-- ------------------------------
-- Filter interface
-- ------------------------------
-- The <b>Filter</b> interface defines one mandatory procedure through
-- which the request/response pair are passed.
--
-- The <b>Filter</b> instance must be registered in the <b>Servlet_Registry</b>
-- by using the <b>Add_Filter</b> procedure. The same filter instance is used
-- to process multiple requests possibly at the same time.
type Filter is limited interface;
type Filter_Access is access all Filter'Class;
type Filter_List is array (Natural range <>) of Filter_Access;
type Filter_List_Access is access all Filter_List;
-- The Do_Filter method of the Filter is called by the container each time
-- a request/response pair is passed through the chain due to a client request
-- for a resource at the end of the chain. The Filter_Chain passed in to this
-- method allows the Filter to pass on the request and response to the next
-- entity in the chain.
--
-- A typical implementation of this method would follow the following pattern:
-- 1. Examine the request
-- 2. Optionally wrap the request object with a custom implementation to
-- filter content or headers for input filtering
-- 3. Optionally wrap the response object with a custom implementation to
-- filter content or headers for output filtering
-- 4. Either invoke the next entity in the chain using the FilterChain
-- object (chain.Do_Filter()),
-- or, not pass on the request/response pair to the next entity in the
-- filter chain to block the request processing
-- 5. Directly set headers on the response after invocation of the next
-- entity in the filter chain.
procedure Do_Filter (F : in Filter;
Request : in out Requests.Request'Class;
Response : in out Responses.Response'Class;
Chain : in out Servlet.Core.Filter_Chain) is abstract;
-- Called by the servlet container to indicate to a filter that the filter
-- instance is being placed into service.
procedure Initialize (Server : in out Filter;
Config : in Servlet.Core.Filter_Config) is null;
end Servlet.Filters;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package Lumen.Events is
-- Translated keysym type and value
type Key_Category is (Key_Control, Key_Graphic, Key_Modifier, Key_Function,
Key_Special, Key_Unknown, Key_Not_Translated);
subtype Key_Symbol is Long_Integer;
-- Keystroke and pointer modifiers
type Modifier is (Mod_Shift, Mod_Lock, Mod_Control, Mod_1, Mod_2, Mod_3,
Mod_4, Mod_5, Mod_Button_1, Mod_Button_2, Mod_Button_3,
Mod_Button_4, Mod_Button_5);
type Modifier_Set is array (Modifier) of Boolean;
No_Modifiers : Modifier_Set := (others => False);
Not_Character : exception; -- key symbol is not a Latin-1 character
---------------------------------------------------------------------------
-- Key translation helpers
-- Convert a Key_Symbol into a Latin-1 character; raises Not_Character if
-- it's not possible. Character'Val is simpler.
function To_Character (Symbol : in Key_Symbol) return Character;
-- Convert a Key_Symbol into a UTF-8 encoded string; raises Not_Character
-- if it's not possible. Really only useful for Latin-1 hibit chars, but
-- works for all Latin-1 chars.
function To_UTF_8 (Symbol : in Key_Symbol) return String;
-- Convert a normal Latin-1 character to a Key_Symbol
function To_Symbol (Char : in Character) return Key_Symbol;
end Lumen.Events;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with agar.core.event;
with agar.core.types;
with agar.gui.widget.label;
with agar.gui.widget.slider;
with agar.gui.widget;
with agar.gui.window;
package slider_callbacks is
package gui_event renames agar.core.event;
package gui_label renames agar.gui.widget.label;
package gui_slider renames agar.gui.widget.slider;
package gui_widget renames agar.gui.widget;
package gui_window renames agar.gui.window;
type slider_t is record
slider : gui_slider.slider_access_t;
label : gui_label.label_access_t;
value : aliased agar.core.types.integer_t;
minimum : aliased agar.core.types.integer_t;
maximum : aliased agar.core.types.integer_t;
changed : gui_event.event_access_t;
end record;
sliders : array (1 .. 8) of slider_t;
procedure init (window : gui_window.window_access_t);
procedure quit (event : gui_event.event_access_t);
procedure changed (event : gui_event.event_access_t);
pragma convention (c, changed);
pragma convention (c, quit);
end slider_callbacks;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
package body SPI_Slave_Pico is
-----------------------------------------------------------------------
-- see .ads
procedure Initialize is
begin
SCK.Configure (RP.GPIO.Input, RP.GPIO.Floating, RP.GPIO.SPI);
NSS.Configure (RP.GPIO.Input, RP.GPIO.Floating, RP.GPIO.SPI);
MOSI.Configure (RP.GPIO.Input, RP.GPIO.Floating, RP.GPIO.SPI);
MISO.Configure (RP.GPIO.Output, RP.GPIO.Floating, RP.GPIO.SPI);
SPI.Configure (Config);
end Initialize;
end SPI_Slave_Pico;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with C.signal;
package body System.Interrupt_Management.Operations is
use type C.signed_int;
procedure Set_Interrupt_Mask (Mask : access Interrupt_Mask) is
begin
Set_Interrupt_Mask (Mask => Mask, OMask => null);
end Set_Interrupt_Mask;
procedure Set_Interrupt_Mask (
Mask : access Interrupt_Mask;
OMask : access Interrupt_Mask)
is
errno : C.signed_int;
begin
errno := C.signal.sigprocmask (C.signal.SIG_SETMASK, Mask, OMask);
if errno /= 0 then
raise Program_Error;
end if;
end Set_Interrupt_Mask;
procedure Get_Interrupt_Mask (Mask : access Interrupt_Mask) is
begin
Set_Interrupt_Mask (Mask => null, OMask => Mask);
end Get_Interrupt_Mask;
procedure Fill_Interrupt_Mask (Mask : access Interrupt_Mask) is
Dummy : C.signed_int;
begin
Dummy := C.signal.sigfillset (Mask);
end Fill_Interrupt_Mask;
procedure Add_To_Interrupt_Mask (
Mask : access Interrupt_Mask;
Interrupt : Interrupt_ID)
is
Dummy : C.signed_int;
begin
Dummy := C.signal.sigaddset (Mask, Interrupt);
end Add_To_Interrupt_Mask;
procedure Copy_Interrupt_Mask (
X : out Interrupt_Mask;
Y : Interrupt_Mask) is
begin
X := Y;
end Copy_Interrupt_Mask;
end System.Interrupt_Management.Operations;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--*
-- OBJECTIVE: See CA5004B2M.ADA
--
-- SPECIAL INSTRUCTIONS: See CA5004B2M.ADA
--
-- TEST FILES:
-- => CA5004B0.ADA
-- CA5004B1.ADA
-- CA5004B2M.ADA
-- PWN 05/31/96 Split test into files without duplicate unit names.
-- RLB 03/11/99 Split test into files so that units that will be replaced
-- and units that won't are not in the same source file.
-------------------------------------------------------------
PACKAGE HEADER IS
PROCEDURE WRONG (WHY : STRING);
END HEADER;
WITH REPORT; USE REPORT;
PRAGMA ELABORATE (REPORT);
PACKAGE BODY HEADER IS
PROCEDURE WRONG (WHY : STRING) IS
BEGIN
FAILED ("PACKAGE WITH " & WHY & " NOT ELABORATED " &
"CORRECTLY");
END WRONG;
BEGIN
TEST ("CA5004B", "PRAGMA ELABORATE IS ACCEPTED AND OBEYED " &
"EVEN WHEN THE BODY OF THE UNIT NAMED IS " &
"MISSING OR OBSOLETE");
END HEADER;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
Write_Eol;
end if;
-- If no mains have been specified on the command line,
-- and we are using a project file, we either find the main(s)
-- in the attribute Main of the main project, or we put all
-- the sources of the project file as mains.
if Main_Project /= No_Project and then Osint.Number_Of_Files = 0 then
Name_Len := 4;
Name_Buffer (1 .. 4) := "main";
declare
Main_Id : constant Name_Id := Name_Find;
Mains : constant Prj.Variable_Value :=
Prj.Util.Value_Of
(Variable_Name => Main_Id,
In_Variables =>
Projects.Table (Main_Project).Decl.Attributes);
Value : String_List_Id := Mains.Values;
begin
-- The attribute Main is an empty list or not specified,
-- or else gnatmake was invoked with the switch "-u".
if Value = Prj.Nil_String or else Unique_Compile then
-- First make sure that the binder and the linker
-- will not be invoked.
Do_Bind_Step := False;
Do_Link_Step := False;
-- Put all the sources in the queue
Insert_Project_Sources
(The_Project => Main_Project, Into_Q => False);
else
-- The attribute Main is not an empty list.
-- Put all the main subprograms in the list as if there were
-- specified on the command line.
while Value /= Prj.Nil_String loop
String_To_Name_Buffer (String_Elements.Table (Value).Value);
Osint.Add_File (Name_Buffer (1 .. Name_Len));
Value := String_Elements.Table (Value).Next;
end loop;
end if;
end;
end if;
-- Output usage information if no files. Note that this can happen
-- in the case of a project file that contains only subunits.
if Osint.Number_Of_Files = 0 then
Makeusg;
Exit_Program (E_Fatal);
end if;
-- If -l was specified behave as if -n was specified
if Opt.List_Dependencies then
Opt.Do_Not_Execute := True;
end if;
-- Note that Osint.Next_Main_Source will always return the (possibly
-- abbreviated file) without any directory information.
Main_Source_File := Next_Main_Source;
if Project_File_Name = null then
Add_Switch ("-I-", Compiler, And_Save => True);
Add_Switch ("-I-", Binder, And_Save => True);
if Opt.Look_In_Primary_Dir then
Add_Switch
("-I" &
Normalize_Directory_Name
(Get_Primary_Src_Search_Directory.all).all,
Compiler, Append_Switch => False,
And_Save => False);
Add_Switch ("-aO" & Normalized_CWD,
Binder,
Append_Switch => False,
And_Save => False);
end if;
end if;
-- If the user wants a program without a main subprogram, add the
-- appropriate switch to the binder.
if Opt.No_Main_Subprogram then
Add_Switch ("-z", Binder, And_Save => True);
end if;
if Main_Project /= No_Project then
Change_Dir
(Get_Name_String (Projects.Table (Main_Project).Object_Directory));
-- Find the file name of the main unit
declare
Main_Source_File_Name : constant String :=
Get_Name_String (Main_Source_File);
Main_Unit_File_Name : constant String :=
Prj.Env.File_Name_Of_Library_Unit_Body
(Name => Main_Source_File_Name,
Project => Main_Project);
The_Packages : constant Package_Id :=
Projects.Table (Main_Project).Decl.Packages;
Gnatmake : constant Prj.Package_Id :=
Prj.Util.Value_Of
(Name => Name_Builder,
In_Packages => The_Packages);
Binder_Package : constant Prj.Package_Id :=
Prj.Util.Value_Of
(Name => Name_Binder,
In_Packages => The_Packages);
Linker_Package : constant Prj.Package_Id :=
Prj.Util.Value_Of
(Name => Name_Linker,
In_Packages => The_Packages);
begin
-- We fail if we cannot find the main source file
-- as an immediate source of the main project file.
if Main_Unit_File_Name = "" then
Fail ('"' & Main_Source_File_Name &
""" is not a unit of project " &
Project_File_Name.all & ".");
else
-- Remove any directory information from the main
-- source file name.
declare
Pos : Natural := Main_Unit_File_Name'Last;
begin
loop
exit when Pos < Main_Unit_File_Name'First or else
Main_Unit_File_Name (Pos) = Directory_Separator;
Pos := Pos - 1;
end loop;
Name_Len := Main_Unit_File_Name'Last - Pos;
Name_Buffer (1 .. Name_Len) :=
Main_Unit_File_Name
(Pos + 1 .. Main_Unit_File_Name'Last);
Main_Source_File := Name_Find;
-- We only output the main source file if there is only one
if Opt.Verbose_Mode and then Osint.Number_Of_Files = 1 then
Write_Str ("Main source file: """);
Write_Str (Main_Unit_File_Name
(Pos + 1 .. Main_Unit_File_Name'Last));
Write_Line (""".");
end if;
end;
end if;
-- If there is a package gnatmake in the main project file, add
-- the switches from it. We also add the switches from packages
-- gnatbind and gnatlink, if any.
if Gnatmake /= No_Package then
-- If there is only one main, we attempt to get the gnatmake
-- switches for this main (if any). If there are no specific
-- switch for this particular main, get the general gnatmake
-- switches (if any).
if Osint.Number_Of_Files = 1 then
if Opt.Verbose_Mode then
Write_Str ("Adding gnatmake switches for """);
Write_Str (Main_Unit_File_Name);
Write_Line (""".");
end if;
Add_Switches
(File_Name => Main_Unit_File_Name,
The_Package => Gnatmake,
Program => None);
else
-- If there are several mains, we always get the general
-- gnatmake switches (if any).
-- Note: As there is never a source with name " ",
-- we are guaranteed to always get the gneneral switches.
Add_Switches
(File_Name => " ",
The_Package => Gnatmake,
Program => None);
end if;
end if;
if Binder_Package /= No_Package then
-- If there is only one main, we attempt to get the gnatbind
-- switches for this main (if any). If there are no specific
-- switch for this particular main, get the general gnatbind
-- switches (if any).
if Osint.Number_Of_Files = 1 then
if Opt.Verbose_Mode then
Write_Str ("Adding binder switches for """);
Write_Str (Main_Unit_File_Name);
Write_Line (""".");
end if;
Add_Switches
(File_Name => Main_Unit_File_Name,
The_Package => Binder_Package,
Program => Binder);
else
-- If there are several mains, we always get the general
-- gnatbind switches (if any).
-- Note: As there is never a source with name " ",
-- we are guaranteed to always get the gneneral switches.
Add_Switches
(File_Name => " ",
The_Package => Binder_Package,
Program => Binder);
end if;
end if;
if Linker_Package /= No_Package then
-- If there is only one main, we attempt to get the
-- gnatlink switches for this main (if any). If there are
-- no specific switch for this particular main, we get the
-- general gnatlink switches (if any).
if Osint.Number_Of_Files = 1 then
if Opt.Verbose_Mode then
Write_Str ("Adding linker switches for""");
Write_Str (Main_Unit_File_Name);
Write_Line (""".");
end if;
Add_Switches
(File_Name => Main_Unit_File_Name,
The_Package => Linker_Package,
Program => Linker);
else
-- If there are several mains, we always get the general
-- gnatlink switches (if any).
-- Note: As there is never a source with name " ",
-- we are guaranteed to always get the general switches.
Add_Switches
(File_Name => " ",
The_Package => Linker_Package,
Program => Linker);
end if;
end if;
end;
end if;
Display_Commands (not Opt.Quiet_Output);
-- We now put in the Binder_Switches and Linker_Switches tables,
-- the binder and linker switches of the command line that have been
-- put in the Saved_ tables. If a project file was used, then the
-- command line switches will follow the project file switches.
for J in 1 .. Saved_Binder_Switches.Last loop
Add_Switch
(Saved_Binder_Switches.Table (J),
Binder,
And_Save => False);
end loop;
for J in 1 .. Saved_Linker_Switches.Last loop
Add_Switch
(Saved_Linker_Switches.Table (J),
Linker,
And_Save => False);
end loop;
-- If no project file is used, we just put the gcc switches
-- from the command line in the Gcc_Switches table.
if Main_Project = No_Project then
for J in 1 .. Saved_Gcc_Switches.Last loop
Add_Switch
(Saved_Gcc_Switches.Table (J),
Compiler,
And_Save => False);
end loop;
else
-- And we put the command line gcc switches in the variable
-- The_Saved_Gcc_Switches. They are going to be used later
-- in procedure Compile_Sources.
The_Saved_Gcc_Switches :=
new Argument_List (1 .. Saved_Gcc_Switches.Last + 2);
for J in 1 .. Saved_Gcc_Switches.Last loop
The_Saved_Gcc_Switches (J) := Saved_Gcc_Switches.Table (J);
Test_If_Relative_Path (The_Saved_Gcc_Switches (J));
end loop;
-- We never use gnat.adc when a project file is used
The_Saved_Gcc_Switches (The_Saved_Gcc_Switches'Last - 1) :=
No_gnat_adc;
-- Create a temporary mapping file and add the switch -gnatem
-- with its name to the compiler.
Prj.Env.Create_Mapping_File (Name => Mapping_File_Name);
The_Saved_Gcc_Switches (The_Saved_Gcc_Switches'Last) :=
new String'("-gnatem" & Mapping_File_Name);
-- Check if there are any relative search paths in the switches.
-- Fail if there is one.
for J in 1 .. Gcc_Switches.Last loop
Test_If_Relative_Path (Gcc_Switches.Table (J));
end loop;
for J in 1 .. Binder_Switches.Last loop
Test_If_Relative_Path (Binder_Switches.Table (J));
end loop;
for J in 1 .. Linker_Switches.Last loop
Test_If_Relative_Path (Linker_Switches.Table (J));
end loop;
end if;
-- If there was a --GCC, --GNATBIND or --GNATLINK switch on
-- the command line, then we have to use it, even if there was
-- another switch in the project file.
if Saved_Gcc /= null then
Gcc := Saved_Gcc;
end if;
if Saved_Gnatbind /= null then
Gnatbind := Saved_Gnatbind;
end if;
if Saved_Gnatlink /= null then
Gnatlink := Saved_Gnatlink;
end if;
Gcc_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Gcc.all);
Gnatbind_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Gnatbind.all);
Gnatlink_Path := GNAT.OS_Lib.Locate_Exec_On_Path (Gnatlink.all);
-- If we have specified -j switch both from the project file
-- and on the command line, the one from the command line takes
-- precedence.
if Saved_Maximum_Processes = 0 then
Saved_Maximum_Processes := Opt.Maximum_Processes;
end if;
-- If either -c, -b or -l has been specified, we will not necessarily
-- execute all steps.
if Compile_Only or else Bind_Only or else Link_Only then
Do_Compile_Step := Do_Compile_Step and Compile_Only;
Do_Bind_Step := Do_Bind_Step and Bind_Only;
Do_Link_Step := Do_Link_Step and Link_Only;
-- If -c has been specified, but not -b, ignore any potential -l
if Do_Compile_Step and then not Do_Bind_Step then
Do_Link_Step := False;
end if;
end if;
-- Here is where the make process is started
-- We do the same process for each main
Multiple_Main_Loop : for N_File in 1 .. Osint.Number_Of_Files loop
if Do_Compile_Step then
Recursive_Compilation_Step : declare
Args : Argument_List (1 .. Gcc_Switches.Last);
First_Compiled_File : Name_Id;
Youngest_Obj_File : Name_Id;
Youngest_Obj_Stamp : Time_Stamp_Type;
Executable_Stamp : Time_Stamp_Type;
-- Executable is the final executable program.
begin
Executable := No_File;
Non_Std_Executable := False;
for J in 1 .. Gcc_Switches.Last loop
Args (J) := Gcc_Switches.Table (J);
end loop;
-- Look inside the linker switches to see if the name
-- of the final executable program was specified.
for
J in reverse Linker_Switches.First .. Linker_Switches.Last
loop
if Linker_Switches.Table (J).all = Output_Flag.all then
pragma Assert (J < Linker_Switches.Last);
-- We cannot specify a single executable for several
-- main subprograms!
if Osint.Number_Of_Files > 1 then
Fail
("cannot specify a single executable " &
"for several mains");
end if;
Name_Len := Linker_Switches.Table (J + 1)'Length;
Name_Buffer (1 .. Name_Len) :=
Linker_Switches.Table (J + 1).all;
-- If target has an executable suffix and it has not been
-- specified then it is added here.
if Executable_Suffix'Length /= 0
and then Linker_Switches.Table (J + 1)
(Name_Len - Executable_Suffix'Length + 1
.. Name_Len) /= Executable_Suffix
then
Name_Buffer (Name_Len + 1 ..
Name_Len + Executable_Suffix'Length) :=
Executable_Suffix;
Name_Len := Name_Len + Executable_Suffix'Length;
end if;
Executable := Name_Enter;
Verbose_Msg (Executable, "final executable");
end if;
end loop;
-- If the name of the final executable program was not
-- specified then construct it from the main input file.
if Executable = No_File then
if Main_Project = No_Project then
Executable :=
Executable_Name (Strip_Suffix (Main_Source_File));
else
-- If we are using a project file, we attempt to
-- remove the body (or spec) termination of the main
-- subprogram. We find it the the naming scheme of the
-- project file. This will avoid to generate an
-- executable "main.2" for a main subprogram
-- "main.2.ada", when the body termination is ".2.ada".
declare
Body_Append : constant String :=
Get_Name_String
(Projects.Table
(Main_Project).
Naming.Current_Impl_Suffix);
Spec_Append : constant String :=
Get_Name_String
(Projects.Table
(Main_Project).
Naming.Current_Spec_Suffix);
begin
Get_Name_String (Main_Source_File);
if Name_Len > Body_Append'Length
and then Name_Buffer
(Name_Len - Body_Append'Length + 1 .. Name_Len) =
Body_Append
then
-- We have found the body termination. We remove it
-- add the executable termination, if any.
Name_Len := Name_Len - Body_Append'Length;
Executable := Executable_Name (Name_Find);
elsif Name_Len > Spec_Append'Length
and then
Name_Buffer
(Name_Len - Spec_Append'Length + 1 .. Name_Len) =
Spec_Append
then
-- We have found the spec termination. We remove
-- it, add the executable termination, if any.
Name_Len := Name_Len - Spec_Append'Length;
Executable := Executable_Name (Name_Find);
else
Executable :=
Executable_Name (Strip_Suffix (Main_Source_File));
end if;
end;
end if;
end if;
if Main_Project /= No_Project then
declare
Exec_File_Name : constant String :=
Get_Name_String (Executable);
begin
if not Is_Absolute_Path (Exec_File_Name) then
for Index in Exec_File_Name'Range loop
if Exec_File_Name (Index) = Directory_Separator then
Fail ("relative executable (""" &
Exec_File_Name &
""") with directory part not allowed " &
"when using project files");
end if;
end loop;
Get_Name_String (Projects.Table
(Main_Project).Exec_Directory);
if
Name_Buffer (Name_Len) /= Directory_Separator
then
Name_Len := Name_Len + 1;
Name_Buffer (Name_Len) := Directory_Separator;
end if;
Name_Buffer (Name_Len + 1 ..
Name_Len + Exec_File_Name'Length) :=
Exec_File_Name;
Name_Len := Name_Len + Exec_File_Name'Length;
Executable := Name_Find;
Non_Std_Executable := True;
end if;
end;
end if;
-- Now we invoke Compile_Sources for the current main
Compile_Sources
(Main_Source => Main_Source_File,
Args => Args,
First_Compiled_File => First_Compiled_File,
Most_Recent_Obj_File => Youngest_Obj_File,
Most_Recent_Obj_Stamp => Youngest_Obj_Stamp,
Main_Unit => Is_Main_Unit,
Compilation_Failures => Compilation_Failures,
Check_Readonly_Files => Opt.Check_Readonly_Files,
Do_Not_Execute => Opt.Do_Not_Execute,
Force_Compilations => Opt.Force_Compilations,
In_Place_Mode => Opt.In_Place_Mode,
Keep_Going => Opt.Keep_Going,
Initialize_ALI_Data => True,
Max_Process => Saved_Maximum_Processes);
if Opt.Verbose_Mode then
Write_Str ("End of compilation");
Write_Eol;
end if;
if Compilation_Failures /= 0 then
List_Bad_Compilations;
raise Compilation_Failed;
end if;
-- Regenerate libraries, if any and if object files
-- have been regenerated
if Main_Project /= No_Project
and then MLib.Tgt.Libraries_Are_Supported
then
for Proj in Projects.First .. Projects.Last loop
if Proj /= Main_Project
and then Projects.Table (Proj).Flag1
then
MLib.Prj.Build_Library (For_Project => Proj);
end if;
end loop;
end if;
if Opt.List_Dependencies then
if First_Compiled_File /= No_File then
Inform
(First_Compiled_File,
"must be recompiled. Can't generate dependence list.");
else
List_Depend;
end if;
elsif First_Compiled_File = No_File
and then not Do_Bind_Step
and then not Opt.Quiet_Output
and then Osint.Number_Of_Files = 1
then
if Unique_Compile then
Inform (Msg => "object up to date.");
else
Inform (Msg => "objects up to date.");
end if;
elsif Opt.Do_Not_Execute
and then First_Compiled_File /= No_File
then
Write_Name (First_Compiled_File);
Write_Eol;
end if;
-- Stop after compile step if any of:
-- 1) -n (Do_Not_Execute) specified
-- 2) -l (List_Dependencies) specified (also sets
-- Do_Not_Execute above, so this is probably superfluous).
-- 3) -c (Compile_Only) specified, but not -b (Bind_Only)
-- 4) Made unit cannot be a main unit
if (Opt.Do_Not_Execute
or Opt.List_Dependencies
or not Do_Bind_Step
or not Is_Main_Unit)
and then not No_Main_Subprogram
then
if Osint.Number_Of_Files = 1 then
exit Multiple_Main_Loop;
else
goto Next_Main;
end if;
end if;
-- If the objects were up-to-date check if the executable file
-- is also up-to-date. For now always bind and link on the JVM
-- since there is currently no simple way to check the
-- up-to-date status of objects
if not Hostparm.Java_VM
and then First_Compiled_File = No_File
then
Executable_Stamp := File_Stamp (Executable);
-- Once Executable_Obsolete is set to True, it is never
-- reset to False, because it is too hard to accurately
-- decide if a subsequent main need to be rebuilt or not.
Executable_Obsolete :=
Executable_Obsolete
or else Youngest_Obj_Stamp > Executable_Stamp;
if not Executable_Obsolete then
-- If no Ada object files obsolete the executable, check
-- for younger or missing linker files.
Check_Linker_Options
(Executable_Stamp,
Youngest_Obj_File,
Youngest_Obj_Stamp);
Executable_Obsolete := Youngest_Obj_File /= No_File;
end if;
-- Return if the executable is up to date
-- and otherwise motivate the relink/rebind.
if not Executable_Obsolete then
if not Opt.Quiet_Output then
Inform (Executable, "up to date.");
end if;
if Osint.Number_Of_Files = 1 then
exit Multiple_Main_Loop;
else
goto Next_Main;
end if;
end if;
if Executable_Stamp (1) = ' ' then
Verbose_Msg (Executable, "missing.", Prefix => " ");
elsif Youngest_Obj_Stamp (1) = ' ' then
Verbose_Msg
(Youngest_Obj_File,
"missing.",
Prefix => " ");
elsif Youngest_Obj_Stamp > Executable_Stamp then
Verbose_Msg
(Youngest_Obj_File,
"(" & String (Youngest_Obj_Stamp) & ") newer than",
Executable,
"(" & String (Executable_Stamp) & ")");
else
Verbose_Msg
(Executable, "needs to be rebuild.",
Prefix => " ");
end if;
end if;
end Recursive_Compilation_Step;
end if;
-- If we are here, it means that we need to rebuilt the current
-- main. So we set Executable_Obsolete to True to make sure that
-- the subsequent mains will be rebuilt.
Executable_Obsolete := True;
Main_ALI_In_Place_Mode_Step :
declare
ALI_File : File_Name_Type;
Src_File : File_Name_Type;
begin
Src_File := Strip_Directory (Main_Source_File);
ALI_File := Lib_File_Name (Src_File);
Main_ALI_File := Full_Lib_File_Name (ALI_File);
-- When In_Place_Mode, the library file can be located in the
-- Main_Source_File directory which may not be present in the
-- library path. In this case, use the corresponding library file
-- name.
if Main_ALI_File = No_File and then Opt.In_Place_Mode then
Get_Name_String (Get_Directory (Full_Source_Name (Src_File)));
Get_Name_String_And_Append (ALI_File);
Main_ALI_File := Name_Find;
Main_ALI_File := Full_Lib_File_Name (Main_ALI_File);
end if;
if Main_ALI_File = No_File then
Fail ("could not find the main ALI file");
end if;
end Main_ALI_In_Place_Mode_Step;
if Do_Bind_Step then
Bind_Step : declare
Args : Argument_List
(Binder_Switches.First .. Binder_Switches.Last);
begin
-- Get all the binder switches
for J in Binder_Switches.First .. Binder_Switches.Last loop
Args (J) := Binder_Switches.Table (J);
end loop;
if Main_Project /= No_Project then
-- Put all the source directories in ADA_INCLUDE_PATH,
-- and all the object directories in ADA_OBJECTS_PATH
Set_Ada_Paths (Main_Project, False);
end if;
Bind (Main_ALI_File, Args);
end Bind_Step;
end if;
if Do_Link_Step then
Link_Step : declare
There_Are_Libraries : Boolean := False;
Linker_Switches_Last : constant Integer := Linker_Switches.Last;
begin
if Main_Project /= No_Project then
if MLib.Tgt.Libraries_Are_Supported then
Set_Libraries (Main_Project, There_Are_Libraries);
end if;
if There_Are_Libraries then
-- Add -L<lib_dir> -lgnarl -lgnat -Wl,-rpath,<lib_dir>
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
new String'("-L" & MLib.Utl.Lib_Directory);
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
new String'("-lgnarl");
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
new String'("-lgnat");
declare
Option : constant String_Access :=
MLib.Tgt.Linker_Library_Path_Option
(MLib.Utl.Lib_Directory);
begin
if Option /= null then
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
Option;
end if;
end;
end if;
-- Put the object directories in ADA_OBJECTS_PATH
Set_Ada_Paths (Main_Project, False);
end if;
declare
Args : Argument_List
(Linker_Switches.First .. Linker_Switches.Last + 2);
Last_Arg : Integer := Linker_Switches.First - 1;
Skip : Boolean := False;
begin
-- Get all the linker switches
for J in Linker_Switches.First .. Linker_Switches.Last loop
if Skip then
Skip := False;
elsif Non_Std_Executable
and then Linker_Switches.Table (J).all = "-o"
then
Skip := True;
else
Last_Arg := Last_Arg + 1;
Args (Last_Arg) := Linker_Switches.Table (J);
end if;
end loop;
-- And invoke the linker
if Non_Std_Executable then
Last_Arg := Last_Arg + 1;
Args (Last_Arg) := new String'("-o");
Last_Arg := Last_Arg + 1;
Args (Last_Arg) :=
new String'(Get_Name_String (Executable));
Link (Main_ALI_File, Args (Args'First .. Last_Arg));
else
Link
(Main_ALI_File,
Args (Args'First .. Last_Arg));
end if;
end;
Linker_Switches.Set_Last (Linker_Switches_Last);
end Link_Step;
end if;
-- We go to here when we skip the bind and link steps.
<<Next_Main>>
-- We go to the next main, if we did not process the last one
if N_File < Osint.Number_Of_Files then
Main_Source_File := Next_Main_Source;
if Main_Project /= No_Project then
-- Find the file name of the main unit
declare
Main_Source_File_Name : constant String :=
Get_Name_String (Main_Source_File);
Main_Unit_File_Name : constant String :=
Prj.Env.
File_Name_Of_Library_Unit_Body
(Name => Main_Source_File_Name,
Project => Main_Project);
begin
-- We fail if we cannot find the main source file
-- as an immediate source of the main project file.
if Main_Unit_File_Name = "" then
Fail ('"' & Main_Source_File_Name &
""" is not a unit of project " &
Project_File_Name.all & ".");
else
-- Remove any directory information from the main
-- source file name.
declare
Pos : Natural := Main_Unit_File_Name'Last;
begin
loop
exit when Pos < Main_Unit_File_Name'First
or else
Main_Unit_File_Name (Pos) = Directory_Separator;
Pos := Pos - 1;
end loop;
Name_Len := Main_Unit_File_Name'Last - Pos;
Name_Buffer (1 .. Name_Len) :=
Main_Unit_File_Name
(Pos + 1 .. Main_Unit_File_Name'Last);
Main_Source_File := Name_Find;
end;
end if;
end;
end if;
end if;
end loop Multiple_Main_Loop;
-- Delete the temporary mapping file that was created if we are
-- using project files.
if Main_Project /= No_Project then
declare
Success : Boolean;
begin
Delete_File (Name => Mapping_File_Name, Success => Success);
end;
end if;
Exit_Program (E_Success);
exception
when Bind_Failed =>
Osint.Fail ("*** bind failed.");
when Compilation_Failed =>
Exit_Program (E_Fatal);
when Link_Failed =>
Osint.Fail ("*** link failed.");
when X : others =>
Write_Line (Exception_Information (X));
Osint.Fail ("INTERNAL ERROR. Please report.");
end Gnatmake;
--------------------
-- In_Ada_Lib_Dir --
--------------------
function In_Ada_Lib_Dir (File : File_Name_Type) return Boolean is
D : constant Name_Id := Get_Directory (File);
B : constant Byte := Get_Name_Table_Byte (D);
begin
return (B and Ada_Lib_Dir) /= 0;
end In_Ada_Lib_Dir;
------------
-- Inform --
------------
procedure Inform (N : Name_Id := No_Name; Msg : String) is
begin
Osint.Write_Program_Name;
Write_Str (": ");
if N /= No_Name then
Write_Str ("""");
Write_Name (N);
Write_Str (""" ");
end if;
Write_Str (Msg);
Write_Eol;
end Inform;
------------
-- Init_Q --
------------
procedure Init_Q is
begin
First_Q_Initialization := False;
Q_Front := Q.First;
Q.Set_Last (Q.First);
end Init_Q;
----------------
-- Initialize --
----------------
procedure Initialize is
Next_Arg : Positive;
begin
-- Override default initialization of Check_Object_Consistency
-- since this is normally False for GNATBIND, but is True for
-- GNATMAKE since we do not need to check source consistency
-- again once GNATMAKE has looked at the sources to check.
Opt.Check_Object_Consistency := True;
-- Package initializations. The order of calls is important here.
Output.Set_Standard_Error;
Osint.Initialize (Osint.Make);
Gcc_Switches.Init;
Binder_Switches.Init;
Linker_Switches.Init;
Csets.Initialize;
Namet.Initialize;
Snames.Initialize;
Prj.Initialize;
Next_Arg := 1;
Scan_Args : while Next_Arg <= Argument_Count loop
Scan_Make_Arg (Argument (Next_Arg), And_Save => True);
Next_Arg := Next_Arg + 1;
end loop Scan_Args;
if Usage_Requested then
Makeusg;
end if;
-- Test for trailing -o switch
if Opt.Output_File_Name_Present
and then not Output_File_Name_Seen
then
Fail ("output file name missing after -o");
end if;
if Project_File_Name /= null then
-- A project file was specified by a -P switch
if Opt.Verbose_Mode then
Write_Eol;
Write_Str ("Parsing Project File """);
Write_Str (Project_File_Name.all);
Write_Str (""".");
Write_Eol;
end if;
-- Avoid looking in the current directory for ALI files
-- Opt.Look_In_Primary_Dir := False;
-- Set the project parsing verbosity to whatever was specified
-- by a possible -vP switch.
Prj.Pars.Set_Verbosity (To => Current_Verbosity);
-- Parse the project file.
-- If there is an error, Main_Project will still be No_Project.
Prj.Pars.Parse
(Project => Main_Project,
Project_File_Name => Project_File_Name.all);
if Main_Project = No_Project then
Fail ("""" & Project_File_Name.all &
""" processing failed");
end if;
if Opt.Verbose_Mode then
Write_Eol;
Write_Str ("Parsing of Project File """);
Write_Str (Project_File_Name.all);
Write_Str (""" is finished.");
Write_Eol;
end if;
-- We add the source directories and the object directories
-- to the search paths.
Add_Source_Directories (Main_Project);
Add_Object_Directories (Main_Project);
end if;
Osint.Add_Default_Search_Dirs;
-- Mark the GNAT libraries if needed.
-- Source file lookups should be cached for efficiency.
-- Source files are not supposed to change.
Osint.Source_File_Data (Cache => True);
-- Read gnat.adc file to initialize Fname.UF
Fname.UF.Initialize;
begin
Fname.SF.Read_Source_File_Name_Pragmas;
exception
when Err : SFN_Scan.Syntax_Error_In_GNAT_ADC =>
Osint.Fail (Exception_Message (Err));
end;
end Initialize;
-----------------------------------
-- Insert_Project_Sources_Into_Q --
-----------------------------------
procedure Insert_Project_Sources
(The_Project : Project_Id;
Into_Q : Boolean)
is
Unit : Com.Unit_Data;
Sfile : Name_Id;
begin
-- For all the sources in the project files,
for Id in Com.Units.First .. Com.Units.Last loop
Unit := Com.Units.Table (Id);
Sfile := No_Name;
-- If there is a source for the body,
if Unit.File_Names (Com.Body_Part).Name /= No_Name then
-- And it is a source of the specified project
if Unit.File_Names (Com.Body_Part).Project = The_Project then
-- If we don't have a spec, we cannot consider the source
-- if it is a subunit
if Unit.File_Names (Com.Specification).Name = No_Name then
declare
Src_Ind : Source_File_Index;
begin
Src_Ind := Sinput.L.Load_Source_File
(Unit.File_Names (Com.Body_Part).Name);
-- If it is a subunit, discard it
if Sinput.L.Source_File_Is_Subunit (Src_Ind) then
Sfile := No_Name;
else
Sfile := Unit.File_Names (Com.Body_Part).Name;
end if;
end;
else
Sfile := Unit.File_Names (Com.Body_Part).Name;
end if;
end if;
elsif Unit.File_Names (Com.Specification).Name /= No_Name
and then Unit.File_Names (Com.Specification).Project = The_Project
then
-- If there is no source for the body, but there is a source
-- for the spec, then we take this one.
Sfile := Unit.File_Names (Com.Specification).Name;
end if;
-- If Into_Q is True, we insert into the Q
if Into_Q then
-- For the first source inserted into the Q, we need
-- to initialize the Q, but not for the subsequent sources.
if First_Q_Initialization then
Init_Q;
end if;
-- And of course, we only insert in the Q if the source
-- is not marked.
if Sfile /= No_Name and then not Is_Marked (Sfile) then
Insert_Q (Sfile);
Mark (Sfile);
end if;
elsif Sfile /= No_Name then
-- If Into_Q is False, we add the source as it it were
-- specified on the command line.
Osint.Add_File (Get_Name_String (Sfile));
end if;
end loop;
end Insert_Project_Sources;
--------------
-- Insert_Q --
--------------
procedure Insert_Q
(Source_File : File_Name_Type;
Source_Unit : Unit_Name_Type := No_Name)
is
begin
if Debug.Debug_Flag_Q then
Write_Str (" Q := Q + [ ");
Write_Name (Source_File);
Write_Str (" ] ");
Write_Eol;
end if;
Q.Table (Q.Last).File := Source_File;
Q.Table (Q.Last).Unit := Source_Unit;
Q.Increment_Last;
end Insert_Q;
----------------------------
-- Is_External_Assignment --
----------------------------
function Is_External_Assignment (Argv : String) return Boolean is
Start : Positive := 3;
Finish : Natural := Argv'Last;
Equal_Pos : Natural;
begin
if Argv'Last < 5 then
return False;
elsif Argv (3) = '"' then
if Argv (Argv'Last) /= '"' or else Argv'Last < 7 then
return False;
else
Start := 4;
Finish := Argv'Last - 1;
end if;
end if;
Equal_Pos := Start;
while Equal_Pos <= Finish and then Argv (Equal_Pos) /= '=' loop
Equal_Pos := Equal_Pos + 1;
end loop;
if Equal_Pos = Start
or else Equal_Pos >= Finish
then
return False;
else
Prj.Ext.Add
(External_Name => Argv (Start .. Equal_Pos - 1),
Value => Argv (Equal_Pos + 1 .. Finish));
return True;
end if;
end Is_External_Assignment;
---------------
-- Is_Marked --
---------------
function Is_Marked (Source_File : File_Name_Type) return Boolean is
begin
return Get_Name_Table_Byte (Source_File) /= 0;
end Is_Marked;
----------
-- Link --
----------
procedure Link (ALI_File : File_Name_Type; Args : Argument_List) is
Link_Args : Argument_List (Args'First .. Args'Last + 1);
Success : Boolean;
begin
Link_Args (Args'Range) := Args;
Get_Name_String (ALI_File);
Link_Args (Args'Last + 1) := new String'(Name_Buffer (1 .. Name_Len));
Display (Gnatlink.all, Link_Args);
if Gnatlink_Path = null then
Osint.Fail ("error, unable to locate " & Gnatlink.all);
end if;
GNAT.OS_Lib.Spawn (Gnatlink_Path.all, Link_Args, Success);
if not Success then
raise Link_Failed;
end if;
end Link;
---------------------------
-- List_Bad_Compilations --
---------------------------
procedure List_Bad_Compilations is
begin
for J in Bad_Compilation.First .. Bad_Compilation.Last loop
if Bad_Compilation.Table (J).File = No_File then
null;
elsif not Bad_Compilation.Table (J).Found then
Inform (Bad_Compilation.Table (J).File, "not found");
else
Inform (Bad_Compilation.Table (J).File, "compilation error");
end if;
end loop;
end List_Bad_Compilations;
-----------------
-- List_Depend --
-----------------
procedure List_Depend is
Lib_Name : Name_Id;
Obj_Name : Name_Id;
Src_Name : Name_Id;
Len : Natural;
Line_Pos : Natural;
Line_Size : constant := 77;
begin
Set_Standard_Output;
for A in ALIs.First .. ALIs.Last loop
Lib_Name := ALIs.Table (A).Afile;
-- We have to provide the full library file name in In_Place_Mode
if Opt.In_Place_Mode then
Lib_Name := Full_Lib_File_Name (Lib_Name);
end if;
Obj_Name := Object_File_Name (Lib_Name);
Write_Name (Obj_Name);
Write_Str (" :");
Get_Name_String (Obj_Name);
Len := Name_Len;
Line_Pos := Len + 2;
for D in ALIs.Table (A).First_Sdep .. ALIs.Table (A).Last_Sdep loop
Src_Name := Sdep.Table (D).Sfile;
if Is_Internal_File_Name (Src_Name)
and then not Check_Readonly_Files
then
null;
else
if not Opt.Quiet_Output then
Src_Name := Full_Source_Name (Src_Name);
end if;
Get_Name_String (Src_Name);
Len := Name_Len;
if Line_Pos + Len + 1 > Line_Size then
Write_Str (" \");
Write_Eol;
Line_Pos := 0;
end if;
Line_Pos := Line_Pos + Len + 1;
Write_Str (" ");
Write_Name (Src_Name);
end if;
end loop;
Write_Eol;
end loop;
Set_Standard_Error;
end List_Depend;
----------
-- Mark --
----------
procedure Mark (Source_File : File_Name_Type) is
begin
Set_Name_Table_Byte (Source_File, 1);
end Mark;
-------------------
-- Mark_Dir_Path --
-------------------
procedure Mark_Dir_Path
(Path : String_Access;
Mark : Lib_Mark_Type)
is
Dir : String_Access;
begin
if Path /= null then
Osint.Get_Next_Dir_In_Path_Init (Path);
loop
Dir := Osint.Get_Next_Dir_In_Path (Path);
exit when Dir = null;
Mark_Directory (Dir.all, Mark);
end loop;
end if;
end Mark_Dir_Path;
--------------------
-- Mark_Directory --
--------------------
procedure Mark_Directory
(Dir : String;
Mark : Lib_Mark_Type)
is
N : Name_Id;
B : Byte;
begin
-- Dir last character is supposed to be a directory separator.
Name_Len := Dir'Length;
Name_Buffer (1 .. Name_Len) := Dir;
if not Is_Directory_Separator (Name_Buffer (Name_Len)) then
Name_Len := Name_Len + 1;
Name_Buffer (Name_Len) := Directory_Separator;
end if;
-- Add flags to the already existing flags
N := Name_Find;
B := Get_Name_Table_Byte (N);
Set_Name_Table_Byte (N, B or Mark);
end Mark_Directory;
----------------------
-- Object_File_Name --
----------------------
function Object_File_Name (Source : String) return String is
Pos : Natural := Source'Last;
begin
while Pos >= Source'First and then
Source (Pos) /= '.' loop
Pos := Pos - 1;
end loop;
if Pos >= Source'First then
Pos := Pos - 1;
end if;
return Source (Source'First .. Pos) & Object_Suffix;
end Object_File_Name;
-------------------
-- Scan_Make_Arg --
-------------------
procedure Scan_Make_Arg (Argv : String; And_Save : Boolean) is
begin
pragma Assert (Argv'First = 1);
if Argv'Length = 0 then
return;
end if;
-- If the previous switch has set the Output_File_Name_Present
-- flag (that is we have seen a -o), then the next argument is
-- the name of the output executable.
if Opt.Output_File_Name_Present and then not Output_File_Name_Seen then
Output_File_Name_Seen := True;
if Argv (1) = Switch_Character or else Argv (1) = '-' then
Fail ("output file name missing after -o");
else
Add_Switch ("-o", Linker, And_Save => And_Save);
-- Automatically add the executable suffix if it has not been
-- specified explicitly.
if Executable_Suffix'Length /= 0
and then Argv (Argv'Last - Executable_Suffix'Length + 1
.. Argv'Last) /= Executable_Suffix
then
Add_Switch
(Argv & Executable_Suffix,
Linker,
And_Save => And_Save);
else
Add_Switch (Argv, Linker, And_Save => And_Save);
end if;
end if;
-- Then check if we are dealing with a -cargs, -bargs or -largs
elsif (Argv (1) = Switch_Character or else Argv (1) = '-')
and then (Argv (2 .. Argv'Last) = "cargs"
or else Argv (2 .. Argv'Last) = "bargs"
or else Argv (2 .. Argv'Last) = "largs"
or else Argv (2 .. Argv'Last) = "margs")
then
case Argv (2) is
when 'c' => Program_Args := Compiler;
when 'b' => Program_Args := Binder;
when 'l' => Program_Args := Linker;
when 'm' => Program_Args := None;
when others =>
raise Program_Error;
end case;
-- A special test is needed for the -o switch within a -largs
-- since that is another way to specify the name of the final
-- executable.
elsif Program_Args = Linker
and then (Argv (1) = Switch_Character or else Argv (1) = '-')
and then Argv (2 .. Argv'Last) = "o"
then
Fail ("switch -o not allowed within a -largs. Use -o directly.");
-- Check to see if we are reading switches after a -cargs,
-- -bargs or -largs switch. If yes save it.
elsif Program_Args /= None then
-- Check to see if we are reading -I switches in order
-- to take into account in the src & lib search directories.
if Argv'Length > 2 and then Argv (1 .. 2) = "-I" then
if Argv (3 .. Argv'Last) = "-" then
Opt.Look_In_Primary_Dir := False;
elsif Program_Args = Compiler then
if Argv (3 .. Argv'Last) /= "-" then
Add_Src_Search_Dir (Argv (3 .. Argv'Last));
end if;
elsif Program_Args = Binder then
Add_Lib_Search_Dir (Argv (3 .. Argv'Last));
end if;
end if;
Add_Switch (Argv, Program_Args, And_Save => And_Save);
-- Handle non-default compiler, binder, linker
elsif Argv'Length > 2 and then Argv (1 .. 2) = "--" then
if Argv'Length > 6
and then Argv (1 .. 6) = "--GCC="
then
declare
Program_Args : Argument_List_Access :=
Argument_String_To_List
(Argv (7 .. Argv'Last));
begin
if And_Save then
Saved_Gcc := new String'(Program_Args.all (1).all);
else
Gcc := new String'(Program_Args.all (1).all);
end if;
for J in 2 .. Program_Args.all'Last loop
Add_Switch
(Program_Args.all (J).all,
Compiler,
And_Save => And_Save);
end loop;
end;
elsif Argv'Length > 11
and then Argv (1 .. 11) = "--GNATBIND="
then
declare
Program_Args : Argument_List_Access :=
Argument_String_To_List
(Argv (12 .. Argv'Last));
begin
if And_Save then
Saved_Gnatbind := new String'(Program_Args.all (1).all);
else
Gnatbind := new String'(Program_Args.all (1).all);
end if;
for J in 2 .. Program_Args.all'Last loop
Add_Switch
(Program_Args.all (J).all, Binder, And_Save => And_Save);
end loop;
end;
elsif Argv'Length > 11
and then Argv (1 .. 11) = "--GNATLINK="
then
declare
Program_Args : Argument_List_Access :=
Argument_String_To_List
(Argv (12 .. Argv'Last));
begin
if And_Save then
Saved_Gnatlink := new String'(Program_Args.all (1).all);
else
Gnatlink := new String'(Program_Args.all (1).all);
end if;
for J in 2 .. Program_Args.all'Last loop
Add_Switch (Program_Args.all (J).all, Linker);
end loop;
end;
else
Fail ("unknown switch: ", Argv);
end if;
-- If we have seen a regular switch process it
elsif Argv (1) = Switch_Character or else Argv (1) = '-' then
if Argv'Length = 1 then
Fail ("switch character cannot be followed by a blank");
-- -I-
elsif Argv (2 .. Argv'Last) = "I-" then
Opt.Look_In_Primary_Dir := False;
-- Forbid -?- or -??- where ? is any character
elsif (Argv'Length = 3 and then Argv (3) = '-')
or else (Argv'Length = 4 and then Argv (4) = '-')
then
Fail ("trailing ""-"" at the end of ", Argv, " forbidden.");
-- -Idir
elsif Argv (2) = 'I' then
Add_Src_Search_Dir (Argv (3 .. Argv'Last));
Add_Lib_Search_Dir (Argv (3 .. Argv'Last));
Add_Switch (Argv, Compiler, And_Save => And_Save);
Add_Switch ("-aO" & Argv (3 .. Argv'Last),
Binder,
And_Save => And_Save);
-- No need to pass any source dir to the binder
-- since gnatmake call it with the -x flag
-- (ie do not check source time stamp)
-- -aIdir (to gcc this is like a -I switch)
elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aI" then
Add_Src_Search_Dir (Argv (4 .. Argv'Last));
Add_Switch ("-I" & Argv (4 .. Argv'Last),
Compiler,
And_Save => And_Save);
-- -aOdir
elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aO" then
Add_Lib_Search_Dir (Argv (4 .. Argv'Last));
Add_Switch (Argv, Binder, And_Save => And_Save);
-- -aLdir (to gnatbind this is like a -aO switch)
elsif Argv'Length >= 3 and then Argv (2 .. 3) = "aL" then
Mark_Directory (Argv (4 .. Argv'Last), Ada_Lib_Dir);
Add_Lib_Search_Dir (Argv (4 .. Argv'Last));
Add_Switch ("-aO" & Argv (4 .. Argv'Last),
Binder,
And_Save => And_Save);
-- -Adir (to gnatbind this is like a -aO switch, to gcc like a -I)
elsif Argv (2) = 'A' then
Mark_Directory (Argv (3 .. Argv'Last), Ada_Lib_Dir);
Add_Src_Search_Dir (Argv (3 .. Argv'Last));
Add_Lib_Search_Dir (Argv (3 .. Argv'Last));
Add_Switch ("-I" & Argv (3 .. Argv'Last),
Compiler,
And_Save => And_Save);
Add_Switch ("-aO" & Argv (3 .. Argv'Last),
Binder,
And_Save => And_Save);
-- -Ldir
elsif Argv (2) = 'L' then
Add_Switch (Argv, Linker, And_Save => And_Save);
-- For -gxxxxx,-pg : give the switch to both the compiler and the
-- linker (except for -gnatxxx which is only for the compiler)
elsif
(Argv (2) = 'g' and then (Argv'Last < 5
or else Argv (2 .. 5) /= "gnat"))
or else Argv (2 .. Argv'Last) = "pg"
then
Add_Switch (Argv, Compiler, And_Save => And_Save);
Add_Switch (Argv, Linker, And_Save => And_Save);
-- -d
elsif Argv (2) = 'd'
and then Argv'Last = 2
then
Opt.Display_Compilation_Progress := True;
-- -j (need to save the result)
elsif Argv (2) = 'j' then
Scan_Make_Switches (Argv);
if And_Save then
Saved_Maximum_Processes := Maximum_Processes;
end if;
-- -m
elsif Argv (2) = 'm'
and then Argv'Last = 2
then
Opt.Minimal_Recompilation := True;
-- -u
elsif Argv (2) = 'u'
and then Argv'Last = 2
then
Unique_Compile := True;
Opt.Compile_Only := True;
Do_Bind_Step := False;
Do_Link_Step := False;
-- -Pprj (only once, and only on the command line)
elsif Argv'Last > 2
and then Argv (2) = 'P'
then
if Project_File_Name /= null then
Fail ("cannot have several project files specified");
elsif not And_Save then
-- It could be a tool other than gnatmake (i.e, gnatdist)
-- or a -P switch inside a project file.
Fail
("either the tool is not ""project-aware"" or " &
"a project file is specified inside a project file");
else
Project_File_Name := new String' (Argv (3 .. Argv'Last));
end if;
-- -S (Assemble)
-- Since no object file is created, don't check object
-- consistency.
elsif Argv (2) = 'S'
and then Argv'Last = 2
then
Opt.Check_Object_Consistency := False;
Add_Switch (Argv, Compiler, And_Save => And_Save);
-- -vPx (verbosity of the parsing of the project files)
elsif Argv'Last = 4
and then Argv (2 .. 3) = "vP"
and then Argv (4) in '0' .. '2'
then
if And_Save then
case Argv (4) is
when '0' =>
Current_Verbosity := Prj.Default;
when '1' =>
Current_Verbosity := Prj.Medium;
when '2' =>
Current_Verbosity := Prj.High;
when others =>
null;
end case;
end if;
-- -Wx (need to save the result)
elsif Argv (2) = 'W' then
Scan_Make_Switches (Argv);
if And_Save then
Saved_WC_Encoding_Method := Wide_Character_Encoding_Method;
Saved_WC_Encoding_Method_Set := True;
end if;
-- -Xext=val (External assignment)
elsif Argv (2) = 'X'
and then Is_External_Assignment (Argv)
then
-- Is_External_Assignment has side effects
-- when it returns True;
null;
-- If -gnath is present, then generate the usage information
-- right now for the compiler, and do not pass this option
-- on to the compiler calls.
elsif Argv = "-gnath" then
null;
-- If -gnatc is specified, make sure the bind step and the link
-- step are not executed.
elsif Argv'Length >= 6 and then Argv (2 .. 6) = "gnatc" then
-- If -gnatc is specified, make sure the bind step and the link
-- step are not executed.
Add_Switch (Argv, Compiler, And_Save => And_Save);
Opt.Operating_Mode := Opt.Check_Semantics;
Opt.Check_Object_Consistency := False;
Opt.Compile_Only := True;
Do_Bind_Step := False;
Do_Link_Step := False;
elsif Argv (2 .. Argv'Last) = "nostdlib" then
-- Don't pass -nostdlib to gnatlink, it will disable
-- linking with all standard library files.
Opt.No_Stdlib := True;
Add_Switch (Argv, Binder, And_Save => And_Save);
elsif Argv (2 .. Argv'Last) = "nostdinc" then
-- Pass -nostdinv to the Compiler and to gnatbind
Opt.No_Stdinc := True;
Add_Switch (Argv, Compiler, And_Save => And_Save);
Add_Switch (Argv, Binder, And_Save => And_Save);
-- By default all switches with more than one character
-- or one character switches which are not in 'a' .. 'z'
-- (except 'M') are passed to the compiler, unless we are dealing
-- with a debug switch (starts with 'd')
elsif Argv (2) /= 'd'
and then Argv (2 .. Argv'Last) /= "M"
and then (Argv'Length > 2 or else Argv (2) not in 'a' .. 'z')
then
Add_Switch (Argv, Compiler, And_Save => And_Save);
-- All other options are handled by Scan_Make_Switches
else
Scan_Make_Switches (Argv);
end if;
-- If not a switch it must be a file name
else
Set_Main_File_Name (Argv);
end if;
end Scan_Make_Arg;
-------------------
-- Set_Ada_Paths --
-------------------
procedure Set_Ada_Paths
(For_Project : Prj.Project_Id;
Including_Libraries : Boolean)
is
New_Ada_Include_Path : constant String_Access :=
Prj.Env.Ada_Include_Path (For_Project);
New_Ada_Objects_Path : constant String_Access :=
Prj.Env.Ada_Objects_Path
(For_Project, Including_Libraries);
begin
-- If ADA_INCLUDE_PATH needs to be changed (we are not using the same
-- project file), set the new ADA_INCLUDE_PATH
if New_Ada_Include_Path /= Current_Ada_Include_Path then
Current_Ada_Include_Path := New_Ada_Include_Path;
if Original_Ada_Include_Path'Length = 0 then
Setenv ("ADA_INCLUDE_PATH",
New_Ada_Include_Path.all);
else
-- If there existed an ADA_INCLUDE_PATH at the invocation of
-- gnatmake, concatenate new ADA_INCLUDE_PATH with the original.
Setenv ("ADA_INCLUDE_PATH",
Original_Ada_Include_Path.all &
Path_Separator &
New_Ada_Include_Path.all);
end if;
if Opt.Verbose_Mode then
declare
Include_Path : constant String_Access :=
Getenv ("ADA_INCLUDE_PATH");
begin
-- Display the new ADA_INCLUDE_PATH
Write_Str ("ADA_INCLUDE_PATH = """);
Prj.Util.Write_Str
(S => Include_Path.all,
Max_Length => Max_Line_Length,
Separator => Path_Separator);
Write_Str ("""");
Write_Eol;
end;
end if;
end if;
-- If ADA_OBJECTS_PATH needs to be changed (we are not using the same
-- project file), set the new ADA_OBJECTS_PATH
if New_Ada_Objects_Path /= Current_Ada_Objects_Path then
Current_Ada_Objects_Path := New_Ada_Objects_Path;
if Original_Ada_Objects_Path'Length = 0 then
Setenv ("ADA_OBJECTS_PATH",
New_Ada_Objects_Path.all);
else
-- If there existed an ADA_OBJECTS_PATH at the invocation of
-- gnatmake, concatenate new ADA_OBJECTS_PATH with the original.
Setenv ("ADA_OBJECTS_PATH",
Original_Ada_Objects_Path.all &
Path_Separator &
New_Ada_Objects_Path.all);
end if;
if Opt.Verbose_Mode then
declare
Objects_Path : constant String_Access :=
Getenv ("ADA_OBJECTS_PATH");
begin
-- Display the new ADA_OBJECTS_PATH
Write_Str ("ADA_OBJECTS_PATH = """);
Prj.Util.Write_Str
(S => Objects_Path.all,
Max_Length => Max_Line_Length,
Separator => Path_Separator);
Write_Str ("""");
Write_Eol;
end;
end if;
end if;
end Set_Ada_Paths;
---------------------
-- Set_Library_For --
---------------------
procedure Set_Library_For
(Project : Project_Id;
There_Are_Libraries : in out Boolean)
is
begin
-- Case of library project
if Projects.Table (Project).Library then
There_Are_Libraries := True;
-- Add the -L switch
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
new String'("-L" &
Get_Name_String
(Projects.Table (Project).Library_Dir));
-- Add the -l switch
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
new String'("-l" &
Get_Name_String
(Projects.Table (Project).Library_Name));
-- Add the Wl,-rpath switch if library non static
if Projects.Table (Project).Library_Kind /= Static then
declare
Option : constant String_Access :=
MLib.Tgt.Linker_Library_Path_Option
(Get_Name_String
(Projects.Table (Project).Library_Dir));
begin
if Option /= null then
Linker_Switches.Increment_Last;
Linker_Switches.Table (Linker_Switches.Last) :=
Option;
end if;
end;
end if;
end if;
end Set_Library_For;
-----------------
-- Switches_Of --
-----------------
function Switches_Of
(Source_File : Name_Id;
Source_File_Name : String;
Naming : Naming_Data;
In_Package : Package_Id;
Allow_ALI : Boolean)
return Variable_Value
is
Switches : Variable_Value;
Defaults : constant Array_Element_Id :=
Prj.Util.Value_Of
(Name => Name_Default_Switches,
In_Arrays =>
Packages.Table (In_Package).Decl.Arrays);
Switches_Array : constant Array_Element_Id :=
Prj.Util.Value_Of
(Name => Name_Switches,
In_Arrays =>
Packages.Table (In_Package).Decl.Arrays);
begin
Switches :=
Prj.Util.Value_Of
(Index => Source_File,
In_Array => Switches_Array);
if Switches = Nil_Variable_Value then
declare
Name : String (1 .. Source_File_Name'Length + 3);
Last : Positive := Source_File_Name'Length;
Spec_Suffix : constant String :=
Get_Name_String (Naming.Current_Spec_Suffix);
Impl_Suffix : constant String :=
Get_Name_String (Naming.Current_Impl_Suffix);
Truncated : Boolean := False;
begin
Name (1 .. Last) := Source_File_Name;
if Last > Impl_Suffix'Length
and then Name (Last - Impl_Suffix'Length + 1 .. Last) =
Impl_Suffix
then
Truncated := True;
Last := Last - Impl_Suffix'Length;
end if;
if not Truncated
and then Last > Spec_Suffix'Length
and then Name (Last - Spec_Suffix'Length + 1 .. Last) =
Spec_Suffix
then
Truncated := True;
Last := Last - Spec_Suffix'Length;
end if;
if Truncated then
Name_Len := Last;
Name_Buffer (1 .. Name_Len) := Name (1 .. Last);
Switches :=
Prj.Util.Value_Of
(Index => Name_Find,
In_Array => Switches_Array);
if Switches = Nil_Variable_Value then
Last := Source_File_Name'Length;
while Name (Last) /= '.' loop
Last := Last - 1;
end loop;
Name (Last + 1 .. Last + 3) := "ali";
Name_Len := Last + 3;
Name_Buffer (1 .. Name_Len) := Name (1 .. Name_Len);
Switches :=
Prj.Util.Value_Of
(Index => Name_Find,
In_Array => Switches_Array);
end if;
end if;
end;
end if;
if Switches = Nil_Variable_Value then
Switches := Prj.Util.Value_Of
(Index => Name_Ada, In_Array => Defaults);
end if;
return Switches;
end Switches_Of;
---------------------------
-- Test_If_Relative_Path --
---------------------------
procedure Test_If_Relative_Path (Switch : String_Access) is
begin
if Switch /= null then
declare
Sw : String (1 .. Switch'Length);
Start : Positive;
begin
Sw := Switch.all;
if Sw (1) = '-' then
if Sw'Length >= 3
and then (Sw (2) = 'A'
or else Sw (2) = 'I'
or else Sw (2) = 'L')
then
Start := 3;
if Sw = "-I-" then
return;
end if;
elsif Sw'Length >= 4
and then (Sw (2 .. 3) = "aL"
or else Sw (2 .. 3) = "aO"
or else Sw (2 .. 3) = "aI")
then
Start := 4;
else
return;
end if;
if not Is_Absolute_Path (Sw (Start .. Sw'Last)) then
Fail ("relative search path switches (""" &
Sw & """) are not allowed when using project files");
end if;
end if;
end;
end if;
end Test_If_Relative_Path;
------------
-- Unmark --
------------
procedure Unmark (Source_File : File_Name_Type) is
begin
Set_Name_Table_Byte (Source_File, 0);
end Unmark;
-----------------
-- Verbose_Msg --
-----------------
procedure Verbose_Msg
(N1 : Name_Id;
S1 : String;
N2 : Name_Id := No_Name;
S2 : String := "";
Prefix : String := " -> ")
is
begin
if not Opt.Verbose_Mode then
return;
end if;
Write_Str (Prefix);
Write_Str ("""");
Write_Name (N1);
Write_Str (""" ");
Write_Str (S1);
if N2 /= No_Name then
Write_Str (" """);
Write_Name (N2);
Write_Str (""" ");
end if;
Write_Str (S2);
Write_Eol;
end Verbose_Msg;
end Make;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Simulation;
with Ada.Text_IO; use Ada.Text_IO;
with Units; use Units;
package body ublox8.driver with
SPARK_Mode => Off,
Refined_State => (State => (null)) is
cur_loc : GPS_Loacation_Type; -- L,L,A
cur_msg : GPS_Message_Type;
cur_fix : GPS_FIX_Type;
cur_vel : Units.Linear_Velocity_Type := 0.0*Meter/Second;
cur_datetime : GPS_DateTime_Type;
cur_vacc : Units.Length_Type := 0.0*Meter;
procedure reset is null;
procedure init is null;
function get_Nsat return Unsigned_8 is ( 0 );
procedure update_val is
begin
--cur_loc.Longitude := Longitude_Type ( Simulation.CSV_here.Get_Column ("Lng"));
--cur_loc.Latitude := Latitude_Type ( Simulation.CSV_here.Get_Column ("Lat"));
--cur_loc.Altitude := Altitude_Type ( Simulation.CSV_here.Get_Column ("Alt"));
cur_fix := NO_FIX;-- GPS_Fix_Type'Enum_Val (Integer ( Simulation.CSV_here.Get_Column ("fix")));
cur_msg.sats := Unsigned_8 ( 0 );
cur_msg.speed := Linear_Velocity_Type ( 0.0 );
-- don't care about the following for now:
cur_msg.datetime.year := 2016;
cur_msg.datetime.mon := 07;
cur_msg.datetime.day := 20;
cur_msg.lat := cur_loc.Latitude;
cur_msg.lon := cur_loc.Longitude;
cur_msg.alt := cur_loc.Altitude;
cur_msg.datetime.min := 0;
cur_msg.datetime.sec := 0;
cur_msg.datetime.hour := 0;
end update_val;
function get_Position return GPS_Loacation_Type is
begin
return cur_loc;
end;
function get_GPS_Message return GPS_Message_Type is
begin
return cur_msg;
end;
function get_Vertical_Accuracy return Units.Length_Type is
begin
return cur_vacc;
end get_Vertical_Accuracy;
function get_Fix return GPS_Fix_Type is
begin
return cur_fix;
end;
function get_Velo return Units.Linear_Velocity_Type is
begin
return cur_vel;
end get_Velo;
function get_Time return GPS_DateTime_Type is begin
return cur_datetime;
end get_Time;
-- function get_Direction return Direction_Type;
procedure perform_Self_Check (Status : out Error_Type) is
begin
Status := SUCCESS;
end perform_Self_Check;
end ublox8.driver;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Vect3_Pkg;
package Vect3 is
-- Unconstrained array types are vectorizable, possibly with special
-- help for the programmer
type Varray is array (Vect3_Pkg.Index_Type range <>) of Long_Float;
for Varray'Alignment use 16;
function "+" (X, Y : Varray) return Varray;
procedure Add (X, Y : Varray; R : out Varray);
procedure Add (X, Y : not null access Varray; R : not null access Varray);
-- Constrained array types are vectorizable
type Sarray is array (Vect3_Pkg.Index_Type(1) .. Vect3_Pkg.Index_Type(4))
of Long_Float;
for Sarray'Alignment use 16;
function "+" (X, Y : Sarray) return Sarray;
procedure Add (X, Y : Sarray; R : out Sarray);
procedure Add (X, Y : not null access Sarray; R : not null access Sarray);
type Darray1 is array (Vect3_Pkg.Index_Type(1) .. Vect3_Pkg.N) of Long_Float;
for Darray1'Alignment use 16;
function "+" (X, Y : Darray1) return Darray1;
procedure Add (X, Y : Darray1; R : out Darray1);
procedure Add (X, Y : not null access Darray1; R : not null access Darray1);
type Darray2 is array (Vect3_Pkg.K .. Vect3_Pkg.Index_Type(4)) of Long_Float;
for Darray2'Alignment use 16;
function "+" (X, Y : Darray2) return Darray2;
procedure Add (X, Y : Darray2; R : out Darray2);
procedure Add (X, Y : not null access Darray2; R : not null access Darray2);
type Darray3 is array (Vect3_Pkg.K .. Vect3_Pkg.N) of Long_Float;
for Darray3'Alignment use 16;
function "+" (X, Y : Darray3) return Darray3;
procedure Add (X, Y : Darray3; R : out Darray3);
procedure Add (X, Y : not null access Darray3; R : not null access Darray3);
end Vect3;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
with Ada.Unchecked_Deallocation;
with Ada.Containers.Hash_Tables.Generic_Operations;
pragma Elaborate_All (Ada.Containers.Hash_Tables.Generic_Operations);
with Ada.Containers.Hash_Tables.Generic_Keys;
pragma Elaborate_All (Ada.Containers.Hash_Tables.Generic_Keys);
package body Ada.Containers.Hashed_Maps is
-----------------------
-- Local Subprograms --
-----------------------
function Copy_Node
(Source : Node_Access) return Node_Access;
pragma Inline (Copy_Node);
function Equivalent_Keys
(Key : Key_Type;
Node : Node_Access) return Boolean;
pragma Inline (Equivalent_Keys);
function Find_Equal_Key
(R_HT : Hash_Table_Type;
L_Node : Node_Access) return Boolean;
function Hash_Node (Node : Node_Access) return Hash_Type;
pragma Inline (Hash_Node);
function Next (Node : Node_Access) return Node_Access;
pragma Inline (Next);
function Read_Node
(Stream : access Root_Stream_Type'Class) return Node_Access;
pragma Inline (Read_Node);
procedure Set_Next (Node : Node_Access; Next : Node_Access);
pragma Inline (Set_Next);
procedure Write_Node
(Stream : access Root_Stream_Type'Class;
Node : Node_Access);
pragma Inline (Write_Node);
--------------------------
-- Local Instantiations --
--------------------------
procedure Free is
new Ada.Unchecked_Deallocation (Node_Type, Node_Access);
package HT_Ops is
new Hash_Tables.Generic_Operations
(HT_Types => HT_Types,
Hash_Node => Hash_Node,
Next => Next,
Set_Next => Set_Next,
Copy_Node => Copy_Node,
Free => Free);
package Key_Ops is
new Hash_Tables.Generic_Keys
(HT_Types => HT_Types,
Next => Next,
Set_Next => Set_Next,
Key_Type => Key_Type,
Hash => Hash,
Equivalent_Keys => Equivalent_Keys);
function Is_Equal is new HT_Ops.Generic_Equal (Find_Equal_Key);
procedure Read_Nodes is new HT_Ops.Generic_Read (Read_Node);
procedure Write_Nodes is new HT_Ops.Generic_Write (Write_Node);
---------
-- "=" --
---------
function "=" (Left, Right : Map) return Boolean is
begin
return Is_Equal (Left.HT, Right.HT);
end "=";
------------
-- Adjust --
------------
procedure Adjust (Container : in out Map) is
begin
HT_Ops.Adjust (Container.HT);
end Adjust;
--------------
-- Capacity --
--------------
function Capacity (Container : Map) return Count_Type is
begin
return HT_Ops.Capacity (Container.HT);
end Capacity;
-----------
-- Clear --
-----------
procedure Clear (Container : in out Map) is
begin
HT_Ops.Clear (Container.HT);
end Clear;
--------------
-- Contains --
--------------
function Contains (Container : Map; Key : Key_Type) return Boolean is
begin
return Find (Container, Key) /= No_Element;
end Contains;
---------------
-- Copy_Node --
---------------
function Copy_Node
(Source : Node_Access) return Node_Access
is
Target : constant Node_Access :=
new Node_Type'(Key => Source.Key,
Element => Source.Element,
Next => null);
begin
return Target;
end Copy_Node;
------------
-- Delete --
------------
procedure Delete (Container : in out Map; Key : Key_Type) is
X : Node_Access;
begin
Key_Ops.Delete_Key_Sans_Free (Container.HT, Key, X);
if X = null then
raise Constraint_Error;
end if;
Free (X);
end Delete;
procedure Delete (Container : in out Map; Position : in out Cursor) is
begin
if Position = No_Element then
return;
end if;
if Position.Container /= Map_Access'(Container'Unchecked_Access) then
raise Program_Error;
end if;
HT_Ops.Delete_Node_Sans_Free (Container.HT, Position.Node);
Free (Position.Node);
Position.Container := null;
end Delete;
-------------
-- Element --
-------------
function Element (Container : Map; Key : Key_Type) return Element_Type is
C : constant Cursor := Find (Container, Key);
begin
return C.Node.Element;
end Element;
function Element (Position : Cursor) return Element_Type is
begin
return Position.Node.Element;
end Element;
---------------------
-- Equivalent_Keys --
---------------------
function Equivalent_Keys
(Key : Key_Type;
Node : Node_Access) return Boolean is
begin
return Equivalent_Keys (Key, Node.Key);
end Equivalent_Keys;
---------------------
-- Equivalent_Keys --
---------------------
function Equivalent_Keys (Left, Right : Cursor)
return Boolean is
begin
return Equivalent_Keys (Left.Node.Key, Right.Node.Key);
end Equivalent_Keys;
function Equivalent_Keys (Left : Cursor; Right : Key_Type) return Boolean is
begin
return Equivalent_Keys (Left.Node.Key, Right);
end Equivalent_Keys;
function Equivalent_Keys (Left : Key_Type; Right : Cursor) return Boolean is
begin
return Equivalent_Keys (Left, Right.Node.Key);
end Equivalent_Keys;
-------------
-- Exclude --
-------------
procedure Exclude (Container : in out Map; Key : Key_Type) is
X : Node_Access;
begin
Key_Ops.Delete_Key_Sans_Free (Container.HT, Key, X);
Free (X);
end Exclude;
--------------
-- Finalize --
--------------
procedure Finalize (Container : in out Map) is
begin
HT_Ops.Finalize (Container.HT);
end Finalize;
----------
-- Find --
----------
function Find (Container : Map; Key : Key_Type) return Cursor is
Node : constant Node_Access := Key_Ops.Find (Container.HT, Key);
begin
if Node = null then
return No_Element;
end if;
return Cursor'(Container'Unchecked_Access, Node);
end Find;
--------------------
-- Find_Equal_Key --
--------------------
function Find_Equal_Key
(R_HT : Hash_Table_Type;
L_Node : Node_Access) return Boolean
is
R_Index : constant Hash_Type := Key_Ops.Index (R_HT, L_Node.Key);
R_Node : Node_Access := R_HT.Buckets (R_Index);
begin
while R_Node /= null loop
if Equivalent_Keys (L_Node.Key, R_Node.Key) then
return L_Node.Element = R_Node.Element;
end if;
R_Node := R_Node.Next;
end loop;
return False;
end Find_Equal_Key;
-----------
-- First --
-----------
function First (Container : Map) return Cursor is
Node : constant Node_Access := HT_Ops.First (Container.HT);
begin
if Node = null then
return No_Element;
end if;
return Cursor'(Container'Unchecked_Access, Node);
end First;
-----------------
-- Has_Element --
-----------------
function Has_Element (Position : Cursor) return Boolean is
begin
return Position /= No_Element;
end Has_Element;
---------------
-- Hash_Node --
---------------
function Hash_Node (Node : Node_Access) return Hash_Type is
begin
return Hash (Node.Key);
end Hash_Node;
-------------
-- Include --
-------------
procedure Include
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type)
is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, Key, New_Item, Position, Inserted);
if not Inserted then
Position.Node.Key := Key;
Position.Node.Element := New_Item;
end if;
end Include;
------------
-- Insert --
------------
procedure Insert
(Container : in out Map;
Key : Key_Type;
Position : out Cursor;
Inserted : out Boolean)
is
function New_Node (Next : Node_Access) return Node_Access;
pragma Inline (New_Node);
procedure Local_Insert is
new Key_Ops.Generic_Conditional_Insert (New_Node);
--------------
-- New_Node --
--------------
function New_Node (Next : Node_Access) return Node_Access is
Node : Node_Access := new Node_Type; -- Ada 2005 aggregate possible?
begin
Node.Key := Key;
Node.Next := Next;
return Node;
exception
when others =>
Free (Node);
raise;
end New_Node;
HT : Hash_Table_Type renames Container.HT;
-- Start of processing for Insert
begin
if HT.Length >= HT_Ops.Capacity (HT) then
HT_Ops.Reserve_Capacity (HT, HT.Length + 1);
end if;
Local_Insert (HT, Key, Position.Node, Inserted);
Position.Container := Container'Unchecked_Access;
end Insert;
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type;
Position : out Cursor;
Inserted : out Boolean)
is
function New_Node (Next : Node_Access) return Node_Access;
pragma Inline (New_Node);
procedure Local_Insert is
new Key_Ops.Generic_Conditional_Insert (New_Node);
--------------
-- New_Node --
--------------
function New_Node (Next : Node_Access) return Node_Access is
Node : constant Node_Access := new Node_Type'(Key, New_Item, Next);
begin
return Node;
end New_Node;
HT : Hash_Table_Type renames Container.HT;
-- Start of processing for Insert
begin
if HT.Length >= HT_Ops.Capacity (HT) then
HT_Ops.Reserve_Capacity (HT, HT.Length + 1);
end if;
Local_Insert (HT, Key, Position.Node, Inserted);
Position.Container := Container'Unchecked_Access;
end Insert;
procedure Insert
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type)
is
Position : Cursor;
Inserted : Boolean;
begin
Insert (Container, Key, New_Item, Position, Inserted);
if not Inserted then
raise Constraint_Error;
end if;
end Insert;
--------------
-- Is_Empty --
--------------
function Is_Empty (Container : Map) return Boolean is
begin
return Container.Length = 0;
end Is_Empty;
-------------
-- Iterate --
-------------
procedure Iterate
(Container : Map;
Process : not null access procedure (Position : Cursor))
is
procedure Process_Node (Node : Node_Access);
pragma Inline (Process_Node);
procedure Local_Iterate is new HT_Ops.Generic_Iteration (Process_Node);
------------------
-- Process_Node --
------------------
procedure Process_Node (Node : Node_Access) is
begin
Process (Cursor'(Container'Unchecked_Access, Node));
end Process_Node;
-- Start of processing for Iterate
begin
Local_Iterate (Container.HT);
end Iterate;
---------
-- Key --
---------
function Key (Position : Cursor) return Key_Type is
begin
return Position.Node.Key;
end Key;
------------
-- Length --
------------
function Length (Container : Map) return Count_Type is
begin
return Container.HT.Length;
end Length;
----------
-- Move --
----------
procedure Move
(Target : in out Map;
Source : in out Map)
is
begin
HT_Ops.Move (Target => Target.HT, Source => Source.HT);
end Move;
----------
-- Next --
----------
function Next (Node : Node_Access) return Node_Access is
begin
return Node.Next;
end Next;
function Next (Position : Cursor) return Cursor is
begin
if Position = No_Element then
return No_Element;
end if;
declare
M : Map renames Position.Container.all;
Node : constant Node_Access := HT_Ops.Next (M.HT, Position.Node);
begin
if Node = null then
return No_Element;
end if;
return Cursor'(Position.Container, Node);
end;
end Next;
procedure Next (Position : in out Cursor) is
begin
Position := Next (Position);
end Next;
-------------------
-- Query_Element --
-------------------
procedure Query_Element
(Position : Cursor;
Process : not null access procedure (Element : Element_Type))
is
begin
Process (Position.Node.Key, Position.Node.Element);
end Query_Element;
----------
-- Read --
----------
procedure Read
(Stream : access Root_Stream_Type'Class;
Container : out Map)
is
begin
Read_Nodes (Stream, Container.HT);
end Read;
---------------
-- Read_Node --
---------------
function Read_Node
(Stream : access Root_Stream_Type'Class) return Node_Access
is
Node : Node_Access := new Node_Type;
begin
Key_Type'Read (Stream, Node.Key);
Element_Type'Read (Stream, Node.Element);
return Node;
exception
when others =>
Free (Node);
raise;
end Read_Node;
-------------
-- Replace --
-------------
procedure Replace
(Container : in out Map;
Key : Key_Type;
New_Item : Element_Type)
is
Node : constant Node_Access := Key_Ops.Find (Container.HT, Key);
begin
if Node = null then
raise Constraint_Error;
end if;
Node.Key := Key;
Node.Element := New_Item;
end Replace;
---------------------
-- Replace_Element --
---------------------
procedure Replace_Element (Position : Cursor; By : Element_Type) is
begin
Position.Node.Element := By;
end Replace_Element;
----------------------
-- Reserve_Capacity --
----------------------
procedure Reserve_Capacity
(Container : in out Map;
Capacity : Count_Type)
is
begin
HT_Ops.Reserve_Capacity (Container.HT, Capacity);
end Reserve_Capacity;
--------------
-- Set_Next --
--------------
procedure Set_Next (Node : Node_Access; Next : Node_Access) is
begin
Node.Next := Next;
end Set_Next;
--------------------
-- Update_Element --
--------------------
procedure Update_Element
(Position : Cursor;
Process : not null access procedure (Element : in out Element_Type))
is
begin
Process (Position.Node.Key, Position.Node.Element);
end Update_Element;
-----------
-- Write --
-----------
procedure Write
(Stream : access Root_Stream_Type'Class;
Container : Map)
is
begin
Write_Nodes (Stream, Container.HT);
end Write;
----------------
-- Write_Node --
----------------
procedure Write_Node
(Stream : access Root_Stream_Type'Class;
Node : Node_Access)
is
begin
Key_Type'Write (Stream, Node.Key);
Element_Type'Write (Stream, Node.Element);
end Write_Node;
end Ada.Containers.Hashed_Maps;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Tests;
package Util.Processes.Tests is
procedure Add_Tests (Suite : in Util.Tests.Access_Test_Suite);
type Test is new Util.Tests.Test with null record;
-- Tests when the process is not launched
procedure Test_No_Process (T : in out Test);
-- Test executing a process
procedure Test_Spawn (T : in out Test);
-- Test output pipe redirection: read the process standard output
procedure Test_Output_Pipe (T : in out Test);
-- Test input pipe redirection: write the process standard input
procedure Test_Input_Pipe (T : in out Test);
-- Test error pipe redirection: read the process standard error
procedure Test_Error_Pipe (T : in out Test);
-- Test shell splitting.
procedure Test_Shell_Splitting_Pipe (T : in out Test);
-- Test launching several processes through pipes in several threads.
procedure Test_Multi_Spawn (T : in out Test);
-- Test output file redirection.
procedure Test_Output_Redirect (T : in out Test);
-- Test input file redirection.
procedure Test_Input_Redirect (T : in out Test);
-- Test changing working directory.
procedure Test_Set_Working_Directory (T : in out Test);
-- Test various errors.
procedure Test_Errors (T : in out Test);
-- Test launching and stopping a process.
procedure Test_Stop (T : in out Test);
-- Test various errors (pipe streams).
procedure Test_Pipe_Errors (T : in out Test);
-- Test launching and stopping a process (pipe streams).
procedure Test_Pipe_Stop (T : in out Test);
-- Test the Tools.Execute operation.
procedure Test_Tools_Execute (T : in out Test);
end Util.Processes.Tests;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
package body Program.Nodes.Character_Literals is
function Create
(Character_Literal_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Character_Literal is
begin
return Result : Character_Literal :=
(Character_Literal_Token => Character_Literal_Token,
Corresponding_Defining_Character_Literal => null,
Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
function Create
(Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Character_Literal is
begin
return Result : Implicit_Character_Literal :=
(Corresponding_Defining_Character_Literal => null,
Is_Part_Of_Implicit => Is_Part_Of_Implicit,
Is_Part_Of_Inherited => Is_Part_Of_Inherited,
Is_Part_Of_Instance => Is_Part_Of_Instance, Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
overriding function Corresponding_Defining_Character_Literal
(Self : Base_Character_Literal)
return Program.Elements.Defining_Character_Literals
.Defining_Character_Literal_Access is
begin
return Self.Corresponding_Defining_Character_Literal;
end Corresponding_Defining_Character_Literal;
overriding function Character_Literal_Token
(Self : Character_Literal)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Character_Literal_Token;
end Character_Literal_Token;
overriding function Image (Self : Character_Literal) return Text is
begin
return Self.Character_Literal_Token.Image;
end Image;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Character_Literal)
return Boolean is
begin
return Self.Is_Part_Of_Implicit;
end Is_Part_Of_Implicit;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Character_Literal)
return Boolean is
begin
return Self.Is_Part_Of_Inherited;
end Is_Part_Of_Inherited;
overriding function Is_Part_Of_Instance
(Self : Implicit_Character_Literal)
return Boolean is
begin
return Self.Is_Part_Of_Instance;
end Is_Part_Of_Instance;
overriding function Image (Self : Implicit_Character_Literal) return Text is
pragma Unreferenced (Self);
begin
return "";
end Image;
procedure Initialize (Self : in out Base_Character_Literal'Class) is
begin
null;
end Initialize;
overriding function Is_Character_Literal
(Self : Base_Character_Literal)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Character_Literal;
overriding function Is_Expression
(Self : Base_Character_Literal)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Expression;
overriding procedure Visit
(Self : not null access Base_Character_Literal;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is
begin
Visitor.Character_Literal (Self);
end Visit;
overriding function To_Character_Literal_Text
(Self : in out Character_Literal)
return Program.Elements.Character_Literals
.Character_Literal_Text_Access is
begin
return Self'Unchecked_Access;
end To_Character_Literal_Text;
overriding function To_Character_Literal_Text
(Self : in out Implicit_Character_Literal)
return Program.Elements.Character_Literals
.Character_Literal_Text_Access is
pragma Unreferenced (Self);
begin
return null;
end To_Character_Literal_Text;
end Program.Nodes.Character_Literals;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body Construct_Conversion_Array with
SPARK_Mode
is
----------------------
-- Conversion_Array --
----------------------
function Conversion_Array return Conversion_Array_Type is
Conversion_Array : Conversion_Array_Type := (others => Zero);
begin
for J in Product_Index_Type loop
Conversion_Array (J) := Two_Power (Exposant (J));
pragma Loop_Invariant (for all K in 0 .. J => Conversion_Array (K) = Two_Power (Exposant (K)));
end loop;
Prove_Property (Conversion_Array);
return Conversion_Array;
end Conversion_Array;
--------------------
-- Prove_Property --
--------------------
procedure Prove_Property (Conversion_Array : Conversion_Array_Type) is
begin
for J in Index_Type loop
for K in Index_Type loop
Exposant_Lemma (J, K); -- The two lemmas will help solvers
Two_Power_Lemma (Exposant (J), Exposant (K)); -- to prove the following code.
pragma Assert (Two_Power (Exposant (J)) = Conversion_Array (J)
and then Two_Power (Exposant (K)) = Conversion_Array (K)
and then Two_Power (Exposant (J + K)) = Conversion_Array (J + K));
-- A reminder of the precondition
-- The following code will split the two different cases of
-- Property. In the statements, assertions are used to guide
-- provers to the goal.
if J mod 2 = 1 and then K mod 2 = 1 then
pragma Assert (Exposant (J + K) + 1 = Exposant (J) + Exposant (K));
pragma Assert (Two_Power (Exposant (J + K) + 1)
= Two_Power (Exposant (J)) * Two_Power (Exposant (K)));
pragma Assert (Two_Power (Exposant (J + K)) * (+2)
= Two_Power (Exposant (J)) * Two_Power (Exposant (K)));
pragma Assert (Property (Conversion_Array, J, K));
else
pragma Assert (Exposant (J + K) = Exposant (J) + Exposant (K));
pragma Assert (Two_Power (Exposant (J + K)) = Two_Power (Exposant (J)) * Two_Power (Exposant (K)));
pragma Assert (Property (Conversion_Array, J, K));
end if;
pragma Loop_Invariant (for all M in 0 .. K =>
Property (Conversion_Array, J, M));
end loop;
pragma Loop_Invariant (for all L in 0 .. J =>
(for all M in Index_Type =>
Property (Conversion_Array, L, M)));
end loop;
end Prove_Property;
end Construct_Conversion_Array;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO;
procedure Guess_Number_Player is
procedure Guess_Number (Lower_Limit : Integer; Upper_Limit : Integer) is
type Feedback is (Lower, Higher, Correct);
package Feedback_IO is new Ada.Text_IO.Enumeration_IO (Feedback);
My_Guess : Integer := Lower_Limit + (Upper_Limit - Lower_Limit) / 2;
Your_Feedback : Feedback;
begin
Ada.Text_IO.Put_Line ("Think of a number!");
loop
Ada.Text_IO.Put_Line ("My guess: " & Integer'Image (My_Guess));
Ada.Text_IO.Put ("Your answer (lower, higher, correct): ");
Feedback_IO.Get (Your_Feedback);
exit when Your_Feedback = Correct;
if Your_Feedback = Lower then
My_Guess := Lower_Limit + (My_Guess - Lower_Limit) / 2;
else
My_Guess := My_Guess + (Upper_Limit - My_Guess) / 2;
end if;
end loop;
Ada.Text_IO.Put_Line ("I guessed well!");
end Guess_Number;
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
Lower_Limit : Integer;
Upper_Limit : Integer;
begin
loop
Ada.Text_IO.Put ("Lower Limit: ");
Int_IO.Get (Lower_Limit);
Ada.Text_IO.Put ("Upper Limit: ");
Int_IO.Get (Upper_Limit);
exit when Lower_Limit < Upper_Limit;
Ada.Text_IO.Put_Line ("Lower limit must be lower!");
end loop;
Guess_Number (Lower_Limit, Upper_Limit);
end Guess_Number_Player;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Locales;
package System.Native_Locales is
pragma Preelaborate;
subtype ISO_639_Alpha_2 is Ada.Locales.ISO_639_Alpha_2;
subtype ISO_639_Alpha_3 is Ada.Locales.ISO_639_Alpha_3;
subtype ISO_3166_1_Alpha_2 is Ada.Locales.ISO_3166_1_Alpha_2;
-- language code defined by ISO 639-1/2
function Language return ISO_639_Alpha_2;
function Language return ISO_639_Alpha_3;
-- country code defined by ISO 3166-1
function Country return ISO_3166_1_Alpha_2;
end System.Native_Locales;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
--
with ewok.interrupts.handler;
with ewok.tasks_shared; use ewok.tasks_shared;
with ewok.devices_shared; use ewok.devices_shared;
with m4.scb;
with soc.nvic;
package body ewok.interrupts
with spark_mode => off
is
procedure init
is
begin
m4.scb.SCB.SHCSR.USGFAULTENA := true;
for i in interrupt_table'range loop
interrupt_table(i) :=
(htype => DEFAULT_HANDLER,
handler => NULL,
task_id => ewok.tasks_shared.ID_UNUSED,
device_id => ewok.devices_shared.ID_DEV_UNUSED);
end loop;
interrupt_table(soc.interrupts.INT_USAGEFAULT) :=
(htype => TASK_SWITCH_HANDLER,
task_switch_handler =>
ewok.interrupts.handler.usagefault_handler'access,
task_id => ewok.tasks_shared.ID_KERNEL,
device_id => ewok.devices_shared.ID_DEV_UNUSED);
interrupt_table(soc.interrupts.INT_HARDFAULT) :=
(htype => TASK_SWITCH_HANDLER,
task_switch_handler =>
ewok.interrupts.handler.hardfault_handler'access,
task_id => ewok.tasks_shared.ID_KERNEL,
device_id => ewok.devices_shared.ID_DEV_UNUSED);
interrupt_table(soc.interrupts.INT_SYSTICK) :=
(htype => TASK_SWITCH_HANDLER,
task_switch_handler =>
ewok.interrupts.handler.systick_default_handler'access,
task_id => ewok.tasks_shared.ID_KERNEL,
device_id => ewok.devices_shared.ID_DEV_UNUSED);
m4.scb.SCB.SHPR1.mem_fault.priority := 0;
m4.scb.SCB.SHPR1.bus_fault.priority := 1;
m4.scb.SCB.SHPR1.usage_fault.priority := 2;
m4.scb.SCB.SHPR2.svc_call.priority := 3;
m4.scb.SCB.SHPR3.pendsv.priority := 4;
m4.scb.SCB.SHPR3.systick.priority := 5;
for irq in soc.nvic.NVIC.IPR'range loop
soc.nvic.NVIC.IPR(irq).priority := 7;
end loop;
end init;
function is_interrupt_already_used
(interrupt : soc.interrupts.t_interrupt) return boolean
is
begin
return interrupt_table(interrupt).task_id /= ewok.tasks_shared.ID_UNUSED;
end is_interrupt_already_used;
procedure set_interrupt_handler
(interrupt : in soc.interrupts.t_interrupt;
handler : in t_interrupt_handler_access;
task_id : in ewok.tasks_shared.t_task_id;
device_id : in ewok.devices_shared.t_device_id;
success : out boolean)
is
begin
if handler = NULL then
raise program_error;
end if;
interrupt_table(interrupt) :=
(DEFAULT_HANDLER, task_id, device_id, handler);
success := true;
end set_interrupt_handler;
procedure reset_interrupt_handler
(interrupt : in soc.interrupts.t_interrupt;
task_id : in ewok.tasks_shared.t_task_id;
device_id : in ewok.devices_shared.t_device_id)
is
begin
if interrupt_table(interrupt).task_id /= task_id or
interrupt_table(interrupt).device_id /= device_id
then
raise program_error;
end if;
interrupt_table(interrupt).handler := NULL;
interrupt_table(interrupt).task_id := ID_UNUSED;
interrupt_table(interrupt).device_id := ID_DEV_UNUSED;
end reset_interrupt_handler;
procedure set_task_switching_handler
(interrupt : in soc.interrupts.t_interrupt;
handler : in t_interrupt_task_switch_handler_access;
task_id : in ewok.tasks_shared.t_task_id;
device_id : in ewok.devices_shared.t_device_id;
success : out boolean)
is
begin
if handler = NULL then
raise program_error;
end if;
interrupt_table(interrupt) :=
(TASK_SWITCH_HANDLER, task_id, device_id, handler);
success := true;
end set_task_switching_handler;
function get_device_from_interrupt
(interrupt : soc.interrupts.t_interrupt)
return ewok.devices_shared.t_device_id
is
begin
return interrupt_table(interrupt).device_id;
end get_device_from_interrupt;
end ewok.interrupts;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Subunit
(Self : access Factory;
Parent_Name : not null Node_Access;
Proper_Body : not null Node_Access) return not null Node_Access;
-- Node lists
not overriding function New_List
(Self : access Factory;
List : Node_Access_Array) return not null Node_Access;
not overriding function New_List
(Self : access Factory;
Head : Node_Access;
Tail : not null Node_Access) return not null Node_Access;
-- Add a Tail item to a Head list. Head could be
-- * a null value, that means an empty list. Result is Tail then.
-- * a non-list node, that means a list with single node inside.
-- * a list of items.
-- Clauses, Pragmas and Aspects
not overriding function New_Aspect
(Self : access Factory;
Name : not null Node_Access;
Value : Node_Access := null) return not null Node_Access;
not overriding function New_Pragma
(Self : access Factory;
Name : not null Node_Access;
Arguments : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Use
(Self : access Factory;
Name : not null Node_Access;
Use_Type : Boolean := False) return not null Node_Access;
not overriding function New_With
(Self : access Factory;
Name : not null Node_Access;
Is_Limited : Boolean := False;
Is_Private : Boolean := False) return not null Node_Access;
-- Declarations
not overriding function New_Package
(Self : access Factory;
Name : not null Node_Access;
Public_Part : Node_Access := null;
Private_Part : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Package_Body
(Self : access Factory;
Name : not null Node_Access;
List : Node_Access := null) return not null Node_Access;
not overriding function New_Package_Instantiation
(Self : access Factory;
Name : not null Node_Access;
Template : not null Node_Access;
Actual_Part : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Parameter
(Self : access Factory;
Name : not null Node_Access;
Type_Definition : not null Node_Access;
Initialization : Node_Access := null;
Is_In : Boolean := False;
Is_Out : Boolean := False;
Is_Aliased : Boolean := False;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Subprogram_Body
(Self : access Factory;
Specification : not null Node_Access;
Declarations : Node_Access := null;
Statements : Node_Access := null;
Exceptions : Node_Access := null) return not null Node_Access;
not overriding function New_Subprogram_Declaration
(Self : access Factory;
Specification : not null Node_Access;
Aspects : Node_Access := null;
Is_Abstract : Boolean := False;
Is_Null : Boolean := False;
Expression : Node_Access := null;
Renamed : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Subtype
(Self : access Factory;
Name : not null Node_Access;
Definition : not null Node_Access;
Constrain : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Type
(Self : access Factory;
Name : not null Node_Access;
Discriminants : Node_Access := null;
Definition : Node_Access := null;
Aspects : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
not overriding function New_Variable
(Self : access Factory;
Name : not null Node_Access;
Type_Definition : Node_Access := null;
Initialization : Node_Access := null;
Rename : Node_Access := null;
Is_Constant : Boolean := False;
Is_Aliased : Boolean := False;
Aspects : Node_Access := null;
Comment : League.Strings.Universal_String :=
League.Strings.Empty_Universal_String) return not null Node_Access;
-- Definitions
type Access_Modifier is (Access_All, Access_Constant, Unspecified);
not overriding function New_Access
(Self : access Factory;
Modifier : Access_Modifier := Unspecified;
Target : not null Node_Access) return not null Node_Access;
not overriding function New_Derived
(Self : access Factory;
Parent : not null Node_Access) return not null Node_Access;
not overriding function New_Null_Exclusion
(Self : access Factory;
Definition : not null Node_Access;
Exclude : Boolean := True) return not null Node_Access;
not overriding function New_Interface
(Self : access Factory;
Is_Limited : Boolean := False;
Parents : Node_Access := null) return not null Node_Access;
not overriding function New_Private_Record
(Self : access Factory;
Is_Tagged : Boolean := False;
Is_Limited : Boolean := False;
Parents : Node_Access := null) return not null Node_Access;
not overriding function New_Record
(Self : access Factory;
Parent : Node_Access := null;
Components : Node_Access := null;
Is_Abstract : Boolean := False;
Is_Tagged : Boolean := False;
Is_Limited : Boolean := False) return not null Node_Access;
not overriding function New_Array
(Self : access Factory;
Indexes : not null Node_Access;
Component : not null Node_Access) return not null Node_Access;
type Trilean is (False, True, Unspecified);
not overriding function New_Subprogram_Specification
(Self : access Factory;
Is_Overriding : Trilean := Unspecified;
Name : Node_Access := null;
Parameters : Node_Access := null;
Result : Node_Access := null) return not null Node_Access;
-- Expressions and Names
not overriding function New_Apply
(Self : access Factory;
Prefix : not null Node_Access;
Arguments : not null Node_Access) return not null Node_Access;
-- This node represent construction in form 'prefix (arguments)'
-- This includes function_call, indexed_component, slice,
-- subtype_indication, etc
not overriding function New_Qualified_Expession
(Self : access Factory;
Prefix : not null Node_Access;
Argument : not null Node_Access) return not null Node_Access;
not overriding function New_Infix
(Self : access Factory;
Operator : League.Strings.Universal_String;
Left : not null Node_Access) return not null Node_Access;
not overriding function New_Literal
(Self : access Factory;
Value : Natural;
Base : Positive := 10) return not null Node_Access;
not overriding function New_Name
(Self : access Factory;
Name : League.Strings.Universal_String) return not null Node_Access;
-- Identifier, character literal ('X'), operator ("<")
not overriding function New_Selected_Name
(Self : access Factory;
Name : League.Strings.Universal_String) return not null Node_Access;
not overriding function New_Selected_Name
(Self : access Factory;
Prefix : not null Node_Access;
Selector : not null Node_Access) return not null Node_Access;
not overriding function New_String_Literal
(Self : access Factory;
Text : League.Strings.Universal_String) return not null Node_Access;
not overriding function New_Parentheses
(Self : access Factory;
Child : not null Node_Access) return not null Node_Access;
not overriding function New_Argument_Association
(Self : access Factory;
Value : not null Node_Access;
Choice : Node_Access := null) return not null Node_Access;
not overriding function New_Component_Association
(Self : access Factory;
Value : not null Node_Access;
Choices : Node_Access := null) return not null Node_Access;
not overriding function New_If_Expression
(Self : access Factory;
Condition : not null Node_Access;
Then_Path : not null Node_Access;
Elsif_List : Node_Access := null;
Else_Path : Node_Access := null) return not null Node_Access;
-- Statements and Paths
not overriding function New_Assignment
(Self : access Factory;
Left : not null Node_Access;
Right : not null Node_Access) return not null Node_Access;
not overriding function New_Case
(Self : access Factory;
Expression : not null Node_Access;
List : not null Node_Access) return not null Node_Access;
not overriding function New_Case_Path
(Self : access Factory;
Choice : not null Node_Access;
List : not null Node_Access) return not null Node_Access;
not overriding function New_Elsif
(Self : access Factory;
Condition : not null Node_Access;
List : not null Node_Access) return not null Node_Access;
not overriding function New_If
(Self : access Factory;
Condition : not null Node_Access;
Then_Path : not null Node_Access;
Elsif_List : Node_Access := null;
Else_Path : Node_Access := null) return not null Node_Access;
not overriding function New_For
(Self : access Factory;
Name : not null Node_Access;
Iterator : not null Node_Access;
Statements : not null Node_Access) return not null Node_Access;
not overriding function New_Loop
(Self : access Factory;
Condition : Node_Access;
Statements : not null Node_Access) return not null Node_Access;
not overriding function New_Return
(Self : access Factory;
Expression : Node_Access := null) return not null Node_Access;
not overriding function New_Extended_Return
(Self : access Factory;
Name : not null Node_Access;
Type_Definition : not null Node_Access;
Initialization : Node_Access := null;
Statements : not null Node_Access) return not null Node_Access;
not overriding function New_Statement
(Self : access Factory;
Expression : Node_Access := null) return not null Node_Access;
not overriding function New_Block
(Self : access Factory;
Declarations : Node_Access := null;
Statements : Node_Access := null;
Exceptions : Node_Access := null) return not null Node_Access;
private
type Node is abstract tagged null record;
not overriding function Document
(Self : Node;
Printer : not null access League.Pretty_Printers.Printer'Class;
Pad : Natural)
return League.Pretty_Printers.Document;
not overriding function Max_Pad (Self : Node) return Natural is (0);
-- Return maximum lengh of name in Node
not overriding function Join
(Self : Node;
List : Node_Access_Array;
Pad : Natural;
Printer : not null access League.Pretty_Printers.Printer'Class)
return League.Pretty_Printers.Document;
-- Join documents of several nodes in a list
type Expression is abstract new Node with null record;
overriding function Join
(Self : Expression;
List : Node_Access_Array;
Pad : Natural;
Printer : not null access League.Pretty_Printers.Printer'Class)
return League.Pretty_Printers.Document;
type Declaration is abstract new Node with null record;
overriding function Join
(Self : Declaration;
List : Node_Access_Array;
Pad : Natural;
Printer : not null access League.Pretty_Printers.Printer'Class)
return League.Pretty_Printers.Document;
-- Declarations are separated by an extra new line
type Factory is tagged null record;
function Print_Aspect
(Aspect : Node_Access;
Printer : not null access League.Pretty_Printers.Printer'Class)
return League.Pretty_Printers.Document;
end Ada_Pretty;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Containers.Vectors; use Ada.Containers;
with MathUtils;
package NeuralNet is
pragma Assertion_Policy (Pre => Check,
Post => Check,
Type_Invariant => Check);
type Activator is (RELU, LOGISTIC);
type LossFunction is (MSE);
type Shape is array (Positive range <>) of Positive;
type Weights is array (Positive range <>) of Float;
type LearningRate is new Float range 0.0 .. Float'Last;
subtype NeuronIndex is Positive range 1 .. 2048;
subtype LayerIndex is Positive range 1 .. 32;
type Neuron (size: NeuronIndex := 1) is record
a: Float := 0.0;
z: Float := 0.0;
bias: Float := 0.0;
act: Activator := RELU;
w: Weights (1 .. size) := (others => MathUtils.rand01 * (1.0 / MathUtils.F.Sqrt(Float(size))));
end record;
type Config (size: LayerIndex) is record
act: Activator := RELU;
inputSize: Positive := 1;
lr: LearningRate := 0.05;
gradientClipAbs: Float := 5.0;
sizes: Shape(1 .. size);
end record;
package NeuronVecPkg is new Ada.Containers.Vectors(Index_Type => NeuronIndex,
Element_Type => Neuron);
package NeuronLayerVecPkg is new Ada.Containers.Vectors(Index_Type => LayerIndex,
Element_Type => NeuronVecPkg.Vector,
"=" => NeuronVecPkg."=");
package LayerErrorVecPkg is new Ada.Containers.Vectors(Index_Type => LayerIndex,
Element_Type => MathUtils.Vector,
"=" => MathUtils.Float_Vec."=");
subtype LayerVector is NeuronLayerVecPkg.Vector;
type Net (size: Positive) is tagged record
layers: LayerVector;
gradients: LayerErrorVecPkg.Vector;
conf: Config (size);
end record;
function create(conf: Config) return Net;
procedure print(n: in Neuron);
procedure print(nn: in Net);
function forward(n: in out Neuron; values: in MathUtils.Vector) return Float
with Pre => values.Length = n.w'Length;
function forward(nn: in out Net; values: in MathUtils.Vector) return MathUtils.Vector
with Pre => values.Length = nn.layers(1)(1).w'Length,
Post => forward'Result.Length = nn.layers.Last_Element.Length;
procedure train(nn: in out Net; input: in MathUtils.Vector; target: MathUtils.Vector)
with Pre => input.Length = nn.layers(1)(1).w'Length;
end NeuralNet;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Strings.Equal_Case_Insensitive;
with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Source_Info; use GNAT.Source_Info;
with Langkit_Support.Text; use Langkit_Support.Text;
with Libadalang.Analysis; use Libadalang.Analysis;
with Libadalang.Common; use Libadalang.Common;
with Rejuvenation.Simple_Factory; use Rejuvenation.Simple_Factory;
package body Test_Exercises_Intro is
procedure Test_LibAdaLang_AST (T : in out Test_Case'Class);
procedure Test_LibAdaLang_AST (T : in out Test_Case'Class) is
pragma Unreferenced (T);
Unit : constant Analysis_Unit := Analyze_File ("src/mismatch.ads");
begin
Put_Line ("Begin - " & Enclosing_Entity);
Unit.Print;
Put_Line ("Done - " & Enclosing_Entity);
end Test_LibAdaLang_AST;
procedure Test_LibAdaLang_Subprograms (T : in out Test_Case'Class);
procedure Test_LibAdaLang_Subprograms (T : in out Test_Case'Class) is
pragma Unreferenced (T);
function Process_Node (Node : Ada_Node'Class) return Visit_Status;
function Process_Node (Node : Ada_Node'Class) return Visit_Status is
begin
if Node.Kind = Ada_Subp_Body then
declare
SB : constant Subp_Body := Node.As_Subp_Body;
begin
Put_Line ("Found " & Image (SB.F_Subp_Spec.F_Subp_Name.Text));
end;
end if;
return Into;
end Process_Node;
Unit : constant Analysis_Unit :=
Analyze_File ("tests/" & GNAT.Source_Info.File);
begin
Put_Line ("Begin - " & Enclosing_Entity);
Unit.Root.Traverse (Process_Node'Access);
Put_Line ("Done - " & Enclosing_Entity);
end Test_LibAdaLang_Subprograms;
procedure Test_LibAdaLang_CallFunction (T : in out Test_Case'Class);
procedure Test_LibAdaLang_CallFunction (T : in out Test_Case'Class) is
pragma Unreferenced (T);
Function_Name : constant String := "Analyze_File";
function Process_Node (Node : Ada_Node'Class) return Visit_Status;
function Process_Node (Node : Ada_Node'Class) return Visit_Status is
begin
if Node.Kind = Ada_Call_Expr then
declare
CE : constant Call_Expr := Node.As_Call_Expr;
begin
if Ada.Strings.Equal_Case_Insensitive
(Image (CE.F_Name.Text), Function_Name)
then
Put_Line
(Image (CE.Full_Sloc_Image) & "Call to '" & Function_Name &
"'");
end if;
end;
end if;
return Into;
end Process_Node;
Project_Filename : constant String := "test_driver.gpr";
Units : constant Analysis_Units.Vector :=
Analyze_Project (Project_Filename);
begin
Put_Line ("Begin - " & Enclosing_Entity);
for Unit of Units loop
Unit.Root.Traverse (Process_Node'Access);
end loop;
Put_Line ("Done - " & Enclosing_Entity);
end Test_LibAdaLang_CallFunction;
-- Test plumbing
overriding function Name
(T : Exercise_Intro_Test_Case) return AUnit.Message_String
is
pragma Unreferenced (T);
begin
return AUnit.Format ("Exercises Introduction");
end Name;
overriding procedure Register_Tests (T : in out Exercise_Intro_Test_Case) is
begin
Registration.Register_Routine
(T, Test_LibAdaLang_AST'Access, "Use LibAdaLang to print AST of file");
Registration.Register_Routine
(T, Test_LibAdaLang_Subprograms'Access,
"Use LibAdaLang to print subprograms in file");
Registration.Register_Routine
(T, Test_LibAdaLang_CallFunction'Access,
"Use LibAdaLang to find all calls " &
"to a particular function in project");
end Register_Tests;
end Test_Exercises_Intro;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
PRIVATE
TYPE BAD_LIM (D : LIES := IDENT_BOOL (TRUE)) IS
RECORD
NULL;
END RECORD;
END PL;
USE PL;
BEGIN
DECLARE
BL : BAD_LIM;
BEGIN
FAILED ( "NO EXCEPTION RAISED AT THE " &
"DECLARATION OF OBJECT BL " &
BOOLEAN'IMAGE(BL.D));
EXCEPTION
WHEN OTHERS =>
FAILED ( "EXCEPTION ATTEMPTING TO USE OBJECT" );
END;
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "WRONG EXCEPTION RAISED AT DECLARATION " &
"OF OBJECT BL" );
END;
EXCEPTION
WHEN OTHERS =>
FAILED ( "EXCEPTION RAISED AT ELABORATION OF TYPE " &
"BAD_LIM" );
END;
RESULT;
END C37211B;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Command_Line;
with Ada.Text_IO;
use Ada.Text_IO;
package body Sarge is
--- SET ARGUMENT ---
procedure setArgument(arg_short: in Unbounded_String; arg_long: in Unbounded_String; desc: in Unbounded_String; hasVal: in boolean) is
arg: aliased Argument := (arg_short => arg_short, arg_long => arg_long, description => desc, hasValue => hasVal, value => +"", parsed => False);
aa: Argument_Access;
begin
args.append(arg);
-- Set up links.
if length(arg_short) > 0 then
aa := args.Last_Element'Access;
argNames.include(arg_short, aa);
end if;
if length(arg_long) > 0 then
argNames.include(arg_long, arg'Access);
end if;
end setArgument;
--- SET DESCRIPTION ---
procedure setDescription(desc: in Unbounded_String) is
begin
description := desc;
end setDescription;
--- SET USAGE ---
procedure setUsage(usage: in Unbounded_String) is
begin
usageStr := usage;
end setUsage;
--- PARSE ARGUMENTS ---
function parseArguments return boolean is
flag_it: argNames_map.Cursor;
expectValue: boolean := False;
begin
--
execName := Ada.Command_Line.command_name;
for arg in 1..Ada.Command_Line.argument_count loop
-- Each flag will start with a '-' character. Multiple flags can be joined together in
-- the same string if they're the short form flag type (one character per flag).
if expectValue = True then
-- Copy value.
argNames(flag_it).value := arg;
expectValue := False;
elsif arg(arg'First) = '-' then
-- Parse flag.
-- First check for the long form.
if arg(arg'First + 1) = '-' then
-- Long form of the flag.
if not argNames.contains(arg(arg'First + 2..arg'Last)) then
-- Flag wasn't found. Abort.
put_line("Long flag " & arg'Image & " wasn't found");
return False;
end if;
-- Mark as found.
flag_it := argNames.find(arg);
argNames_map.Element(flag_it).parsed := True;
flagCounter := flagCounter + 1;
if argNames_map.Element(flag_it).hasValue = True then
expectValue := True;
end if;
else
-- Parse short form flag. Parse all of them sequentially. Only the last one
-- is allowed to have an additional value following it.
for i in arg'range loop
flag_it := argNames.find(arg(arg'First + (1 + i)..arg'First + (2 + i)));
if flag_it = argNames_map.No_Element then
-- Flag wasn't found. Abort.
put_line("Short flag " & arg(arg'First + (1 + i)..arg'First + (2 + i)) &
" wasn't found.");
return False;
end if;
-- Mark as found.
argNames_map.Element(flag_it).parsed := True;
flagCounter := flagCounter + 1;
if argNames_map.Element(flag_it).hasValue = True then
if i /= (arg'Length - 1) then
-- Flag isn't at end, thus cannot have value.
put_line("Flag " & arg(arg'First + (1 + i)..arg'First + (2 + i))
& " needs to be followed by a value string.");
return False;
else
expectValue := True;
end if;
end if;
end loop;
end if;
else
put_line("Expected flag, not value.");
return False;
end if;
end loop;
parsed := True;
return True;
end parseArguments;
--- GET FLAG ---
function getFlag(arg_flag: in Unbounded_String; arg_value: out Unbounded_String) return boolean is
flag_it: argNames_map.Cursor;
begin
if parsed /= True then
return False;
end if;
flag_it := argNames.find(arg_flag);
if flag_it = No_Elements then
return False;
elsif Element(flag_it).parsed /= True then
return False;
end if;
if Element(flag_it).hasValue = True then
arg_value := Element(flag_it).value;
end if;
return True;
end getFlag;
--- EXISTS ---
function exists(arg_flag: in Unbounded_String) return boolean is
flag_it: argNames_map.Cursor;
begin
if parsed /= True then
return False;
end if;
flag_it := argNames.find(arg_flag);
if flag_it = No_Elements then
return False;
elsif Element(flag_it).parsed /= True then
return False;
end if;
return True;
end exists;
--- PRINT HELP ---
procedure printHelp is
begin
put_line;
put_line(description);
put_line("Usage:");
put_line(usageStr);
put_line;
put_line("Options:");
-- Print out the options.
for opt in args.Iterate loop
put_line("-" & opt.arg_short & " --" & opt.arg_long & " " & opt.description);
end loop;
end printHelp;
--- FLAG COUNT ---
function flagCount return integer is
begin
return flagCount;
end flagCount;
--- EXECUTABLE NAME ---
function executableName return Unbounded_String is
begin
return execName;
end executableName;
end Sarge;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Strings;
package body MAT.Formats is
use type MAT.Types.Target_Tick_Ref;
Hex_Prefix : constant Boolean := True;
Hex_Length : Positive := 16;
Conversion : constant String (1 .. 10) := "0123456789";
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String;
-- Format a short description of a malloc event.
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- Format a short description of a realloc event.
function Event_Realloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- Format a short description of a free event.
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String;
-- ------------------------------
-- Set the size of a target address to format them.
-- ------------------------------
procedure Set_Address_Size (Size : in Positive) is
begin
Hex_Length := Size;
end Set_Address_Size;
-- ------------------------------
-- Format the PID into a string.
-- ------------------------------
function Pid (Value : in MAT.Types.Target_Process_Ref) return String is
begin
return Util.Strings.Image (Natural (Value));
end Pid;
-- ------------------------------
-- Format the address into a string.
-- ------------------------------
function Addr (Value : in MAT.Types.Target_Addr) return String is
Hex : constant String := MAT.Types.Hex_Image (Value, Hex_Length);
begin
if Hex_Prefix then
return "0x" & Hex;
else
return Hex;
end if;
end Addr;
-- ------------------------------
-- Format the size into a string.
-- ------------------------------
function Size (Value : in MAT.Types.Target_Size) return String is
Result : constant String := MAT.Types.Target_Size'Image (Value);
begin
if Result (Result'First) = ' ' then
return Result (Result'First + 1 .. Result'Last);
else
return Result;
end if;
end Size;
-- ------------------------------
-- Format the memory growth size into a string.
-- ------------------------------
function Size (Alloced : in MAT.Types.Target_Size;
Freed : in MAT.Types.Target_Size) return String is
use type MAT.Types.Target_Size;
begin
if Alloced > Freed then
return "+" & Size (Alloced - Freed);
elsif Alloced < Freed then
return "-" & Size (Freed - Alloced);
else
return "=" & Size (Alloced);
end if;
end Size;
-- ------------------------------
-- Format the time relative to the start time.
-- ------------------------------
function Time (Value : in MAT.Types.Target_Tick_Ref;
Start : in MAT.Types.Target_Tick_Ref) return String is
T : constant MAT.Types.Target_Tick_Ref := Value - Start;
Sec : constant MAT.Types.Target_Tick_Ref := T / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := T mod 1_000_000;
Msec : Natural := Natural (Usec / 1_000);
Frac : String (1 .. 5);
begin
Frac (5) := 's';
Frac (4) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (3) := Conversion (Msec mod 10 + 1);
Msec := Msec / 10;
Frac (2) := Conversion (Msec mod 10 + 1);
Frac (1) := '.';
return MAT.Types.Target_Tick_Ref'Image (Sec) & Frac;
end Time;
-- ------------------------------
-- Format the duration in seconds, milliseconds or microseconds.
-- ------------------------------
function Duration (Value : in MAT.Types.Target_Tick_Ref) return String is
Sec : constant MAT.Types.Target_Tick_Ref := Value / 1_000_000;
Usec : constant MAT.Types.Target_Tick_Ref := Value mod 1_000_000;
Msec : constant Natural := Natural (Usec / 1_000);
Val : Natural;
Frac : String (1 .. 5);
begin
if Sec = 0 and Msec = 0 then
return Util.Strings.Image (Integer (Usec)) & "us";
elsif Sec = 0 then
Val := Natural (Usec mod 1_000);
Frac (5) := 's';
Frac (4) := 'm';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Msec)) & Frac;
else
Val := Msec;
Frac (4) := 's';
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (3) := Conversion (Val mod 10 + 1);
Val := Val / 10;
Frac (2) := Conversion (Val mod 10 + 1);
Frac (1) := '.';
return Util.Strings.Image (Integer (Sec)) & Frac (1 .. 4);
end if;
end Duration;
function Location (File : in Ada.Strings.Unbounded.Unbounded_String) return String is
Pos : constant Natural := Ada.Strings.Unbounded.Index (File, "/", Ada.Strings.Backward);
Len : constant Natural := Ada.Strings.Unbounded.Length (File);
begin
if Pos /= 0 then
return Ada.Strings.Unbounded.Slice (File, Pos + 1, Len);
else
return Ada.Strings.Unbounded.To_String (File);
end if;
end Location;
-- ------------------------------
-- Format a file, line, function information into a string.
-- ------------------------------
function Location (File : in Ada.Strings.Unbounded.Unbounded_String;
Line : in Natural;
Func : in Ada.Strings.Unbounded.Unbounded_String) return String is
begin
if Ada.Strings.Unbounded.Length (File) = 0 then
return Ada.Strings.Unbounded.To_String (Func);
elsif Line > 0 then
declare
Num : constant String := Natural'Image (Line);
begin
return Ada.Strings.Unbounded.To_String (Func) & " ("
& Location (File) & ":" & Num (Num'First + 1 .. Num'Last) & ")";
end;
else
return Ada.Strings.Unbounded.To_String (Func) & " (" & Location (File) & ")";
end if;
end Location;
-- ------------------------------
-- Format an event range description.
-- ------------------------------
function Event (First : in MAT.Events.Target_Event_Type;
Last : in MAT.Events.Target_Event_Type) return String is
use type MAT.Events.Event_Id_Type;
Id1 : constant String := MAT.Events.Event_Id_Type'Image (First.Id);
Id2 : constant String := MAT.Events.Event_Id_Type'Image (Last.Id);
begin
if First.Id = Last.Id then
return Id1 (Id1'First + 1 .. Id1'Last);
else
return Id1 (Id1'First + 1 .. Id1'Last) & ".." & Id2 (Id2'First + 1 .. Id2'Last);
end if;
end Event;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Mode : in Format_Type := NORMAL) return String is
use type MAT.Types.Target_Addr;
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
if Mode = BRIEF then
return "malloc";
else
return "malloc(" & Size (Item.Size) & ") = " & Addr (Item.Addr);
end if;
when MAT.Events.MSG_REALLOC =>
if Mode = BRIEF then
if Item.Old_Addr = 0 then
return "realloc";
else
return "realloc";
end if;
else
if Item.Old_Addr = 0 then
return "realloc(0," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
else
return "realloc(" & Addr (Item.Old_Addr) & "," & Size (Item.Size) & ") = "
& Addr (Item.Addr);
end if;
end if;
when MAT.Events.MSG_FREE =>
if Mode = BRIEF then
return "free";
else
return "free(" & Addr (Item.Addr) & "), " & Size (Item.Size);
end if;
when MAT.Events.MSG_BEGIN =>
return "begin";
when MAT.Events.MSG_END =>
return "end";
when MAT.Events.MSG_LIBRARY =>
return "library";
end case;
end Event;
-- ------------------------------
-- Format a short description of a malloc event.
-- ------------------------------
function Event_Malloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Free_Event : MAT.Events.Target_Event_Type;
Slot_Addr : constant String := Addr (Item.Addr);
begin
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes allocated at "
& Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
;
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes allocated at " & Slot_Addr & " (never freed)";
end Event_Malloc;
-- ------------------------------
-- Format a short description of a realloc event.
-- ------------------------------
function Event_Realloc (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
use type MAT.Events.Event_Id_Type;
Free_Event : MAT.Events.Target_Event_Type;
Slot_Addr : constant String := Addr (Item.Addr);
begin
if Item.Next_Id = 0 and Item.Prev_Id = 0 then
return Size (Item.Size) & " bytes reallocated at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& " (never freed)";
end if;
Free_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_FREE);
return Size (Item.Size) & " bytes reallocated at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& ", freed " & Duration (Free_Event.Time - Item.Time)
& " after by event" & MAT.Events.Event_Id_Type'Image (Free_Event.Id)
& " " & Size (Item.Size, Item.Old_Size) & " bytes";
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes reallocated at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& " (never freed) " & Size (Item.Size, Item.Old_Size) & " bytes";
end Event_Realloc;
-- ------------------------------
-- Format a short description of a free event.
-- ------------------------------
function Event_Free (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
Alloc_Event : MAT.Events.Target_Event_Type;
Slot_Addr : constant String := Addr (Item.Addr);
begin
Alloc_Event := MAT.Events.Tools.Find (Related, MAT.Events.MSG_MALLOC);
return Size (Alloc_Event.Size) & " bytes freed at " & Slot_Addr
& " after " & Duration (Item.Time - Start_Time)
& ", alloc'ed for " & Duration (Item.Time - Alloc_Event.Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Alloc_Event.Id);
exception
when MAT.Events.Tools.Not_Found =>
return Size (Item.Size) & " bytes freed at " & Slot_Addr;
end Event_Free;
-- ------------------------------
-- Format a short description of the event.
-- ------------------------------
function Event (Item : in MAT.Events.Target_Event_Type;
Related : in MAT.Events.Tools.Target_Event_Vector;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
case Item.Index is
when MAT.Events.MSG_MALLOC =>
return Event_Malloc (Item, Related, Start_Time);
when MAT.Events.MSG_REALLOC =>
return Event_Realloc (Item, Related, Start_Time);
when MAT.Events.MSG_FREE =>
return Event_Free (Item, Related, Start_Time);
when MAT.Events.MSG_BEGIN =>
return "Begin event";
when MAT.Events.MSG_END =>
return "End event";
when MAT.Events.MSG_LIBRARY =>
return "Library information event";
end case;
end Event;
-- ------------------------------
-- Format the difference between two event IDs (offset).
-- ------------------------------
function Offset (First : in MAT.Events.Event_Id_Type;
Second : in MAT.Events.Event_Id_Type) return String is
use type MAT.Events.Event_Id_Type;
begin
if First = Second or First = 0 or Second = 0 then
return "";
elsif First > Second then
return "+" & Util.Strings.Image (Natural (First - Second));
else
return "-" & Util.Strings.Image (Natural (Second - First));
end if;
end Offset;
-- ------------------------------
-- Format a short description of the memory allocation slot.
-- ------------------------------
function Slot (Value : in MAT.Types.Target_Addr;
Item : in MAT.Memory.Allocation;
Start_Time : in MAT.Types.Target_Tick_Ref) return String is
begin
return Addr (Value) & " is " & Size (Item.Size)
& " bytes allocated after " & Duration (Item.Time - Start_Time)
& " by event" & MAT.Events.Event_Id_Type'Image (Item.Event);
end Slot;
end MAT.Formats;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- $Id: scanner.ads,v 1.5 2000/09/04 11:17:27 grosch rel $
with Position, Strings;
use Position, Strings;
$- user import declarations
$@ package @ is
$E[ user export declarations
type tScanAttribute is record Position: tPosition; end record;
procedure ErrorAttribute (Token: Integer; Attribute: out tScanAttribute);
$]
EofToken : constant Integer := 0;
TokenLength : Integer;
TokenIndex : Integer;
Attribute : tScanAttribute;
procedure BeginScanner ;
procedure BeginFile (FileName: String);
function GetToken return Integer;
procedure GetWord (Word: out Strings.tString);
procedure GetLower (Word: out Strings.tString);
procedure GetUpper (Word: out Strings.tString);
procedure CloseFile ;
procedure CloseScanner ;
$@ end @;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Streams.Stream_IO; use Ada.Streams.Stream_IO;
with Headers; use Headers;
package body Identify is
function Try (H : Unsigned_64) return Boolean is
begin
for I in Integer range Headers.All_File_Signatures'Range loop
declare
Curr_Sig : constant Headers.File_Signature :=
Headers.All_File_Signatures (I);
Treated_Header : constant Unsigned_64 :=
(if Curr_Sig.Bits = 0 then
H
else
Shift_Right (H, 64 - Curr_Sig.Bits));
begin
if Curr_Sig.Magic_Number = Treated_Header then
Headers.Print_File_Info (Curr_Sig);
return True;
end if;
end;
end loop;
return False;
end Try;
procedure Identify_File
(Filename : String) is
Input_File : Ada.Streams.Stream_IO.File_Type;
Input_Stream : Ada.Streams.Stream_IO.Stream_Access;
Num_Bytes : Natural := 8;
Element : Interfaces.Unsigned_64 := 0;
U8 : Interfaces.Unsigned_8 := 0;
begin
Ada.Streams.Stream_IO.Open (
Input_File,
Ada.Streams.Stream_IO.In_File,
Filename
);
Input_Stream := Ada.Streams.Stream_IO.Stream (Input_File);
Get_Headers :
while not Ada.Streams.Stream_IO.End_Of_File (Input_File) loop
Interfaces.Unsigned_8'Read (Input_Stream, U8);
Element := Shift_Left (Element, 8);
Element := Element or Interfaces.Unsigned_64 (U8);
Num_Bytes := Num_Bytes - 1;
exit Get_Headers when Num_Bytes = 0;
end loop Get_Headers;
Ada.Streams.Stream_IO.Close (Input_File);
Put (Filename & ": ");
if Try (Element) then
return;
end if;
raise Headers.Unknown_Header with "file could not be identified";
end Identify_File;
end Identify;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with GL.Objects.Shaders;
with Program_Loader;
package body Shader_Manager is
Black : constant GL.Types.Singles.Vector4 := (0.0, 0.0, 0.0, 0.0);
Render_Uniforms : Shader_Uniforms;
procedure Init (Render_Program : in out GL.Objects.Programs.Program) is
use GL.Objects.Programs;
use GL.Objects.Shaders;
use GL.Types.Singles;
use Program_Loader;
Light : constant Singles.Vector3 := (0.0, 4.0, 1.0);
Direction : constant Singles.Vector3 := (0.0, 0.0, 1.0);
begin
Render_Program := Program_From
((Src ("src/shaders/vertex_shader_1_1.glsl", Vertex_Shader),
Src ("src/shaders/fragment_shader_1_1.glsl", Fragment_Shader)));
Render_Uniforms.View_Matrix_ID :=
Uniform_Location (Render_Program, "view_matrix");
Render_Uniforms.Model_Matrix_ID :=
Uniform_Location (Render_Program, "model_matrix");
Render_Uniforms.Projection_Matrix_ID :=
Uniform_Location (Render_Program, "projection_matrix");
Render_Uniforms.Rotation_Matrix_ID :=
Uniform_Location (Render_Program, "rotation_matrix");
Render_Uniforms.Translation_Matrix_ID :=
Uniform_Location (Render_Program, "translation_matrix");
Render_Uniforms.Light_Direction_ID :=
Uniform_Location (Render_Program, "light_direction");
Render_Uniforms.Light_Position_ID :=
Uniform_Location (Render_Program, "light_position");
Render_Uniforms.Line_Width_ID :=
Uniform_Location (Render_Program, "line_width");
Render_Uniforms.Ambient_Colour_ID :=
Uniform_Location (Render_Program, "Ambient_Colour");
Render_Uniforms.Diffuse_Colour_ID :=
Uniform_Location (Render_Program, "Diffuse_Colour");
Render_Uniforms.Drawing_Colour_ID :=
Uniform_Location (Render_Program, "Drawing_Colour");
Use_Program (Render_Program);
GL.Uniforms.Set_Single (Render_Uniforms.Light_Direction_ID, Direction);
GL.Uniforms.Set_Single (Render_Uniforms.Light_Position_ID, Light);
GL.Uniforms.Set_Single (Render_Uniforms.Line_Width_ID, 1.0);
GL.Uniforms.Set_Single (Render_Uniforms.Model_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.View_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Projection_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Rotation_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Translation_Matrix_ID, Identity4);
GL.Uniforms.Set_Single (Render_Uniforms.Ambient_Colour_ID, Black);
GL.Uniforms.Set_Single (Render_Uniforms.Diffuse_Colour_ID, Black);
GL.Uniforms.Set_Single (Render_Uniforms.Drawing_Colour_ID, Black);
exception
when others =>
Put_Line ("An exception occurred in Shader_Manager.Init.");
raise;
end Init;
-- -------------------------------------------------------------------------
procedure Set_Ambient_Colour (Ambient_Colour : Singles.Vector4) is
begin
GL.Uniforms.Set_Single (Render_Uniforms.Ambient_Colour_ID, Ambient_Colour);
end Set_Ambient_Colour;
-- -------------------------------------------------------------------------
procedure Set_Diffuse_Colour (Diffuse_Colour : Singles.Vector4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Diffuse_Colour_ID, Diffuse_Colour);
end Set_Diffuse_Colour;
-- -------------------------------------------------------------------------
procedure Set_Drawing_Colour (Drawing_Colour : Singles.Vector4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Drawing_Colour_ID, Drawing_Colour);
end Set_Drawing_Colour;
-- -------------------------------------------------------------------------
procedure Set_Light_Direction_Vector (Light_Direction : Singles.Vector3) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Light_Direction_ID, Light_Direction);
end Set_Light_Direction_Vector;
-- -------------------------------------------------------------------------
procedure Set_Light_Position_Vector (Light_Position : Singles.Vector3) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Light_Position_ID, Light_Position);
end Set_Light_Position_Vector;
-- -------------------------------------------------------------------------
procedure Set_Line_Width (Width : Single) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Line_Width_ID, Width);
end Set_Line_Width;
-- -------------------------------------------------------------------------
procedure Set_Model_Matrix (Model_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single (Render_Uniforms.Model_Matrix_ID, Model_Matrix);
end Set_Model_Matrix;
-- -------------------------------------------------------------------------
procedure Set_View_Matrix (View_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single (Render_Uniforms.View_Matrix_ID, View_Matrix);
end Set_View_Matrix;
-- -------------------------------------------------------------------------
procedure Set_Projection_Matrix (Projection_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Projection_Matrix_ID, Projection_Matrix);
end Set_Projection_Matrix;
-- -------------------------------------------------------------------------
procedure Set_Rotation_Matrix (Rotation_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Rotation_Matrix_ID, Rotation_Matrix);
end Set_Rotation_Matrix;
-- -------------------------------------------------------------------------
procedure Set_Translation_Matrix (Translation_Matrix : Singles.Matrix4) is
begin
GL.Uniforms.Set_Single
(Render_Uniforms.Translation_Matrix_ID, Translation_Matrix);
end Set_Translation_Matrix;
-- -------------------------------------------------------------------------
end Shader_Manager;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Strings;
with ASF.Utils;
package body ASF.Components.Html.Selects is
-- ------------------------------
-- UISelectItem Component
-- ------------------------------
ITEM_LABEL_NAME : constant String := "itemLabel";
ITEM_VALUE_NAME : constant String := "itemValue";
ITEM_DESCRIPTION_NAME : constant String := "itemDescription";
ITEM_DISABLED_NAME : constant String := "itemDisabled";
SELECT_ATTRIBUTE_NAMES : Util.Strings.String_Set.Set;
-- ------------------------------
-- UISelectBoolean Component
-- ------------------------------
-- Render the checkbox element.
overriding
procedure Render_Input (UI : in UISelectBoolean;
Context : in out Faces_Context'Class;
Write_Id : in Boolean := True) is
use ASF.Components.Html.Forms;
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Value : constant EL.Objects.Object := UIInput'Class (UI).Get_Value;
begin
Writer.Start_Element ("input");
Writer.Write_Attribute (Name => "type", Value => "checkbox");
UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer, Write_Id);
Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id);
if not EL.Objects.Is_Null (Value) and then EL.Objects.To_Boolean (Value) then
Writer.Write_Attribute (Name => "checked", Value => "true");
end if;
Writer.End_Element ("input");
end Render_Input;
-- ------------------------------
-- Convert the string into a value. If a converter is specified on the component,
-- use it to convert the value. Make sure the result is a boolean.
-- ------------------------------
overriding
function Convert_Value (UI : in UISelectBoolean;
Value : in String;
Context : in Faces_Context'Class) return EL.Objects.Object is
use type EL.Objects.Data_Type;
Result : constant EL.Objects.Object := Forms.UIInput (UI).Convert_Value (Value, Context);
begin
case EL.Objects.Get_Type (Result) is
when EL.Objects.TYPE_BOOLEAN =>
return Result;
when EL.Objects.TYPE_INTEGER =>
return EL.Objects.To_Object (EL.Objects.To_Boolean (Result));
when others =>
if Value = "on" then
return EL.Objects.To_Object (True);
else
return EL.Objects.To_Object (False);
end if;
end case;
end Convert_Value;
-- ------------------------------
-- Iterator over the Select_Item elements
-- ------------------------------
-- ------------------------------
-- Get an iterator to scan the component children.
-- ------------------------------
procedure First (UI : in UISelectOne'Class;
Context : in Faces_Context'Class;
Iterator : out Cursor) is
begin
Iterator.Component := UI.First;
Iterator.Pos := 0;
Iterator.Last := 0;
while ASF.Components.Base.Has_Element (Iterator.Component) loop
Iterator.Current := ASF.Components.Base.Element (Iterator.Component);
if Iterator.Current.all in UISelectItem'Class then
return;
end if;
if Iterator.Current.all in UISelectItems'Class then
Iterator.List := UISelectItems'Class (Iterator.Current.all)
.Get_Select_Item_List (Context);
Iterator.Last := Iterator.List.Length;
Iterator.Pos := 1;
if Iterator.Last > 0 then
return;
end if;
end if;
ASF.Components.Base.Next (Iterator.Component);
end loop;
Iterator.Pos := 0;
Iterator.Current := null;
end First;
-- ------------------------------
-- Returns True if the iterator points to a valid child.
-- ------------------------------
function Has_Element (Pos : in Cursor) return Boolean is
use type ASF.Components.Base.UIComponent_Access;
begin
if Pos.Pos > 0 and Pos.Pos <= Pos.Last then
return True;
else
return Pos.Current /= null;
end if;
end Has_Element;
-- ------------------------------
-- Get the child component pointed to by the iterator.
-- ------------------------------
function Element (Pos : in Cursor;
Context : in Faces_Context'Class) return ASF.Models.Selects.Select_Item is
begin
if Pos.Pos > 0 and Pos.Pos <= Pos.Last then
return Pos.List.Get_Select_Item (Pos.Pos);
else
return UISelectItem'Class (Pos.Current.all).Get_Select_Item (Context);
end if;
end Element;
-- ------------------------------
-- Move to the next child.
-- ------------------------------
procedure Next (Pos : in out Cursor;
Context : in Faces_Context'Class) is
begin
if Pos.Pos > 0 and Pos.Pos < Pos.Last then
Pos.Pos := Pos.Pos + 1;
else
Pos.Pos := 0;
loop
Pos.Current := null;
ASF.Components.Base.Next (Pos.Component);
exit when not ASF.Components.Base.Has_Element (Pos.Component);
Pos.Current := ASF.Components.Base.Element (Pos.Component);
exit when Pos.Current.all in UISelectItem'Class;
if Pos.Current.all in UISelectItems'Class then
Pos.List := UISelectItems'Class (Pos.Current.all).Get_Select_Item_List (Context);
Pos.Last := Pos.List.Length;
Pos.Pos := 1;
exit when Pos.Last > 0;
Pos.Pos := 0;
end if;
end loop;
end if;
end Next;
-- ------------------------------
-- Get the <b>Select_Item</b> represented by the component.
-- ------------------------------
function Get_Select_Item (From : in UISelectItem;
Context : in Faces_Context'Class)
return ASF.Models.Selects.Select_Item is
use Util.Beans.Objects;
Val : constant Object := From.Get_Attribute (Name => VALUE_NAME,
Context => Context);
begin
if not Is_Null (Val) then
return ASF.Models.Selects.To_Select_Item (Val);
end if;
declare
Label : constant Object := From.Get_Attribute (Name => ITEM_LABEL_NAME,
Context => Context);
Value : constant Object := From.Get_Attribute (Name => ITEM_VALUE_NAME,
Context => Context);
Description : constant Object := From.Get_Attribute (Name => ITEM_DESCRIPTION_NAME,
Context => Context);
Disabled : constant Boolean := From.Get_Attribute (Name => ITEM_DISABLED_NAME,
Context => Context);
begin
if Is_Null (Label) then
return ASF.Models.Selects.Create_Select_Item (Value, Value, Description, Disabled);
else
return ASF.Models.Selects.Create_Select_Item (Label, Value, Description, Disabled);
end if;
end;
end Get_Select_Item;
-- ------------------------------
-- UISelectItems Component
-- ------------------------------
-- ------------------------------
-- Get the <b>Select_Item</b> represented by the component.
-- ------------------------------
function Get_Select_Item_List (From : in UISelectItems;
Context : in Faces_Context'Class)
return ASF.Models.Selects.Select_Item_List is
use Util.Beans.Objects;
Value : constant Object := From.Get_Attribute (Name => VALUE_NAME,
Context => Context);
begin
return ASF.Models.Selects.To_Select_Item_List (Value);
end Get_Select_Item_List;
-- ------------------------------
-- SelectOne Component
-- ------------------------------
-- ------------------------------
-- Render the <b>select</b> element.
-- ------------------------------
overriding
procedure Encode_Begin (UI : in UISelectOne;
Context : in out Faces_Context'Class) is
begin
if UI.Is_Rendered (Context) then
UISelectOne'Class (UI).Render_Select (Context);
end if;
end Encode_Begin;
-- ------------------------------
-- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if
-- the component is rendered.
-- ------------------------------
procedure Render_Select (UI : in UISelectOne;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value;
begin
Writer.Start_Element ("select");
Writer.Write_Attribute (Name => "name", Value => UI.Get_Client_Id);
UI.Render_Attributes (Context, SELECT_ATTRIBUTE_NAMES, Writer);
UISelectOne'Class (UI).Render_Options (Value, Context);
Writer.End_Element ("select");
end Render_Select;
-- ------------------------------
-- Renders the <b>option</b> element. This is called by <b>Render_Select</b> to
-- generate the component options.
-- ------------------------------
procedure Render_Options (UI : in UISelectOne;
Value : in Util.Beans.Objects.Object;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value);
Iter : Cursor;
begin
UI.First (Context, Iter);
while Has_Element (Iter) loop
declare
Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context);
Item_Value : constant Wide_Wide_String := Item.Get_Value;
begin
Writer.Start_Element ("option");
Writer.Write_Wide_Attribute ("value", Item_Value);
if Item_Value = Selected then
Writer.Write_Attribute ("selected", "selected");
end if;
if Item.Is_Escaped then
Writer.Write_Wide_Text (Item.Get_Label);
else
Writer.Write_Wide_Text (Item.Get_Label);
end if;
Writer.End_Element ("option");
Next (Iter, Context);
end;
end loop;
end Render_Options;
-- ------------------------------
-- Returns True if the radio options must be rendered vertically.
-- ------------------------------
function Is_Vertical (UI : in UISelectOneRadio;
Context : in Faces_Context'Class) return Boolean is
Dir : constant String := UI.Get_Attribute (Context => Context,
Name => "layout",
Default => "");
begin
return Dir = "pageDirection";
end Is_Vertical;
-- ------------------------------
-- Renders the <b>select</b> element. This is called by <b>Encode_Begin</b> if
-- the component is rendered.
-- ------------------------------
overriding
procedure Render_Select (UI : in UISelectOneRadio;
Context : in out Faces_Context'Class) is
Writer : constant Response_Writer_Access := Context.Get_Response_Writer;
Value : constant EL.Objects.Object := UISelectOne'Class (UI).Get_Value;
Vertical : constant Boolean := UI.Is_Vertical (Context);
Selected : constant Wide_Wide_String := Util.Beans.Objects.To_Wide_Wide_String (Value);
Iter : Cursor;
Id : constant String := To_String (UI.Get_Client_Id);
N : Natural := 0;
Disabled_Class : constant EL.Objects.Object := UI.Get_Attribute (Context => Context,
Name => "disabledClass");
Enabled_Class : constant EL.Objects.Object := UI.Get_Attribute (Context => Context,
Name => "enabledClass");
begin
Writer.Start_Element ("table");
UI.Render_Attributes (Context, Writer);
if not Vertical then
Writer.Start_Element ("tr");
end if;
UI.First (Context, Iter);
while Has_Element (Iter) loop
declare
Item : constant ASF.Models.Selects.Select_Item := Element (Iter, Context);
Item_Value : constant Wide_Wide_String := Item.Get_Value;
begin
if Vertical then
Writer.Start_Element ("tr");
end if;
Writer.Start_Element ("td");
-- Render the input radio checkbox.
Writer.Start_Element ("input");
Writer.Write_Attribute ("type", "radio");
Writer.Write_Attribute ("name", Id);
if Item.Is_Disabled then
Writer.Write_Attribute ("disabled", "disabled");
end if;
Writer.Write_Attribute ("id", Id & "_" & Util.Strings.Image (N));
Writer.Write_Wide_Attribute ("value", Item_Value);
if Item_Value = Selected then
Writer.Write_Attribute ("checked", "checked");
end if;
Writer.End_Element ("input");
-- Render the label associated with the checkbox.
Writer.Start_Element ("label");
if Item.Is_Disabled then
if not Util.Beans.Objects.Is_Null (Disabled_Class) then
Writer.Write_Attribute ("class", Disabled_Class);
end if;
else
if not Util.Beans.Objects.Is_Null (Enabled_Class) then
Writer.Write_Attribute ("class", Enabled_Class);
end if;
end if;
Writer.Write_Attribute ("for", Id & "_" & Util.Strings.Image (N));
if Item.Is_Escaped then
Writer.Write_Wide_Text (Item.Get_Label);
else
Writer.Write_Wide_Text (Item.Get_Label);
end if;
Writer.End_Element ("label");
Writer.End_Element ("td");
if Vertical then
Writer.End_Element ("tr");
end if;
Next (Iter, Context);
N := N + 1;
end;
end loop;
if not Vertical then
Writer.End_Element ("tr");
end if;
Writer.End_Element ("table");
end Render_Select;
begin
ASF.Utils.Set_Text_Attributes (SELECT_ATTRIBUTE_NAMES);
ASF.Utils.Set_Interactive_Attributes (SELECT_ATTRIBUTE_NAMES);
end ASF.Components.Html.Selects;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with YAML;
use type YAML.Error_Kind;
procedure Parser is
function LStrip (S : String) return String;
function Image (M : YAML.Mark_Type) return String;
procedure Process (P : in out YAML.Parser_Type);
procedure Put (N : YAML.Node_Ref; Indent : Natural);
function LStrip (S : String) return String is
begin
return (if S (S'First) = ' '
then S (S'First + 1 .. S'Last)
else S);
end LStrip;
function Image (M : YAML.Mark_Type) return String is
begin
return LStrip (Natural'Image (M.Line))
& ':' & LStrip (Natural'Image (M.Column));
end Image;
procedure Process (P : in out YAML.Parser_Type) is
D : YAML.Document_Type;
E : YAML.Error_Type;
begin
P.Load (E, D);
if E.Kind /= YAML.No_Error then
Put_Line (YAML.Image (E));
else
Put (D.Root_Node, 0);
end if;
P.Discard_Input;
New_Line;
end Process;
procedure Put (N : YAML.Node_Ref; Indent : Natural) is
Prefix : constant String := (1 .. Indent => ' ');
begin
Put (Prefix
& '[' & Image (N.Start_Mark) & '-' & Image (N.End_Mark) & "]");
case YAML.Kind (N) is
when YAML.No_Node =>
Put_Line (" <null>");
when YAML.Scalar_Node =>
Put_Line (' ' & String (N.Value));
when YAML.Sequence_Node =>
for I in 1 .. N.Length loop
New_Line;
Put_Line (Prefix & "- ");
Put (N.Item (I), Indent + 2);
end loop;
when YAML.Mapping_Node =>
New_Line;
Put_Line (Prefix & "Pairs:");
for I in 1 .. N.Length loop
declare
Pair : constant YAML.Node_Pair := N.Item (I);
begin
Put (Prefix & "Key:");
Put (Pair.Key, Indent + 2);
Put (Prefix & "Value:");
Put (Pair.Value, Indent + 2);
end;
end loop;
end case;
end Put;
P : YAML.Parser_Type;
begin
P.Set_Input_String ("1", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_String ("[1, 2, 3, a, null]", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_String ("foo: 1", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-valid.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-scanner-error-0.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-scanner-error-1.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-parser-error-0.yaml", YAML.UTF8_Encoding);
Process (P);
P.Set_Input_File ("parser-parser-error-1.yaml", YAML.UTF8_Encoding);
Process (P);
end Parser;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Interfaces.C.Extensions;
with Interfaces.C.Strings;
with a_nodes_h;
package lal_adapter_wrapper_h is
function lal_adapter_wrapper
(project_file_name : in Interfaces.C.Strings.chars_ptr;
input_file_name : in Interfaces.C.Strings.chars_ptr;
output_dir_name : in Interfaces.C.Strings.chars_ptr;
process_predefined_units : in Interfaces.C.Extensions.bool;
process_implementation_units : in Interfaces.C.Extensions.bool;
debug : in Interfaces.C.Extensions.bool
)
return a_nodes_h.Nodes_Struct;
pragma Export (C, lal_adapter_wrapper);
private
-- for debugging:
Module_Name : constant String := "lal_adapter_wrapper_h";
end lal_adapter_wrapper_h;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
package body Program.Nodes.Null_Statements is
function Create
(Null_Token : not null Program.Lexical_Elements
.Lexical_Element_Access;
Semicolon_Token : not null Program.Lexical_Elements
.Lexical_Element_Access)
return Null_Statement is
begin
return Result : Null_Statement :=
(Null_Token => Null_Token, Semicolon_Token => Semicolon_Token,
Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
function Create
(Is_Part_Of_Implicit : Boolean := False;
Is_Part_Of_Inherited : Boolean := False;
Is_Part_Of_Instance : Boolean := False)
return Implicit_Null_Statement is
begin
return Result : Implicit_Null_Statement :=
(Is_Part_Of_Implicit => Is_Part_Of_Implicit,
Is_Part_Of_Inherited => Is_Part_Of_Inherited,
Is_Part_Of_Instance => Is_Part_Of_Instance, Enclosing_Element => null)
do
Initialize (Result);
end return;
end Create;
overriding function Null_Token
(Self : Null_Statement)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Null_Token;
end Null_Token;
overriding function Semicolon_Token
(Self : Null_Statement)
return not null Program.Lexical_Elements.Lexical_Element_Access is
begin
return Self.Semicolon_Token;
end Semicolon_Token;
overriding function Is_Part_Of_Implicit
(Self : Implicit_Null_Statement)
return Boolean is
begin
return Self.Is_Part_Of_Implicit;
end Is_Part_Of_Implicit;
overriding function Is_Part_Of_Inherited
(Self : Implicit_Null_Statement)
return Boolean is
begin
return Self.Is_Part_Of_Inherited;
end Is_Part_Of_Inherited;
overriding function Is_Part_Of_Instance
(Self : Implicit_Null_Statement)
return Boolean is
begin
return Self.Is_Part_Of_Instance;
end Is_Part_Of_Instance;
procedure Initialize (Self : aliased in out Base_Null_Statement'Class) is
begin
null;
end Initialize;
overriding function Is_Null_Statement_Element
(Self : Base_Null_Statement)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Null_Statement_Element;
overriding function Is_Statement_Element
(Self : Base_Null_Statement)
return Boolean is
pragma Unreferenced (Self);
begin
return True;
end Is_Statement_Element;
overriding procedure Visit
(Self : not null access Base_Null_Statement;
Visitor : in out Program.Element_Visitors.Element_Visitor'Class) is
begin
Visitor.Null_Statement (Self);
end Visit;
overriding function To_Null_Statement_Text
(Self : aliased in out Null_Statement)
return Program.Elements.Null_Statements.Null_Statement_Text_Access is
begin
return Self'Unchecked_Access;
end To_Null_Statement_Text;
overriding function To_Null_Statement_Text
(Self : aliased in out Implicit_Null_Statement)
return Program.Elements.Null_Statements.Null_Statement_Text_Access is
pragma Unreferenced (Self);
begin
return null;
end To_Null_Statement_Text;
end Program.Nodes.Null_Statements;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Ada.Containers.Hashed_Maps;
with Util.Strings;
package Babel.Files.Maps is
-- Babel.Base.Get_File_Map (Directory, File_Map);
-- Babel.Base.Get_Directory_Map (Directory, Dir_Map);
-- File_Map.Find (New_File);
-- Dir_Map.Find (New_File);
-- Hash string -> File
package File_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access,
Element_Type => File_Type,
Hash => Util.Strings.Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys,
"=" => "=");
subtype File_Map is File_Maps.Map;
subtype File_Cursor is File_Maps.Cursor;
-- Find the file with the given name in the file map.
function Find (From : in File_Map;
Name : in String) return File_Cursor;
-- Find the file with the given name in the file map.
function Find (From : in File_Map;
Name : in String) return File_Type;
-- Insert the file in the file map.
procedure Insert (Into : in out File_Map;
File : in File_Type);
-- Hash string -> Directory
package Directory_Maps is new
Ada.Containers.Hashed_Maps (Key_Type => Util.Strings.Name_Access,
Element_Type => Directory_Type,
Hash => Util.Strings.Hash,
Equivalent_Keys => Util.Strings.Equivalent_Keys,
"=" => "=");
subtype Directory_Map is Directory_Maps.Map;
subtype Directory_Cursor is Directory_Maps.Cursor;
-- Find the directory with the given name in the directory map.
function Find (From : in Directory_Map;
Name : in String) return Directory_Cursor;
-- Find the directory with the given name in the directory map.
function Find (From : in Directory_Map;
Name : in String) return Directory_Type;
procedure Add_File (Dirs : in out Directory_Map;
Files : in out File_Map;
Path : in String;
File : out File_Type);
type Differential_Container is new Babel.Files.Default_Container with private;
-- Add the file with the given name in the container.
overriding
procedure Add_File (Into : in out Differential_Container;
Element : in File_Type);
-- Add the directory with the given name in the container.
overriding
procedure Add_Directory (Into : in out Differential_Container;
Element : in Directory_Type);
-- Create a new file instance with the given name in the container.
overriding
function Create (Into : in Differential_Container;
Name : in String) return File_Type;
-- Create a new directory instance with the given name in the container.
overriding
function Create (Into : in Differential_Container;
Name : in String) return Directory_Type;
-- Find the file with the given name in this file container.
-- Returns NO_FILE if the file was not found.
overriding
function Find (From : in Differential_Container;
Name : in String) return File_Type;
-- Find the directory with the given name in this file container.
-- Returns NO_DIRECTORY if the directory was not found.
overriding
function Find (From : in Differential_Container;
Name : in String) return Directory_Type;
-- Set the directory object associated with the container.
overriding
procedure Set_Directory (Into : in out Differential_Container;
Directory : in Directory_Type);
-- Prepare the differential container by setting up the known files and known
-- directories. The <tt>Update</tt> procedure is called to give access to the
-- maps that can be updated.
procedure Prepare (Container : in out Differential_Container;
Update : access procedure (Files : in out File_Map;
Dirs : in out Directory_Map));
private
type Differential_Container is new Babel.Files.Default_Container with record
Known_Files : File_Map;
Known_Dirs : Directory_Map;
end record;
end Babel.Files.Maps;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
--
with ewok.tasks; use ewok.tasks;
with ewok.tasks_shared; use ewok.tasks_shared;
with ewok.perm; use ewok.perm;
with ewok.debug;
with m4.scb;
package body ewok.syscalls.reset
with spark_mode => off
is
procedure sys_reset
(caller_id : in ewok.tasks_shared.t_task_id;
mode : in ewok.tasks_shared.t_task_mode)
is
begin
if not ewok.perm.ressource_is_granted (PERM_RES_TSK_RESET, caller_id)
then
set_return_value (caller_id, mode, SYS_E_DENIED);
ewok.tasks.set_state (caller_id, mode, TASK_STATE_RUNNABLE);
return;
end if;
m4.scb.reset;
debug.panic ("soc.nvic.reset failed !?!");
end sys_reset;
end ewok.syscalls.reset;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with DDS.Request_Reply.Tests.Simple.Octets_Replier;
with DDS.Request_Reply.Tests.Simple.String_Replier;
with DDS.Request_Reply.Replier.Typed_Replier_Generic.Passive_Replier_Generic;
package DDS.Request_Reply.Tests.Simple.Server is
type Ref_Base is limited interface;
package Octets_Srv is new Octets_Replier.Passive_Replier_Generic (Ref_Base);
package String_Srv is new String_Replier.Passive_Replier_Generic (Octets_Srv.Listners.Ref);
task type Ref2 is new String_Srv.Listners.Ref with
entry Compute_And_Reply (Replier : Octets_Replier.Ref_Access;
Data : DDS.Octets;
Id : DDS.SampleIdentity_T);
entry Compute_And_Reply (Replier : String_Replier.Ref_Access;
Data : DDS.String;
Id : DDS.SampleIdentity_T);
end Ref2;
type Ref is new String_Srv.Listners.Ref with null record;
procedure Compute_And_Reply (Self : not null access Ref;
Replier : Octets_Replier.Ref_Access;
Data : DDS.Octets;
Id : DDS.SampleIdentity_T);
procedure Compute_And_Reply (Self : not null access Ref;
Replier : String_Replier.Ref_Access;
Data : DDS.String;
Id : DDS.SampleIdentity_T);
end DDS.Request_Reply.Tests.Simple.Server;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- *
-- * This file is subject to the Apple OS-Developed Software exception.
--
function pwgFormatSizeName
(keyword : Interfaces.C.Strings.chars_ptr;
keysize : size_t;
prefix : Interfaces.C.Strings.chars_ptr;
name : Interfaces.C.Strings.chars_ptr;
width : int;
length : int;
units : Interfaces.C.Strings.chars_ptr) return int; -- cups/pwg.h:75
pragma Import (C, pwgFormatSizeName, "pwgFormatSizeName");
function pwgInitSize
(size : access pwg_size_t;
job : System.Address;
margins_set : access int) return int; -- cups/pwg.h:79
pragma Import (C, pwgInitSize, "pwgInitSize");
function pwgMediaForLegacy (legacy : Interfaces.C.Strings.chars_ptr) return access pwg_media_t; -- cups/pwg.h:81
pragma Import (C, pwgMediaForLegacy, "pwgMediaForLegacy");
function pwgMediaForPPD (ppd : Interfaces.C.Strings.chars_ptr) return access pwg_media_t; -- cups/pwg.h:82
pragma Import (C, pwgMediaForPPD, "pwgMediaForPPD");
function pwgMediaForPWG (pwg : Interfaces.C.Strings.chars_ptr) return access pwg_media_t; -- cups/pwg.h:83
pragma Import (C, pwgMediaForPWG, "pwgMediaForPWG");
function pwgMediaForSize (width : int; length : int) return access pwg_media_t; -- cups/pwg.h:84
pragma Import (C, pwgMediaForSize, "pwgMediaForSize");
end CUPS.cups_pwg_h;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--*
-- MAIN PROGRAM REQUIRING A SEPARATELY COMPILED PACKAGE
-- ( C83F01C0 ; SPECIFICATION IN C83F01C0.ADA ,
-- BODY IN C83F01C1.ADA )
-- CHECK THAT INSIDE A PACKAGE BODY NESTED WITHIN A SEPARATELY COMPILED
-- PACKAGE BODY AN ATTEMPT TO REFERENCE AN IDENTIFIER DECLARED IN THE
-- CORRESPONDING PACKAGE SPECIFICATION
-- IS SUCCESSFUL EVEN IF THE SAME IDENTIFIER IS DECLARED IN THE
-- OUTER PACKAGE (SPECIFICATION OR BODY).
-- CASE 1: PACKAGE IS A FULL-FLEDGED COMPILATION UNIT
-- RM 11 AUGUST 1980
-- RM 22 AUGUST 1980
-- RM 29 AUGUST 1980 (MOVED 'FAILED(.)' FROM C83F01C1.ADA TO HERE)
WITH REPORT , C83F01C0 ;
PROCEDURE C83F01C2M IS
USE REPORT , C83F01C0 ;
BEGIN
TEST( "C83F01C" , "CHECK THAT INSIDE A PACKAGE BODY" &
" NESTED WITHIN A SEPARATELY" &
" COMPILED PACKAGE BODY LIBRARY UNIT," &
" AN ATTEMPT TO REFERENCE AN IDENTIFIER" &
" DECLARED IN THE CORRESPONDING PACKAGE SPECI" &
"FICATION IS SUCCESSFUL EVEN IF THE SAME IDEN" &
"TIFIER IS DECLARED IN THE OUTER PACKAGE" &
" (SPECIFICATION OR BODY)" ) ;
IF NOT P.X1 OR
P.Z /= 13 OR
P.Y2 /= 55 OR
P.Y4 /= 55
THEN FAILED( "INCORRECT ACCESSING" );
END IF;
RESULT ;
END C83F01C2M;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with DDS.DataReader;
with DDS.DataWriter;
with DDS.Publisher;
with DDS.Subscriber;
with DDS.TopicDescription;
with Interfaces.C.Extensions;
with DDS.DomainParticipant;
with DDS.Treats_Generic;
with DDS.Request_Reply.Connext_C_Entity_Params;
with DDS;
with DDS.DataReaderListener;
with Interfaces.C.Extensions;
with Ada.Finalization;
with DDS.Request_Reply.Untypedcommon;
package DDS.Request_Reply.Connext_C_Replier is
use Connext_C_Entity_Params;
type RTI_Connext_ReplierUntypedImpl is abstract new Untypedcommon.RTI_Connext_EntityUntypedImpl with null Record;
type RTI_Connext_ReplierUntypedImpl_Access is access all RTI_Connext_ReplierUntypedImpl'Class;
type RTI_Connext_Replier is tagged;
type RTI_Connext_Replier_Access is access RTI_Connext_Replier'Class;
type RTI_Connext_ReplierListener is tagged;
type RTI_Connext_ReplierListener_Access is access RTI_Connext_ReplierListener'Class;
type RTI_Connext_SimpleReplierListener is interface;
type RTI_Connext_SimpleReplierListener_Access is access all RTI_Connext_SimpleReplierListener'Class;
procedure On_Request_Available (Self : RTI_Connext_SimpleReplierListener;
Request : Interfaces.C.Extensions.Void_Ptr;
Replier : not null access RTI_Connext_Replier) is abstract;
procedure (Self : RTI_Connext_SimpleReplierListener;
Requreplyest : Interfaces.C.Extensions.Void_Ptr) is abstract;
function RTI_Connext_ReplierUntypedImpl_Initialize
(Self : RTI_Connext_ReplierUntypedImpl;
Params : RTI_Connext_EntityParams;
Request_Type_Name : DDS.String;
Reply_Type_Name : DDS.String;
Request_Size : DDS.Integer;
Reader_Listener : DDS.DataReaderListener.Ref_Access)
return DDS.ReturnCode_T;
function RTI_Connext_ReplierUntypedImpl_Send_Sample
(Self : RTI_Connext_ReplierUntypedImpl;
Data : Interfaces.C.Extensions.Void_Ptr;
Related_Request_Info : DDS.SampleIdentity_T;
WriteParams : DDS.WriteParams_T) return DDS.ReturnCode_T;
type RTI_Connext_Replier is abstract new RTI_Connext_ReplierUntypedImpl with record
Listener : RTI_Connext_ReplierListener_Access;
SimpleListener : RTI_Connext_SimpleReplierListener;
end record;
type RTI_Connext_Replier_Access is access RTI_Connext_Replier'Class;
function Create_Writer_Topic
(Self : access RTI_Connext_Replier;
Params : access RTI_Connext_EntityParams;
Name : DDS.String) return DDS.TopicDescription.Ref_Access;
type RTI_Connext_ReplierListener_OnRequestAvailableCallback is access
procedure (Self : RTI_Connext_ReplierListener;
Replier : not null RTI_Connext_Replier_Access);
type RTI_Connext_ReplierListener is interface;
procedure On_Request_Available (Self : not null access RTI_Connext_ReplierListener;
Replier : not null access RTI_Connext_Replier'Class) is abstract;
type RTI_Connext_ReplierParams is new Ada.Finalization.Limited_Controlled with record
Participant : DDS.DomainParticipant.Ref_Access;
Service_Name : DDS.String;
Request_Topic_Name : DDS.String;
Reply_Topic_Name : DDS.String;
Qos_Library_Name : DDS.String;
Qos_Profile_Name : DDS.String;
Datawriter_Qos : DDS.DataWriterQos;
Datareader_Qos : DDS.DataReaderQos;
Publisher : DDS.Publisher.Ref_Access;
Subscriber : DDS.Subscriber.Ref_Access;
Listener : RTI_Connext_ReplierListener_Access;
end record;
procedure Initialize (Object : in out RTI_Connext_ReplierParams) is null;
procedure Finalize (Object : in out RTI_Connext_ReplierParams) is null;
function RTI_Connext_Replier_Delete (Self : RTI_Connext_Replier_Access) return DDS.ReturnCode_T;
function RTI_Connext_Replier_Wait_For_Requests (Self : access RTI_Connext_Replier;
Min_Count : DDS.Integer;
Max_Wait : DDS.Duration_T) return DDS.ReturnCode_T;
function RTI_Connext_ReplierUntypedImpl_Create return RTI_Connext_ReplierUntypedImpl_Access;
function RTI_Connext_ReplierParams_toEntityParams
(Self : not null access RTI_Connext_ReplierParams;
ToParams : out RTI_Connext_EntityParams) return DDS.ReturnCode_T;
end DDS.Request_Reply.Connext_C_Replier;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Characters.Handling;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Interfaces.C;
with Interfaces.C.Strings; use Interfaces.C.Strings;
with Tashy2; use Tashy2;
with Tcl.Variables; use Tcl.Variables;
package body Tcl is
--## rule off GLOBAL_REFERENCES
-- ****iv* Tcl/Tcl.Default_Interpreter
-- FUNCTION Pointer to the default Tcl interpreter
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
Default_Interpreter: Tcl_Interpreter := Null_Interpreter;
-- ****
--## rule on GLOBAL_REFERENCES
procedure Set_Interpreter(Interpreter: Tcl_Interpreter) is
begin
if Interpreter = Null_Interpreter then
return;
end if;
Default_Interpreter := Interpreter;
end Set_Interpreter;
function Get_Interpreter return Tcl_Interpreter is
begin
return Default_Interpreter;
end Get_Interpreter;
function Tcl_Init(Interpreter: Tcl_Interpreter) return Boolean is
function Native_Tcl_Init(Interp: Tcl_Interpreter) return Tcl_Results with
Global => null,
Import,
Convention => C,
External_Name => "Tcl_Init";
begin
if Native_Tcl_Init(Interp => Interpreter) = TCL_ERROR then
return False;
end if;
return True;
end Tcl_Init;
-- ****if* Tcl/Tcl.Native_Tcl_Eval
-- FUNCTION
-- Binding to C function Tcl_Eval, evalutate the selected Tcl script
-- PARAMETERS
-- Interp - Tcl interpreter on which the Tcl script will be evaluated
-- Script - Tcl script to evaluate
-- RESULT
-- Tcl_Results value
-- HISTORY
-- 8.6.0 - Added
-- SOURCE
function Native_Tcl_Eval
(Interp: Tcl_Interpreter; Script: chars_ptr) return Tcl_Results with
Global => null,
Import,
Convention => C,
External_Name => "Tcl_Eval";
-- ****
procedure Tcl_Eval
(Tcl_Script: String; Interpreter: Tcl_Interpreter := Get_Interpreter) is
begin
if Native_Tcl_Eval
(Interp => Interpreter, Script => To_C_String(Str => Tcl_Script)) =
TCL_ERROR then
return;
end if;
end Tcl_Eval;
function Tcl_Eval
(Tcl_Script: String; Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tcl_String_Result is
Message: Unbounded_String := Null_Unbounded_String;
Result_Code: constant Tcl_Results :=
Native_Tcl_Eval
(Interp => Interpreter, Script => To_C_String(Str => Tcl_Script));
Result_String: constant String :=
Tcl_Get_Result(Interpreter => Interpreter);
begin
if Result_Code = TCL_ERROR then
Message :=
To_Unbounded_String
(Source =>
Tcl_Get_Var
(Var_Name => "errorInfo", Interpreter => Interpreter));
end if;
Return_Result_Block :
declare
Message_Length: constant Natural := Length(Source => Message);
Result: constant Tcl_String_Result
(Message_Length => Message_Length,
Result_Length => Result_String'Length) :=
(Message_Length => Message_Length,
Result_Length => Result_String'Length, Return_Code => Result_Code,
Result => Result_String, Message => To_String(Source => Message));
begin
return Result;
end Return_Result_Block;
end Tcl_Eval;
function Tcl_Eval
(Tcl_Script: String; Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tcl_Boolean_Result is
Message: Unbounded_String := Null_Unbounded_String;
Result_Code: constant Tcl_Results :=
Native_Tcl_Eval
(Interp => Interpreter, Script => To_C_String(Str => Tcl_Script));
begin
if Result_Code = TCL_ERROR then
Message :=
To_Unbounded_String
(Source =>
Tcl_Get_Var
(Var_Name => "errorInfo", Interpreter => Interpreter));
end if;
Return_Result_Block :
declare
Message_Length: constant Natural := Length(Source => Message);
Result: constant Tcl_Boolean_Result
(Message_Length => Message_Length) :=
(Message_Length => Message_Length, Return_Code => Result_Code,
Result =>
(if
Tcl_Get_Result(Interpreter => Interpreter) in "1" | "true" |
"on" | "yes"
then True
else False),
Message => To_String(Source => Message));
begin
return Result;
end Return_Result_Block;
end Tcl_Eval;
function Tcl_Eval
(Tcl_Script: String; Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tcl_Integer_Result is
Message: Unbounded_String := Null_Unbounded_String;
Result_Code: constant Tcl_Results :=
Native_Tcl_Eval
(Interp => Interpreter, Script => To_C_String(Str => Tcl_Script));
begin
if Result_Code = TCL_ERROR then
Message :=
To_Unbounded_String
(Source =>
Tcl_Get_Var
(Var_Name => "errorInfo", Interpreter => Interpreter));
end if;
Return_Result_Block :
declare
Message_Length: constant Natural := Length(Source => Message);
Result: constant Tcl_Integer_Result
(Message_Length => Message_Length) :=
(Message_Length => Message_Length, Return_Code => Result_Code,
Result => Tcl_Get_Result(Interpreter => Interpreter),
Message => To_String(Source => Message));
begin
return Result;
end Return_Result_Block;
end Tcl_Eval;
function Tcl_Eval
(Tcl_Script: String; Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tcl_Float_Result is
Message: Unbounded_String := Null_Unbounded_String;
Result_Code: constant Tcl_Results :=
Native_Tcl_Eval
(Interp => Interpreter, Script => To_C_String(Str => Tcl_Script));
begin
if Result_Code = TCL_ERROR then
Message :=
To_Unbounded_String
(Source =>
Tcl_Get_Var
(Var_Name => "errorInfo", Interpreter => Interpreter));
end if;
Return_Result_Block :
declare
Message_Length: constant Natural := Length(Source => Message);
Result: constant Tcl_Float_Result
(Message_Length => Message_Length) :=
(Message_Length => Message_Length, Return_Code => Result_Code,
Result => Tcl_Get_Result(Interpreter => Interpreter),
Message => To_String(Source => Message));
begin
return Result;
end Return_Result_Block;
end Tcl_Eval;
function Tcl_Eval_File
(File_Name: String; Interpreter: Tcl_Interpreter := Get_Interpreter)
return Tcl_Results is
function Native_Tcl_Eval_File
(Interp: Tcl_Interpreter; File: chars_ptr) return Tcl_Results with
Global => null,
Import,
Convention => C,
External_Name => "Tcl_EvalFile";
begin
return
Native_Tcl_Eval_File
(Interp => Interpreter, File => To_C_String(Str => File_Name));
end Tcl_Eval_File;
function Tcl_Get_Result
(Interpreter: Tcl_Interpreter := Get_Interpreter) return String is
function Tcl_Get_String_Result
(Interp: Tcl_Interpreter) return chars_ptr with
Global => null,
Import,
Convention => C,
External_Name => "Tcl_GetStringResult";
begin
return
From_C_String(Item => Tcl_Get_String_Result(Interp => Interpreter));
end Tcl_Get_Result;
function Tcl_Get_Result
(Interpreter: Tcl_Interpreter := Get_Interpreter) return Integer is
use Ada.Characters.Handling;
Result: constant String := Tcl_Get_Result(Interpreter => Interpreter);
Value: Integer := 0;
begin
if Result = "" then
return 0;
end if;
if Result'Length > Integer'Width then
return 0;
end if;
Check_Characters_Loop :
for I in reverse Result'Range loop
if I = Result'First and Result(I) = '-' then
Value := -(Value);
end if;
exit Check_Characters_Loop when Value < 0;
if Is_Digit(Item => Result(I)) then
if Value + (Integer'Value("" & Result(I)) * (10**(Result'Last - I))) >
Integer'Last then
return 0;
end if;
Value :=
Value + (Integer'Value("" & Result(I)) * (10**(Result'Last - I)));
else
return 0;
end if;
end loop Check_Characters_Loop;
return Value;
end Tcl_Get_Result;
procedure Tcl_Set_Result
(Tcl_Result: String; Result_Type: Result_Types := Default_Result_Type;
Interpreter: Tcl_Interpreter := Get_Interpreter) is
use Interfaces.C;
procedure Native_Tcl_Set_Result
(Interp: Tcl_Interpreter; Result: chars_ptr; Free_Proc: int) with
Global => null,
Import,
Convention => C,
External_Name => "Tcl_SetResult";
begin
Native_Tcl_Set_Result
(Interp => Interpreter, Result => To_C_String(Str => Tcl_Result),
Free_Proc => Result_Types'Enum_Rep(Result_Type));
end Tcl_Set_Result;
procedure Tcl_Update
(Interpreter: Tcl_Interpreter := Get_Interpreter;
Idle_Tasks_Only: Boolean := False) is
begin
Tcl_Eval
(Tcl_Script =>
"update" & (if Idle_Tasks_Only then " idletasks" else ""),
Interpreter => Interpreter);
end Tcl_Update;
end Tcl;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO;
--------------------------------------------------------------------------------
-- Image subprograms for binary (i.e. information technology related) values.
--------------------------------------------------------------------------------
package SI_Units.Binary is
type Prefixes is (None, kibi, mebi, gibi, tebi, pebi, exbi, zebi, yobi);
-- Prefixes supported in instantiated Image subprograms.
Magnitude : constant := 1024.0;
-- Magnitude change when trying to find the best representation for a given
-- value.
-- As this is intended for binary values (i.e. kibiBytes etc.), we neither
-- support negative nor non-integral values.
--
-- TODO: We could support non-modular integral types, though.
generic
type Item is mod <>;
Default_Aft : in Ada.Text_IO.Field;
Unit : in Unit_Name;
function Image
(Value : in Item;
Aft : in Ada.Text_IO.Field := Default_Aft) return String with
Global => null;
-- Image function for modular types.
--
-- Parameters:
--
-- Item - the type you want an Image function instantiated for.
-- Default_Aft - the default number of digits after the decimal point
-- (regardless of the prefix finally used).
-- Unit - The name of your unit, e.g. "Bytes", "Bit/s" or such.
end SI_Units.Binary;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Profile (No_Implementation_Extensions);
with Ada.Unchecked_Deallocation;
package body Basic_Counters is
function Make_New_Counter return Counter_Ptr is
(new Counter'(SP_Count => 1,
WP_Count => 0
)
);
procedure Deallocate_Counter is new Ada.Unchecked_Deallocation
(Object => Counter,
Name => Counter_Ptr);
procedure Deallocate_If_Unused (C : in out Counter_Ptr) is
begin
if C.SP_Count = 0 and C.WP_Count = 0 then
Deallocate_Counter(C);
end if;
end Deallocate_If_Unused;
procedure Check_Increment_Use_Count (C : in out Counter) is
begin
if C.SP_Count > 0 then
C.SP_Count := C.SP_Count + 1;
end if;
end Check_Increment_Use_Count;
procedure Decrement_Use_Count (C : in out Counter) is
begin
C.SP_Count := C.SP_Count - 1;
end Decrement_Use_Count;
procedure Increment_Weak_Ptr_Count (C : in out Counter) is
begin
C.WP_Count := C.WP_Count + 1;
end Increment_Weak_Ptr_Count;
procedure Decrement_Weak_Ptr_Count (C : in out Counter) is
begin
C.WP_Count := C.WP_Count - 1;
end Decrement_Weak_Ptr_Count;
end Basic_Counters;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body Set_Cons is
function "+"(E: Element) return Set is
S: Set := (others => False);
begin
S(E) := True;
return S;
end "+";
function "+"(Left, Right: Element) return Set is
begin
return (+Left) + Right;
end "+";
function "+"(Left: Set; Right: Element) return Set is
S: Set := Left;
begin
S(Right) := True;
return S;
end "+";
function "-"(Left: Set; Right: Element) return Set is
S: Set := Left;
begin
S(Right) := False;
return S;
end "-";
function Nonempty_Intersection(Left, Right: Set) return Boolean is
begin
for E in Element'Range loop
if Left(E) and then Right(E) then return True;
end if;
end loop;
return False;
end Nonempty_Intersection;
function Union(Left, Right: Set) return Set is
S: Set := Left;
begin
for E in Right'Range loop
if Right(E) then S(E) := True;
end if;
end loop;
return S;
end Union;
function Image(S: Set) return String is
function Image(S: Set; Found: Natural) return String is
begin
for E in S'Range loop
if S(E) then
if Found = 0 then
return Image(E) & Image((S-E), Found+1);
else
return "," & Image(E) & Image((S-E), Found+1);
end if;
end if;
end loop;
return "";
end Image;
begin
return "{" & Image(S, 0) & "}";
end Image;
function Image(V: Set_Vec) return String is
begin
if V'Length = 0 then
return "";
else
return Image(V(V'First)) & Image(V(V'First+1 .. V'Last));
end if;
end Image;
end Set_Cons;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Profile (No_Implementation_Extensions);
with Ada.Unchecked_Conversion;
package body KVFlyweights.Refcounted_Ptrs is
type Access_Value is access all Value;
function Access_Value_To_Value_Access is
new Ada.Unchecked_Conversion(Source => Access_Value,
Target => Value_Access);
subtype Hash_Type is Ada.Containers.Hash_Type;
use type Ada.Containers.Hash_Type;
--------------------------
-- Refcounted_Value_Ptr --
--------------------------
function P (P : Refcounted_Value_Ptr) return V_Ref is
(V_Ref'(V => P.V));
function Get (P : Refcounted_Value_Ptr) return Value_Access is
(P.V);
function Make_Ref (P : Refcounted_Value_Ptr'Class)
return Refcounted_Value_Ref is
begin
KVFlyweight_Hashtables.Increment(F => P.Containing_KVFlyweight.all,
Bucket => P.Containing_Bucket,
Key_Ptr => P.K);
return Refcounted_Value_Ref'(Ada.Finalization.Controlled
with V => P.V,
K => P.K,
Containing_KVFlyweight => P.Containing_KVFlyweight,
Containing_Bucket => P.Containing_Bucket);
end Make_Ref;
function Insert_Ptr (F : aliased in out KVFlyweight_Hashtables.KVFlyweight;
K : in Key) return Refcounted_Value_Ptr is
Bucket : Hash_Type;
Key_Ptr : Key_Access;
Value_Ptr : Value_Access;
begin
KVFlyweight_Hashtables.Insert (F => F,
Bucket => Bucket,
K => K,
Key_Ptr => Key_Ptr,
Value_Ptr => Value_Ptr);
return Refcounted_Value_Ptr'(Ada.Finalization.Controlled
with V => Value_Ptr,
K => Key_Ptr,
Containing_KVFlyweight => F'Access,
Containing_Bucket => Bucket);
end Insert_Ptr;
overriding procedure Adjust (Object : in out Refcounted_Value_Ptr) is
begin
if Object.V /= null and Object.Containing_KVFlyweight /= null then
KVFlyweight_Hashtables.Increment(F => Object.Containing_KVFlyweight.all,
Bucket => Object.Containing_Bucket,
Key_Ptr => Object.K);
end if;
end Adjust;
overriding procedure Finalize (Object : in out Refcounted_Value_Ptr) is
begin
if Object.V /= null and Object.Containing_KVFlyweight /= null then
KVFlyweight_Hashtables.Remove(F => Object.Containing_KVFlyweight.all,
Bucket => Object.Containing_Bucket,
Key_Ptr => Object.K);
Object.Containing_KVFlyweight := null;
end if;
end Finalize;
--------------------------
-- Refcounted_Value_Ref --
--------------------------
function Make_Ptr (R : Refcounted_Value_Ref'Class)
return Refcounted_Value_Ptr is
begin
KVFlyweight_Hashtables.Increment(F => R.Containing_KVFlyweight.all,
Bucket => R.Containing_Bucket,
Key_Ptr => R.K);
return Refcounted_Value_Ptr'(Ada.Finalization.Controlled
with V => Access_Value_To_Value_Access(R.V),
K => R.K,
Containing_KVFlyweight => R.Containing_KVFlyweight,
Containing_Bucket => R.Containing_Bucket);
end Make_Ptr;
function Get (P : Refcounted_Value_Ref) return Value_Access is
(Access_Value_To_Value_Access(P.V));
function Insert_Ref (F : aliased in out KVFlyweight_Hashtables.KVFlyweight;
K : in Key) return Refcounted_Value_Ref is
Bucket : Hash_Type;
Key_Ptr : Key_Access;
Value_Ptr : Value_Access;
begin
KVFlyweight_Hashtables.Insert (F => F,
Bucket => Bucket,
K => K,
Key_Ptr => Key_Ptr,
Value_Ptr => Value_Ptr);
return Refcounted_Value_Ref'(Ada.Finalization.Controlled
with V => Value_Ptr,
K => Key_Ptr,
Containing_KVFlyweight => F'Access,
Containing_Bucket => Bucket);
end Insert_Ref;
overriding procedure Initialize (Object : in out Refcounted_Value_Ref) is
begin
raise Program_Error
with "Refcounted_Value_Ref should not be created outside the package";
end Initialize;
overriding procedure Adjust (Object : in out Refcounted_Value_Ref) is
begin
if Object.Containing_KVFlyweight /= null then
KVFlyweight_Hashtables.Increment(F => Object.Containing_KVFlyweight.all,
Bucket => Object.Containing_Bucket,
Key_Ptr => Object.K);
end if;
end Adjust;
overriding procedure Finalize (Object : in out Refcounted_Value_Ref) is
begin
if Object.Containing_KVFlyweight /= null then
KVFlyweight_Hashtables.Remove(F => Object.Containing_KVFlyweight.all,
Bucket => Object.Containing_Bucket,
Key_Ptr => Object.K);
Object.Containing_KVFlyweight := null;
end if;
end Finalize;
end KVFlyweights.Refcounted_Ptrs;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with STM32.Device;
-- @summary
-- Target-specific mapping for HIL of Clock
package body HIL.Clock with
SPARK_Mode => Off
is
procedure configure is
begin
-- GPIOs
STM32.Device.Enable_Clock(STM32.Device.GPIO_A );
STM32.Device.Enable_Clock(STM32.Device.GPIO_B);
STM32.Device.Enable_Clock(STM32.Device.GPIO_C);
STM32.Device.Enable_Clock(STM32.Device.GPIO_D);
STM32.Device.Enable_Clock(STM32.Device.GPIO_E);
-- SPI
STM32.Device.Enable_Clock(STM32.Device.SPI_2);
-- I2C
--STM32.Device.Enable_Clock( STM32.Device.I2C_1 ); -- I2C
-- USARTs
-- STM32.Device.Enable_Clock( STM32.Device.USART_1 );
-- STM32.Device.Enable_Clock( STM32.Device.USART_2 );
-- STM32.Device.Enable_Clock( STM32.Device.USART_3 );
-- STM32.Device.Enable_Clock( STM32.Device.UART_4 );
STM32.Device.Enable_Clock( STM32.Device.USART_7 );
-- Timers
-- STM32.Device.Enable_Clock (STM32.Device.Timer_2);
-- STM32.Device.Reset (STM32.Device.Timer_2);
end configure;
-- get number of systicks since POR
function getSysTick return Natural is
begin
null;
return 0;
end getSysTick;
-- get system time since POR
function getSysTime return Ada.Real_Time.Time is
begin
return Ada.Real_Time.Clock;
end getSysTime;
end HIL.Clock;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--
with Text_IO, File_Names;
use Text_IO, File_Names;
with String_Pkg; use String_Pkg;
package body Parse_Template_File is
SCCS_ID : constant String := "@(#) parse_template_file.ada, Version 1.2";
Rcs_ID : constant String := "$Header: /cf/ua/arcadia/alex-ayacc/ayacc/src/RCS/parse_template_file.a,v 1.1 88/08/08 14:20:23 arcadia Exp $";
File_Pointer : Natural := 0;
type File_Data is array (Positive range <>) of String_Type;
-- Verdix 5.2 Compiler Bug will not accept aggregate size as implied constraint
-->> YYParse_Template_File : File_Data :=
-- Verdix 5.2 Compiler Bug
YYParse_Template_File : constant File_Data :=
( -- Start of File Contents
Create ("procedure YYParse is"),
Create (""),
Create (" -- Rename User Defined Packages to Internal Names."),
Create ("%%"),
Create (""),
Create (" use yy_tokens, yy_goto_tables, yy_shift_reduce_tables;"),
Create (""),
Create (" procedure yyerrok;"),
Create (" procedure yyclearin;"),
Create (""),
Create ("-- UMASS CODES :"),
Create ("-- One of the extension of ayacc. Used for"),
Create ("-- error recovery and error reporting."),
Create (""),
Create (" package yyparser_input is"),
Create (" --"),
Create (" -- TITLE"),
Create (" -- yyparser input."),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- In Ayacc, parser get the input directly from lexical scanner."),
Create (" -- In the extension, we have more power in error recovery which will"),
Create (" -- try to replace, delete or insert a token into the input"),
Create (" -- stream. Since general lexical scanner does not support"),
Create (" -- replace, delete or insert a token, we must maintain our"),
Create (" -- own input stream to support these functions. It is the"),
Create (" -- purpose that we introduce yyparser_input. So parser no"),
Create (" -- longer interacts with lexical scanner, instead, parser"),
Create (" -- will get the input from yyparser_input. Yyparser_Input"),
Create (" -- get the input from lexical scanner and supports"),
Create (" -- replacing, deleting and inserting tokens."),
Create (" --"),
Create (""),
Create (" type string_ptr is access string;"),
Create (""),
Create (" type tokenbox is record"),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- Tokenbox is the type of the element of the input"),
Create (" -- stream maintained in yyparser_input. It contains"),
Create (" -- the value of the token, the line on which the token"),
Create (" -- resides, the line number on which the token resides."),
Create (" -- It also contains the begin and end column of the token."),
Create (" token : yy_tokens.token;"),
Create (" lval : yystype;"),
Create (" line : string_ptr;"),
Create (" line_number : natural := 1;"),
Create (" token_start : natural := 1;"),
Create (" token_end : natural := 1;"),
Create (" end record;"),
Create (""),
Create (" type boxed_token is access tokenbox;"),
Create (""),
Create (" procedure unget(tok : in boxed_token);"),
Create (" -- push a token back into input stream."),
Create (""),
Create (" function get return boxed_token;"),
Create (" -- get a token from input stream"),
Create (""),
Create (" procedure reset_peek;"),
Create (" function peek return boxed_token;"),
Create (" -- During error recovery, we will lookahead to see the"),
Create (" -- affect of the error recovery. The lookahead does not"),
Create (" -- means that we actually accept the input, instead, it"),
Create (" -- only means that we peek the future input. It is the"),
Create (" -- purpose of function peek and it is also the difference"),
Create (" -- between peek and get. We maintain a counter indicating"),
Create (" -- how many token we have peeked and reset_peek will"),
Create (" -- reset that counter."),
Create (""),
Create (" function tbox (token : yy_tokens.token ) return boxed_token;"),
Create (" -- Given the token got from the lexical scanner, tbox"),
Create (" -- collect other information, such as, line, line number etc."),
Create (" -- to construct a boxed_token."),
Create (""),
Create (" input_token : yyparser_input.boxed_token;"),
Create (" previous_token : yyparser_input.boxed_token;"),
Create (" -- The current and previous token processed by parser."),
Create (""),
Create (" end yyparser_input;"),
Create (""),
Create (" package yyerror_recovery is"),
Create (" --"),
Create (" -- TITLE"),
Create (" --"),
Create (" -- Yyerror_Recovery."),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This package contains all of errro recovery staff,"),
Create (" -- in addition to those of Ayacc."),
Create (""),
Create (" previous_action : integer;"),
Create (" -- This variable is used to save the previous action the parser made."),
Create (""),
Create (" previous_error_flag : natural := 0;"),
Create (" -- This variable is used to save the previous error flag."),
Create (""),
Create (" valuing : Boolean := True;"),
Create (" -- Indicates whether to perform semantic actions. If exception"),
Create (" -- is raised during semantic action after error recovery, we"),
Create (" -- set valuing to False which causes no semantic actions to"),
Create (" -- be invoked any more."),
Create (""),
Create (" procedure flag_token ( error : in Boolean := True );"),
Create (" -- This procedure will point out the position of the"),
Create (" -- current token."),
Create (""),
Create (" procedure finale;"),
Create (" -- This procedure prepares the final report for error report."),
Create (""),
Create (" procedure try_recovery;"),
Create (" -- It is the main procedure for error recovery."),
Create (""),
Create (" line_number : integer := 0;"),
Create (" -- Indicates the last line having been outputed to the error file."),
Create (""),
Create (" procedure put_new_line;"),
Create (" -- This procedure outputs the whole line on which input_token"),
Create (" -- resides along with line number to the file for error reporting."),
Create (" end yyerror_recovery;"),
Create (""),
Create (" use yyerror_recovery;"),
Create (""),
Create (" package user_defined_errors is"),
Create (" --"),
Create (" -- TITLE"),
Create (" -- User Defined Errors."),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This package is used to facilite the error reporting."),
Create (""),
Create (" procedure parser_error(Message : in String );"),
Create (" procedure parser_warning(Message : in String );"),
Create (""),
Create (" end user_defined_errors;"),
Create (""),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" package yy is"),
Create (""),
Create (" -- the size of the value and state stacks"),
Create (" stack_size : constant Natural := 1500;"),
Create (""),
Create (" -- subtype rule is natural;"),
Create (" subtype parse_state is natural;"),
Create (" -- subtype nonterminal is integer;"),
Create (""),
Create (" -- encryption constants"),
Create (" default : constant := -1;"),
Create (" first_shift_entry : constant := 0;"),
Create (" accept_code : constant := -3001;"),
Create (" error_code : constant := -3000;"),
Create (""),
Create (" -- stack data used by the parser"),
Create (" tos : natural := 0;"),
Create (" value_stack : array(0..stack_size) of yy_tokens.yystype;"),
Create (" state_stack : array(0..stack_size) of parse_state;"),
Create (""),
Create (" -- current input symbol and action the parser is on"),
Create (" action : integer;"),
Create (" rule_id : rule;"),
Create (" input_symbol : yy_tokens.token;"),
Create (""),
Create (""),
Create (" -- error recovery flag"),
Create (" error_flag : natural := 0;"),
Create (" -- indicates 3 - (number of valid shifts after an error occurs)"),
Create (""),
Create (" look_ahead : boolean := true;"),
Create (" index : integer;"),
Create (""),
Create (" -- Is Debugging option on or off"),
Create ("%%"),
Create (""),
Create (" end yy;"),
Create (""),
Create (""),
Create (" function goto_state"),
Create (" (state : yy.parse_state;"),
Create (" sym : nonterminal) return yy.parse_state;"),
Create (""),
Create (" function parse_action"),
Create (" (state : yy.parse_state;"),
Create (" t : yy_tokens.token) return integer;"),
Create (""),
Create (" pragma inline(goto_state, parse_action);"),
Create (""),
Create (""),
Create (" function goto_state(state : yy.parse_state;"),
Create (" sym : nonterminal) return yy.parse_state is"),
Create (" index : integer;"),
Create (" begin"),
Create (" index := goto_offset(state);"),
Create (" while integer(goto_matrix(index).nonterm) /= sym loop"),
Create (" index := index + 1;"),
Create (" end loop;"),
Create (" return integer(goto_matrix(index).newstate);"),
Create (" end goto_state;"),
Create (""),
Create (""),
Create (" function parse_action(state : yy.parse_state;"),
Create (" t : yy_tokens.token) return integer is"),
Create (" index : integer;"),
Create (" tok_pos : integer;"),
Create (" default : constant integer := -1;"),
Create (" begin"),
Create (" tok_pos := yy_tokens.token'pos(t);"),
Create (" index := shift_reduce_offset(state);"),
Create (" while integer(shift_reduce_matrix(index).t) /= tok_pos and then"),
Create (" integer(shift_reduce_matrix(index).t) /= default"),
Create (" loop"),
Create (" index := index + 1;"),
Create (" end loop;"),
Create (" return integer(shift_reduce_matrix(index).act);"),
Create (" end parse_action;"),
Create (""),
Create ("-- error recovery stuff"),
Create (""),
Create (" procedure handle_error is"),
Create (" temp_action : integer;"),
Create (" begin"),
Create (""),
Create (" if yy.error_flag = 3 then -- no shift yet, clobber input."),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Error Recovery Clobbers "" &"),
Create (" yy_tokens.token'image(yy.input_symbol));"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Error Recovery Clobbers "" &"),
Create (" yy_tokens.token'image(yy.input_symbol));"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create (" if yy.input_symbol = yy_tokens.end_of_input then -- don't discard,"),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Can't discard END_OF_INPUT, quiting..."");"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Can't discard END_OF_INPUT, quiting..."");"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create ("-- UMASS CODES :"),
Create (" yyerror_recovery.finale;"),
Create ("-- END OF UMASS CODES."),
Create (" raise yy_tokens.syntax_error;"),
Create (" end if;"),
Create (""),
Create (" yy.look_ahead := true; -- get next token"),
Create (" return; -- and try again..."),
Create (" end if;"),
Create (""),
Create (" if yy.error_flag = 0 then -- brand new error"),
Create (" yyerror(""Syntax Error"");"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line ( ""Skipping..."" );"),
Create (" yy_error_report.put_line ( """" );"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create (""),
Create (" yy.error_flag := 3;"),
Create (""),
Create (" -- find state on stack where error is a valid shift --"),
Create (""),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Looking for state with error as valid shift"");"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Looking for state with error as valid shift"");"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create (""),
Create (" loop"),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Examining State "" &"),
Create (" yy.parse_state'image(yy.state_stack(yy.tos)));"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Examining State "" &"),
Create (" yy.parse_state'image(yy.state_stack(yy.tos)));"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create (" temp_action := parse_action(yy.state_stack(yy.tos), error);"),
Create (""),
Create (" if temp_action >= yy.first_shift_entry then"),
Create (" yy.tos := yy.tos + 1;"),
Create (" yy.state_stack(yy.tos) := temp_action;"),
Create (" exit;"),
Create (" end if;"),
Create (""),
Create (" Decrement_Stack_Pointer :"),
Create (" begin"),
Create (" yy.tos := yy.tos - 1;"),
Create (" exception"),
Create (" when Constraint_Error =>"),
Create (" yy.tos := 0;"),
Create (" end Decrement_Stack_Pointer;"),
Create (""),
Create (" if yy.tos = 0 then"),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Error recovery popped entire stack, aborting..."");"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Error recovery popped entire stack, aborting..."");"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create ("-- UMASS CODES :"),
Create (" yyerror_recovery.finale;"),
Create ("-- END OF UMASS CODES."),
Create (" raise yy_tokens.syntax_error;"),
Create (" end if;"),
Create (" end loop;"),
Create (""),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Shifted error token in state "" &"),
Create (" yy.parse_state'image(yy.state_stack(yy.tos)));"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Shifted error token in state "" &"),
Create (" yy.parse_state'image(yy.state_stack(yy.tos)));"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create (""),
Create (" end handle_error;"),
Create (""),
Create (" -- print debugging information for a shift operation"),
Create (" procedure shift_debug(state_id: yy.parse_state; lexeme: yy_tokens.token) is"),
Create (" begin"),
Create (" text_io.put_line(""Ayacc.YYParse: Shift ""& yy.parse_state'image(state_id)&"" on input symbol ""&"),
Create (" yy_tokens.token'image(lexeme) );"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Shift ""& yy.parse_state'image(state_id)&"" on input symbol ""&"),
Create (" yy_tokens.token'image(lexeme) );"),
Create ("-- END OF UMASS CODES."),
Create (" end;"),
Create (""),
Create (" -- print debugging information for a reduce operation"),
Create (" procedure reduce_debug(rule_id: rule; state_id: yy.parse_state) is"),
Create (" begin"),
Create (" text_io.put_line(""Ayacc.YYParse: Reduce by rule ""&rule'image(rule_id)&"" goto state ""&"),
Create (" yy.parse_state'image(state_id));"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Reduce by rule ""&rule'image(rule_id)&"" goto state ""&"),
Create (" yy.parse_state'image(state_id));"),
Create ("-- END OF UMASS CODES."),
Create (" end;"),
Create (""),
Create (" -- make the parser believe that 3 valid shifts have occured."),
Create (" -- used for error recovery."),
Create (" procedure yyerrok is"),
Create (" begin"),
Create (" yy.error_flag := 0;"),
Create (" end yyerrok;"),
Create (""),
Create (" -- called to clear input symbol that caused an error."),
Create (" procedure yyclearin is"),
Create (" begin"),
Create (" -- yy.input_symbol := yylex;"),
Create (" yy.look_ahead := true;"),
Create (" end yyclearin;"),
Create (""),
Create ("-- UMASS CODES :"),
Create ("-- Bodies of yyparser_input, yyerror_recovery, user_define_errors."),
Create (""),
Create ("package body yyparser_input is"),
Create (""),
Create (" input_stream_size : constant integer := 10;"),
Create (" -- Input_stream_size indicates how many tokens can"),
Create (" -- be hold in input stream."),
Create (""),
Create (" input_stream : array (0..input_stream_size-1) of boxed_token;"),
Create (""),
Create (" index : integer := 0; -- Indicates the position of the next"),
Create (" -- buffered token in the input stream."),
Create (" peek_count : integer := 0; -- # of tokens seen by peeking in the input stream."),
Create (" buffered : integer := 0; -- # of buffered tokens in the input stream."),
Create (""),
Create (" function tbox(token : yy_tokens.token) return boxed_token is"),
Create (" boxed : boxed_token;"),
Create (" line : string ( 1 .. 1024 );"),
Create (" line_length : integer;"),
Create (" begin"),
Create (" boxed := new tokenbox;"),
Create (" boxed.token := token;"),
Create (" boxed.lval := yylval;"),
Create (" boxed.line_number := yy_line_number;"),
Create (" yy_get_token_line(line, line_length);"),
Create (" boxed.line := new String ( 1 .. line_length );"),
Create (" boxed.line ( 1 .. line_length ) := line ( 1 .. line_length );"),
Create (" boxed.token_start := yy_begin_column;"),
Create (" boxed.token_end := yy_end_column;"),
Create (" return boxed;"),
Create (" end tbox;"),
Create (""),
Create (" function get return boxed_token is"),
Create (" t : boxed_token;"),
Create (" begin"),
Create (" if buffered = 0 then"),
Create (" -- No token is buffered in the input stream"),
Create (" -- so we get input from lexical scanner and return."),
Create (" return tbox(yylex);"),
Create (" else"),
Create (" -- return the next buffered token. And remove"),
Create (" -- it from input stream."),
Create (" t := input_stream(index);"),
Create (" yylval := t.lval;"),
Create (" -- Increase index and decrease buffered has"),
Create (" -- the affect of removing the returned token"),
Create (" -- from input stream."),
Create (" index := (index + 1 ) mod input_stream_size;"),
Create (" buffered := buffered - 1;"),
Create (" if peek_count > 0 then"),
Create (" -- Previously we were peeking the tokens"),
Create (" -- from index - 1 to index - 1 + peek_count."),
Create (" -- But now token at index - 1 is returned"),
Create (" -- and remove, so this token is no longer"),
Create (" -- one of the token being peek. So we must"),
Create (" -- decrease the peek_count. If peek_count"),
Create (" -- is 0, we remains peeking 0 token, so we"),
Create (" -- do nothing."),
Create (" peek_count := peek_count - 1;"),
Create (" end if;"),
Create (" return t;"),
Create (" end if;"),
Create (" end get;"),
Create (""),
Create (" procedure reset_peek is"),
Create (" -- Make it as if we have not peeked anything."),
Create (" begin"),
Create (" peek_count := 0;"),
Create (" end reset_peek;"),
Create (""),
Create (" function peek return boxed_token is"),
Create (" t : boxed_token;"),
Create (" begin"),
Create (" if peek_count = buffered then"),
Create (" -- We have peeked all the buffered tokens"),
Create (" -- in the input stream, so next peeked"),
Create (" -- token should be got from lexical scanner."),
Create (" -- Also we must buffer that token in the"),
Create (" -- input stream. It is the difference between"),
Create (" -- peek and get."),
Create (" t := tbox(yylex);"),
Create (" input_stream((index + buffered) mod input_stream_size) := t;"),
Create (" buffered := buffered + 1;"),
Create (" if buffered > input_stream_size then"),
Create (" text_io.Put_Line ( ""Warning : input stream size exceed."""),
Create (" & "" So token is lost in the input stream."" );"),
Create (" end if;"),
Create (""),
Create (" else"),
Create (" -- We have not peeked all the buffered tokens,"),
Create (" -- so we peek next buffered token."),
Create (""),
Create (" t := input_stream((index+peek_count) mod input_stream_size);"),
Create (" end if;"),
Create (""),
Create (" peek_count := peek_count + 1;"),
Create (" return t;"),
Create (" end peek;"),
Create (""),
Create (" procedure unget (tok : in boxed_token) is"),
Create (" begin"),
Create (" -- First decrease the index."),
Create (" if index = 0 then"),
Create (" index := input_stream_size - 1;"),
Create (" else"),
Create (" index := index - 1;"),
Create (" end if;"),
Create (" input_stream(index) := tok;"),
Create (" buffered := buffered + 1;"),
Create (" if buffered > input_stream_size then"),
Create (" text_io.Put_Line ( ""Warning : input stream size exceed."""),
Create (" & "" So token is lost in the input stream."" );"),
Create (" end if;"),
Create (""),
Create (" if peek_count > 0 then"),
Create (" -- We are peeking tokens, so we must increase"),
Create (" -- peek_count to maintain the correct peeking position."),
Create (" peek_count := peek_count + 1;"),
Create (" end if;"),
Create (" end unget;"),
Create (""),
Create (" end yyparser_input;"),
Create (""),
Create (""),
Create (" package body user_defined_errors is"),
Create (""),
Create (" procedure parser_error(Message : in String) is"),
Create (" begin"),
Create (" yy_error_report.report_continuable_error"),
Create (" (yyparser_input.input_token.line_number,"),
Create (" yyparser_input.input_token.token_start,"),
Create (" yyparser_input.input_token.token_end,"),
Create (" Message,"),
Create (" True);"),
Create (" yy_error_report.total_errors := yy_error_report.total_errors + 1;"),
Create (" end parser_error;"),
Create (""),
Create (" procedure parser_warning(Message : in String) is"),
Create (" begin"),
Create (" yy_error_report.report_continuable_error"),
Create (" (yyparser_input.input_token.line_number,"),
Create (" yyparser_input.input_token.token_start,"),
Create (" yyparser_input.input_token.token_end,"),
Create (" Message,"),
Create (" False);"),
Create (" yy_error_report.total_warnings := yy_error_report.total_warnings + 1;"),
Create (" end parser_warning;"),
Create (""),
Create (" end user_defined_errors;"),
Create (""),
Create (""),
Create (" package body yyerror_recovery is"),
Create (""),
Create (" max_forward_moves : constant integer := 5;"),
Create (" -- Indicates how many tokens we will peek at most during error recovery."),
Create (""),
Create (" type change_type is ( replace, insert, delete );"),
Create (" -- Indicates what kind of change error recovery does to the input stream."),
Create (""),
Create (" type correction_type is record"),
Create (" -- Indicates the correction error recovery does to the input stream."),
Create (" change : change_type;"),
Create (" score : integer;"),
Create (" tokenbox : yyparser_input.boxed_token;"),
Create (" end record;"),
Create (""),
Create (" procedure put_new_line is"),
Create (" line_number_string : constant string :="),
Create (" integer'image( yyparser_input.input_token.line_number );"),
Create (" begin"),
Create (" yy_error_report.put(line_number_string);"),
Create (" for i in 1 .. 5 - integer ( line_number_string'length ) loop"),
Create (" yy_error_report.put("" "");"),
Create (" end loop;"),
Create (" yy_error_report.put(yyparser_input.input_token.line.all);"),
Create (" end put_new_line;"),
Create (""),
Create (""),
Create (" procedure finale is"),
Create (" begin"),
Create (" if yy_error_report.total_errors > 0 then"),
Create (" yy_error_report.put_line("""");"),
Create (" yy_error_report.put(""Ayacc.YYParse : "" & natural'image(yy_error_report.total_errors));"),
Create (" if yy_error_report.total_errors = 1 then"),
Create (" yy_error_report.put_line("" syntax error found."");"),
Create (" else"),
Create (" yy_error_report.put_line("" syntax errors found."");"),
Create (" end if;"),
Create (" yy_error_report.Finish_Output;"),
Create (" raise yy_error_report.syntax_error;"),
Create (" elsif yy_error_report.total_warnings > 0 then"),
Create (" yy_error_report.put_line("""");"),
Create (" yy_error_report.put(""Ayacc.YYParse : "" & natural'image(yy_error_report.total_warnings));"),
Create (" if yy_error_report.total_warnings = 1 then"),
Create (" yy_error_report.put_line("" syntax warning found."");"),
Create (" else"),
Create (" yy_error_report.put_line("" syntax warnings found."");"),
Create (" end if;"),
Create (""),
Create (" yy_error_report.Finish_Output;"),
Create (" raise yy_error_report.syntax_warning;"),
Create (" end if;"),
Create (" yy_error_report.Finish_Output;"),
Create (" end finale;"),
Create (""),
Create (" procedure flag_token ( error : in Boolean := True ) is"),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This procedure will point out the position of the"),
Create (" -- current token."),
Create (" --"),
Create (" begin"),
Create (" if yy.error_flag > 0 then"),
Create (" -- We have not seen 3 valid shift yet, so we"),
Create (" -- do not need to report this error."),
Create (" return;"),
Create (" end if;"),
Create (""),
Create (" if error then"),
Create (" yy_error_report.put(""Error""); -- 5 characters for line number."),
Create (" else"),
Create (" yy_error_report.put(""OK "");"),
Create (" end if;"),
Create (""),
Create (" for i in 1 .. yyparser_input.input_token.token_start - 1 loop"),
Create (" if yyparser_input.input_token.line(i) = Ascii.ht then"),
Create (" yy_error_report.put(Ascii.ht);"),
Create (" else"),
Create (" yy_error_report.put("" "");"),
Create (" end if;"),
Create (" end loop;"),
Create (" yy_error_report.put_line(""^"");"),
Create (" end flag_token;"),
Create (""),
Create (""),
Create (" procedure print_correction_message (correction : in correction_type) is"),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This is a local procedure used to print out the message"),
Create (" -- about the correction error recovery did."),
Create (" --"),
Create (" begin"),
Create (" if yy.error_flag > 0 then"),
Create (" -- We have not seen 3 valid shift yet, so we"),
Create (" -- do not need to report this error."),
Create (" return;"),
Create (" end if;"),
Create (""),
Create (" flag_token;"),
Create (" case correction.change is"),
Create (" when delete =>"),
Create (" yy_error_report.put(""token delete "" );"),
Create (" user_defined_errors.parser_error(""token delete "" );"),
Create (""),
Create (" when replace =>"),
Create (" yy_error_report.put(""token replaced by "" &"),
Create (" yy_tokens.token'image(correction.tokenbox.token));"),
Create (" user_defined_errors.parser_error(""token replaced by "" &"),
Create (" yy_tokens.token'image(correction.tokenbox.token));"),
Create (""),
Create (" when insert =>"),
Create (" yy_error_report.put(""inserted token "" &"),
Create (" yy_tokens.token'image(correction.tokenbox.token));"),
Create (" user_defined_errors.parser_error(""inserted token "" &"),
Create (" yy_tokens.token'image(correction.tokenbox.token));"),
Create (" end case;"),
Create (""),
Create (" if yy.debug then"),
Create (" yy_error_report.put_line(""... Correction Score is"" &"),
Create (" integer'image(correction.score));"),
Create (" else"),
Create (" yy_error_report.put_line("""");"),
Create (" end if;"),
Create (" yy_error_report.put_line("""");"),
Create (" end print_correction_message;"),
Create (""),
Create (" procedure install_correction(correction : correction_type) is"),
Create (" -- This is a local procedure used to install the correction."),
Create (" begin"),
Create (" case correction.change is"),
Create (" when delete => null;"),
Create (" -- Since error found for current token,"),
Create (" -- no state is changed for current token."),
Create (" -- If we resume Parser now, Parser will"),
Create (" -- try to read next token which has the"),
Create (" -- affect of ignoring current token."),
Create (" -- So for deleting correction, we need to"),
Create (" -- do nothing."),
Create (" when replace => yyparser_input.unget(correction.tokenbox);"),
Create (" when insert => yyparser_input.unget(yyparser_input.input_token);"),
Create (" yyparser_input.input_token := null;"),
Create (" yyparser_input.unget(correction.tokenbox);"),
Create (" end case;"),
Create (" end install_correction;"),
Create (""),
Create (""),
Create (" function simulate_moves return integer is"),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This is a local procedure simulating the Parser work to"),
Create (" -- evaluate a potential correction. It will look at most"),
Create (" -- max_forward_moves tokens. It behaves very similarly as"),
Create (" -- the actual Parser except that it does not invoke user"),
Create (" -- action and it exits when either error is found or"),
Create (" -- the whole input is accepted. Simulate_moves also"),
Create (" -- collects and returns the score. Simulate_Moves"),
Create (" -- do the simulation on the copied state stack to"),
Create (" -- avoid changing the original one."),
Create (""),
Create (" -- the score for each valid shift."),
Create (" shift_increment : constant integer := 20;"),
Create (" -- the score for each valid reduce."),
Create (" reduce_increment : constant integer := 10;"),
Create (" -- the score for accept action."),
Create (" accept_increment : integer := 14 * max_forward_moves;"),
Create (" -- the decrement for error found."),
Create (" error_decrement : integer := -10 * max_forward_moves;"),
Create (""),
Create (" -- Indicates how many reduces made between last shift"),
Create (" -- and current shift."),
Create (" current_reduces : integer := 0;"),
Create (""),
Create (" -- Indicates how many reduces made till now."),
Create (" total_reduces : integer := 0;"),
Create (""),
Create (" -- Indicates how many tokens seen so far during simulation."),
Create (" tokens_seen : integer := 0;"),
Create (""),
Create (" score : integer := 0; -- the score of the simulation."),
Create (""),
Create (" The_Copied_Stack : array (0..yy.stack_size) of yy.parse_state;"),
Create (" The_Copied_Tos : integer;"),
Create (" The_Copied_Input_Token : yyparser_input.boxed_token;"),
Create (" Look_Ahead : Boolean := True;"),
Create (""),
Create (" begin"),
Create (""),
Create (" -- First we copy the state stack."),
Create (" for i in 0 .. yy.tos loop"),
Create (" The_Copied_Stack(i) := yy.state_stack(i);"),
Create (" end loop;"),
Create (" The_Copied_Tos := yy.tos;"),
Create (" The_Copied_Input_Token := yyparser_input.input_token;"),
Create (" -- Reset peek_count because each simulation"),
Create (" -- starts a new process of peeking."),
Create (" yyparser_input.reset_peek;"),
Create (""),
Create (" -- Do the simulation."),
Create (" loop"),
Create (" -- We peek at most max_forward_moves tokens during simulation."),
Create (" exit when tokens_seen = max_forward_moves;"),
Create (""),
Create (" -- The following codes is very similar the codes in Parser."),
Create (" yy.index := shift_reduce_offset(yy.state_stack(yy.tos));"),
Create (" if integer(shift_reduce_matrix(yy.index).t) = yy.default then"),
Create (" yy.action := integer(shift_reduce_matrix(yy.index).act);"),
Create (" else"),
Create (" if look_ahead then"),
Create (" look_ahead := false;"),
Create (" -- Since it is in simulation, we peek the token instead of"),
Create (" -- get the token."),
Create (" The_Copied_Input_Token := yyparser_input.peek;"),
Create (" end if;"),
Create (" yy.action :="),
Create (" parse_action(The_Copied_Stack(The_Copied_Tos), The_Copied_Input_Token.token);"),
Create (" end if;"),
Create (""),
Create (" if yy.action >= yy.first_shift_entry then -- SHIFT"),
Create (" if yy.debug then"),
Create (" shift_debug(yy.action, The_Copied_Input_Token.token);"),
Create (" end if;"),
Create (""),
Create (" -- Enter new state"),
Create (" The_Copied_Tos := The_Copied_Tos + 1;"),
Create (" The_Copied_Stack(The_Copied_Tos) := yy.action;"),
Create (""),
Create (" -- Advance lookahead"),
Create (" look_ahead := true;"),
Create (""),
Create (" score := score + shift_increment + current_reduces * reduce_increment;"),
Create (" current_reduces := 0;"),
Create (" tokens_seen := tokens_seen + 1;"),
Create (""),
Create (" elsif yy.action = yy.error_code then -- ERROR"),
Create (" score := score - total_reduces * reduce_increment;"),
Create (" exit; -- exit the loop for simulation."),
Create (""),
Create (" elsif yy.action = yy.accept_code then"),
Create (" score := score + accept_increment;"),
Create (" exit; -- exit the loop for simulation."),
Create (""),
Create (" else -- Reduce Action"),
Create (""),
Create (" -- Convert action into a rule"),
Create (" yy.rule_id := -1 * yy.action;"),
Create (""),
Create (" -- Don't Execute User Action"),
Create (""),
Create (" -- Pop RHS states and goto next state"),
Create (" The_Copied_Tos := The_Copied_Tos - rule_length(yy.rule_id) + 1;"),
Create (" The_Copied_Stack(The_Copied_Tos) := goto_state(The_Copied_Stack(The_Copied_Tos-1) ,"),
Create (" get_lhs_rule(yy.rule_id));"),
Create (""),
Create (" -- Leave value stack alone"),
Create (""),
Create (" if yy.debug then"),
Create (" reduce_debug(yy.rule_id,"),
Create (" goto_state(The_Copied_Stack(The_Copied_Tos - 1),"),
Create (" get_lhs_rule(yy.rule_id)));"),
Create (" end if;"),
Create (""),
Create (" -- reduces only credited to score when a token can be shifted"),
Create (" -- but no more than 3 reduces can count between shifts"),
Create (" current_reduces := current_reduces + 1;"),
Create (" total_reduces := total_reduces + 1;"),
Create (""),
Create (" end if;"),
Create (""),
Create (" end loop; -- loop for simulation;"),
Create (""),
Create (" yyparser_input.reset_peek;"),
Create (""),
Create (" return score;"),
Create (" end simulate_moves;"),
Create (""),
Create (""),
Create (""),
Create (" procedure primary_recovery ( best_correction : in out correction_type;"),
Create (" stop_score : in integer ) is"),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This is a local procedure used by try_recovery. This"),
Create (" -- procedure will try the following corrections :"),
Create (" -- 1. Delete current token."),
Create (" -- 2. Replace current token with any token acceptible"),
Create (" -- from current state, or,"),
Create (" -- Insert any one of the tokens acceptible from current state."),
Create (" --"),
Create (" token_code : integer;"),
Create (" new_score : integer;"),
Create (" the_boxed_token : yyparser_input.boxed_token;"),
Create (" begin"),
Create (""),
Create (" -- First try to delete current token."),
Create (" if yy.debug then"),
Create (" yy_error_report.put_line(""trying to delete "" &"),
Create (" yy_tokens.token'image(yyparser_input.input_token.token));"),
Create (" end if;"),
Create (""),
Create (" best_correction.change := delete;"),
Create (" -- try to evaluate the correction. NOTE : simulating the Parser"),
Create (" -- from current state has affect of ignoring current token"),
Create (" -- because error was found for current token and no state"),
Create (" -- was pushed to state stack."),
Create (" best_correction.score := simulate_moves;"),
Create (" best_correction.tokenbox := null;"),
Create (""),
Create (" -- If the score is less than stop_score, we try"),
Create (" -- the 2nd kind of corrections, that is, replace or insert."),
Create (" if best_correction.score < stop_score then"),
Create (" for i in shift_reduce_offset(yy.state_stack(yy.tos)).."),
Create (" (shift_reduce_offset(yy.state_stack(yy.tos)+1) - 1) loop"),
Create (" -- We try to use the acceptible token from current state"),
Create (" -- to replace current token or try to insert the acceptible token."),
Create (" token_code := integer(shift_reduce_matrix(i).t);"),
Create (" -- yy.default is not a valid token, we must exit."),
Create (" exit when token_code = yy.default;"),
Create (""),
Create (" the_boxed_token := yyparser_input.tbox(yy_tokens.token'val(token_code));"),
Create (" for change in replace .. insert loop"),
Create (" -- We try replacing and the inserting."),
Create (" case change is"),
Create (" when replace => yyparser_input.unget(the_boxed_token);"),
Create (" -- put the_boxed_token into the input stream"),
Create (" -- has the affect of replacing current token"),
Create (" -- because current token has been retrieved"),
Create (" -- but no state was change because of the error."),
Create (" if yy.debug then"),
Create (" yy_error_report.put_line(""trying to replace """),
Create (" & yy_tokens.token'image"),
Create (" (yyparser_input.input_token.token)"),
Create (" & "" with """),
Create (" & yy_tokens.token'image(the_boxed_token.token));"),
Create (" end if;"),
Create (" when insert => yyparser_input.unget(yyparser_input.input_token);"),
Create (" yyparser_input.unget(the_boxed_token);"),
Create (" if yy.debug then"),
Create (" yy_error_report.put_line(""trying to insert """),
Create (" & yy_tokens.token'image(the_boxed_token.token)"),
Create (" & "" before """),
Create (" & yy_tokens.token'image("),
Create (" yyparser_input.input_token.token));"),
Create (" end if;"),
Create (" end case;"),
Create (""),
Create (" -- Evaluate the correction."),
Create (" new_score := simulate_moves;"),
Create (""),
Create (" if new_score > best_correction.score then"),
Create (" -- We find a higher score, so we overwrite the old one."),
Create (" best_correction := (change, new_score, the_boxed_token);"),
Create (" end if;"),
Create (""),
Create (" -- We have change the input stream when we do replacing or"),
Create (" -- inserting. So we must undo the affect."),
Create (" declare"),
Create (" ignore_result : yyparser_input.boxed_token;"),
Create (" begin"),
Create (" case change is"),
Create (" when replace => ignore_result := yyparser_input.get;"),
Create (" when insert => ignore_result := yyparser_input.get;"),
Create (" ignore_result := yyparser_input.get;"),
Create (" end case;"),
Create (" end;"),
Create (""),
Create (" -- If we got a score higher than stop score, we"),
Create (" -- feel it is good enough, so we exit."),
Create (" exit when best_correction.score > stop_score;"),
Create (""),
Create (" end loop; -- change in replace .. insert"),
Create (""),
Create (" -- If we got a score higher than stop score, we"),
Create (" -- feel it is good enough, so we exit."),
Create (" exit when best_correction.score > stop_score;"),
Create (""),
Create (" end loop; -- i in shift_reduce_offset..."),
Create (""),
Create (" end if; -- best_correction.score < stop_score;"),
Create (""),
Create (" end primary_recovery;"),
Create (""),
Create (""),
Create (" procedure try_recovery is"),
Create (" --"),
Create (" -- OVERVIEW"),
Create (" -- This is the main procedure doing error recovery."),
Create (" -- During the process of error recovery, we use score to"),
Create (" -- evaluate the potential correction. When we try a potential"),
Create (" -- correction, we will peek some future tokens and simulate"),
Create (" -- the work of Parser. Any valid shift, reduce or accept action"),
Create (" -- in the simulation leading from a potential correction"),
Create (" -- will increase the score of the potential correction."),
Create (" -- Any error found during the simulation will decrease the"),
Create (" -- score of the potential correction and stop the simulation."),
Create (" -- Since we limit the number of tokens being peeked, the"),
Create (" -- simulation will stop no matter what the correction is."),
Create (" -- If the score of a potential correction is higher enough,"),
Create (" -- we will accept that correction and install and let the Parser"),
Create (" -- continues. During the simulation, we will do almost the"),
Create (" -- same work as the actual Parser does, except that we do"),
Create (" -- not invoke any user actions and we collect the score."),
Create (" -- So we will use the state_stack of the Parser. In order"),
Create (" -- to avoid change the value of state_stack, we will make"),
Create (" -- a copy of the state_stack and the simulation is done"),
Create (" -- on the copy. Below is the outline of sequence of corrections"),
Create (" -- the error recovery algorithm tries:"),
Create (" -- 1. Delete current token."),
Create (" -- 2. Replace current token with any token acceptible"),
Create (" -- from current state, or,"),
Create (" -- Insert any one of the tokens acceptible from current state."),
Create (" -- 3. If previous parser action is shift, back up one state,"),
Create (" -- and try the corrections in 1 and 2 again."),
Create (" -- 4. If none of the scores of the corrections above are highed"),
Create (" -- enough, we invoke the handle_error in Ayacc."),
Create (" --"),
Create (" correction : correction_type;"),
Create (" backed_up : boolean := false; -- indicates whether or not we backed up"),
Create (" -- during error recovery."),
Create (" -- scoring : evaluate a potential correction with a number. high is good"),
Create (" min_ok_score : constant integer := 70; -- will rellluctantly use"),
Create (" stop_score : constant integer := 100; -- this or higher is best."),
Create (" begin"),
Create (""),
Create (" -- First try recovery without backing up."),
Create (" primary_recovery(correction, stop_score);"),
Create (""),
Create (" if correction.score < stop_score then"),
Create (" -- The score of the correction is not high enough,"),
Create (" -- so we try to back up and try more corrections."),
Create (" -- But we can back up only if previous Parser action"),
Create (" -- is shift."),
Create (" if previous_action >= yy.first_shift_entry then"),
Create (" -- Previous action is a shift, so we back up."),
Create (" backed_up := true;"),
Create (""),
Create (" -- we put back the input token and"),
Create (" -- roll back the state stack and input token."),
Create (" yyparser_input.unget(yyparser_input.input_token);"),
Create (" yyparser_input.input_token := yyparser_input.previous_token;"),
Create (" yy.tos := yy.tos - 1;"),
Create (""),
Create (" -- Then we try recovery again"),
Create (" primary_recovery(correction, stop_score);"),
Create (" end if;"),
Create (" end if; -- correction_score < stop_score"),
Create (""),
Create (" -- Now we have try all possible correction."),
Create (" -- The highest score is in correction."),
Create (" if correction.score >= min_ok_score then"),
Create (" -- We accept this correction."),
Create (""),
Create (" -- First, if the input token resides on the different line"),
Create (" -- of previous token and we have not backed up, we must"),
Create (" -- output the new line before we printed the error message."),
Create (" -- If we have backed up, we do nothing here because"),
Create (" -- previous line has been output."),
Create (" if not backed_up and then"),
Create (" ( line_number <"),
Create (" yyparser_input.input_token.line_number ) then"),
Create (" put_new_line;"),
Create (" line_number := yyparser_input.input_token.line_number;"),
Create (" end if;"),
Create (""),
Create (" print_correction_message(correction);"),
Create (" install_correction(correction);"),
Create (""),
Create (" else"),
Create (" -- No score is high enough, we try to invoke handle_error"),
Create (" -- First, if we backed up during error recovery, we now must"),
Create (" -- try to undo the affect of backing up."),
Create (" if backed_up then"),
Create (" yyparser_input.input_token := yyparser_input.get;"),
Create (" yy.tos := yy.tos + 1;"),
Create (" end if;"),
Create (""),
Create (" -- Output the new line if necessary because the"),
Create (" -- new line has not been output yet."),
Create (" if line_number <"),
Create (" yyparser_input.input_token.line_number then"),
Create (" put_new_line;"),
Create (" line_number := yyparser_input.input_token.line_number;"),
Create (" end if;"),
Create (""),
Create (" if yy.debug then"),
Create (" if not backed_up then"),
Create (" yy_error_report.put_line(""can't back yp over last token..."");"),
Create (" end if;"),
Create (" yy_error_report.put_line(""1st level recovery failed, going to 2nd level..."");"),
Create (" end if;"),
Create (""),
Create (" -- Point out the position of the token on which error occurs."),
Create (" flag_token;"),
Create (""),
Create (" -- count it as error if it is a new error. NOTE : if correction is accepted, total_errors"),
Create (" -- count will be increase during error reporting."),
Create (" if yy.error_flag = 0 then -- brand new error"),
Create (" yy_error_report.total_errors := yy_error_report.total_errors + 1;"),
Create (" end if;"),
Create (""),
Create (" -- Goes to 2nd level."),
Create (" handle_error;"),
Create (""),
Create (" end if; -- correction.score >= min_ok_score"),
Create (""),
Create (" -- No matter what happen, let the parser move forward."),
Create (" yy.look_ahead := true;"),
Create (""),
Create (" end try_recovery;"),
Create (""),
Create (""),
Create (" end yyerror_recovery;"),
Create (""),
Create (""),
Create ("-- END OF UMASS CODES."),
Create (""),
Create ("begin"),
Create (" -- initialize by pushing state 0 and getting the first input symbol"),
Create (" yy.state_stack(yy.tos) := 0;"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.Initialize_Output;"),
Create (" -- initialize input token and previous token"),
Create (" yyparser_input.input_token := new yyparser_input.tokenbox;"),
Create (" yyparser_input.input_token.line_number := 0;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (""),
Create (" loop"),
Create (""),
Create (" yy.index := shift_reduce_offset(yy.state_stack(yy.tos));"),
Create (" if integer(shift_reduce_matrix(yy.index).t) = yy.default then"),
Create (" yy.action := integer(shift_reduce_matrix(yy.index).act);"),
Create (" else"),
Create (" if yy.look_ahead then"),
Create (" yy.look_ahead := false;"),
Create ("-- UMASS CODES :"),
Create ("-- Let Parser get the input from yyparser_input and"),
Create ("-- maintain previous_token and input_token."),
Create (" yyparser_input.previous_token := yyparser_input.input_token;"),
Create (" yyparser_input.input_token := yyparser_input.get;"),
Create (" yy.input_symbol := yyparser_input.input_token.token;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create ("-- UCI CODES DELETED :"),
Create (" yy.input_symbol := yylex;"),
Create ("-- END OF UCI CODES DELETED."),
Create (" end if;"),
Create (" yy.action :="),
Create (" parse_action(yy.state_stack(yy.tos), yy.input_symbol);"),
Create (" end if;"),
Create (""),
Create ("-- UMASS CODES :"),
Create ("-- If input_token is not on the line yyerror_recovery.line_number,"),
Create ("-- we just get to a new line. So we output the new line to"),
Create ("-- file of error report. But if yy.action is error, we"),
Create ("-- will not output the new line because we will do error"),
Create ("-- recovery and during error recovery, we may back up"),
Create ("-- which may cause error reported on previous line."),
Create ("-- So if yy.action is error, we will let error recovery"),
Create ("-- to output the new line."),
Create (" if ( yyerror_recovery.line_number <"),
Create (" yyparser_input.input_token.line_number ) and then"),
Create (" yy.action /= yy.error_code then"),
Create (" put_new_line;"),
Create (" yyerror_recovery.line_number := yyparser_input.input_token.line_number;"),
Create (" end if;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" if yy.action >= yy.first_shift_entry then -- SHIFT"),
Create (""),
Create (" if yy.debug then"),
Create (" shift_debug(yy.action, yy.input_symbol);"),
Create (" end if;"),
Create (""),
Create (" -- Enter new state"),
Create (" yy.tos := yy.tos + 1;"),
Create (" yy.state_stack(yy.tos) := yy.action;"),
Create ("-- UMASS CODES :"),
Create ("-- Set value stack only if valuing is True." ),
Create (" if yyerror_recovery.valuing then"),
Create ("-- END OF UMASS CODES."),
Create (" yy.value_stack(yy.tos) := yylval;"),
Create ("-- UMASS CODES :"),
Create (" end if;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" if yy.error_flag > 0 then -- indicate a valid shift"),
Create (" yy.error_flag := yy.error_flag - 1;"),
Create (" end if;"),
Create (""),
Create (" -- Advance lookahead"),
Create (" yy.look_ahead := true;"),
Create (""),
Create (" elsif yy.action = yy.error_code then -- ERROR"),
Create ("-- UMASS CODES :"),
Create (" try_recovery;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create ("-- UCI CODES DELETED :"),
Create (" handle_error;"),
Create ("-- END OF UCI CODES DELETED."),
Create (""),
Create (" elsif yy.action = yy.accept_code then"),
Create (" if yy.debug then"),
Create (" text_io.put_line(""Ayacc.YYParse: Accepting Grammar..."");"),
Create ("-- UMASS CODES :"),
Create (" yy_error_report.put_line(""Ayacc.YYParse: Accepting Grammar..."");"),
Create ("-- END OF UMASS CODES."),
Create (" end if;"),
Create (" exit;"),
Create (""),
Create (" else -- Reduce Action"),
Create (""),
Create (" -- Convert action into a rule"),
Create (" yy.rule_id := -1 * yy.action;"),
Create (""),
Create (" -- Execute User Action"),
Create (" -- user_action(yy.rule_id);"),
Create (""),
Create ("-- UMASS CODES :" ),
Create ("-- Only invoke semantic action if valuing is True."),
Create ("-- And if exception is raised during semantic action"),
Create ("-- and total_errors is not zero, we set valuing to False"),
Create ("-- because we assume that error recovery causes the exception"),
Create ("-- and we no longer want to invoke any semantic action."),
Create (" if yyerror_recovery.valuing then"),
Create (" begin"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" case yy.rule_id is"),
Create ("%%"),
Create (""),
Create (" when others => null;"),
Create (" end case;"),
Create (""),
Create ("-- UMASS CODES :"),
Create ("-- Corresponding to the codes above."),
Create (" exception"),
Create (" when others =>"),
Create (" if yy_error_report.total_errors > 0 then"),
Create (" yyerror_recovery.valuing := False;"),
Create (" -- We no longer want to invoke any semantic action."),
Create (" else"),
Create (" -- this exception is not caused by syntax error,"),
Create (" -- so we reraise anyway."),
Create (" yy_error_report.Finish_Output;"),
Create (" raise;"),
Create (" end if;"),
Create (" end;"),
Create (" end if;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" -- Pop RHS states and goto next state"),
Create (" yy.tos := yy.tos - rule_length(yy.rule_id) + 1;"),
Create (" yy.state_stack(yy.tos) := goto_state(yy.state_stack(yy.tos-1) ,"),
Create (" get_lhs_rule(yy.rule_id));"),
Create (""),
Create ("-- UMASS CODES :"),
Create ("-- Set value stack only if valuing is True." ),
Create (" if yyerror_recovery.valuing then"),
Create ("-- END OF UMASS CODES."),
Create (" yy.value_stack(yy.tos) := yyval;"),
Create ("-- UMASS CODES :"),
Create (" end if;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" if yy.debug then"),
Create (" reduce_debug(yy.rule_id,"),
Create (" goto_state(yy.state_stack(yy.tos - 1),"),
Create (" get_lhs_rule(yy.rule_id)));"),
Create (" end if;"),
Create (""),
Create (" end if;"),
Create (""),
Create ("-- UMASS CODES :"),
Create ("-- If the error flag is set to zero at current token,"),
Create ("-- we flag current token out."),
Create (" if yyerror_recovery.previous_error_flag > 0 and then"),
Create (" yy.error_flag = 0 then"),
Create (" yyerror_recovery.flag_token ( error => False );"),
Create (" end if;"),
Create (""),
Create ("-- save the action made and error flag."),
Create (" yyerror_recovery.previous_action := yy.action;"),
Create (" yyerror_recovery.previous_error_flag := yy.error_flag;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create (" end loop;"),
Create (""),
Create ("-- UMASS CODES :"),
Create (" finale;"),
Create ("-- END OF UMASS CODES."),
Create (""),
Create ("end yyparse;") ); -- End of File Contents
procedure Open is
begin
File_Pointer := YYParse_Template_File'First;
end Open;
procedure Close is
begin
File_Pointer := 0;
end Close;
procedure Read (S: out String; Length : out Integer) is
Next_Line : constant String :=
String_Pkg.Value (YYParse_Template_File (File_Pointer));
begin
S := Next_Line & (1 .. S'Length - Next_Line'Length => ' ');
Length := Next_Line'Length;
File_Pointer := File_Pointer + 1;
exception
when Constraint_Error =>
if Is_End_of_File then
raise End_Error;
else
raise Status_Error;
end if;
end;
function Is_End_of_File return Boolean is
begin
return File_Pointer = (YYParse_Template_File'Last + 1);
end Is_End_of_File;
end Parse_Template_File;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body Generator is
--------------
-- Identity --
--------------
function Identity (X : Natural) return Natural is
begin
return X;
end Identity;
----------
-- Skip --
----------
procedure Skip (Gen : access Generator'Class; Count : Positive := 1) is
Val : Natural;
pragma Unreferenced (Val);
begin
for I in 1 .. Count loop
Val := Gen.Get_Next;
end loop;
end Skip;
-----------
-- Reset --
-----------
procedure Reset (Gen : in out Generator) is
begin
Gen.Last_Source := 0;
Gen.Last_Value := 0;
end Reset;
--------------
-- Get_Next --
--------------
function Get_Next (Gen : access Generator) return Natural is
begin
Gen.Last_Source := Gen.Last_Source + 1;
Gen.Last_Value := Gen.Gen_Func (Gen.Last_Source);
return Gen.Last_Value;
end Get_Next;
----------------------------
-- Set_Generator_Function --
----------------------------
procedure Set_Generator_Function
(Gen : in out Generator;
Func : Generator_Function)
is
begin
if Func = null then
Gen.Gen_Func := Identity'Access;
else
Gen.Gen_Func := Func;
end if;
end Set_Generator_Function;
end Generator;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Interfaces;
package Tkmrpc.Types is
subtype Byte is Interfaces.Unsigned_8;
subtype Byte_Sequence_Range is Natural range 0 .. 2 ** 31 - 2;
type Byte_Sequence is array (Byte_Sequence_Range range <>) of Byte;
type Request_Id_Type is new Interfaces.Unsigned_64;
type Version_Type is new Interfaces.Unsigned_64;
type Active_Requests_Type is new Interfaces.Unsigned_64;
type Authag_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Cag_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Li_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Ri_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Iag_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Eag_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Dhag_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Sp_Id_Type is new Interfaces.Unsigned_32 range 1 .. 100;
type Authp_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Dhp_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Autha_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Ca_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Lc_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Ia_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Ea_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Dha_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Nc_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Dh_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Cc_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Ae_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Isa_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Esa_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Esp_Enc_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Esp_Dec_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Esp_Map_Id_Type is new Interfaces.Unsigned_64 range 1 .. 100;
type Abs_Time_Type is new Interfaces.Unsigned_64;
type Rel_Time_Type is new Interfaces.Unsigned_64;
type Duration_Type is new Interfaces.Unsigned_64;
type Counter_Type is new Interfaces.Unsigned_64;
type Pfs_Flag_Type is new Interfaces.Unsigned_64;
type Cc_Time_Flag_Type is new Interfaces.Unsigned_64;
type Expiry_Flag_Type is new Interfaces.Unsigned_8;
type Auth_Algorithm_Type is new Interfaces.Unsigned_64;
type Dh_Algorithm_Type is new Interfaces.Unsigned_16;
type Prf_Algorithm_Type is new Interfaces.Unsigned_16;
type Int_Algorithm_Type is new Interfaces.Unsigned_16;
type Enc_Algorithm_Type is new Interfaces.Unsigned_16;
type Key_Length_Bits_Type is new Interfaces.Unsigned_64;
type Block_Length_Bits_Type is new Interfaces.Unsigned_64;
type Protocol_Type is new Interfaces.Unsigned_32;
type Init_Type is new Interfaces.Unsigned_64;
type Ike_Spi_Type is new Interfaces.Unsigned_64;
type Esp_Spi_Type is new Interfaces.Unsigned_32;
type Nonce_Length_Type is new Interfaces.Unsigned_64;
subtype Init_Message_Type_Range is Byte_Sequence_Range range 1 .. 1500;
subtype Init_Message_Type_Data_Type is Byte_Sequence (
Init_Message_Type_Range);
type Init_Message_Type is record
Size : Init_Message_Type_Range;
Data : Init_Message_Type_Data_Type;
end record;
for Init_Message_Type'Size use 1504 * 8;
Null_Init_Message_Type : constant Init_Message_Type :=
Init_Message_Type'
(Size => Init_Message_Type_Range'First,
Data => Init_Message_Type_Data_Type'(others => 0));
subtype Certificate_Type_Range is Byte_Sequence_Range range 1 .. 1500;
subtype Certificate_Type_Data_Type is Byte_Sequence (Certificate_Type_Range)
;
type Certificate_Type is record
Size : Certificate_Type_Range;
Data : Certificate_Type_Data_Type;
end record;
for Certificate_Type'Size use 1504 * 8;
Null_Certificate_Type : constant Certificate_Type :=
Certificate_Type'
(Size => Certificate_Type_Range'First,
Data => Certificate_Type_Data_Type'(others => 0));
subtype Nonce_Type_Range is Byte_Sequence_Range range 1 .. 256;
subtype Nonce_Type_Data_Type is Byte_Sequence (Nonce_Type_Range);
type Nonce_Type is record
Size : Nonce_Type_Range;
Data : Nonce_Type_Data_Type;
end record;
for Nonce_Type'Size use 260 * 8;
Null_Nonce_Type : constant Nonce_Type :=
Nonce_Type'
(Size => Nonce_Type_Range'First,
Data => Nonce_Type_Data_Type'(others => 0));
subtype Dh_Pubvalue_Type_Range is Byte_Sequence_Range range 1 .. 512;
subtype Dh_Pubvalue_Type_Data_Type is Byte_Sequence (Dh_Pubvalue_Type_Range)
;
type Dh_Pubvalue_Type is record
Size : Dh_Pubvalue_Type_Range;
Data : Dh_Pubvalue_Type_Data_Type;
end record;
for Dh_Pubvalue_Type'Size use 516 * 8;
Null_Dh_Pubvalue_Type : constant Dh_Pubvalue_Type :=
Dh_Pubvalue_Type'
(Size => Dh_Pubvalue_Type_Range'First,
Data => Dh_Pubvalue_Type_Data_Type'(others => 0));
subtype Dh_Priv_Type_Range is Byte_Sequence_Range range 1 .. 512;
subtype Dh_Priv_Type_Data_Type is Byte_Sequence (Dh_Priv_Type_Range);
type Dh_Priv_Type is record
Size : Dh_Priv_Type_Range;
Data : Dh_Priv_Type_Data_Type;
end record;
for Dh_Priv_Type'Size use 516 * 8;
Null_Dh_Priv_Type : constant Dh_Priv_Type :=
Dh_Priv_Type'
(Size => Dh_Priv_Type_Range'First,
Data => Dh_Priv_Type_Data_Type'(others => 0));
subtype Dh_Key_Type_Range is Byte_Sequence_Range range 1 .. 512;
subtype Dh_Key_Type_Data_Type is Byte_Sequence (Dh_Key_Type_Range);
type Dh_Key_Type is record
Size : Dh_Key_Type_Range;
Data : Dh_Key_Type_Data_Type;
end record;
for Dh_Key_Type'Size use 516 * 8;
Null_Dh_Key_Type : constant Dh_Key_Type :=
Dh_Key_Type'
(Size => Dh_Key_Type_Range'First,
Data => Dh_Key_Type_Data_Type'(others => 0));
subtype Key_Type_Range is Byte_Sequence_Range range 1 .. 64;
subtype Key_Type_Data_Type is Byte_Sequence (Key_Type_Range);
type Key_Type is record
Size : Key_Type_Range;
Data : Key_Type_Data_Type;
end record;
for Key_Type'Size use 68 * 8;
Null_Key_Type : constant Key_Type :=
Key_Type'
(Size => Key_Type_Range'First,
Data => Key_Type_Data_Type'(others => 0));
subtype Identity_Type_Range is Byte_Sequence_Range range 1 .. 64;
subtype Identity_Type_Data_Type is Byte_Sequence (Identity_Type_Range);
type Identity_Type is record
Size : Identity_Type_Range;
Data : Identity_Type_Data_Type;
end record;
for Identity_Type'Size use 68 * 8;
Null_Identity_Type : constant Identity_Type :=
Identity_Type'
(Size => Identity_Type_Range'First,
Data => Identity_Type_Data_Type'(others => 0));
subtype Signature_Type_Range is Byte_Sequence_Range range 1 .. 384;
subtype Signature_Type_Data_Type is Byte_Sequence (Signature_Type_Range);
type Signature_Type is record
Size : Signature_Type_Range;
Data : Signature_Type_Data_Type;
end record;
for Signature_Type'Size use 388 * 8;
Null_Signature_Type : constant Signature_Type :=
Signature_Type'
(Size => Signature_Type_Range'First,
Data => Signature_Type_Data_Type'(others => 0));
subtype Auth_Parameter_Type_Range is Byte_Sequence_Range range 1 .. 1024;
subtype Auth_Parameter_Type_Data_Type is Byte_Sequence (
Auth_Parameter_Type_Range);
type Auth_Parameter_Type is record
Size : Auth_Parameter_Type_Range;
Data : Auth_Parameter_Type_Data_Type;
end record;
for Auth_Parameter_Type'Size use 1028 * 8;
Null_Auth_Parameter_Type : constant Auth_Parameter_Type :=
Auth_Parameter_Type'
(Size => Auth_Parameter_Type_Range'First,
Data => Auth_Parameter_Type_Data_Type'(others => 0));
subtype Dh_Parameter_Type_Range is Byte_Sequence_Range range 1 .. 1024;
subtype Dh_Parameter_Type_Data_Type is Byte_Sequence (
Dh_Parameter_Type_Range);
type Dh_Parameter_Type is record
Size : Dh_Parameter_Type_Range;
Data : Dh_Parameter_Type_Data_Type;
end record;
for Dh_Parameter_Type'Size use 1028 * 8;
Null_Dh_Parameter_Type : constant Dh_Parameter_Type :=
Dh_Parameter_Type'
(Size => Dh_Parameter_Type_Range'First,
Data => Dh_Parameter_Type_Data_Type'(others => 0));
end Tkmrpc.Types;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Calendar;
with Ada.Text_IO;
use Ada.Calendar;
package body Timer is
function start return T is
result: T;
begin
result.clock := Ada.Calendar.Clock;
return result;
end start;
procedure reset(tm: in out T) is
begin
tm.clock := Ada.Calendar.Clock;
end reset;
function reset(tm: in out T) return Float is
oldTime: Ada.Calendar.Time;
begin
oldTime := tm.clock;
tm.clock := Ada.Calendar.Clock;
return Float(tm.clock - oldTime);
end reset;
procedure report(tm: in out T) is
dur: Float;
begin
dur := tm.reset;
Ada.Text_IO.Put_Line("Elapsed: " & dur'Image);
end report;
procedure report(tm: in out T; message: in String) is
dur: Float;
begin
dur := tm.reset;
Ada.Text_IO.Put_Line(message & ", elapsed: " & dur'Image);
end report;
end Timer;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Exception_Identification.From_Here;
with System.Debug; -- assertions
with C.winbase;
with C.windef;
with C.winerror;
package body System.Synchronous_Objects is
use Ada.Exception_Identification.From_Here;
use type C.windef.DWORD;
use type C.windef.WINBOOL;
function atomic_load (
ptr : not null access constant Counter;
memorder : Integer := C.ATOMIC_ACQUIRE)
return Counter
with Import, Convention => Intrinsic, External_Name => "__atomic_load_4";
procedure atomic_store (
ptr : not null access Counter;
val : Counter;
memorder : Integer := C.ATOMIC_RELEASE)
with Import,
Convention => Intrinsic, External_Name => "__atomic_store_4";
procedure atomic_add_fetch (
ptr : not null access Counter;
val : Counter;
memorder : Integer := C.ATOMIC_ACQ_REL)
with Import,
Convention => Intrinsic, External_Name => "__atomic_add_fetch_4";
function atomic_sub_fetch (
ptr : not null access Counter;
val : Counter;
memorder : Integer := C.ATOMIC_ACQ_REL)
return Counter
with Import,
Convention => Intrinsic, External_Name => "__atomic_sub_fetch_4";
function atomic_compare_exchange (
ptr : not null access Counter;
expected : not null access Counter;
desired : Counter;
weak : Boolean := False;
success_memorder : Integer := C.ATOMIC_ACQ_REL;
failure_memorder : Integer := C.ATOMIC_ACQUIRE)
return Boolean
with Import,
Convention => Intrinsic,
External_Name => "__atomic_compare_exchange_4";
-- mutex
procedure Initialize (Object : in out Mutex) is
begin
Object.Handle := C.winbase.CreateMutex (null, 0, null);
pragma Check (Debug,
Check =>
Address (Object.Handle) /= Null_Address
or else Debug.Runtime_Error ("CreateMutex failed"));
end Initialize;
procedure Finalize (Object : in out Mutex) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.CloseHandle (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("CloseHandle failed"));
end Finalize;
procedure Enter (Object : in out Mutex) is
begin
if C.winbase.WaitForSingleObject (Object.Handle, C.winbase.INFINITE) /=
C.winbase.WAIT_OBJECT_0
then
Raise_Exception (Tasking_Error'Identity);
end if;
end Enter;
procedure Leave (Object : in out Mutex) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.ReleaseMutex (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("ReleaseMutex failed"));
end Leave;
-- condition variable
procedure Initialize (Object : in out Condition_Variable) is
begin
atomic_store (Object.Waiters'Access, 0);
Initialize (Object.Event, Manual => True);
Initialize (Object.Reset_Barrier, Manual => True);
end Initialize;
procedure Finalize (Object : in out Condition_Variable) is
begin
Finalize (Object.Event);
Finalize (Object.Reset_Barrier);
end Finalize;
procedure Notify_All (Object : in out Condition_Variable) is
begin
Reset (Object.Reset_Barrier);
Set (Object.Event);
end Notify_All;
procedure Wait (
Object : in out Condition_Variable;
Mutex : in out Synchronous_Objects.Mutex)
is
Signaled : C.windef.DWORD;
begin
atomic_add_fetch (Object.Waiters'Access, 1);
Signaled :=
C.winbase.SignalObjectAndWait (
hObjectToSignal => Mutex.Handle,
hObjectToWaitOn => Object.Event.Handle,
dwMilliseconds => C.winbase.INFINITE,
bAlertable => 0);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Debug.Runtime_Error ("SignalObjectAndWait failed"));
if atomic_sub_fetch (Object.Waiters'Access, 1) = 0 then
Reset (Object.Event);
Set (Object.Reset_Barrier);
else
Wait (Object.Reset_Barrier);
end if;
Enter (Mutex);
end Wait;
-- queue
procedure Initialize (
Object : in out Queue;
Mutex : not null Mutex_Access) is
begin
Object.Mutex := Mutex;
Initialize (Object.Event, Manual => False);
Object.Head := null;
Object.Tail := null;
Object.Filter := null;
Object.Waiting := False;
Object.Canceled := False;
end Initialize;
procedure Finalize (Object : in out Queue) is
begin
Finalize (Object.Event);
end Finalize;
function Count (
Object : Queue;
Params : Address;
Filter : Queue_Filter)
return Natural
is
Result : Natural;
begin
Enter (Object.Mutex.all);
Result := Unsynchronized_Count (Object, Params, Filter);
Leave (Object.Mutex.all);
return Result;
end Count;
function Unsynchronized_Count (
Object : Queue;
Params : Address;
Filter : Queue_Filter)
return Natural
is
Result : Natural := 0;
I : Queue_Node_Access := Object.Head;
begin
while I /= null loop
if Filter = null or else Filter (I, Params) then
Result := Result + 1;
end if;
I := I.Next;
end loop;
return Result;
end Unsynchronized_Count;
function Canceled (Object : Queue) return Boolean is
begin
return Object.Canceled;
end Canceled;
procedure Cancel (
Object : in out Queue;
Cancel_Node : access procedure (X : in out Queue_Node_Access)) is
begin
Enter (Object.Mutex.all);
Object.Canceled := True;
if Cancel_Node /= null then
while Object.Head /= null loop
declare
Next : constant Queue_Node_Access := Object.Head.Next;
begin
Cancel_Node (Object.Head);
Object.Head := Next;
end;
end loop;
end if;
Leave (Object.Mutex.all);
end Cancel;
procedure Unsynchronized_Prepend (
Object : in out Queue;
Item : not null Queue_Node_Access;
Canceled : out Boolean) is
begin
Canceled := Object.Canceled;
if not Canceled then
Item.Next := Object.Head;
Object.Head := Item;
if Object.Tail = null then
Object.Tail := Item;
end if;
Notify_All (Object, Item);
end if;
end Unsynchronized_Prepend;
procedure Add (
Object : in out Queue;
Item : not null Queue_Node_Access;
Canceled : out Boolean) is
begin
Enter (Object.Mutex.all);
Canceled := Object.Canceled;
if not Canceled then
if Object.Head = null then
Object.Head := Item;
else
Object.Tail.Next := Item;
end if;
Object.Tail := Item;
Item.Next := null;
Notify_All (Object, Item);
end if;
Leave (Object.Mutex.all);
end Add;
procedure Take (
Object : in out Queue;
Item : out Queue_Node_Access;
Params : Address;
Filter : Queue_Filter) is
begin
Enter (Object.Mutex.all);
Unsynchronized_Take (Object, Item, Params, Filter);
Leave (Object.Mutex.all);
end Take;
procedure Unsynchronized_Take (
Object : in out Queue;
Item : out Queue_Node_Access;
Params : Address;
Filter : Queue_Filter)
is
Previous : Queue_Node_Access := null;
I : Queue_Node_Access := Object.Head;
begin
Take_No_Sync (Object, Item, Params, Filter, Previous, I);
end Unsynchronized_Take;
procedure Take_No_Sync (
Object : in out Queue;
Item : out Queue_Node_Access;
Params : Address;
Filter : Queue_Filter;
Previous : in out Queue_Node_Access;
Current : in out Queue_Node_Access) is
begin
Item := null;
Search : while Current /= null loop
if Filter = null or else Filter (Current, Params) then
if Previous /= null then
Previous.Next := Current.Next;
else
Object.Head := Current.Next;
end if;
if Current = Object.Tail then
Object.Tail := Previous;
end if;
Item := Current;
exit Search;
end if;
Previous := Current;
Current := Current.Next;
end loop Search;
end Take_No_Sync;
procedure Notify_All (
Object : in out Queue;
Item : not null Queue_Node_Access) is
begin
if Object.Waiting
and then (
Object.Filter = null or else Object.Filter (Item, Object.Params))
then
Set (Object.Event);
end if;
end Notify_All;
-- event
procedure Initialize (Object : in out Event; Manual : Boolean := True) is
begin
Object.Handle :=
C.winbase.CreateEvent (null, Boolean'Pos (Manual), 0, null);
end Initialize;
procedure Finalize (Object : in out Event) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.CloseHandle (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("CloseHandle failed"));
end Finalize;
function Get (Object : Event) return Boolean is
Signaled : C.windef.DWORD;
begin
Signaled := C.winbase.WaitForSingleObject (Object.Handle, 0);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Signaled = C.winerror.WAIT_TIMEOUT
or else Debug.Runtime_Error ("WaitForSingleObject failed"));
return Signaled = C.winbase.WAIT_OBJECT_0;
end Get;
procedure Set (Object : in out Event) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.SetEvent (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("SetEvent failed"));
end Set;
procedure Reset (Object : in out Event) is
Success : C.windef.WINBOOL;
begin
Success := C.winbase.ResetEvent (Object.Handle);
pragma Check (Debug,
Check =>
Success /= C.windef.FALSE
or else Debug.Runtime_Error ("ResetEvent failed"));
end Reset;
procedure Wait (
Object : in out Event)
is
Signaled : C.windef.DWORD;
begin
Signaled :=
C.winbase.WaitForSingleObject (Object.Handle, C.winbase.INFINITE);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Debug.Runtime_Error ("WaitForSingleObject failed"));
end Wait;
procedure Wait (
Object : in out Event;
Timeout : Duration;
Value : out Boolean)
is
Milliseconds : constant C.windef.DWORD :=
C.windef.DWORD (Duration'Max (0.0, Timeout) * 1_000);
Signaled : C.windef.DWORD;
begin
Signaled := C.winbase.WaitForSingleObject (Object.Handle, Milliseconds);
pragma Check (Debug,
Check =>
Signaled = C.winbase.WAIT_OBJECT_0
or else Signaled = C.winerror.WAIT_TIMEOUT
or else Debug.Runtime_Error ("WaitForSingleObject failed"));
Value := Signaled = C.winbase.WAIT_OBJECT_0;
end Wait;
function Handle (Object : Event) return C.winnt.HANDLE is
begin
return Object.Handle;
end Handle;
-- multi-read/exclusive-write lock for protected
procedure Initialize (Object : in out RW_Lock) is
begin
atomic_store (Object.State'Access, 0);
Initialize (Object.Reader_Barrier, Manual => True);
Initialize (Object.Writer_Barrier, Manual => False);
end Initialize;
procedure Finalize (Object : in out RW_Lock) is
begin
Finalize (Object.Reader_Barrier);
Finalize (Object.Writer_Barrier);
end Finalize;
procedure Enter_Reading (Object : in out RW_Lock) is
begin
loop
declare
Current : constant Counter := atomic_load (Object.State'Access);
begin
if Current >= 0 then
declare
Expected : aliased Counter := Current;
begin
exit when atomic_compare_exchange (
Object.State'Access,
Expected'Access,
Current + 1);
end;
else
Wait (Object.Reader_Barrier);
end if;
end;
end loop;
end Enter_Reading;
procedure Enter_Writing (Object : in out RW_Lock) is
begin
loop
declare
Expected : aliased Counter := 0;
begin
exit when atomic_compare_exchange (
Object.State'Access,
Expected'Access,
-999);
end;
Wait (Object.Writer_Barrier);
end loop;
Reset (Object.Reader_Barrier);
end Enter_Writing;
procedure Leave (Object : in out RW_Lock) is
Expected : aliased Counter := -999;
begin
if atomic_compare_exchange (Object.State'Access, Expected'Access, 0) then
-- writer
Set (Object.Reader_Barrier);
Set (Object.Writer_Barrier);
else
-- reader
if atomic_sub_fetch (Object.State'Access, 1) = 0 then
Reset (Object.Reader_Barrier);
Set (Object.Writer_Barrier);
end if;
end if;
end Leave;
end System.Synchronous_Objects;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Lv.Mem;
package body Lv.Strings is
----------------
-- New_String --
----------------
function New_String (Str : String) return Lv.C_String_Ptr is
use System;
use Interfaces;
Addr : constant System.Address := Lv.Mem.Alloc (Str'Length + 1);
Out_Str : String (1 .. Str'Length + 1) with Address => Addr;
begin
if Addr = System.Null_Address then
return System.Null_Address;
else
Out_Str (1 .. Str'Length) := Str;
Out_Str (Out_Str'Last) := ASCII.NUL;
return Addr;
end if;
end New_String;
----------
-- Free --
----------
procedure Free (Ptr : in out Lv.C_String_Ptr) is
begin
Lv.Mem.Free (Ptr);
Ptr := System.Null_Address;
end Free;
end Lv.Strings;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Unchecked_Conversion;
with System;
-- =============================================================================
-- Package AVR.TIMERS
--
-- Implements timers configurations for the MCU micro-controller.
-- =============================================================================
package AVR.TIMERS is
type General_Timer_Counter_Control_Register_Type is
record
PSRSYNC : Boolean; -- Prescaler Reset for Synchronous Timer/Counters
PSRASY : Boolean; -- Prescaler Reset Timer/Counter2
Spare : Spare_Type (0 .. 4);
TSM : Boolean; -- Timer/Counter Synchronization Mode
end record;
pragma Pack (General_Timer_Counter_Control_Register_Type);
for General_Timer_Counter_Control_Register_Type'Size use BYTE_SIZE;
Reg_GTCCR : General_Timer_Counter_Control_Register_Type;
for Reg_GTCCR'Address use System'To_Address (16#43#);
-- =============================
-- 8-bit Timer/Counter0 with PWM
-- =============================
type Timer_Counter_Control_Register_A_For_8_Bit_Timer_Type is
record
WGM0 : Boolean; -- Waveform Generation Mode Bit 0
WGM1 : Boolean; -- Waveform Generation Mode Bit 1
Spare : Spare_Type (0 .. 1);
COMB : Bit_Array_Type (0 .. 1); -- Compare Output Mode Channel B Bits
COMA : Bit_Array_Type (0 .. 1); -- Compare Output Mode Channel A Bits
end record;
pragma Pack (Timer_Counter_Control_Register_A_For_8_Bit_Timer_Type);
for Timer_Counter_Control_Register_A_For_8_Bit_Timer_Type'Size use BYTE_SIZE;
type Timer_Counter_Control_Register_B_For_8_Bit_Timer_Type is
record
CS : Bit_Array_Type (0 .. 2); -- Clock Select Bits
WGM2 : Boolean; -- Waveform Generation Mode Bit 2
Spare : Spare_Type (0 .. 1);
FOCB : Boolean; -- Force Output Compare B
FOCA : Boolean; -- Force Output Compare A
end record;
pragma Pack (Timer_Counter_Control_Register_B_For_8_Bit_Timer_Type);
for Timer_Counter_Control_Register_B_For_8_Bit_Timer_Type'Size use BYTE_SIZE;
type Timer_8_Bits_Type is
record
TCCRA : Timer_Counter_Control_Register_A_For_8_Bit_Timer_Type;
TCCRB : Timer_Counter_Control_Register_B_For_8_Bit_Timer_Type;
TCNT : Byte_Type; -- Timer/Counter
OCRA : Byte_Type; -- Output Compare Register A
OCRB : Byte_Type; -- Output Compare Register A
end record;
pragma Pack (Timer_8_Bits_Type);
for Timer_8_Bits_Type'Size use 5 * BYTE_SIZE;
Reg_Timer0 : Timer_8_Bits_Type;
for Reg_Timer0'Address use System'To_Address (16#44#);
type Timer_Counter_Interrupt_Mask_For_8_Bit_Timer_Type is
record
TOIE : Boolean; -- Timer/Counter Overflow Interrupt Enable
OCIEA : Boolean; -- Timer/Counter Output Compare Match A Interrupt Enable
OCIEB : Boolean; -- Timer/Counter Output Compare Match B Interrupt Enable
Spare : Spare_Type (0 .. 4);
end record;
pragma Pack (Timer_Counter_Interrupt_Mask_For_8_Bit_Timer_Type);
for Timer_Counter_Interrupt_Mask_For_8_Bit_Timer_Type'Size use BYTE_SIZE;
Reg_Timer0_TIMSK : Timer_Counter_Interrupt_Mask_For_8_Bit_Timer_Type;
for Reg_Timer0_TIMSK'Address use System'To_Address (16#6E#);
type Timer_Counter_Interrupt_Flag_For_8_Bit_Timer_Type is
record
TOV : Boolean; -- Timer/Counter Overflow Flag
OCFA : Boolean; -- Output Compare Flag A
OCFB : Boolean; -- Output Compare Flag B
Spare : Spare_Type (0 .. 4);
end record;
pragma Pack (Timer_Counter_Interrupt_Flag_For_8_Bit_Timer_Type);
for Timer_Counter_Interrupt_Flag_For_8_Bit_Timer_Type'Size use BYTE_SIZE;
Reg_Timer0_TIFR : Timer_Counter_Interrupt_Flag_For_8_Bit_Timer_Type;
for Reg_Timer0_TIFR'Address use System'To_Address (16#35#);
-- =========================================================
-- 16-bit Timer/Counter0 with (Timer/Counter 1, 3, 4, and 5)
-- =========================================================
type Timer_Counter_Control_Register_A_For_16_Bit_Timer_Type is
record
WGM0 : Boolean; -- Waveform Generation Mode Bit 0
WGM1 : Boolean; -- Waveform Generation Mode Bit 0
#if MCU="ATMEGA2560" then
COMC : Bit_Array_Type (0 .. 1); -- Compare Output Mode Channel C Bits
#elsif MCU="ATMEGA328P" then
Spare_23 : Spare_Type (0 .. 1);
#end if;
COMB : Bit_Array_Type (0 .. 1); -- Compare Output Mode Channel B Bits
COMA : Bit_Array_Type (0 .. 1); -- Compare Output Mode Channel A Bits
end record;
pragma Pack (Timer_Counter_Control_Register_A_For_16_Bit_Timer_Type);
for Timer_Counter_Control_Register_A_For_16_Bit_Timer_Type'Size use
BYTE_SIZE;
type Timer_Counter_Control_Register_B_For_16_Bit_Timer_Type is
record
CS : Bit_Array_Type (0 .. 2); -- Clock Select Bits
WGM2 : Boolean; -- Waveform Generation Mode Bit 2
WGM3 : Boolean; -- Waveform Generation Mode Bit 3
Spare : Spare_Type (0 .. 0);
ICES : Boolean; -- Input Capture Edge Select
ICNC : Boolean; -- Input Capture Noise Canceler
end record;
pragma Pack (Timer_Counter_Control_Register_B_For_16_Bit_Timer_Type);
for Timer_Counter_Control_Register_B_For_16_Bit_Timer_Type'Size use
BYTE_SIZE;
type Timer_Counter_Control_Register_C_For_16_Bit_Timer_Type is
record
#if MCU="ATMEGA2560" then
Spare : Spare_Type (0 .. 4);
FOCC : Boolean; -- Force Output Compare C
#elsif MCU="ATMEGA328P" then
Spare : Spare_Type (0 .. 5);
#end if;
FOCB : Boolean; -- Force Output Compare B
FOCA : Boolean; -- Force Output Compare A
end record;
pragma Pack (Timer_Counter_Control_Register_C_For_16_Bit_Timer_Type);
for Timer_Counter_Control_Register_C_For_16_Bit_Timer_Type'Size use
BYTE_SIZE;
type Timer_16_Bits_Type is
record
TCCRA : Timer_Counter_Control_Register_A_For_16_Bit_Timer_Type;
TCCRB : Timer_Counter_Control_Register_B_For_16_Bit_Timer_Type;
TCCRC : Timer_Counter_Control_Register_C_For_16_Bit_Timer_Type;
Spare : Spare_Type (0 .. 7);
TCNT : Byte_Array_Type (0 .. 1); -- Timer/Counter
ICR : Byte_Array_Type (0 .. 1); -- Input Capture Register
OCRA : Byte_Array_Type (0 .. 1); -- Output Compare Register A
OCRB : Byte_Array_Type (0 .. 1); -- Output Compare Register B
#if MCU="ATMEGA2560" then
OCRC : Byte_Array_Type (0 .. 1); -- Output Compare Register C
#end if;
end record;
pragma Pack (Timer_16_Bits_Type);
#if MCU="ATMEGA2560" then
for Timer_16_Bits_Type'Size use 14 * BYTE_SIZE;
#elsif MCU="ATMEGA328P" then
for Timer_16_Bits_Type'Size use 12 * BYTE_SIZE;
#end if;
Reg_Timer1 : Timer_16_Bits_Type;
for Reg_Timer1'Address use System'To_Address (16#80#);
Reg_Timer3 : Timer_16_Bits_Type;
for Reg_Timer3'Address use System'To_Address (16#90#);
Reg_Timer4 : Timer_16_Bits_Type;
for Reg_Timer4'Address use System'To_Address (16#A0#);
Reg_Timer5 : Timer_16_Bits_Type;
for Reg_Timer5'Address use System'To_Address (16#120#);
type Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type is
record
TOIE : Boolean; -- Timer/Counter Overflow Interrupt Enable
OCIEA : Boolean; -- Timer/Counter Output Compare Match A Interrupt Enable
OCIEB : Boolean; -- Timer/Counter Output Compare Match B Interrupt Enable
#if MCU="ATMEGA2560" then
OCIEC : Boolean; -- Timer/Counter Output Compare Match C Interrupt Enable
Spare_4 : Spare_Type (0 .. 0);
#elsif MCU="ATMEGA328P" then
Spare_34 : Spare_Type (0 .. 1);
#end if;
ICIE : Boolean; -- Timer/Counter Input Capture Interrupt Enable
Spare_67 : Spare_Type (0 .. 1);
end record;
pragma Pack (Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type);
for Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type'Size use
BYTE_SIZE;
Reg_Timer1_TIMSK : Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type;
for Reg_Timer1_TIMSK'Address use System'To_Address (16#6F#);
Reg_Timer3_TIMSK : Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type;
for Reg_Timer3_TIMSK'Address use System'To_Address (16#71#);
Reg_Timer4_TIMSK : Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type;
for Reg_Timer4_TIMSK'Address use System'To_Address (16#72#);
Reg_Timer5_TIMSK : Timer_Counter_Interrupt_Mask_For_16_Bit_Timer_Type;
for Reg_Timer5_TIMSK'Address use System'To_Address (16#73#);
type Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type is
record
TOV : Boolean; -- Timer/Counter Overflow Flag
OCFA : Boolean; -- Output Compare Flag A
OCFB : Boolean; -- Output Compare Flag B
#if MCU="ATMEGA2560" then
OCFC : Boolean; -- Output Compare Flag C
Spare_1 : Spare_Type (0 .. 0);
#elsif MCU="ATMEGA328P" then
Spare_34 : Spare_Type (0 .. 1);
#end if;
ICF : Boolean; -- Timer/Counter Input Capture Flag
Spare_7 : Spare_Type (0 .. 1);
end record;
pragma Pack (Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type);
for Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type'Size use BYTE_SIZE;
Reg_Timer1_TIFR : Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type;
for Reg_Timer1_TIFR'Address use System'To_Address (16#36#);
Reg_Timer3_TIFR : Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type;
for Reg_Timer3_TIFR'Address use System'To_Address (16#36#);
Reg_Timer4_TIFR : Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type;
for Reg_Timer4_TIFR'Address use System'To_Address (16#36#);
Reg_Timer5_TIFR : Timer_Counter_Interrupt_Flag_For_16_Bit_Timer_Type;
for Reg_Timer5_TIFR'Address use System'To_Address (16#36#);
-- ========================================================
-- 8-bit Timer/Counter2 with PWM and Asynchronous Operation
-- ========================================================
Reg_Timer2 : Timer_8_Bits_Type;
for Reg_Timer2'Address use System'To_Address (16#B0#);
type Asynchronous_Status_Register_For_Timer2_Type is
record
TCR2BUB : Boolean; -- Timer/Counter 2 Control Register Update Busy B
TCR2AUB : Boolean; -- Timer/Counter 2 Control Register Update Busy A
OCR2BUB : Boolean; -- Output Compare Register 2 Update Busy B
OCR2AUB : Boolean; -- Output Compare Register 2 Update Busy A
TCN2UB : Boolean; -- Timer/Counter 2 Update Busy
AS2 : Boolean; -- Asynchronous Timer/Counter 2
EXCLK : Boolean; -- Enable External Clock Input
Spare : Spare_Type (0 .. 0);
end record;
pragma Pack (Asynchronous_Status_Register_For_Timer2_Type);
for Asynchronous_Status_Register_For_Timer2_Type'Size use BYTE_SIZE;
Reg_Timer2_ASSR : Asynchronous_Status_Register_For_Timer2_Type;
for Reg_Timer2_ASSR'Address use System'To_Address (16#B6#);
Reg_Timer2_TIMSK : Timer_Counter_Interrupt_Mask_For_8_Bit_Timer_Type;
for Reg_Timer2_TIMSK'Address use System'To_Address (16#70#);
Reg_Timer2_TIFR : Timer_Counter_Interrupt_Flag_For_8_Bit_Timer_Type;
for Reg_Timer2_TIFR'Address use System'To_Address (16#37#);
#if MCU="ATMEGA2560" then
type Timer_Type is
(TIMER0,
TIMER1,
TIMER2,
TIMER3,
TIMER4,
TIMER5);
#elsif MCU="ATMEGA328P" then
type Timer_Type is
(TIMER0,
TIMER1,
TIMER2);
#end if;
#if MCU="ATMEGA2560" then
type Channel_Type is
(CHANNEL_A,
CHANNEL_B,
CHANNEL_C);
#elsif MCU="ATMEGA328P" then
type Channel_Type is
(CHANNEL_A,
CHANNEL_B);
#end if;
type Channel_Priority_Type is array (Channel_Type) of Unsigned_16;
type Unsigned_16_Array_Byte is
record
L : Unsigned_8;
H : Unsigned_8;
end record;
function Get_Compare_Value
(Timer : TIMERS.Timer_Type;
Channel : TIMERS.Channel_Type)
return Unsigned_16;
function Get_Compare_Value
(Timer : TIMERS.Timer_Type;
Channel : TIMERS.Channel_Type)
return Unsigned_16_Array_Byte;
function Get_Current_Value
(Timer : TIMERS.Timer_Type)
return Unsigned_16;
function Get_Current_Value
(Timer : TIMERS.Timer_Type)
return Unsigned_16_Array_Byte;
function To_Unsigned_16_Array_Byte is new Unchecked_Conversion
(Source => Unsigned_16,
Target => Unsigned_16_Array_Byte);
private
function To_Unsigned_16 is new Unchecked_Conversion
(Source => Unsigned_16_Array_Byte,
Target => Unsigned_16);
end AVR.TIMERS;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with TH;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
procedure TH_Sujet is
package TH_str_int is
new TH (Capacite => 11, T_Cle => Unbounded_String, T_Donnee => Integer, Hachage => Length);
use TH_str_int;
Donnees : T_TH;
procedure Afficher_Element(Cle: Unbounded_String; Donnee: Integer) is
begin
Put(To_String(Cle) & " -> ");
Put(Donnee, 1);
New_Line;
end Afficher_Element;
procedure Afficher_Elements is
new Pour_Chaque(Afficher_Element);
begin
Initialiser(Donnees);
Enregistrer(Donnees, To_Unbounded_String("un"), 1);
Enregistrer(Donnees, To_Unbounded_String("deux"), 2);
Enregistrer(Donnees, To_Unbounded_String("trois"), 3);
Enregistrer(Donnees, To_Unbounded_String("quatre"), 4);
Enregistrer(Donnees, To_Unbounded_String("cinq"), 5);
Enregistrer(Donnees, To_Unbounded_String("quatre-vingt-dix-neuf"), 99);
Enregistrer(Donnees, To_Unbounded_String("vingt-et-un"), 21);
Put("Elements de la table de hachage.");
Afficher_Elements(Donnees);
Vider(Donnees);
end TH_Sujet;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Strings.Unbounded;
with Config_File_Parser;
pragma Elaborate_All (Config_File_Parser);
package Config is
function TUS (S : String) return Ada.Strings.Unbounded.Unbounded_String
renames Ada.Strings.Unbounded.To_Unbounded_String;
-- Convenience rename. TUS is much shorter than To_Unbounded_String.
type Keys is (
FULLNAME,
FAVOURITEFRUIT,
NEEDSPEELING,
SEEDSREMOVED,
OTHERFAMILY);
-- These are the valid configuration keys.
type Defaults_Array is
array (Keys) of Ada.Strings.Unbounded.Unbounded_String;
-- The array type we'll use to hold our default configuration settings.
Defaults_Conf : Defaults_Array :=
(FULLNAME => TUS ("<NAME>"),
FAVOURITEFRUIT => TUS ("blackberry"),
NEEDSPEELING => TUS ("False"),
SEEDSREMOVED => TUS ("False"),
OTHERFAMILY => TUS ("<NAME>, Ada Byron"));
-- Default values for the Program object. These can be overwritten by
-- the contents of the rosetta.cfg file(see below).
package Rosetta_Config is new Config_File_Parser (
Keys => Keys,
Defaults_Array => Defaults_Array,
Defaults => Defaults_Conf,
Config_File => "rosetta.cfg");
-- Instantiate the Config configuration object.
end Config;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
package body Orka.Containers.Bounded_Vectors is
function Length (Container : Vector) return Length_Type is
(Container.Length);
function Is_Empty (Container : Vector) return Boolean is
(Length (Container) = 0);
function Is_Full (Container : Vector) return Boolean is
(Length (Container) = Container.Capacity);
procedure Append (Container : in out Vector; Elements : Vector) is
Start_Index : constant Index_Type := Container.Length + Index_Type'First;
Stop_Index : constant Index_Type'Base := Start_Index + Elements.Length - 1;
procedure Copy_Elements (Elements : Element_Array) is
begin
Container.Elements (Start_Index .. Stop_Index) := Elements;
end Copy_Elements;
begin
Elements.Query (Copy_Elements'Access);
Container.Length := Container.Length + Elements.Length;
end Append;
procedure Append (Container : in out Vector; Element : Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First;
begin
Container.Length := Container.Length + 1;
Container.Elements (Index) := Element;
end Append;
procedure Remove_Last (Container : in out Vector; Element : out Element_Type) is
Index : constant Index_Type := Container.Length + Index_Type'First - 1;
begin
Element := Container.Elements (Index);
Container.Elements (Index .. Index) := (others => <>);
Container.Length := Container.Length - 1;
end Remove_Last;
procedure Clear (Container : in out Vector) is
begin
Container.Elements := (others => <>);
Container.Length := 0;
end Clear;
procedure Query
(Container : Vector;
Process : not null access procedure (Elements : Element_Array))
is
Last_Index : constant Index_Type'Base := Container.Length + Index_Type'First - 1;
begin
Process (Container.Elements (Index_Type'First .. Last_Index));
end Query;
procedure Update
(Container : in out Vector;
Index : Index_Type;
Process : not null access procedure (Element : in out Element_Type)) is
begin
Process (Container.Elements (Index));
end Update;
function Element (Container : Vector; Index : Index_Type) return Element_Type is
(Container.Elements (Index));
function Element (Container : aliased Vector; Position : Cursor) return Element_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Element (Container, Position.Index);
end if;
end Element;
function Constant_Reference
(Container : aliased Vector;
Index : Index_Type) return Constant_Reference_Type is
begin
return Constant_Reference_Type'(Value => Container.Elements (Index)'Access);
end Constant_Reference;
function Constant_Reference
(Container : aliased Vector;
Position : Cursor) return Constant_Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Constant_Reference (Container, Position.Index);
end if;
end Constant_Reference;
function Reference
(Container : aliased in out Vector;
Index : Index_Type) return Reference_Type is
begin
return Reference_Type'(Value => Container.Elements (Index)'Access);
end Reference;
function Reference
(Container : aliased in out Vector;
Position : Cursor) return Reference_Type is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Object.all /= Container then
raise Program_Error;
else
return Reference (Container, Position.Index);
end if;
end Reference;
function Iterate (Container : Vector)
return Vector_Iterator_Interfaces.Reversible_Iterator'Class is
begin
return Iterator'(Container => Container'Unchecked_Access);
end Iterate;
overriding function First (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container, Index => Index_Type'First);
end if;
end First;
overriding function Last (Object : Iterator) return Cursor is
begin
if Object.Container.all.Is_Empty then
return No_Element;
else
return Cursor'(Object => Object.Container,
Index => Object.Container.all.Length);
end if;
end Last;
overriding function Next
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Position.Object.Length + Index_Type'First - 1 then
return No_Element;
else
return Cursor'(Position.Object, Position.Index + 1);
end if;
end Next;
overriding function Previous
(Object : Iterator;
Position : Cursor) return Cursor is
begin
if Position = No_Element then
raise Constraint_Error;
elsif Position.Index = Index_Type'First then
return No_Element;
else
return Cursor'(Position.Object, Position.Index - 1);
end if;
end Previous;
end Orka.Containers.Bounded_Vectors;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- COPYING. If not, write to the Free Software Foundation, 59 Temple Place --
-- - Suite 330, Boston, MA 02111-1307, USA. --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- --
-- ASIS-for-GNAT was originally developed by the ASIS-for-GNAT team at the --
-- Software Engineering Laboratory of the Swiss Federal Institute of --
-- Technology (LGL-EPFL) in Lausanne, Switzerland, in cooperation with the --
-- Scientific Research Computer Center of Moscow State University (SRCC --
-- MSU), Russia, with funding partially provided by grants from the Swiss --
-- National Science Foundation and the Swiss Academy of Engineering --
-- Sciences. ASIS-for-GNAT is now maintained by Ada Core Technologies Inc --
-- (http://www.gn<EMAIL>). --
-- --
------------------------------------------------------------------------------
with Asis; use Asis;
with A4G.A_Types; use A4G.A_Types;
with Types; use Types;
-- This package contains the routines used to compute the unit attributes
-- during the second pass through the tree files, when ASIS operates in
-- Use_Pre_Created_Trees mode. There is some duplication of the
-- functionalities provided by this package and by A4G.C_U_Info and
-- A4G.S_U_Info; the last two packages were coded before for
-- Compile_On_The_Fly ASIS operation mode. The intent is to get rid of
-- A4G.C_U_Info and A4G.S_U_Info in the final ASIS version, so we do not
-- bother about these duplications for now.
-- ???THIS COMMENT HEADER SHOULD BE REVISED!!!???
package A4G.CU_Info2 is
procedure Set_Kind_and_Class
(C : Context_Id;
U : Unit_Id;
Top : Node_Id);
-- Taking the unit's subtree top node, this procedure computes and sets
-- the Unit Kind and the Unit Class for U. Because of some technical ,
-- reasons, it is more easy to define the Unit Kind and the Unit Class
-- in the same routine
procedure Get_Ada_Name (Top : Node_Id);
-- Computes (by traversing the tree) the fully expanded Ada name
-- of a compilation unit whose subtree contained as having Top as
-- its top node in the full tree currently being accessed. This name
-- then is set in A_Name_Buffer, and A_Name_Len is set as its length
procedure Set_S_F_Name_and_Origin
(Context : Context_Id;
Unit : Unit_Id;
Top : Node_Id);
-- This procedure obtains the source file name from the GNAT tree and
-- stores it in the Unit_Table. By analyzing the file name (this analysis
-- is based on the Fname.Is_Predefined_File_Name GNAt function, the
-- Unit_Origin for the Unit is defined and stored in the Unit table.
function Is_Main (Top : Node_Id; Kind : Unit_Kinds) return Boolean;
-- Defines if the Unit having Top as its N_Compilation_Unit node
-- can be a main subprogram for a partition. Asis Unit Kind is
-- used to optimize this computation
procedure Set_Dependencies
(C : Context_Id;
U : Unit_Id;
Top : Node_Id);
-- Taking the unit's subtree top node, this procedure computes and sets
-- all the dependency information needed for semantic queries from the
-- Asis.Compilation_Units package. This information is stored as unit
-- lists (see A4G.Unit_Rec). For now, we do not compute the lists of
-- *direct* supporters and *direct* dependents, because we think, that
-- these ASIS notions are ill-defined and cannot be mapped onto RM95
-- in a natural way.
end A4G.CU_Info2;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-- implementation unit specialized for Windows
with C.winnt;
package System.Zero_Terminated_WStrings is
pragma Preelaborate;
-- This package targets at not Wide_String in Ada, not wchar_t in C
-- but LPWSTR in Windows.
-- convert from zero-terminated LPWSTR to UTF-8 String
function Value (Item : not null access constant C.winnt.WCHAR)
return String;
function Value (
Item : not null access constant C.winnt.WCHAR;
Length : C.size_t)
return String;
-- convert from UTF-8 String to zero-terminated LPWSTR
procedure To_C (Source : String; Result : not null access C.winnt.WCHAR);
procedure To_C (
Source : String;
Result : not null access C.winnt.WCHAR;
Result_Length : out C.size_t);
Expanding : constant := 1; -- same as Expanding_From_8_To_16
end System.Zero_Terminated_WStrings;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-----------------------------------------------------------------------
with Util.Log.Loggers;
package body Util.Serialize.Mappers.Vector_Mapper is
use Vectors;
use Util.Log;
-- The logger
Log : constant Loggers.Logger := Loggers.Create ("Util.Serialize.Mappers.Vector_Mapper",
Util.Log.WARN_LEVEL);
Key : Util.Serialize.Contexts.Data_Key;
-- -----------------------
-- Data context
-- -----------------------
-- Data context to get access to the target element.
-- -----------------------
-- Get the vector object.
-- -----------------------
function Get_Vector (Data : in Vector_Data) return Vector_Type_Access is
begin
return Data.Vector;
end Get_Vector;
-- -----------------------
-- Set the vector object.
-- -----------------------
procedure Set_Vector (Data : in out Vector_Data;
Vector : in Vector_Type_Access) is
begin
Data.Vector := Vector;
end Set_Vector;
-- -----------------------
-- Record mapper
-- -----------------------
-- -----------------------
-- Set the <b>Data</b> vector in the context.
-- -----------------------
procedure Set_Context (Ctx : in out Util.Serialize.Contexts.Context'Class;
Data : in Vector_Type_Access) is
Data_Context : constant Vector_Data_Access := new Vector_Data;
begin
Data_Context.Vector := Data;
Data_Context.Position := Index_Type'First;
Ctx.Set_Data (Key => Key, Content => Data_Context.all'Unchecked_Access);
end Set_Context;
-- -----------------------
-- Execute the mapping operation on the object associated with the current context.
-- The object is extracted from the context and the <b>Execute</b> operation is called.
-- -----------------------
procedure Execute (Handler : in Mapper;
Map : in Mapping'Class;
Ctx : in out Util.Serialize.Contexts.Context'Class;
Value : in Util.Beans.Objects.Object) is
pragma Unreferenced (Handler);
procedure Process (Element : in out Element_Type);
procedure Process (Element : in out Element_Type) is
begin
Element_Mapper.Set_Member (Map, Element, Value);
end Process;
D : constant Contexts.Data_Access := Ctx.Get_Data (Key);
begin
Log.Debug ("Updating vector element");
if not (D.all in Vector_Data'Class) then
raise Util.Serialize.Contexts.No_Data;
end if;
declare
DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access;
begin
if DE.Vector = null then
raise Util.Serialize.Contexts.No_Data;
end if;
-- Update the element through the generic procedure
Update_Element (DE.Vector.all, DE.Position - 1, Process'Access);
end;
end Execute;
procedure Set_Mapping (Into : in out Mapper;
Inner : in Element_Mapper.Mapper_Access) is
begin
Into.Mapper := Inner.all'Unchecked_Access;
Into.Map.Bind (Inner);
end Set_Mapping;
-- -----------------------
-- Find the mapper associated with the given name.
-- Returns null if there is no mapper.
-- -----------------------
function Find_Mapper (Controller : in Mapper;
Name : in String) return Util.Serialize.Mappers.Mapper_Access is
begin
return Controller.Mapper.Find_Mapper (Name);
end Find_Mapper;
overriding
procedure Initialize (Controller : in out Mapper) is
begin
Controller.Mapper := Controller.Map'Unchecked_Access;
end Initialize;
procedure Start_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
pragma Unreferenced (Handler);
procedure Set_Context (Item : in out Element_Type);
D : constant Contexts.Data_Access := Context.Get_Data (Key);
procedure Set_Context (Item : in out Element_Type) is
begin
Element_Mapper.Set_Context (Ctx => Context, Element => Item'Unrestricted_Access);
end Set_Context;
begin
Log.Debug ("Creating vector element {0}", Name);
if not (D.all in Vector_Data'Class) then
raise Util.Serialize.Contexts.No_Data;
end if;
declare
DE : constant Vector_Data_Access := Vector_Data'Class (D.all)'Access;
begin
if DE.Vector = null then
raise Util.Serialize.Contexts.No_Data;
end if;
Insert_Space (DE.Vector.all, DE.Position);
DE.Vector.Update_Element (Index => DE.Position, Process => Set_Context'Access);
DE.Position := DE.Position + 1;
end;
end Start_Object;
procedure Finish_Object (Handler : in Mapper;
Context : in out Util.Serialize.Contexts.Context'Class;
Name : in String) is
begin
null;
end Finish_Object;
-- -----------------------
-- Write the element on the stream using the mapper description.
-- -----------------------
procedure Write (Handler : in Mapper;
Stream : in out Util.Serialize.IO.Output_Stream'Class;
Element : in Vectors.Vector) is
Pos : Vectors.Cursor := Element.First;
begin
Stream.Start_Array (Element.Length);
while Vectors.Has_Element (Pos) loop
Element_Mapper.Write (Handler.Mapper.all, Handler.Map.Get_Getter,
Stream, Vectors.Element (Pos));
Vectors.Next (Pos);
end loop;
Stream.End_Array;
end Write;
begin
-- Allocate the unique data key.
Util.Serialize.Contexts.Allocate (Key);
end Util.Serialize.Mappers.Vector_Mapper;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--____________________________________________________________________--
package body IEEE_754.Generic_Double_Precision is
Exponent_Bias : constant := 2**10 - 1;
Exponent_First : constant := -51;
Exponent_Last : constant := 2**11 - 1;
Fraction_Bits : constant := 52;
Mantissa_Bits : constant := 53;
function Exponent (Value : Float_64) return Integer is
pragma Inline (Exponent);
begin
return
Integer
( Shift_Left (Unsigned_16 (Value (1)) and 16#7F#, 4)
or Shift_Right (Unsigned_16 (Value (2)), 4)
);
end Exponent;
function Mantissa (Value : Float_64) return Unsigned_64 is
pragma Inline (Mantissa);
begin
return
( Unsigned_64 (Value (8))
or Shift_Left (Unsigned_64 (Value (7)), 8 )
or Shift_Left (Unsigned_64 (Value (6)), 2*8)
or Shift_Left (Unsigned_64 (Value (5)), 3*8)
or Shift_Left (Unsigned_64 (Value (4)), 4*8)
or Shift_Left (Unsigned_64 (Value (3)), 5*8)
or Shift_Left (Unsigned_64 (Value (2)) and 16#0F#, 6*8)
or 2 ** Fraction_Bits
);
end Mantissa;
procedure Normalize
( Value : Number;
Mantissa : out Unsigned_64;
Exponent : out Integer
) is
begin
if Number'Machine_Radix = 2 then
--
-- The machine radix is binary. We can use the hardware
-- representation attributes in order to get the exponent and
-- the fraction.
--
Exponent := Number'Exponent (Value) - Mantissa_Bits;
Mantissa := Unsigned_64 (Number'Scaling (Value, -Exponent));
else
--
-- OK, this gets more tricky. The number is normalized to be in
-- the range 2**53 > X >= 2**52, by multiplying to the powers
-- of two. Some optimization is made to factor out the powers
-- 2**(2**n)). Though we do not use powers bigger than 30.
--
declare
Accum : Number := Value;
Shift : Integer;
begin
Exponent := 0;
if Accum < 2.0**Fraction_Bits then
Shift := 24;
while Shift > 0 loop
if Accum < 2.0**(Mantissa_Bits - Shift) then
Accum := Accum * 2.0**Shift;
Exponent := Exponent - Shift;
else
Shift := Shift / 2;
end if;
end loop;
elsif Accum >= 2.0**Mantissa_Bits then
Shift := 8;
while Shift > 0 loop
if Accum >= 2.0**(Fraction_Bits + Shift) then
Accum := Accum / 2.0**Shift;
Exponent := Exponent + Shift;
else
Shift := Shift / 2;
end if;
end loop;
end if;
Mantissa := Unsigned_64 (Accum);
end;
end if;
end Normalize;
function From_IEEE (Value : Float_64) return Number is
begin
if 0 = (Value (1) and 16#7F#)
and then
Value (2) = 0
and then
Value (3) = 0
and then
Value (4) = 0
and then
Value (5) = 0
and then
Value (6) = 0
and then
Value (7) = 0
and then
Value (8) = 0
then
return 0.0;
end if;
declare
Power : Integer := Exponent (Value);
Fraction : Unsigned_64 := Mantissa (Value);
Result : Number;
begin
if Power = Exponent_Last then
if Fraction /= 2#1000_0000_0000# then
raise Not_A_Number_Error;
elsif Value (1) > 127 then
raise Negative_Overflow_Error;
else
raise Positive_Overflow_Error;
end if;
elsif Power = 0 then -- Denormalized number
Fraction := Fraction and 16#0F_FF_FF_FF_FF_FF_FF_FF#;
Power := Exponent_First - Exponent_Bias;
if Number'Machine_Radix = 2 then
Result := Number'Scaling (Number (Fraction), Power);
else
Result := Number (Fraction) * 2.0 ** Power;
end if;
else -- Normalized number
Power := Power - Exponent_Bias - Fraction_Bits;
if Number'Machine_Radix = 2 then
Result := Number'Scaling (Number (Fraction), Power);
else
Result := Number (Fraction) * 2.0 ** Power;
end if;
end if;
if Value (1) > 127 then
return -Result;
else
return Result;
end if;
exception
when Constraint_Error =>
if Value (1) > 127 then
raise Negative_Overflow_Error;
else
raise Positive_Overflow_Error;
end if;
end;
end From_IEEE;
function Is_NaN (Value : Float_64) return Boolean is
begin
return
( Exponent (Value) = Exponent_Last
and then
Mantissa (Value) /= 2 ** Fraction_Bits
);
end Is_NaN;
function Is_Negative (Value : Float_64) return Boolean is
begin
return Value (1) > 127;
end Is_Negative;
function Is_Real (Value : Float_64) return Boolean is
begin
return Exponent (Value) < Exponent_Last;
end Is_Real;
function To_IEEE (Value : Number) return Float_64 is
begin
if Value = 0.0 then
return (others => 0);
end if;
declare
Exponent : Integer;
Fraction : Unsigned_64;
Sign : Byte := 0;
begin
if Value > 0.0 then
Normalize (Value, Fraction, Exponent);
else
Normalize (-Value, Fraction, Exponent);
Sign := 2**7;
end if;
Exponent := Exponent + Exponent_Bias + Fraction_Bits;
if Exponent < Exponent_First then
-- Underflow, resuls in zero
return (others => 0);
elsif Exponent >= Exponent_Last then
-- Overflow, results in infinities
if Sign = 0 then
return Positive_Infinity;
else
return Negative_Infinity;
end if;
elsif Exponent <= 0 then -- Denormalized
Fraction := Shift_Right (Fraction, 1 - Exponent);
Exponent := 0;
end if;
return
( Sign or Byte (Exponent / 2**4),
( Byte (Shift_Right (Fraction, 8*6) and 16#0F#)
or Shift_Left (Byte (Exponent mod 2**4), 4)
),
Byte (Shift_Right (Fraction, 8*5) and 16#FF#),
Byte (Shift_Right (Fraction, 8*4) and 16#FF#),
Byte (Shift_Right (Fraction, 8*3) and 16#FF#),
Byte (Shift_Right (Fraction, 8*2) and 16#FF#),
Byte (Shift_Right (Fraction, 8 ) and 16#FF#),
Byte (Fraction and 16#FF#)
);
end;
end To_IEEE;
end IEEE_754.Generic_Double_Precision;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with agar.gui.types;
package agar.gui.widget.titlebar is
subtype titlebar_t is agar.gui.types.widget_titlebar_t;
subtype titlebar_access_t is agar.gui.types.widget_titlebar_access_t;
subtype flags_t is agar.gui.types.widget_titlebar_flags_t;
TITLEBAR_NO_CLOSE : constant flags_t := 16#01#;
TITLEBAR_NO_MINIMIZE : constant flags_t := 16#02#;
TITLEBAR_NO_MAXIMIZE : constant flags_t := 16#04#;
function allocate
(parent : widget_access_t;
flags : flags_t) return titlebar_access_t;
pragma import (c, allocate, "AG_TitlebarNew");
procedure set_caption
(titlebar : titlebar_access_t;
caption : string);
pragma inline (set_caption);
function widget (titlebar : titlebar_access_t)
return agar.gui.widget.widget_access_t
renames agar.gui.types.widget_titlebar_widget;
end agar.gui.widget.titlebar;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Real_Time; use Ada.Real_Time;
with Ada.Calendar; use Ada.Calendar;
procedure Tetris is
Rows: Integer := 38;
Cols: Integer := 22;
FPS: Integer := 240;
-- Höjd: Integer := 18;
-- Bredd: Integer := 10;
I: Integer := 0;
Poll_Time : Time_Span := Milliseconds (1000/FPS);
Blockcol: Integer := 6;
Blockrow: Integer := 0;
Answer : Character;
Available: Boolean := False;
Fastdrop: Boolean := False;
-- Framestart: Time;
-- Period : constant Time_Span := Milliseconds (1000/60);
begin
loop
Get_Immediate(Answer, Available);
if Available then
case Answer is
when 'd' => Blockcol := Blockcol + 2;
when 'a' => Blockcol := Blockcol - 2;
when ' ' => Fastdrop := True;
when others => null;
end case;
Available := False;
end if;
-- Framestart := Clock;
Put(I); New_Line(1);
for Row in 1..Rows loop
for Col in 1..Cols loop
if Row = 1 or Row = Rows then
Put("--");
else if Col = 1 or Col = Cols then
Put("|");
else
if Row = Blockrow or Row = Blockrow + 1 then
if Col = Blockcol or Col = Blockcol +1 then
Put("[]");
else
Put(" ");
end if;
else
Put(" ");
end if;
end if;
end if;
end loop;
New_Line(1);
end loop;
if Fastdrop or I mod FPS = 0 then
if Blockrow = Rows -2 then
Fastdrop := False;
delay until Clock + Milliseconds(500);
Blockrow := 0;
Blockcol := 6;
else
Blockrow := Blockrow + 2;
end if;
end if;
I := I + 1;
delay until Clock + Poll_Time;
--New_Line(30);
-- CLEAR TERMINAL
Ada.TEXT_IO.Put(ASCII.ESC & "[2J");
end loop;
end Tetris;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Interfaces.C;
with Interfaces.C.Strings;
with Ada.Exceptions;
with Ada.Exceptions.Traceback;
with Ada.Finalization;
with GNAT.Traceback;
with GNAT.Traceback.Symbolic;
with GDNative.Tokenizer;
with GDNative.Context;
package body GDNative.Exceptions is
package IC renames Interfaces.C;
package ICS renames Interfaces.C.Strings;
package AE renames Ada.Exceptions;
package AF renames Ada.Finalization;
package GT renames GNAT.Traceback;
package GTS renames GNAT.Traceback.Symbolic;
type Error_Report is new AF.Controlled with record
Subprogram : ICS.chars_ptr;
File : ICS.chars_ptr;
Line : IC.int;
end record;
---------------------------
-- Error_Report Finalize --
---------------------------
overriding procedure Finalize (Object : in out Error_Report) is begin
ICS.Free (Object.Subprogram);
ICS.Free (Object.File);
end;
-----------
-- Parse --
-----------
-- Will extract stack trace info from a GNAT symbolic stack trace output.
--
-- Example Input:
--
-- [C:\project\libproject.dll]
-- test_stack_trace.call_stack at test_stack_trace.adb:10
-- test_stack_trace.inner at test_stack_trace.adb:16
-- test_stack_trace.middle at test_stack_trace.adb:21
-- test_stack_trace.outer at test_stack_trace.adb:26
-- _ada_test_stack_trace at test_stack_trace.adb:30
procedure Parse (Report : in out Error_Report) is
use Tokenizer;
Traces : GT.Tracebacks_Array := GT.Call_Chain (Max_Len => 8, Skip_Frames => 3);
Input : String := GTS.Symbolic_Traceback (Traces);
Seps : Character_Array := (' ', ':', ASCII.LF, ASCII.CR);
State : Tokenizer_State := Initialize (Input, Seps);
begin
Skip_Line (State); -- [path/lib<project.library_name>.dll]
Report.Subprogram := ICS.New_String (Read_String (State));
Skip (State); -- at
Report.File := ICS.New_String (Read_String (State));
Report.Line := IC.int (Read_Integer (State));
end;
-----------------
-- Put Warning --
-----------------
procedure Put_Warning (Message : in Wide_String) is
Description : ICS.chars_ptr := ICS.New_String (To_Str (Message));
Report : Error_Report;
begin
pragma Assert (Context.Core_Initialized, "Please run Context.GDNative_Initialize");
Parse (Report);
Context.Core_Api.godot_print_warning (Description, Report.Subprogram, Report.File, Report.Line);
ICS.Free (Description);
end;
---------------
-- Put Error --
---------------
procedure Put_Error (Occurrence : in Ada.Exceptions.Exception_Occurrence) is
Description : ICS.chars_ptr := ICS.New_String (AE.Exception_Information (Occurrence));
Report : Error_Report;
begin
pragma Assert (Context.Core_Initialized, "Please run Context.GDNative_Initialize");
Parse (Report);
Context.Core_Api.godot_print_error (Description, Report.Subprogram, Report.File, Report.Line);
ICS.Free (Description);
end;
end;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
--*
-- OBJECTIVE:
-- CHECK THAT WHEN AN ENTRY FAMILY MEMBER IS RENAMED THE FORMAL
-- PARAMETER CONSTRAINTS FOR THE NEW NAME ARE IGNORED IN
-- FAVOR OF THE CONSTRAINTS ASSOCIATED WITH THE RENAMED ENTITY.
-- HISTORY:
-- RJW 06/03/86 CREATED ORIGINAL TEST.
-- DHH 10/15/87 CORRECTED RANGE ERRORS.
-- GJD 11/15/95 REMOVED ADA 95 INCOMPATIBILITY (INDEX CONSTRAINT).
-- PWN 10/24/96 RESTORED CHECKS WITH ADA 95 RESULTS NOW EXPECTED.
-- PWN 12/11/96 ADJUSTED VALUES FOR ADA 95 COMPATIBILITY.
-- PWB.CTA 2/17/97 CHANGED CALL TO ENT2 TO NOT EXPECT EXCEPTION
WITH REPORT; USE REPORT;
PROCEDURE C85018B IS
BEGIN
TEST( "C85018B", "CHECK THAT WHEN AN ENTRY FAMILY MEMBER IS " &
"RENAMED THE FORMAL PARAMETER CONSTRAINTS " &
"FOR THE NEW NAME ARE IGNORED IN FAVOR OF " &
"THE CONSTRAINTS ASSOCIATED WITH THE RENAMED " &
"ENTITY" );
DECLARE
TYPE INT IS RANGE 1 .. 10;
SUBTYPE INT1 IS INT RANGE 1 .. 5;
SUBTYPE INT2 IS INT RANGE 6 .. 10;
OBJ1 : INT1 := 5;
OBJ2 : INT2 := 6;
SUBTYPE SHORTCHAR IS CHARACTER RANGE 'A' .. 'C';
TASK T IS
ENTRY ENT1 (SHORTCHAR)
(A : INT1; OK : BOOLEAN);
END T;
PROCEDURE ENT2 (A : INT2; OK : BOOLEAN)
RENAMES T.ENT1 ('C');
TASK BODY T IS
BEGIN
LOOP
SELECT
ACCEPT ENT1 ('C')
(A : INT1; OK : BOOLEAN) DO
IF NOT OK THEN
FAILED ( "WRONG CALL EXECUTED " &
"WITH INTEGER TYPE" );
END IF;
END;
OR
TERMINATE;
END SELECT;
END LOOP;
END T;
BEGIN
BEGIN
ENT2 (OBJ1, TRUE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ( "CONSTRAINT_ERROR RAISED WITH " &
"INTEGER TYPE" );
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"INTEGER TYPE - 1" );
END;
BEGIN
ENT2 (OBJ2, TRUE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"INTEGER TYPE - 2" );
END;
END;
DECLARE
TYPE REAL IS DIGITS 3;
SUBTYPE REAL1 IS REAL RANGE -2.0 .. 0.0;
SUBTYPE REAL2 IS REAL RANGE 0.0 .. 2.0;
OBJ1 : REAL1 := -0.25;
OBJ2 : REAL2 := 0.25;
SUBTYPE SHORTINT IS INTEGER RANGE 9 .. 11;
TASK T IS
ENTRY ENT1 (SHORTINT)
(A : REAL1; OK : BOOLEAN);
END T;
PROCEDURE ENT2 (A : REAL2; OK : BOOLEAN)
RENAMES T.ENT1 (10);
TASK BODY T IS
BEGIN
LOOP
SELECT
ACCEPT ENT1 (10)
(A : REAL1; OK : BOOLEAN) DO
IF NOT OK THEN
FAILED ( "WRONG CALL EXECUTED " &
"WITH FLOATING POINT " &
"TYPE" );
END IF;
END;
OR
TERMINATE;
END SELECT;
END LOOP;
END T;
BEGIN
BEGIN
ENT2 (OBJ1, TRUE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ( "CONSTRAINT_ERROR RAISED WITH " &
"FLOATING POINT " &
"TYPE" );
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"FLOATING POINT " &
"TYPE - 1" );
END;
BEGIN
ENT2 (OBJ2, FALSE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"FLOATING POINT " &
"TYPE - 2" );
END;
END;
DECLARE
TYPE COLOR IS (RED, YELLOW, BLUE, GREEN);
TYPE FIXED IS DELTA 0.125 RANGE -1.0 .. 1.0;
SUBTYPE FIXED1 IS FIXED RANGE 0.0 .. 0.5;
SUBTYPE FIXED2 IS FIXED RANGE -0.5 .. 0.0;
OBJ1 : FIXED1 := 0.125;
OBJ2 : FIXED2 := -0.125;
TASK T IS
ENTRY ENT1 (COLOR)
(A : FIXED1; OK : BOOLEAN);
END T;
PROCEDURE ENT2 (A : FIXED2; OK : BOOLEAN)
RENAMES T.ENT1 (BLUE);
TASK BODY T IS
BEGIN
LOOP
SELECT
ACCEPT ENT1 (BLUE)
(A : FIXED1; OK : BOOLEAN) DO
IF NOT OK THEN
FAILED ( "WRONG CALL EXECUTED " &
"WITH FIXED POINT " &
"TYPE" );
END IF;
END;
OR
TERMINATE;
END SELECT;
END LOOP;
END T;
BEGIN
BEGIN
ENT2 (OBJ1, TRUE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ( "CONSTRAINT_ERROR RAISED WITH " &
"FIXED POINT " &
"TYPE" );
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"FIXED POINT " &
"TYPE - 1" );
END;
BEGIN
ENT2 (OBJ2, FALSE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
NULL;
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"FIXED POINT " &
"TYPE - 2" );
END;
END;
DECLARE
TYPE TA IS ARRAY (INTEGER RANGE <>) OF INTEGER;
SUBTYPE STA1 IS TA(1 .. 5);
SUBTYPE STA2 IS TA(6 .. 10);
OBJ1 : STA1 := (1, 2, 3, 4, 5);
OBJ2 : STA2 := (6, 7, 8, 9, 10);
TASK T IS
ENTRY ENT1 (BOOLEAN)
(A : STA1; OK : BOOLEAN);
END T;
PROCEDURE ENT2 (A : STA2; OK : BOOLEAN)
RENAMES T.ENT1 (FALSE);
TASK BODY T IS
BEGIN
LOOP
SELECT
ACCEPT ENT1 (FALSE)
(A : STA1; OK : BOOLEAN) DO
IF NOT OK THEN
FAILED ( "WRONG CALL EXECUTED " &
"WITH CONSTRAINED " &
"ARRAY" );
END IF;
END;
OR
TERMINATE;
END SELECT;
END LOOP;
END T;
BEGIN
BEGIN
ENT2 (OBJ1, TRUE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ( "CONSTRAINT_ERROR RAISED WITH " &
"CONSTRAINED ARRAY" );
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"CONSTRAINED ARRAY - 1" );
END;
BEGIN
ENT2 (OBJ2, TRUE);
EXCEPTION
WHEN CONSTRAINT_ERROR =>
FAILED ( "CONSTRAINT_ERROR RAISED WITH " &
"CONSTRAINED ARRAY" );
WHEN OTHERS =>
FAILED ( "OTHER EXCEPTION RAISED WITH " &
"CONSTRAINED ARRAY - 2" );
END;
END;
RESULT;
END C85018B;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
pragma Ada_2012;
package body GStreamer.Rtsp.Transport is
--------------
-- Get_Type --
--------------
function Get_Type return GLIB.GType is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Get_Type unimplemented");
return raise Program_Error with "Unimplemented function Get_Type";
end Get_Type;
-----------
-- Parse --
-----------
procedure Parse
(Str : String;
Transport : out GstRTSPTransport_Record)
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Parse unimplemented");
raise Program_Error with "Unimplemented procedure Parse";
end Parse;
-------------
-- As_Text --
-------------
function As_Text (Transport : GstRTSPTransport) return String is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "As_Text unimplemented");
return raise Program_Error with "Unimplemented function As_Text";
end As_Text;
--------------
-- Get_Mime --
--------------
function Get_Mime (Trans : GstRTSPTransMode) return String is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Get_Mime unimplemented");
return raise Program_Error with "Unimplemented function Get_Mime";
end Get_Mime;
-----------------
-- Get_Manager --
-----------------
function Get_Manager
(Trans : GstRTSPTransMode;
Manager : System.Address;
Option : GLIB.Guint)
return GstRTSPResult
is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Get_Manager unimplemented");
return raise Program_Error with "Unimplemented function Get_Manager";
end Get_Manager;
----------
-- Free --
----------
function Free (Transport : access GstRTSPTransport) return GstRTSPResult is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Free unimplemented");
return raise Program_Error with "Unimplemented function Free";
end Free;
-------------
-- Gst_New --
-------------
function Gst_New (Transport : System.Address) return GstRTSPResult is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Gst_New unimplemented");
return raise Program_Error with "Unimplemented function Gst_New";
end Gst_New;
----------
-- Init --
----------
function Init (Transport : access GstRTSPTransport) return GstRTSPResult is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Init unimplemented");
return raise Program_Error with "Unimplemented function Init";
end Init;
----------------
-- Initialize --
----------------
procedure Initialize (Object : in out GstRTSPTransport_Record) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Initialize unimplemented");
raise Program_Error with "Unimplemented procedure Initialize";
end Initialize;
--------------
-- Finalize --
--------------
procedure Finalize (Object : in out GstRTSPTransport_Record) is
begin
-- Generated stub: replace with real body!
pragma Compile_Time_Warning (Standard.True, "Finalize unimplemented");
raise Program_Error with "Unimplemented procedure Finalize";
end Finalize;
end GStreamer.Rtsp.Transport;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
separate (Numerics.Sparse_Matrices)
function Permute_By_Col (Mat : in Sparse_Matrix;
P : in Int_Array) return Sparse_Matrix is
Result : Sparse_Matrix;
Tmp : Nat := 1;
use Ada.Text_IO;
begin
pragma Assert (Mat.Format = CSC);
pragma Assert (P'Length = Integer (Mat.P.Length) - 1);
Result.Format := CSC;
Result.N_Row := Mat.N_Row;
Result.N_Col := Mat.N_Col;
Result.X.Reserve_Capacity (Mat.X.Length);
Result.I.Reserve_Capacity (Mat.I.Length);
Result.P.Reserve_Capacity (Mat.P.Length);
for J of P loop
for K in Mat.P (J) .. Mat.P (J + 1) - 1 loop
Result.X.Append (Mat.X (K));
Result.I.Append (Mat.I (K));
end loop;
Result.P.Append (Tmp);
Tmp := Tmp + Mat.P (J + 1) - Mat.P (J);
end loop;
Result.P.Append (Tmp);
return Result;
end Permute_By_Col;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
-- reporter.adb
--
-- Implementation of the Reporter package.
------------------------------------------------------------------------------
with Ada.Text_IO;
use Ada.Text_IO;
package body Reporter is
protected Output is
procedure Send (Message: String);
end Output;
protected body Output is
procedure Send (Message: String) is
begin
Put_Line (Message);
end Send;
end Output;
procedure Report (Message: String) is
begin
Output.Send (Message);
end Report;
procedure Report (Message: Unbounded_String) is
begin
Output.Send (To_String(Message));
end Report;
end Reporter;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Containers.Vectors;
with Ada.Characters.Latin_1;
with Ada.Exceptions;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Wayland.Enums.Client;
with Wayland.Protocols.Client;
with Wayland.Protocols.Presentation_Time;
package body Wayland_Ada_Info_Events is
package WE renames Wayland.Enums;
package WP renames Wayland.Protocols;
procedure Put_Line (Value : String) renames Ada.Text_IO.Put_Line;
procedure Put (Value : String) renames Ada.Text_IO.Put;
package L1 renames Ada.Characters.Latin_1;
package SU renames Ada.Strings.Unbounded;
function "+" (Value : SU.Unbounded_String) return String renames SU.To_String;
function "+" (Value : String) return SU.Unbounded_String renames SU.To_Unbounded_String;
Wayland_Error : exception;
use Wayland;
use type SU.Unbounded_String;
use all type WP.Client.Keyboard;
use all type WP.Client.Seat;
use all type WP.Client.Output;
use type WE.Client.Shm_Format;
Compositor : WP.Client.Compositor;
Shm : WP.Client.Shm;
Display : WP.Client.Display;
Registry : WP.Client.Registry;
Presentation : WP.Presentation_Time.Presentation;
type Interface_Data is record
Name : SU.Unbounded_String;
Id : Unsigned_32;
Version : Unsigned_32;
end record;
type Seat_Data is limited record
Keyboard : WP.Client.Keyboard;
Seat : WP.Client.Seat;
Name : SU.Unbounded_String;
Capabilities : WE.Client.Seat_Capability := (others => False);
Keyboard_Rate : Integer := Integer'First;
Keyboard_Delay : Integer := Integer'First;
end record;
type Output_Data is limited record
Output : WP.Client.Output;
-- Geometry
X, Y : Integer;
Physical_Width : Natural;
Physical_Height : Natural;
Subpixel : WE.Client.Output_Subpixel;
Make : SU.Unbounded_String;
Model : SU.Unbounded_String;
Transform : WE.Client.Output_Transform;
-- Mode
Flags : WE.Client.Output_Mode;
Width : Natural;
Height : Natural;
Refresh : Positive;
-- Scale
Factor : Positive := 1;
end record;
package Interface_Vectors is new Ada.Containers.Vectors
(Positive, Interface_Data);
package Format_Vectors is new Ada.Containers.Vectors
(Positive, WE.Client.Shm_Format);
Interfaces : Interface_Vectors.Vector;
Formats : Format_Vectors.Vector;
-- Arbitrary maximum of 4 seats
Seats : array (1 .. 4) of Seat_Data;
Seat_First_Index : Natural := Seats'First;
Seat_Last_Index : Natural := Seats'First - 1;
-- Arbitrary maximum of 12 outputs
Outputs : array (1 .. 12) of Output_Data;
Output_First_Index : Natural := Outputs'First;
Output_Last_Index : Natural := Outputs'First - 1;
Clock : Unsigned_32;
procedure Image (Data : Interface_Data) is
begin
Put_Line
("interface: '" & (+Data.Name) & "', " &
"version:" & Data.Version'Image & ", " &
"name:" & Data.Id'Image);
end Image;
procedure Image (Data : Seat_Data) is
begin
if not Data.Seat.Has_Proxy then
return;
end if;
Put_Line (L1.HT & "name: " & (+Data.Name));
if Data.Capabilities.Pointer or
Data.Capabilities.Keyboard or
Data.Capabilities.Touch
then
Put (L1.HT & "capabilities:");
if Data.Capabilities.Pointer then
Put (" pointer");
end if;
if Data.Capabilities.Keyboard then
Put (" keyboard");
end if;
if Data.Capabilities.Touch then
Put (" touch");
end if;
Put_Line ("");
end if;
if not Data.Keyboard.Has_Proxy then
return;
end if;
Put_Line (L1.HT & "keyboard repeat rate:" & Data.Keyboard_Rate'Image);
Put_Line (L1.HT & "keyboard repeat delay:" & Data.Keyboard_Delay'Image);
end Image;
procedure Image (Data : Output_Data) is
begin
if not Data.Output.Has_Proxy then
return;
end if;
Put_Line (L1.HT &
"x:" & Data.X'Image & ", " &
"y:" & Data.Y'Image & ", " &
"scale:" & Data.Factor'Image);
Put_Line (L1.HT & "physical size:" &
Data.Physical_Width'Image & " x" & Data.Physical_Height'Image & " mm");
Put_Line (L1.HT & "make: '" & (+Data.Make) & "', model: '" & (+Data.Model) & "'");
Put_Line (L1.HT &
"subpixel_orientation: " & Data.Subpixel'Image & ", " &
"output_transform: " & Data.Transform'Image);
Put_Line (L1.HT & "mode:");
Put_Line (L1.HT & L1.HT & "size:" &
Data.Width'Image & " x" & Data.Height'Image & " px, " &
"refresh:" & Data.Refresh'Image & " mHz");
if Data.Flags.Current or Data.Flags.Preferred then
Put (L1.HT & L1.HT & "flags:");
if Data.Flags.Current then
Put (" current");
end if;
if Data.Flags.Preferred then
Put (" preferred");
end if;
Put_Line ("");
end if;
end Image;
procedure Shm_Format
(Shm : in out WP.Client.Shm'Class;
Format : WE.Client.Shm_Format) is
begin
Formats.Append (Format);
end Shm_Format;
procedure Keyboard_Repeat_Info
(Keyboard : in out WP.Client.Keyboard'Class;
Rate : Integer;
Delay_V : Integer) is
begin
for E of Seats loop
if E.Keyboard = Keyboard then
E.Keyboard_Rate := Rate;
E.Keyboard_Delay := Delay_V;
end if;
end loop;
end Keyboard_Repeat_Info;
package Keyboard_Events is new WP.Client.Keyboard_Events
(Repeat_Info => Keyboard_Repeat_Info);
procedure Seat_Capabilities
(Seat : in out WP.Client.Seat'Class;
Capabilities : WE.Client.Seat_Capability) is
begin
for E of Seats loop
if E.Seat = Seat then
E.Capabilities := Capabilities;
if Capabilities.Keyboard then
Seat.Get_Keyboard (E.Keyboard);
if not E.Keyboard.Has_Proxy then
raise Wayland_Error with "No keyboard";
end if;
Keyboard_Events.Subscribe (E.Keyboard);
end if;
end if;
end loop;
end Seat_Capabilities;
procedure Seat_Name
(Seat : in out WP.Client.Seat'Class;
Name : String) is
begin
for E of Seats loop
if E.Seat = Seat then
E.Name := +Name;
end if;
end loop;
end Seat_Name;
procedure Output_Geometry
(Output : in out WP.Client.Output'Class;
X, Y : Integer;
Physical_Width : Integer;
Physical_Height : Integer;
Subpixel : WE.Client.Output_Subpixel;
Make : String;
Model : String;
Transform : WE.Client.Output_Transform) is
begin
for E of Outputs loop
if E.Output = Output then
E.X := X;
E.Y := Y;
E.Physical_Width := Physical_Width;
E.Physical_Height := Physical_Height;
E.Subpixel := Subpixel;
E.Make := +Make;
E.Model := +Model;
E.Transform := Transform;
end if;
end loop;
end Output_Geometry;
procedure Output_Mode
(Output : in out WP.Client.Output'Class;
Flags : WE.Client.Output_Mode;
Width : Integer;
Height : Integer;
Refresh : Integer) is
begin
for E of Outputs loop
if E.Output = Output then
E.Flags := Flags;
E.Width := Width;
E.Height := Height;
E.Refresh := Refresh;
end if;
end loop;
end Output_Mode;
procedure Output_Scale
(Output : in out WP.Client.Output'Class;
Factor : Integer) is
begin
for E of Outputs loop
if E.Output = Output then
E.Factor := Factor;
end if;
end loop;
end Output_Scale;
procedure Presentation_Clock
(Presentation : in out WP.Presentation_Time.Presentation'Class;
Id : Unsigned_32) is
begin
Clock := Id;
end Presentation_Clock;
package Shm_Events is new WP.Client.Shm_Events
(Format => Shm_Format);
package Seat_Events is new WP.Client.Seat_Events
(Seat_Capabilities => Seat_Capabilities,
Seat_Name => Seat_Name);
package Output_Events is new WP.Client.Output_Events
(Geometry => Output_Geometry,
Mode => Output_Mode,
Scale => Output_Scale);
package Presentation_Events is new WP.Presentation_Time.Presentation_Events
(Clock => Presentation_Clock);
procedure Global_Registry_Handler
(Registry : in out WP.Client.Registry'Class;
Id : Unsigned_32;
Name : String;
Version : Unsigned_32) is
begin
Interfaces.Append ((Name => +Name, Id => Id, Version => Version));
if Name = WP.Client.Compositor_Interface.Name then
Compositor.Bind (Registry, Id, Unsigned_32'Min (Version, 4));
elsif Name = WP.Client.Shm_Interface.Name then
Shm.Bind (Registry, Id, Unsigned_32'Min (Version, 1));
if not Shm.Has_Proxy then
raise Wayland_Error with "No shm";
end if;
Shm_Events.Subscribe (Shm);
elsif Name = WP.Client.Seat_Interface.Name then
declare
Seat : WP.Client.Seat renames Seats (Seat_Last_Index + 1).Seat;
begin
Seat.Bind (Registry, Id, Unsigned_32'Min (Version, 6));
if not Seat.Has_Proxy then
raise Wayland_Error with "No seat";
end if;
Seat_Events.Subscribe (Seat);
Seat_Last_Index := Seat_Last_Index + 1;
end;
elsif Name = WP.Client.Output_Interface.Name then
declare
Output : WP.Client.Output renames Outputs (Output_Last_Index + 1).Output;
begin
Output.Bind (Registry, Id, Unsigned_32'Min (Version, 3));
if not Output.Has_Proxy then
raise Wayland_Error with "No output";
end if;
Output_Events.Subscribe (Output);
Output_Last_Index := Output_Last_Index + 1;
end;
elsif Name = WP.Presentation_Time.Presentation_Interface.Name then
Presentation.Bind (Registry, Id, Unsigned_32'Min (Version, 1));
if not Presentation.Has_Proxy then
raise Wayland_Error with "No presentation";
end if;
Presentation_Events.Subscribe (Presentation);
end if;
end Global_Registry_Handler;
package Registry_Events is new WP.Client.Registry_Events
(Global_Object_Added => Global_Registry_Handler);
procedure Run is
begin
Display.Connect;
if not Display.Is_Connected then
raise Wayland_Error with "Not connected to display";
end if;
Display.Get_Registry (Registry);
if not Registry.Has_Proxy then
raise Wayland_Error with "No global registry";
end if;
Registry_Events.Subscribe (Registry);
Display.Roundtrip;
Display.Roundtrip;
Display.Roundtrip;
for E of Interfaces loop
Image (E);
if E.Name = WP.Client.Shm_Interface.Name then
if not Formats.Is_Empty then
Put (L1.HT & "formats:");
for Format of Formats loop
Put (" " & Format'Image);
end loop;
Put_Line ("");
end if;
elsif E.Name = WP.Client.Seat_Interface.Name then
Image (Seats (Seat_First_Index));
pragma Assert (Seat_First_Index <= Seat_Last_Index);
Seat_First_Index := Seat_First_Index + 1;
elsif E.Name = WP.Client.Output_Interface.Name then
Image (Outputs (Output_First_Index));
pragma Assert (Output_First_Index <= Output_Last_Index);
Output_First_Index := Output_First_Index + 1;
elsif E.Name = WP.Presentation_Time.Presentation_Interface.Name then
Put_Line (L1.HT & "presentation clock id:" & Clock'Image);
end if;
end loop;
Registry.Destroy;
Display.Disconnect;
exception
when E : others =>
Put_Line ("Error: " & Ada.Exceptions.Exception_Message (E));
if Display.Is_Connected then
Display.Disconnect;
end if;
end Run;
end Wayland_Ada_Info_Events;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
------------------------------------------------------------------------------
-- edp.adb
--
-- A compact Ada 95 simulation of the Enhanced Dining Philosophers Problem.
-- By "compact" it is meant that tasks representing simulation objects are
-- actually made visible to the simulation program as a whole rather than
-- being hidden in packages.
--
-- The objects in the simulation are:
--
-- 5 philosophers;
-- 5 chopsticks;
-- 2 waiters;
-- 3 cooks;
-- A host, who lets the philosophers into the restaurant and escorts them
-- out.
-- Meals, which are certain combinations of foods served by the restaurant;
-- Orders, which are of the form [philosopher, meal];
-- A heat lamp, under which cooks place the cooked orders and from which the
-- waiters pick them up (to bring them back to the philosophers);
-- A reporter, for logging events.
--
-- This is the main subprogram, EDP. The entire program consists of twelve
-- packages and this subprogram. Four packages are very general utilities;
-- the other eight are intrinsic to the simulation. The packages are
--
-- Randoms a collection of operations producing randoms
-- Protected_Counters exports a protected type Protected_Counter
-- Buffers generic package with bounded, blocking queue ADT
-- Reporter unsophisticated package for serializing messages
--
-- Names names for the simulation objects
-- Meals Meal datatype and associated operations
-- Orders Order datatype, order-bin, and heat-lamp
-- Chopsticks the chopsticks
-- Cooks the cooks
-- Host the host
-- Philosophers the philosophers
-- Waiters the waiters
--
-- The main subprogram simply reports that the restaurant is open and then
-- initializes all library tasks. The restaurant will be "closed" by the last
-- waiter to leave.
------------------------------------------------------------------------------
with Ada.Text_IO, Philosophers, Waiters, Cooks, Reporter;
use Ada.Text_IO, Philosophers, Waiters, Cooks, Reporter;
procedure EDP is
begin
Report ("The restaurant is open for business");
for C in Cook_Array'Range loop
Cook_Array(C).Here_Is_Your_Name(C);
end loop;
for W in Waiter_Array'Range loop
Waiter_Array(W).Here_Is_Your_Name(W);
end loop;
for P in Philosopher_Array'Range loop
Philosopher_Array(P).Here_Is_Your_Name(P);
end loop;
end EDP;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Slim.Message_Visiters;
with Slim.Messages.BUTN;
with Slim.Messages.SETD;
with Slim.Messages.STAT;
package Slim.Players.Idle_State_Visiters is
type Visiter (Player : not null access Players.Player) is
new Slim.Message_Visiters.Visiter with null record;
overriding procedure BUTN
(Self : in out Visiter;
Message : not null access Slim.Messages.BUTN.BUTN_Message);
overriding procedure SETD
(Self : in out Visiter;
Message : not null access Slim.Messages.SETD.SETD_Message);
overriding procedure STAT
(Self : in out Visiter;
Message : not null access Slim.Messages.STAT.STAT_Message);
end Slim.Players.Idle_State_Visiters;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Float;
with Ada.Numerics.Distributions;
with Ada.Numerics.SFMT_216091;
with Ada.Text_IO;
procedure random_dist is
package R renames Ada.Numerics.SFMT_216091;
package D renames Ada.Numerics.Distributions;
generic
type Target is range <>;
with procedure Process (X : out Target);
procedure Generic_Check;
procedure Generic_Check is
Req : constant := 100;
Box : array (Target) of Natural := (others => 0);
N : Natural := 0;
Max : Natural := 0;
begin
while N < Req * Target'Range_Length loop
declare
X : Target;
begin
Process (X);
if Box (X) < Req then
N := N + 1;
end if;
Box (X) := Box (X) + 1;
if Box (X) > Max then
Max := Box (X);
end if;
end;
end loop;
for I in Target loop
Ada.Text_IO.Put_Line (" " & (1 .. Box (I) * 40 / Max => '*'));
end loop;
end Generic_Check;
Gen : aliased R.Generator := R.Initialize;
begin
Ada.Text_IO.Put_Line ("Linear_Discrete");
Ada.Text_IO.Put_Line (" ==== 0 bit ====");
declare
type S is mod 10;
type T is range 3 .. 3;
function To is new D.Linear_Discrete (S, T);
procedure Process (X : out T) is
begin
X := To (S'Mod (R.Random_32 (Gen)));
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== 1:1 ====");
declare
type S is mod 10;
type T is range 2 .. 11;
pragma Assert (S'Range_Length = T'Range_Length);
function To is new D.Linear_Discrete (S, T);
procedure Process (X : out T) is
begin
X := To (S'Mod (R.Random_32 (Gen)));
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== integer arithmetic ====");
declare
type S is mod 20;
type T is range 2 .. 11;
pragma Assert (S'Range_Length = T'Range_Length * 2);
function To is new D.Linear_Discrete (S, T);
procedure Process (X : out T) is
begin
X := To (S'Mod (R.Random_32 (Gen)));
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== float arithmetic ====");
declare
type S1 is mod 2 ** (Long_Long_Integer'Size / 2 + 1);
type S2 is mod 2 ** (Long_Long_Integer'Size / 2);
function To is new D.Linear_Discrete (S1, S2);
type T is range 0 .. 7;
procedure Process (X : out T) is
begin
X := T (To (S1'Mod (R.Random_64 (Gen))) mod 8);
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line ("Linear_Float_0_To_1");
declare
type S is mod 11;
function To is new D.Linear_Float_0_To_1 (S, Long_Long_Float'Base);
type T is range 0 .. 10;
procedure Process (X : out T) is
begin
X := T (Long_Long_Float'Floor (To (S'Mod (R.Random_64 (Gen))) * 10.0));
end Process;
procedure Check is new Generic_Check (T, Process);
begin
pragma Assert (To (0) = 0.0);
pragma Assert (To (5) = 0.5);
pragma Assert (To (S'Last) = 1.0);
Check;
end;
Ada.Text_IO.Put_Line ("Linear_Float_0_To_Less_Than_1");
declare
type S is mod 10;
function To is new D.Linear_Float_0_To_Less_Than_1 (S, Long_Long_Float'Base);
begin
pragma Assert (To (0) = 0.0);
pragma Assert (To (5) = 0.5);
pragma Assert (To (S'Last) < 1.0);
null;
end;
Ada.Text_IO.Put_Line ("Linear_Float_Greater_Than_0_To_Less_Than_1");
declare
type S is mod 9;
function To is new D.Linear_Float_Greater_Than_0_To_Less_Than_1 (S, Long_Long_Float'Base);
begin
pragma Assert (To (0) > 0.0);
pragma Assert (To (4) = 0.5);
pragma Assert (To (S'Last) < 1.0);
null;
end;
Ada.Text_IO.Put_Line ("Exponentially_Float");
declare
function To is new D.Exponentially_Float (R.Unsigned_32, Long_Long_Float'Base);
type T is range 0 .. 9;
procedure Process (X : out T) is
function Is_Infinity is new Ada.Float.Is_Infinity (Long_Long_Float'Base);
function Is_NaN is new Ada.Float.Is_NaN (Long_Long_Float'Base);
begin
loop
declare
F : Long_Long_Float'Base := To (R.Random_32 (Gen)) * 2.5;
begin
pragma Assert (not Is_Infinity (F));
pragma Assert (not Is_NaN (F));
if F < 10.0 then
X := T (Long_Long_Float'Floor (F));
exit;
end if;
end;
end loop;
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line ("Uniform_Discrete_Random");
Ada.Text_IO.Put_Line (" ==== 0 bit ====");
declare
type T is range 3 .. 3;
function Random is new D.Uniform_Discrete_Random (R.Unsigned_32, T, R.Generator, R.Random_32);
procedure Process (X : out T) is
begin
X := Random (Gen);
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== 1:1 ====");
declare
type S2 is range
Long_Long_Integer (R.Unsigned_32'First) + 1 ..
Long_Long_Integer (R.Unsigned_32'Last) + 1;
function Random is new D.Uniform_Discrete_Random (R.Unsigned_32, S2, R.Generator, R.Random_32);
type T is range 0 .. 7;
procedure Process (X : out T) is
begin
X := T (Random (Gen) mod 8);
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== narrow (2 ** n) ====");
declare
type T is range 2 .. 9;
function Random is new D.Uniform_Discrete_Random (R.Unsigned_64, T, R.Generator, R.Random_64);
procedure Process (X : out T) is
begin
X := Random (Gen);
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== narrow ====");
declare
type T is range 3 .. 12;
function Random is new D.Uniform_Discrete_Random (R.Unsigned_64, T, R.Generator, R.Random_64);
procedure Process (X : out T) is
begin
X := Random (Gen);
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line (" ==== wide ====");
declare
type S2 is mod 2 ** (R.Unsigned_32'Size + 1);
function Random is new D.Uniform_Discrete_Random (R.Unsigned_32, S2, R.Generator, R.Random_32);
type T is range 0 .. 7;
procedure Process (X : out T) is
begin
X := T (Random (Gen) mod 8);
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line ("Uniform_Float_Random_0_To_1");
declare
function Random is new D.Uniform_Float_Random_0_To_1 (R.Unsigned_32, Float'Base, R.Generator, R.Random_32);
type T is range 0 .. 9;
procedure Process (X : out T) is
Z : T'Base;
begin
loop
Z := T'Base (Float'Floor (Random (Gen) * 10.0));
exit when Z /= 10; -- 1.0 is a rare case
end loop;
X := Z;
end Process;
procedure Check is new Generic_Check (T, Process);
begin
Check;
end;
Ada.Text_IO.Put_Line ("Uniform_Float_Random_0_To_Less_Than_1");
declare
function Random is new D.Uniform_Float_Random_0_To_Less_Than_1 (R.Unsigned_32, Long_Float'Base, R.Generator, R.Random_32);
begin
pragma Assert (Random (Gen) < 1.0);
null;
end;
Ada.Text_IO.Put_Line ("Uniform_Float_Random_Greater_Than_0_To_Less_Than_1");
declare
function Random is new D.Uniform_Float_Random_Greater_Than_0_To_Less_Than_1 (R.Unsigned_32, Long_Long_Float'Base, R.Generator, R.Random_32);
X : constant Long_Long_Float'Base := Random (Gen);
begin
pragma Assert (X > 0.0 and then X < 1.0);
null;
end;
pragma Debug (Ada.Debug.Put ("OK"));
end random_dist;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
with Ada.Text_IO, Ada.Command_Line;
procedure Magic_Square is
N: constant Positive := Positive'Value(Ada.Command_Line.Argument(1));
subtype Constants is Natural range 1 .. N*N;
package CIO is new Ada.Text_IO.Integer_IO(Constants);
Undef: constant Natural := 0;
subtype Index is Natural range 0 .. N-1;
function Inc(I: Index) return Index is (if I = N-1 then 0 else I+1);
function Dec(I: Index) return Index is (if I = 0 then N-1 else I-1);
A: array(Index, Index) of Natural := (others => (others => Undef));
-- initially undefined; at the end holding the magic square
X: Index := 0; Y: Index := N/2; -- start position for the algorithm
begin
for I in Constants loop -- write 1, 2, ..., N*N into the magic array
A(X, Y) := I; -- write I into the magic array
if A(Dec(X), Inc(Y)) = Undef then
X := Dec(X); Y := Inc(Y); -- go right-up
else
X := Inc(X); -- go down
end if;
end loop;
for Row in Index loop -- output the magic array
for Collumn in Index loop
CIO.Put(A(Row, Collumn),
Width => (if N*N < 10 then 2 elsif N*N < 100 then 3 else 4));
end loop;
Ada.Text_IO.New_Line;
end loop;
end Magic_Square;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
-------------------------------------------------------------
with Program.Elements.Defining_Names;
with Program.Lexical_Elements;
package Program.Elements.Defining_Operator_Symbols is
pragma Pure (Program.Elements.Defining_Operator_Symbols);
type Defining_Operator_Symbol is
limited interface and Program.Elements.Defining_Names.Defining_Name;
type Defining_Operator_Symbol_Access is
access all Defining_Operator_Symbol'Class with Storage_Size => 0;
type Defining_Operator_Symbol_Text is limited interface;
type Defining_Operator_Symbol_Text_Access is
access all Defining_Operator_Symbol_Text'Class with Storage_Size => 0;
not overriding function To_Defining_Operator_Symbol_Text
(Self : aliased in out Defining_Operator_Symbol)
return Defining_Operator_Symbol_Text_Access is abstract;
not overriding function Operator_Symbol_Token
(Self : Defining_Operator_Symbol_Text)
return not null Program.Lexical_Elements.Lexical_Element_Access
is abstract;
end Program.Elements.Defining_Operator_Symbols;
|
{
"source": "starcoderdata",
"programming_language": "ada"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.